view src/net/kryshen/indyvon/core.clj @ 90:dd7b8dbb20bc

Viewport miniature: preserve aspect ratio; draw visible area highlight synchronously.
author Mikhail Kryshen <mikhail@kryshen.net>
date Sun, 28 Nov 2010 03:46:59 +0300
parents 54f6e6d196c3
children df9dedc80485
line source
1 ;;
2 ;; Copyright 2010 Mikhail Kryshen <mikhail@kryshen.net>
3 ;;
4 ;; This file is part of Indyvon.
5 ;;
6 ;; Indyvon is free software: you can redistribute it and/or modify it
7 ;; under the terms of the GNU Lesser General Public License version 3
8 ;; only, as published by the Free Software Foundation.
9 ;;
10 ;; Indyvon is distributed in the hope that it will be useful, but
11 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;; Lesser General Public License for more details.
14 ;;
15 ;; You should have received a copy of the GNU Lesser General Public
16 ;; License along with Indyvon. If not, see
17 ;; <http://www.gnu.org/licenses/>.
18 ;;
20 (ns net.kryshen.indyvon.core
21 (:import
22 (java.awt Graphics2D RenderingHints Component Color Font Shape)
23 (java.awt.geom AffineTransform Point2D$Double Rectangle2D$Double Area)
24 (java.awt.event MouseListener MouseMotionListener)
25 (java.awt.font FontRenderContext)
26 (com.google.common.collect MapMaker)))
28 ;;
29 ;; Layer context
30 ;;
32 (def ^Graphics2D *graphics*)
34 (def ^FontRenderContext *font-context*)
36 (def ^{:tag Component
37 :doc "Target AWT component, may be nil if drawing off-screen."}
38 *target*)
40 (def ^{:doc "Width of the rendering area."}
41 *width*)
43 (def ^{:doc "Height of the rendering area."}
44 *height*)
46 (def ^Shape *clip*)
48 (def ^{:doc "The root (background) layer of the scene."}
49 *root*)
51 (def ^{:doc "Time in nanoseconds when the rendering of the current
52 frame starts."}
53 *time*)
55 (def *event-dispatcher*)
57 (def ^{:tag AffineTransform
58 :doc "Initial transform associated with the graphics context."}
59 *initial-transform*)
61 (def ^{:tag AffineTransform
62 :doc "Inversion of the initial transform associated with
63 the graphics context."}
64 *inverse-initial-transform*)
66 (defrecord Theme [fore-color back-color alt-back-color border-color font])
68 ;; REMIND: use system colors, see java.awt.SystemColor.
69 (defn default-theme []
70 (Theme. Color/BLACK Color/WHITE Color/LIGHT_GRAY
71 Color/BLUE (Font. "Sans" Font/PLAIN 12)))
73 (def *theme* (default-theme))
75 (defrecord Location [x y])
76 (defrecord Size [width height])
77 (defrecord Bounds [x y width height])
79 ;;
80 ;; Core protocols and types
81 ;;
83 (defprotocol Layer
84 "Basic UI element."
85 (render! [this])
86 (layer-size [this]))
88 ;; TODO: modifiers
89 (defrecord MouseEvent [id when x y x-on-screen y-on-screen button])
91 ;; TODO: KeyEvent
93 (defprotocol EventDispatcher
94 (listen! [this ^Component component]
95 "Listen for events on the specified AWT Component.")
96 (create-dispatcher [this handle handlers]
97 "Returns new event dispatcher associated with the specified event
98 handlers (an event-id -> handler-fn map). Handle is used to
99 match the contexts between commits.")
100 (commit [this]
101 "Apply the registered handlers for event processing.")
102 (handle-picked? [this handle]
103 "Returns true if the specified handle received the :mouse-pressed
104 event and have not yet received :moused-released.")
105 (handle-hovered? [this handle]
106 "Returns true if the specified handle received the :mouse-entered
107 event and have not yet received :mouse-exited."))
109 (defprotocol Anchored
110 "Provide anchor point for Layers. Used by viewport."
111 (anchor [this h-align v-align]
112 "Anchor point: [x y], h-align could be :left, :center or :right,
113 v-align is :top, :center or :bottom"))
115 (defn default-anchor [layer h-align v-align]
116 (if (and (= h-align :left)
117 (= v-align :top))
118 (Location. 0 0)
119 (let [size (layer-size layer)]
120 (Location.
121 (case h-align
122 :top 0
123 :center (/ (:width size) 2)
124 :right (:width size))
125 (case v-align
126 :left 0
127 :center (/ (:height size) 2)
128 :bottom (:height size))))))
130 ;; Default implementation of Anchored for any Layer.
131 (extend-protocol Anchored
132 net.kryshen.indyvon.core.Layer
133 (anchor [this h-align v-align]
134 (default-anchor this h-align v-align)))
136 (defn- assoc-cons [m key val]
137 (->> (get m key) (cons val) (assoc m key)))
139 ;;
140 ;; Observers
141 ;; The mechanism used by layers to request repaints
142 ;;
144 (def ^java.util.Map observers
145 (-> (MapMaker.) (.weakKeys) (.makeMap)))
147 (defn add-observer
148 "Add observer fn for the target. Watcher identifies the group of
149 observers and could be used to remove the group. Watcher is weakly
150 referenced, all associated observers will be removed when the
151 wathcer is removed by gc. The observer fn will be called with
152 watcher and target arguments and any additional arguments specified
153 in update call."
154 [watcher target f]
155 (.put observers watcher (assoc-cons (.get observers watcher) target f))
156 nil)
158 (defn remove-observers
159 "Remove group of observers associated with the specified watcher."
160 [watcher]
161 (.remove observers watcher)
162 nil)
164 (defn- replace-observers-watcher
165 [old-watcher new-watcher]
166 (if-let [old (.remove observers old-watcher)]
167 (.put observers new-watcher old))
168 nil)
170 (defn update
171 "Notify observers."
172 [target & args]
173 (doseq [entry observers
174 f (get (val entry) target)]
175 (apply f (key entry) target args)))
177 (defn add-context-observer
178 "Observer registered with this function will be automatically
179 removed after the next frame rendering is complete."
180 [target f]
181 (let [root *root*]
182 (add-observer root target f)))
184 (defn repaint-on-update
185 "Trigger repaint of the current scene when the target updates."
186 [target]
187 (let [root *root*]
188 (if (not= root target)
189 (add-observer root target (fn [w _] (update w))))))
191 (defn repaint
192 "Repaint the current scene."
193 []
194 (update *root*))
196 ;;
197 ;; Rendering
198 ;;
200 (defn relative-transform
201 "Returns AffineTransform: layer context -> AWT component."
202 []
203 (let [tr (.getTransform *graphics*)]
204 (.preConcatenate tr *inverse-initial-transform*)
205 tr))
207 (defn inverse-relative-transform
208 "Returns AffineTransform: AWT component -> layer context."
209 []
210 (let [tr (.getTransform *graphics*)]
211 (.invert tr) ; absolute -> layer
212 (.concatenate tr *initial-transform*) ; component -> absolute
213 tr))
215 (defn transform-point [^AffineTransform tr x y]
216 (let [p (Point2D$Double. x y)]
217 (.transform tr p p)
218 [(.x p) (.y p)]))
220 ;; (defn- clip
221 ;; "Intersect clipping area with the specified shape or bounds.
222 ;; Returns new clip (Shape or nil if empty)."
223 ;; ([x y w h]
224 ;; (clip (Rectangle2D$Double. x y w h)))
225 ;; ([shape]
226 ;; (let [a1 (Area. shape)
227 ;; a2 (if (instance? Area *clip*) *clip* (Area. *clip*))]
228 ;; (.transform a1 (relative-transform))
229 ;; (.intersect a1 a2)
230 ;; (if (.isEmpty a1)
231 ;; nil
232 ;; a1))))
234 ;; Use faster clipping calculation provided by Graphics2D.
235 (defn- clip
236 "Intersect clipping area with the specified bounds in current
237 transform coordinates. Returns new clip in the AWT component
238 coordinates (Shape or nil if empty)."
239 [x y w h]
240 (let [^Graphics2D clip-g (.create *graphics*)]
241 (doto clip-g
242 (.setClip x y w h)
243 (.setTransform *initial-transform*)
244 (.clip *clip*))
245 (try
246 (if (.isEmpty (.getClipBounds clip-g))
247 nil
248 (.getClip clip-g))
249 (finally
250 (.dispose clip-g)))))
252 (defn- ^Graphics2D apply-theme
253 "Set graphics' color and font to match theme.
254 Modifies and returns the first argument."
255 ([]
256 (apply-theme *graphics* *theme*))
257 ([^Graphics2D graphics theme]
258 (doto graphics
259 (.setColor (:fore-color theme))
260 (.setFont (:font theme)))))
262 (defn- ^Graphics2D create-graphics
263 ([]
264 (create-graphics 0 0 *width* *height*))
265 ([x y w h]
266 (apply-theme (.create *graphics* x y w h) *theme*)))
268 (defn with-bounds*
269 [x y w h f & args]
270 (when-let [clip (clip x y w h)]
271 (let [graphics (create-graphics x y w h)]
272 (try
273 (binding [*width* w
274 *height* h
275 *clip* clip
276 *graphics* graphics]
277 (apply f args))
278 (finally
279 (.dispose graphics))))))
281 (defmacro with-bounds
282 [x y w h & body]
283 `(with-bounds* ~x ~y ~w ~h (fn [] ~@body)))
285 (defmacro with-theme
286 [theme & body]
287 `(binding [*theme* (merge *theme* ~theme)]
288 ~@body))
290 (defmacro with-color
291 [color-or-keyword & body]
292 (let [color-form (if (keyword? color-or-keyword)
293 `(~color-or-keyword *theme*)
294 color-or-keyword)]
295 `(let [color# ~color-form
296 old-color# (.getColor *graphics*)]
297 (try
298 (.setColor *graphics* color#)
299 ~@body
300 (finally
301 (.setColor *graphics* old-color#))))))
303 ;; TODO: constructor for AffineTransform.
304 ;; (transform :scale 0.3 0.5
305 ;; :translate 5 10
306 ;; :rotate (/ Math/PI 2))
308 (defmacro with-transform [transform & body]
309 `(let [old-t# (.getTransform *graphics*)]
310 (try
311 (.transform *graphics* ~transform)
312 ~@body
313 (finally
314 (.setTransform *graphics* old-t#)))))
316 (defmacro with-rotate [theta ax ay & body]
317 `(let [transform# (AffineTransform/getRotateInstance ~theta ~ax ~ay)]
318 (with-transform transform# ~@body)))
320 (defn draw!
321 "Draws layer."
322 ([layer]
323 (let [graphics (create-graphics)]
324 (try
325 (binding [*graphics* graphics]
326 (render! layer))
327 (finally
328 (.dispose graphics)))))
329 ([layer x y]
330 (let [size (layer-size layer)]
331 (draw! layer x y (:width size) (:height size))))
332 ([layer x y width height]
333 (with-bounds* x y width height render! layer)))
335 (defn draw-anchored!
336 "Draws layer. Location is relative to the layer's anchor point for
337 the specified alignment."
338 ([layer h-align v-align x y]
339 (let [anchor (anchor layer h-align v-align)]
340 (draw! layer (- x (:x anchor)) (- y (:y anchor)))))
341 ([layer h-align v-align x y w h]
342 (let [anchor (anchor layer h-align v-align)]
343 (draw! layer (- x (:x anchor)) (- y (:y anchor)) w h))))
345 (defn draw-root!
346 "Draws the root layer."
347 ([layer graphics width height event-dispatcher]
348 (draw-root! layer graphics width height event-dispatcher nil))
349 ([layer ^Graphics2D graphics width height event-dispatcher target]
350 (binding [*root* layer
351 *target* target
352 *graphics* graphics
353 *font-context* (.getFontRenderContext graphics)
354 *initial-transform* (.getTransform graphics)
355 *inverse-initial-transform*
356 (-> graphics .getTransform .createInverse)
357 *event-dispatcher* event-dispatcher
358 *width* width
359 *height* height
360 *clip* (Rectangle2D$Double. 0 0 width height)
361 *time* (System/nanoTime)]
362 ;; (.setRenderingHint graphics
363 ;; RenderingHints/KEY_INTERPOLATION
364 ;; RenderingHints/VALUE_INTERPOLATION_BILINEAR)
365 ;; (.setRenderingHint graphics
366 ;; RenderingHints/KEY_ALPHA_INTERPOLATION
367 ;; RenderingHints/VALUE_ALPHA_INTERPOLATION_QUALITY)
368 ;; (.setRenderingHint graphics
369 ;; RenderingHints/KEY_ANTIALIASING
370 ;; RenderingHints/VALUE_ANTIALIAS_ON)
371 (apply-theme)
372 (let [tmp-watcher (Object.)]
373 ;; Keep current context observers until the rendering is
374 ;; complete. Some observers may be invoked twice if they
375 ;; appear in both groups until tmp-watcher is removed.
376 (replace-observers-watcher layer tmp-watcher)
377 (try
378 (render! layer)
379 (finally
380 (remove-observers tmp-watcher)
381 (commit event-dispatcher)))))))
383 (defn root-size
384 ([layer font-context]
385 (root-size layer font-context nil))
386 ([layer font-context target]
387 (binding [*root* layer
388 *target* target
389 *font-context* font-context]
390 (layer-size layer))))
392 ;;
393 ;; Event handling.
394 ;;
396 (defn with-handlers*
397 [handle handlers f & args]
398 (binding [*event-dispatcher* (create-dispatcher
399 *event-dispatcher* handle handlers)]
400 (apply f args)))
402 (defmacro with-handlers
403 "specs => (:event-id name & handler-body)*
405 Execute form with the specified event handlers."
406 [handle form & specs]
407 `(with-handlers* ~handle
408 ~(reduce (fn [m spec]
409 (assoc m (first spec)
410 `(fn [~(second spec)]
411 ~@(nnext spec)))) {}
412 specs)
413 (fn [] ~form)))
415 (defn picked? [handle]
416 (handle-picked? *event-dispatcher* handle))
418 (defn hovered? [handle]
419 (handle-hovered? *event-dispatcher* handle))
422 ;;
423 ;; EventDispatcher implementation
424 ;;
426 (def awt-events
427 {java.awt.event.MouseEvent/MOUSE_CLICKED :mouse-clicked
428 java.awt.event.MouseEvent/MOUSE_DRAGGED :mouse-dragged
429 java.awt.event.MouseEvent/MOUSE_ENTERED :mouse-entered
430 java.awt.event.MouseEvent/MOUSE_EXITED :mouse-exited
431 java.awt.event.MouseEvent/MOUSE_MOVED :mouse-moved
432 java.awt.event.MouseEvent/MOUSE_PRESSED :mouse-pressed
433 java.awt.event.MouseEvent/MOUSE_RELEASED :mouse-released})
435 (def dummy-event-dispatcher
436 (reify
437 EventDispatcher
438 (listen! [this component])
439 (create-dispatcher [this handle handlers] this)
440 (commit [this])
441 (handle-picked? [this handle])
442 (handle-hovered? [this handle])))
444 (defrecord DispatcherNode [handle handlers parent
445 ^Shape clip ^AffineTransform transform
446 bindings]
447 EventDispatcher
448 (listen! [this component]
449 (listen! parent component))
450 (create-dispatcher [this handle handlers]
451 (create-dispatcher parent handle handlers))
452 (commit [this]
453 (commit parent))
454 (handle-picked? [this handle]
455 (handle-picked? parent handle))
456 (handle-hovered? [this handle]
457 (handle-hovered? parent handle)))
459 (defn- make-node [handle handlers]
460 (DispatcherNode. handle handlers *event-dispatcher* *clip*
461 (inverse-relative-transform)
462 (get-thread-bindings)))
464 (defn- add-node [tree node]
465 (assoc-cons tree (:parent node) node))
467 (defn- under-cursor
468 "Returns a vector of child nodes under cursor."
469 [x y tree node]
470 (some #(if (.contains ^Shape (:clip %) x y)
471 (conj (vec (under-cursor x y tree %)) %))
472 (get tree node)))
474 (defn- remove-all [coll1 coll2 pred]
475 (filter #(not (some (partial pred %) coll2)) coll1))
477 (defn- translate-mouse-event [^java.awt.event.MouseEvent event
478 ^AffineTransform tr id]
479 (let [[x y] (transform-point tr (.getX event) (.getY event))]
480 (MouseEvent. id (.getWhen event) x y
481 (.getXOnScreen event) (.getYOnScreen event)
482 (.getButton event))))
484 (defn- translate-and-dispatch
485 ([nodes first-only ^java.awt.event.MouseEvent event]
486 (translate-and-dispatch nodes first-only
487 event (awt-events (.getID event))))
488 ([nodes first-only event id]
489 (if-let [node (first nodes)]
490 (if-let [handler (get (:handlers node) id)]
491 (do
492 (with-bindings* (:bindings node)
493 handler
494 (translate-mouse-event event (:transform node) id))
495 (if-not first-only
496 (recur (rest nodes) false event id)))
497 (recur (rest nodes) first-only event id)))))
499 (defn- dispatch-mouse-motion
500 "Dispatches mouse motion events."
501 [hovered-ref tree root ^java.awt.event.MouseEvent event]
502 (let [x (.getX event)
503 y (.getY event)
504 [hovered hovered2] (dosync
505 [@hovered-ref
506 (ref-set hovered-ref
507 (under-cursor x y tree root))])
508 pred #(= (:handle %1) (:handle %2))
509 exited (remove-all hovered hovered2 pred)
510 entered (remove-all hovered2 hovered pred)
511 moved (remove-all hovered2 entered pred)]
512 (translate-and-dispatch exited false event :mouse-exited)
513 (translate-and-dispatch entered false event :mouse-entered)
514 (translate-and-dispatch moved true event :mouse-moved)))
516 (defn- dispatch-mouse-button
517 [picked-ref hovered-ref ^java.awt.event.MouseEvent event]
518 (let [id (awt-events (.getID event))
519 nodes (case id
520 :mouse-pressed
521 (dosync
522 (ref-set picked-ref @hovered-ref))
523 :mouse-released
524 (dosync
525 (let [picked @picked-ref]
526 (ref-set picked-ref nil)
527 picked))
528 @hovered-ref)]
529 (translate-and-dispatch nodes true event id)))
531 (defn root-event-dispatcher []
532 (let [tree-r (ref {}) ; register
533 tree (ref {}) ; dispatch
534 hovered (ref '())
535 picked (ref '())]
536 (reify
537 EventDispatcher
538 (listen! [this component]
539 (doto component
540 (.addMouseListener this)
541 (.addMouseMotionListener this)))
542 (create-dispatcher [this handle handlers]
543 (let [node (make-node handle handlers)]
544 (dosync (alter tree-r add-node node))
545 node))
546 (commit [this]
547 (dosync (ref-set tree @tree-r)
548 (ref-set tree-r {})))
549 (handle-picked? [this handle]
550 (some #(= handle (:handle %)) @picked))
551 (handle-hovered? [this handle]
552 (some #(= handle (:handle %)) @hovered))
553 MouseListener
554 (mouseEntered [this event]
555 (dispatch-mouse-motion hovered @tree this event))
556 (mouseExited [this event]
557 (dispatch-mouse-motion hovered @tree this event))
558 (mouseClicked [this event]
559 (dispatch-mouse-button picked hovered event))
560 (mousePressed [this event]
561 (dispatch-mouse-button picked hovered event))
562 (mouseReleased [this event]
563 (dispatch-mouse-button picked hovered event))
564 MouseMotionListener
565 (mouseDragged [this event]
566 (translate-and-dispatch @picked true event))
567 (mouseMoved [this event]
568 (dispatch-mouse-motion hovered @tree this event)))))