bugfix: crash when using mouse wheel
[view.love.git] / edit.lua
blobd30dbdcc2eb88b1eabbb5ec23e7f78722a4e5fde
1 -- some constants people might like to tweak
2 Text_color = {r=0, g=0, b=0}
3 Cursor_color = {r=1, g=0, b=0}
4 Stroke_color = {r=0, g=0, b=0}
5 Current_stroke_color = {r=0.7, g=0.7, b=0.7} -- in process of being drawn
6 Current_name_background_color = {r=1, g=0, b=0, a=0.1} -- name currently being edited
7 Focus_stroke_color = {r=1, g=0, b=0} -- what mouse is hovering over
8 Highlight_color = {r=0.7, g=0.7, b=0.9} -- selected text
9 Icon_color = {r=0.7, g=0.7, b=0.7} -- color of current mode icon in drawings
10 Help_color = {r=0, g=0.5, b=0}
11 Help_background_color = {r=0, g=0.5, b=0, a=0.1}
13 Margin_top = 15
14 Margin_left = 25
15 Margin_right = 25
17 Drawing_padding_top = 10
18 Drawing_padding_bottom = 10
19 Drawing_padding_height = Drawing_padding_top + Drawing_padding_bottom
21 Same_point_distance = 4 -- pixel distance at which two points are considered the same
23 edit = {}
25 -- run in both tests and a real run
26 function edit.initialize_state(top, left, right, font_height, line_height) -- currently always draws to bottom of screen
27 local result = {
28 -- a line is either text or a drawing
29 -- a text is a table with:
30 -- mode = 'text',
31 -- string data,
32 -- a drawing is a table with:
33 -- mode = 'drawing'
34 -- a (y) coord in pixels (updated while painting screen),
35 -- a (h)eight,
36 -- an array of points, and
37 -- an array of shapes
38 -- a shape is a table containing:
39 -- a mode
40 -- an array points for mode 'freehand' (raw x,y coords; freehand drawings don't pollute the points array of a drawing)
41 -- an array vertices for mode 'polygon', 'rectangle', 'square'
42 -- p1, p2 for mode 'line'
43 -- center, radius for mode 'circle'
44 -- center, radius, start_angle, end_angle for mode 'arc'
45 -- Unless otherwise specified, coord fields are normalized; a drawing is always 256 units wide
46 -- The field names are carefully chosen so that switching modes in midstream
47 -- remembers previously entered points where that makes sense.
48 lines = {{mode='text', data=''}}, -- array of lines
50 -- Lines can be too long to fit on screen, in which case they _wrap_ into
51 -- multiple _screen lines_.
53 -- rendering wrapped text lines needs some additional short-lived data per line:
54 -- startpos, the index of data the line starts rendering from, can only be >1 for topmost line on screen
55 -- starty, the y coord in pixels the line starts rendering from
56 -- fragments: snippets of the line guaranteed to not straddle screen lines
57 -- screen_line_starting_pos: optional array of grapheme indices if it wraps over more than one screen line
58 line_cache = {},
60 -- Given wrapping, any potential location for the text cursor can be described in two ways:
61 -- * schema 1: As a combination of line index and position within a line (in utf8 codepoint units)
62 -- * schema 2: As a combination of line index, screen line index within the line, and a position within the screen line.
64 -- Most of the time we'll only persist positions in schema 1, translating to
65 -- schema 2 when that's convenient.
67 -- Make sure these coordinates are never aliased, so that changing one causes
68 -- action at a distance.
69 screen_top1 = {line=1, pos=1}, -- position of start of screen line at top of screen
70 cursor1 = {line=1, pos=1}, -- position of cursor
71 screen_bottom1 = {line=1, pos=1}, -- position of start of screen line at bottom of screen
73 selection1 = {},
74 -- some extra state to compute selection between mouse press and release
75 old_cursor1 = nil,
76 old_selection1 = nil,
77 mousepress_shift = nil,
79 -- cursor coordinates in pixels
80 cursor_x = 0,
81 cursor_y = 0,
83 current_drawing_mode = 'line',
84 previous_drawing_mode = nil, -- extra state for some ephemeral modes like moving/deleting/naming points
86 font_height = font_height,
87 line_height = line_height,
89 top = top,
90 left = math.floor(left),
91 right = math.floor(right),
92 width = right-left,
94 filename = love.filesystem.getSourceBaseDirectory()..'/lines.txt', -- '/' should work even on Windows
95 next_save = nil,
97 -- undo
98 history = {},
99 next_history = 1,
101 -- search
102 search_term = nil,
103 search_backup = nil, -- stuff to restore when cancelling search
105 return result
106 end -- App.initialize_state
108 function edit.check_locs(State)
109 -- if State is inconsistent (i.e. file changed by some other program),
110 -- throw away all cursor state entirely
111 if edit.invalid1(State, State.screen_top1)
112 or edit.invalid_cursor1(State)
113 or not edit.cursor_on_text(State)
114 or not Text.le1(State.screen_top1, State.cursor1) then
115 State.screen_top1 = {line=1, pos=1}
116 edit.put_cursor_on_next_text_line(State)
120 function edit.invalid1(State, loc1)
121 if loc1.line > #State.lines then return true end
122 local l = State.lines[loc1.line]
123 if l.mode ~= 'text' then return false end -- pos is irrelevant to validity for a drawing line
124 return loc1.pos > #State.lines[loc1.line].data
127 -- cursor loc in particular differs from other locs in one way:
128 -- pos might occur just after end of line
129 function edit.invalid_cursor1(State)
130 local cursor1 = State.cursor1
131 if cursor1.line > #State.lines then return true end
132 local l = State.lines[cursor1.line]
133 if l.mode ~= 'text' then return false end -- pos is irrelevant to validity for a drawing line
134 return cursor1.pos > #State.lines[cursor1.line].data + 1
137 function edit.cursor_on_text(State)
138 return State.cursor1.line <= #State.lines
139 and State.lines[State.cursor1.line].mode == 'text'
142 function edit.put_cursor_on_next_text_line(State)
143 while true do
144 if State.cursor1.line >= #State.lines then
145 break
147 if State.lines[State.cursor1.line].mode == 'text' then
148 break
150 State.cursor1.line = State.cursor1.line+1
151 State.cursor1.pos = 1
155 -- return y drawn until
156 function edit.draw(State)
157 State.button_handlers = {}
158 App.color(Text_color)
159 if #State.lines ~= #State.line_cache then
160 print(('line_cache is out of date; %d when it should be %d'):format(#State.line_cache, #State.lines))
161 assert(false)
163 if not Text.le1(State.screen_top1, State.cursor1) then
164 print(State.screen_top1.line, State.screen_top1.pos, State.cursor1.line, State.cursor1.pos)
165 assert(false)
167 State.cursor_x = nil
168 State.cursor_y = nil
169 local y = State.top
170 local screen_bottom1 = {line=nil, pos=nil}
171 --? print('== draw')
172 for line_index = State.screen_top1.line,#State.lines do
173 local line = State.lines[line_index]
174 --? print('draw:', y, line_index, line)
175 if y + State.line_height > App.screen.height then break end
176 screen_bottom1.line = line_index
177 if line.mode == 'text' then
178 --? print('text.draw', y, line_index)
179 local startpos = 1
180 if line_index == State.screen_top1.line then
181 startpos = State.screen_top1.pos
183 if line.data == '' then
184 -- button to insert new drawing
185 button(State, 'draw', {x=State.left-Margin_left+4, y=y+4, w=12,h=12, color={1,1,0},
186 icon = icon.insert_drawing,
187 onpress1 = function()
188 Drawing.before = snapshot(State, line_index-1, line_index)
189 table.insert(State.lines, line_index, {mode='drawing', y=y, h=256/2, points={}, shapes={}, pending={}})
190 table.insert(State.line_cache, line_index, {})
191 if State.cursor1.line >= line_index then
192 State.cursor1.line = State.cursor1.line+1
194 schedule_save(State)
195 record_undo_event(State, {before=Drawing.before, after=snapshot(State, line_index-1, line_index+1)})
196 end,
199 y, screen_bottom1.pos = Text.draw(State, line_index, y, startpos)
200 --? print('=> y', y)
201 elseif line.mode == 'drawing' then
202 y = y+Drawing_padding_top
203 Drawing.draw(State, line_index, y)
204 y = y + Drawing.pixels(line.h, State.width) + Drawing_padding_bottom
205 else
206 print(line.mode)
207 assert(false)
210 State.screen_bottom1 = screen_bottom1
211 if State.search_term then
212 Text.draw_search_bar(State)
214 return y
217 function edit.update(State, dt)
218 Drawing.update(State, dt)
219 if State.next_save and State.next_save < Current_time then
220 save_to_disk(State)
221 State.next_save = nil
225 function schedule_save(State)
226 if State.next_save == nil then
227 State.next_save = Current_time + 3 -- short enough that you're likely to still remember what you did
231 function edit.quit(State)
232 -- make sure to save before quitting
233 if State.next_save then
234 save_to_disk(State)
235 -- give some time for the OS to flush everything to disk
236 love.timer.sleep(0.1)
240 function edit.mouse_press(State, x,y, mouse_button)
241 if State.search_term then return end
242 --? print_and_log(('edit.mouse_press: cursor at %d,%d'):format(State.cursor1.line, State.cursor1.pos))
243 if mouse_press_consumed_by_any_button_handler(State, x,y, mouse_button) then
244 -- press on a button and it returned 'true' to short-circuit
245 return
248 if y < State.top then
249 State.old_cursor1 = State.cursor1
250 State.old_selection1 = State.selection1
251 State.mousepress_shift = App.shift_down()
252 State.selection1 = {
253 line=State.screen_top1.line,
254 pos=State.screen_top1.pos,
256 return
259 for line_index,line in ipairs(State.lines) do
260 if line.mode == 'text' then
261 if Text.in_line(State, line_index, x,y) then
262 -- delicate dance between cursor, selection and old cursor/selection
263 -- scenarios:
264 -- regular press+release: sets cursor, clears selection
265 -- shift press+release:
266 -- sets selection to old cursor if not set otherwise leaves it untouched
267 -- sets cursor
268 -- press and hold to start a selection: sets selection on press, cursor on release
269 -- press and hold, then press shift: ignore shift
270 -- i.e. mouse_release should never look at shift state
271 --? print_and_log(('edit.mouse_press: in line %d'):format(line_index))
272 State.old_cursor1 = State.cursor1
273 State.old_selection1 = State.selection1
274 State.mousepress_shift = App.shift_down()
275 State.selection1 = {
276 line=line_index,
277 pos=Text.to_pos_on_line(State, line_index, x, y),
279 return
281 elseif line.mode == 'drawing' then
282 local line_cache = State.line_cache[line_index]
283 if Drawing.in_drawing(line, line_cache, x, y, State.left,State.right) then
284 State.lines.current_drawing_index = line_index
285 State.lines.current_drawing = line
286 Drawing.before = snapshot(State, line_index)
287 Drawing.mouse_press(State, line_index, x,y, mouse_button)
288 return
293 -- still here? click is below all screen lines
294 State.old_cursor1 = State.cursor1
295 State.old_selection1 = State.selection1
296 State.mousepress_shift = App.shift_down()
297 State.selection1 = {
298 line=State.screen_bottom1.line,
299 pos=Text.pos_at_end_of_screen_line(State, State.screen_bottom1),
303 function edit.mouse_release(State, x,y, mouse_button)
304 if State.search_term then return end
305 --? print_and_log(('edit.mouse_release: cursor at %d,%d'):format(State.cursor1.line, State.cursor1.pos))
306 if State.lines.current_drawing then
307 Drawing.mouse_release(State, x,y, mouse_button)
308 schedule_save(State)
309 if Drawing.before then
310 record_undo_event(State, {before=Drawing.before, after=snapshot(State, State.lines.current_drawing_index)})
311 Drawing.before = nil
313 else
314 --? print_and_log('edit.mouse_release: no current drawing')
315 for line_index,line in ipairs(State.lines) do
316 if line.mode == 'text' then
317 if Text.in_line(State, line_index, x,y) then
318 --? print_and_log(('edit.mouse_release: in line %d'):format(line_index))
319 State.cursor1 = {
320 line=line_index,
321 pos=Text.to_pos_on_line(State, line_index, x, y),
323 --? print_and_log(('edit.mouse_release: cursor now %d,%d'):format(State.cursor1.line, State.cursor1.pos))
324 if State.mousepress_shift then
325 if State.old_selection1.line == nil then
326 State.selection1 = State.old_cursor1
327 else
328 State.selection1 = State.old_selection1
331 State.old_cursor1, State.old_selection1, State.mousepress_shift = nil
332 if eq(State.cursor1, State.selection1) then
333 State.selection1 = {}
335 break
339 --? print_and_log(('edit.mouse_release: finally selection %s,%s cursor %d,%d'):format(tostring(State.selection1.line), tostring(State.selection1.pos), State.cursor1.line, State.cursor1.pos))
343 function edit.mouse_wheel_move(State, dx,dy)
344 if dy > 0 then
345 State.cursor1 = {line=State.screen_top1.line, pos=State.screen_top1.pos}
346 edit.put_cursor_on_next_text_line(State)
347 for i=1,math.floor(dy) do
348 Text.up(State)
350 elseif dy < 0 then
351 State.cursor1 = {line=State.screen_bottom1.line, pos=State.screen_bottom1.pos}
352 edit.put_cursor_on_next_text_line(State)
353 for i=1,math.floor(-dy) do
354 Text.down(State)
359 function edit.text_input(State, t)
360 --? print('text input', t)
361 if State.search_term then
362 State.search_term = State.search_term..t
363 Text.search_next(State)
364 elseif State.lines.current_drawing and State.current_drawing_mode == 'name' then
365 local before = snapshot(State, State.lines.current_drawing_index)
366 local drawing = State.lines.current_drawing
367 local p = drawing.points[drawing.pending.target_point]
368 p.name = p.name..t
369 record_undo_event(State, {before=before, after=snapshot(State, State.lines.current_drawing_index)})
370 else
371 local drawing_index, drawing = Drawing.current_drawing(State)
372 if drawing_index == nil then
373 for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end -- just in case we scroll
374 Text.text_input(State, t)
377 schedule_save(State)
380 function edit.keychord_press(State, chord, key)
381 if State.selection1.line and
382 not State.lines.current_drawing and
383 -- printable character created using shift key => delete selection
384 -- (we're not creating any ctrl-shift- or alt-shift- combinations using regular/printable keys)
385 (not App.shift_down() or utf8.len(key) == 1) and
386 chord ~= 'C-a' and chord ~= 'C-c' and chord ~= 'C-x' and chord ~= 'backspace' and chord ~= 'delete' and chord ~= 'C-z' and chord ~= 'C-y' and not App.is_cursor_movement(chord) then
387 Text.delete_selection(State, State.left, State.right)
389 if State.search_term then
390 for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end -- just in case we scroll
391 if chord == 'escape' then
392 State.search_term = nil
393 State.cursor1 = State.search_backup.cursor
394 State.screen_top1 = State.search_backup.screen_top
395 State.search_backup = nil
396 Text.redraw_all(State) -- if we're scrolling, reclaim all fragments to avoid memory leaks
397 elseif chord == 'return' then
398 State.search_term = nil
399 State.search_backup = nil
400 elseif chord == 'backspace' then
401 local len = utf8.len(State.search_term)
402 local byte_offset = Text.offset(State.search_term, len)
403 State.search_term = string.sub(State.search_term, 1, byte_offset-1)
404 elseif chord == 'down' then
405 State.cursor1.pos = State.cursor1.pos+1
406 Text.search_next(State)
407 elseif chord == 'up' then
408 Text.search_previous(State)
410 return
411 elseif chord == 'C-f' then
412 State.search_term = ''
413 State.search_backup = {
414 cursor={line=State.cursor1.line, pos=State.cursor1.pos},
415 screen_top={line=State.screen_top1.line, pos=State.screen_top1.pos},
417 -- zoom
418 elseif chord == 'C-=' then
419 edit.update_font_settings(State, State.font_height+2)
420 Text.redraw_all(State)
421 elseif chord == 'C--' then
422 if State.font_height > 2 then
423 edit.update_font_settings(State, State.font_height-2)
424 Text.redraw_all(State)
426 elseif chord == 'C-0' then
427 edit.update_font_settings(State, 20)
428 Text.redraw_all(State)
429 -- undo
430 elseif chord == 'C-z' then
431 for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end -- just in case we scroll
432 local event = undo_event(State)
433 if event then
434 local src = event.before
435 State.screen_top1 = deepcopy(src.screen_top)
436 State.cursor1 = deepcopy(src.cursor)
437 State.selection1 = deepcopy(src.selection)
438 patch(State.lines, event.after, event.before)
439 patch_placeholders(State.line_cache, event.after, event.before)
440 -- invalidate various cached bits of lines
441 State.lines.current_drawing = nil
442 -- if we're scrolling, reclaim all fragments to avoid memory leaks
443 Text.redraw_all(State)
444 schedule_save(State)
446 elseif chord == 'C-y' then
447 for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end -- just in case we scroll
448 local event = redo_event(State)
449 if event then
450 local src = event.after
451 State.screen_top1 = deepcopy(src.screen_top)
452 State.cursor1 = deepcopy(src.cursor)
453 State.selection1 = deepcopy(src.selection)
454 patch(State.lines, event.before, event.after)
455 -- invalidate various cached bits of lines
456 State.lines.current_drawing = nil
457 -- if we're scrolling, reclaim all fragments to avoid memory leaks
458 Text.redraw_all(State)
459 schedule_save(State)
461 -- clipboard
462 elseif chord == 'C-a' then
463 State.selection1 = {line=1, pos=1}
464 State.cursor1 = {line=#State.lines, pos=utf8.len(State.lines[#State.lines].data)+1}
465 elseif chord == 'C-c' then
466 local s = Text.selection(State)
467 if s then
468 App.set_clipboard(s)
470 elseif chord == 'C-x' then
471 for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end -- just in case we scroll
472 local s = Text.cut_selection(State, State.left, State.right)
473 if s then
474 App.set_clipboard(s)
476 schedule_save(State)
477 elseif chord == 'C-v' then
478 for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end -- just in case we scroll
479 -- We don't have a good sense of when to scroll, so we'll be conservative
480 -- and sometimes scroll when we didn't quite need to.
481 local before_line = State.cursor1.line
482 local before = snapshot(State, before_line)
483 local clipboard_data = App.get_clipboard()
484 for _,code in utf8.codes(clipboard_data) do
485 local c = utf8.char(code)
486 if c == '\n' then
487 Text.insert_return(State)
488 else
489 Text.insert_at_cursor(State, c)
492 if Text.cursor_out_of_screen(State) then
493 Text.snap_cursor_to_bottom_of_screen(State, State.left, State.right)
495 schedule_save(State)
496 record_undo_event(State, {before=before, after=snapshot(State, before_line, State.cursor1.line)})
497 -- dispatch to drawing or text
498 elseif App.mouse_down(1) or chord:sub(1,2) == 'C-' then
499 -- DON'T reset line_cache.starty here
500 local drawing_index, drawing = Drawing.current_drawing(State)
501 if drawing_index then
502 local before = snapshot(State, drawing_index)
503 Drawing.keychord_press(State, chord)
504 record_undo_event(State, {before=before, after=snapshot(State, drawing_index)})
505 schedule_save(State)
507 elseif chord == 'escape' and not App.mouse_down(1) then
508 for _,line in ipairs(State.lines) do
509 if line.mode == 'drawing' then
510 line.show_help = false
513 elseif State.lines.current_drawing and State.current_drawing_mode == 'name' then
514 if chord == 'return' then
515 State.current_drawing_mode = State.previous_drawing_mode
516 State.previous_drawing_mode = nil
517 else
518 local before = snapshot(State, State.lines.current_drawing_index)
519 local drawing = State.lines.current_drawing
520 local p = drawing.points[drawing.pending.target_point]
521 if chord == 'escape' then
522 p.name = nil
523 record_undo_event(State, {before=before, after=snapshot(State, State.lines.current_drawing_index)})
524 elseif chord == 'backspace' then
525 local len = utf8.len(p.name)
526 if len > 0 then
527 local byte_offset = Text.offset(p.name, len-1)
528 if len == 1 then byte_offset = 0 end
529 p.name = string.sub(p.name, 1, byte_offset)
530 record_undo_event(State, {before=before, after=snapshot(State, State.lines.current_drawing_index)})
534 schedule_save(State)
535 else
536 for _,line_cache in ipairs(State.line_cache) do line_cache.starty = nil end -- just in case we scroll
537 Text.keychord_press(State, chord)
541 function edit.key_release(State, key, scancode)
544 function edit.update_font_settings(State, font_height)
545 State.font_height = font_height
546 love.graphics.setFont(love.graphics.newFont(State.font_height))
547 State.line_height = math.floor(font_height*1.3)
550 --== some methods for tests
552 -- Insulate tests from some key globals so I don't have to change the vast
553 -- majority of tests when they're modified for the real app.
554 Test_margin_left = 25
555 Test_margin_right = 0
557 function edit.initialize_test_state()
558 -- if you change these values, tests will start failing
559 return edit.initialize_state(
560 15, -- top margin
561 Test_margin_left,
562 App.screen.width - Test_margin_right,
563 14, -- font height assuming default LÖVE font
564 15) -- line height
567 -- all text_input events are also keypresses
568 -- TODO: handle chords of multiple keys
569 function edit.run_after_text_input(State, t)
570 edit.keychord_press(State, t)
571 edit.text_input(State, t)
572 edit.key_release(State, t)
573 App.screen.contents = {}
574 edit.update(State, 0)
575 edit.draw(State)
578 -- not all keys are text_input
579 function edit.run_after_keychord(State, chord)
580 edit.keychord_press(State, chord)
581 edit.key_release(State, chord)
582 App.screen.contents = {}
583 edit.update(State, 0)
584 edit.draw(State)
587 function edit.run_after_mouse_click(State, x,y, mouse_button)
588 App.fake_mouse_press(x,y, mouse_button)
589 edit.mouse_press(State, x,y, mouse_button)
590 App.fake_mouse_release(x,y, mouse_button)
591 edit.mouse_release(State, x,y, mouse_button)
592 App.screen.contents = {}
593 edit.update(State, 0)
594 edit.draw(State)
597 function edit.run_after_mouse_press(State, x,y, mouse_button)
598 App.fake_mouse_press(x,y, mouse_button)
599 edit.mouse_press(State, x,y, mouse_button)
600 App.screen.contents = {}
601 edit.update(State, 0)
602 edit.draw(State)
605 function edit.run_after_mouse_release(State, x,y, mouse_button)
606 App.fake_mouse_release(x,y, mouse_button)
607 edit.mouse_release(State, x,y, mouse_button)
608 App.screen.contents = {}
609 edit.update(State, 0)
610 edit.draw(State)