8 Putting It Together🔗ℹ

Combine the previous sections to build a paint app:

  • State: cursor position, painted cells, current color.

  • Update: arrow keys move, Space/left click paints, wheel changes color, c clears, Esc quits.

  • Render: redraw the whole frame after each event; on resize, update the size and clamp the cursor.

The core structure:

(define (update! ev) ...)
(define (draw) ...)
(define (handle ev) (update! ev) (draw))
(loop-input/stop (not running?) handle)

The complete code is in cursor/examples/en/07-paint.rkt. The key input handling looks like this:

(build-input
 #:up    (λ () (move! -1 0))
 #:down  (λ () (move! 1 0))
 #:left  (λ () (move! 0 -1))
 #:right (λ () (move! 0 1))
 #:space (λ () (toggle! cursor-row cursor-col))
 #:text  (λ (s) (when (string=? s "c") (hash-clear! marks)))
 #:escape (λ () (set! running? #f))
 #:mouse (λ (action button x y mods)
           (case action
             [(press) (when (eq? button 'left) (toggle! y x))]
             [(scroll) (cycle-color! (if (eq? button 'up) 1 -1))]))
 #:resize (λ (r c) (set! rows r) (set! cols c) (clamp!)))

Exercises:

  • Add undo/redo to the paint app.

  • Add a text input using #:text / #:backspace / #:enter.

  • Make draw a pure (render state) -> bytes function so it can be reused.