7 Mouse, Paste, and Window Size🔗ℹ

Window size:

(let-values ([(rows cols) (get-window-size)])
  (when rows
    (printf "~a x ~a\n" rows cols)))

A resize-event arrives when the window changes. Mouse and paste are enabled automatically when the terminal supports them; no extra switch is needed. Mouse actions are 'press, 'release, 'move, or 'scroll, and coordinates start at 1 like put-at. Pasted content arrives as a paste-event; without a #:paste callback, build-input passes it to #:text.

#lang racket
 
(require tui
         racket/string)
 
(define rows 24)
(define cols 80)
(define last-event "(none)")
(define running? #t)
 
(define (clip s n)
  (if (> (string-length s) n)
      (string-append (substring s 0 n) "…")
      s))
 
(define (read-size!)
  (define-values (r c) (get-window-size))
  (when (and r c)
    (set! rows r)
    (set! cols c)))
 
(define (draw)
  (put-format-bytes
   format-screen-clear
   (format-cursor-move 2 3)
   (format-styled 'title "Mouse / paste / resize")
   (format-cursor-move 4 3)
   (format-styled 'heading "Last event:")
   (format-cursor-move 5 3)
   (format-styled 'success (clip last-event 50))
   (format-cursor-move 7 3)
   (format-styled 'heading "Window:")
   (format-content (format "~a rows x ~a columns" rows cols))
   (format-cursor-move 10 3)
   (format-styled 'info "Click, scroll, paste, resize; Esc quit")))
 
(define handler
  (build-input
   #:mouse (λ (action button x y mods)
             (set! last-event
                   (format "mouse ~a button=~a at (~a, ~a)"
                           action button x y)))
   #:resize (λ (r c)
              (set! rows r)
              (set! cols c)
              (set! last-event (format "resize ~a x ~a" r c)))
   #:paste (λ (bs)
             (set! last-event (format "paste ~a bytes" (bytes-length bs))))
   #:text (λ (s)
            (set! last-event (format "text ~s" (clip s 40))))
   #:escape (λ () (set! running? #f))))
 
(define (handle ev)
  (handler ev)
  (draw))
 
(with-tui
 (λ ()
   (cursor-hide)
   (read-size!)
   (draw)
   (loop-input/stop (not running?) handle)))

For list-like UIs, scroll-region, scroll-up, and scroll-down scroll whole lines. Wheel events arrive at #:mouse with the 'scroll action.