view src/indyvon/core.clj @ 156:dc13cacf3a43

API changes (themed, hinted, add-handlers); formatting.
author Mikhail Kryshen <mikhail@kryshen.net>
date Wed, 16 Apr 2014 00:10:48 +0400
parents c3782e84486f
children 4fea68ec12f4
line source
1 ;;
2 ;; Copyright 2010-2014 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 indyvon.core
21 (:import
22 (java.awt Graphics2D RenderingHints Component Color Font Shape
23 Rectangle Cursor EventQueue)
24 (java.awt.geom AffineTransform Point2D$Double Rectangle2D$Double Area)
25 (java.awt.event MouseListener MouseMotionListener
26 MouseWheelListener MouseWheelEvent)
27 (java.awt.font FontRenderContext)
28 java.util.concurrent.ConcurrentMap
29 com.google.common.collect.MapMaker))
31 ;;
32 ;; View context
33 ;;
35 (def ^:dynamic ^Graphics2D *graphics*)
37 (def ^:dynamic ^FontRenderContext *font-context*
38 "FontRenderContext to use when Graphics2D is not available."
39 (FontRenderContext.
40 nil
41 RenderingHints/VALUE_TEXT_ANTIALIAS_DEFAULT
42 RenderingHints/VALUE_FRACTIONALMETRICS_DEFAULT))
44 (def ^:dynamic *width*
45 "Width of the rendering area.")
47 (def ^:dynamic *height*
48 "Height of the rendering area.")
50 (def ^:dynamic ^Shape *clip*)
52 (def ^:dynamic ^Shape *input-clip*
53 "Clipping area used for dispatching pointer events (intersected with
54 *clip*). If nil, *clip* will be used.")
56 (def ^:dynamic *time*
57 "Timestamp of the current frame (in nanoseconds).")
59 (def ^:dynamic *scene*
60 "Encloses state that should be retained between repaints.")
62 (def ^:dynamic *states*
63 "Transient scene states, a map.")
65 (def ^:dynamic *event-dispatcher*)
67 (def ^:dynamic ^AffineTransform *initial-transform*
68 "Initial transform associated with the graphics context.")
70 (def ^:dynamic ^AffineTransform *inverse-initial-transform*
71 "Inversion of the initial transform associated with the graphics
72 context.")
74 (defrecord Theme [fore-color back-color alt-back-color border-color
75 shadow-color font])
77 ;; REMIND: use system colors, see java.awt.SystemColor.
78 (defn default-theme []
79 (Theme. Color/BLACK
80 Color/WHITE
81 (Color. 0xDD 0xDD 0xDD)
82 (Color. 0 0 0xCC)
83 (Color. 0x44 0x44 0x44)
84 (Font. "Sans" Font/PLAIN 12)))
86 (def ^:dynamic *theme* (default-theme))
88 ;;
89 ;; Core protocols and types
90 ;;
92 (defprotocol View
93 "Basic UI element."
94 (render! [view]
95 "Draws the view in the current *graphics* context.")
96 (geometry [view]
97 "Returns the preferred Geometry for the view."))
99 (defprotocol Geometry
100 "Describes geometry of a View. Prefer using the available
101 implementations (Size, FixedGeometry and NestedGeometry) over
102 extending this protocol directly as it is likely to be changed in
103 the future versions."
104 (width [geom] [geom height])
105 (height [geom] [geom width])
106 (anchor-x [geom h-align width]
107 "Returns the x coordinate of the anchor point for the specified
108 horizontal alignment and width, h-align could be :left, :center
109 or :right.")
110 (anchor-y [geom v-align height]
111 "Returns the y coordinate of the anchor point for the specified
112 vertical alignment and height, v-align could be :top, :center
113 or :bottom."))
115 (defn- emit-align-xy [align size first center last]
116 `(case ~align
117 ~first 0
118 ~center (/ ~size 2)
119 ~last ~size))
121 ;; Define as macro to avoid unnecessary calculation of width or height.
122 (defmacro align-x
123 ([align inner outer]
124 `(align-x ~align (- ~outer ~inner)))
125 ([align width]
126 (emit-align-xy align width :left :center :right)))
128 (defmacro align-y
129 ([align inner outer]
130 `(align-y ~align (- ~outer ~inner)))
131 ([align height]
132 (emit-align-xy align height :top :center :bottom)))
134 (defrecord Size [width height]
135 Geometry
136 (width [_] width)
137 (width [_ _] width)
138 (height [_] height)
139 (height [_ _] height)
140 (anchor-x [_ h-align width]
141 (align-x h-align width))
142 (anchor-y [_ v-align height]
143 (align-y v-align height)))
145 (defrecord FixedGeometry [ax ay width height]
146 Geometry
147 (width [_] width)
148 (width [_ _] width)
149 (height [_] height)
150 (height [_ _] height)
151 (anchor-x [_ _ _] ax)
152 (anchor-y [_ _ _] ay))
154 (defrecord NestedGeometry [geometry top left bottom right]
155 Geometry
156 (width [_]
157 (+ left right (width geometry)))
158 (width [_ h]
159 (+ left right (width geometry (- h top bottom))))
160 (height [_]
161 (+ top bottom (height geometry)))
162 (height [_ w]
163 (+ top bottom (height geometry (- w left right))))
164 (anchor-x [_ h-align w]
165 (+ left (anchor-x geometry h-align (- w left right))))
166 (anchor-y [_ v-align h]
167 (+ top (anchor-y geometry v-align (- h top bottom)))))
169 (defrecord ScaledGeometry [geometry sx sy]
170 Geometry
171 (width [_]
172 (* sx (width geometry)))
173 (width [_ h]
174 (* sx (width geometry (/ h sy))))
175 (height [_]
176 (* sy (height geometry)))
177 (height [_ w]
178 (* sy (height geometry (/ w sx))))
179 (anchor-x [_ h-align w]
180 (* sx (anchor-x geometry h-align (/ w sx))))
181 (anchor-y [_ v-align h]
182 (* sy (anchor-y geometry v-align (/ h sy)))))
184 ;; (defn ^:private to-integer
185 ;; ^long [align x]
186 ;; (if (integer? x)
187 ;; x
188 ;; (let [x (double x)]
189 ;; (Math/round
190 ;; (case align
191 ;; (:top :left) (Math/floor x)
192 ;; :center x
193 ;; (:bottom :right) (Math/ceil x))))))
195 ;; (defrecord IntegerGeometry [geometry]
196 ;; Geometry
197 ;; (width [_]
198 ;; (to-integer :right (width geometry)))
199 ;; (width [_ h]
200 ;; (to-integer :right (width geometry h)))
201 ;; (height [_]
202 ;; (to-integer :bottom (height geometry)))
203 ;; (height [_ w]
204 ;; (to-integer :bottom (height geometry w)))
205 ;; (anchor-x [_ h-align w]
206 ;; (to-integer h-align (anchor-x geometry h-align w)))
207 ;; (anchor-y [_ v-align h]
208 ;; (to-integer v-align (anchor-y geometry v-align h))))
210 ;; TODO: modifiers
211 (defrecord MouseEvent [id when x y x-on-screen y-on-screen button
212 wheel-rotation transform component])
214 ;; TODO: KeyEvent
216 (defprotocol EventDispatcher
217 (listen! [this component]
218 "Listen for events on the specified AWT Component.")
219 (create-dispatcher [this handle handlers]
220 "Returns new event dispatcher associated with the specified event
221 handlers (an event-id -> handler-fn map). Handle is used to match
222 the contexts between commits.")
223 (commit [this]
224 "Apply the registered handlers for event processing.")
225 (handle-picked? [this handle]
226 "Returns true if the specified handle received the :mouse-pressed
227 event and have not yet received :moused-released.")
228 (handle-hovered? [this handle]
229 "Returns true if the specified handle received the :mouse-entered
230 event and have not yet received :mouse-exited."))
232 (defn- assoc-cons [m key val]
233 (->> (get m key) (cons val) (assoc m key)))
235 ;;
236 ;; Observers
237 ;; The mechanism used by views to request repaints
238 ;;
240 (def ^ConcurrentMap observers
241 (-> (MapMaker.) (.weakKeys) (.makeMap)))
243 (defn- cm-replace!
244 "Wrap ConcurrentMap replace method to treat nil value as absent
245 mapping. Use with maps that does not support nil values."
246 [^ConcurrentMap cmap key old new]
247 (if (nil? old)
248 (nil? (.putIfAbsent cmap key new))
249 (.replace cmap key old new)))
251 (defn- cm-swap!
252 "Atomically swaps the value associated with key in ConcurrentMap
253 to be (apply f current-value args). Returns the new value."
254 [^ConcurrentMap cmap key f & args]
255 (loop []
256 (let [old (.get cmap key)
257 new (apply f old args)]
258 (if (cm-replace! cmap key old new)
259 new
260 (recur)))))
262 (defn add-observer
263 "Add observer fn for the target. Watcher identifies the group of
264 observers and could be used to remove the group. Watcher is weakly
265 referenced, all associated observers will be removed when the
266 wathcer is removed by gc. The observer fn will be called with
267 watcher and target arguments and any additional arguments specified
268 in update call."
269 [watcher target f]
270 (cm-swap! observers watcher assoc-cons target f)
271 nil)
273 (defn remove-observers
274 "Remove group of observers associated with the specified watcher."
275 [watcher]
276 (.remove observers watcher)
277 nil)
279 (defn- replace-observers-watcher
280 [old-watcher new-watcher]
281 (if-let [old (.remove observers old-watcher)]
282 (.put observers new-watcher old))
283 nil)
285 (defn update
286 "Notify observers."
287 [target & args]
288 (doseq [entry observers
289 f (get (val entry) target)]
290 (apply f (key entry) target args)))
292 (defn add-context-observer
293 "Observer registered with this function will be automatically
294 removed after the next repaint is complete."
295 [target f]
296 (add-observer *scene* target f))
298 (defn repaint-on-update
299 "Trigger repaint of the current scene when the target updates."
300 [target]
301 (let [scene *scene*]
302 (if-not (identical? scene target)
303 (add-observer scene target (fn [w _] (update w))))))
305 (defn repaint
306 "Requests repaint of the current scene. If handle and state are
307 specified, the handle will be associated with the state in the
308 *states* map for the next paint iteration."
309 ([]
310 (update *scene*))
311 ([handle state]
312 (let [scene *scene*]
313 (swap! (:next-state scene) assoc handle state)
314 (update scene))))
316 ;;
317 ;; Rendering
318 ;;
320 (defn ^FontRenderContext font-context
321 "Returns FontRenderContext for the current view context."
322 []
323 (if (bound? (var *graphics*))
324 (.getFontRenderContext *graphics*)
325 *font-context*))
327 (defn ^AffineTransform relative-transform
328 "Returns AffineTransform: view context -> AWT component."
329 []
330 (let [tr (.getTransform *graphics*)]
331 (.preConcatenate tr *inverse-initial-transform*)
332 tr))
334 (defn ^AffineTransform inverse-relative-transform
335 "Returns AffineTransform: AWT component -> view context."
336 []
337 (let [tr (.getTransform *graphics*)]
338 (.invert tr) ; absolute -> view
339 (.concatenate tr *initial-transform*) ; component -> absolute
340 tr))
342 (defn transform-point [^AffineTransform tr ^double x ^double y]
343 (let [p (Point2D$Double. x y)]
344 (.transform tr p p)
345 [(.x p) (.y p)]))
347 (defn inverse-transform-point [^AffineTransform tr ^double x ^double y]
348 (let [p (Point2D$Double. x y)]
349 (.inverseTransform tr p p)
350 [(.x p) (.y p)]))
352 ;; (defn- clip
353 ;; "Intersect clipping area with the specified shape or bounds.
354 ;; Returns new clip (Shape or nil if empty)."
355 ;; ([x y w h]
356 ;; (clip (Rectangle2D$Double. x y w h)))
357 ;; ([shape]
358 ;; (let [a1 (Area. shape)
359 ;; a2 (if (instance? Area *clip*) *clip* (Area. *clip*))]
360 ;; (.transform a1 (relative-transform))
361 ;; (.intersect a1 a2)
362 ;; (if (.isEmpty a1)
363 ;; nil
364 ;; a1))))
366 ;; Use faster clipping calculation provided by Graphics2D.
367 (defn- clip
368 "Intersect clipping area with the specified Shape in current
369 transform coordinates. Returns new clip in the AWT component
370 coordinates (Shape or nil if empty)."
371 [^Shape shape]
372 (let [^Graphics2D clip-g (.create *graphics*)]
373 (try
374 (doto clip-g
375 (.setClip shape)
376 (.setTransform *initial-transform*)
377 (.clip *clip*))
378 (if (.isEmpty (.getClipBounds clip-g))
379 nil
380 (.getClip clip-g))
381 (finally
382 (.dispose clip-g)))))
384 (defn- ^Graphics2D apply-theme
385 "Set graphics' color and font to match theme.
386 Modifies and returns the first argument."
387 ([]
388 (apply-theme *graphics* *theme*))
389 ([^Graphics2D graphics theme]
390 (doto graphics
391 (.setColor (:fore-color theme))
392 (.setFont (:font theme)))))
394 (defn- ^Graphics2D create-graphics
395 ([]
396 (apply-theme (.create *graphics*) *theme*))
397 ([^long x ^long y ^long w ^long h]
398 (apply-theme (.create *graphics* x y w h) *theme*)))
400 (defn- with-bounds-noclip*
401 [x y w h f & args]
402 (let [graphics (create-graphics)]
403 (try
404 (.translate graphics (double x) (double y))
405 (binding [*width* w
406 *height* h
407 *input-clip* (Rectangle2D$Double. 0.0 0.0 w h)
408 *graphics* graphics]
409 (apply f args))
410 (finally
411 (.dispose graphics)))))
413 (defn with-bounds*
414 [x y w h f & args]
415 (let [x (double x)
416 y (double y)
417 bounds (Rectangle2D$Double. x y w h)]
418 (when-let [clip (clip bounds)]
419 (let [^Graphics2D graphics (create-graphics)]
420 (try
421 (.clip graphics bounds)
422 (.translate graphics x y)
423 (binding [*width* w
424 *height* h
425 *clip* clip
426 *input-clip* nil
427 *graphics* graphics]
428 (apply f args))
429 (finally
430 (.dispose graphics)))))))
432 (defmacro with-bounds
433 [x y w h & body]
434 `(with-bounds* ~x ~y ~w ~h (fn [] ~@body)))
436 (defmacro with-theme
437 [theme & body]
438 `(binding [*theme* (merge *theme* ~theme)]
439 ~@body))
441 (defn with-theme* [theme f & args]
442 (with-theme theme
443 (apply f args)))
445 (defmacro with-color [color-or-key & body]
446 `(let [color# ~color-or-key
447 color# (get *theme* color# color#)
448 g# *graphics*
449 old-color# (.getColor g#)]
450 (try
451 (.setColor g# color#)
452 ~@body
453 (finally
454 (.setColor g# old-color#)))))
456 (defmacro with-stroke [stroke & body]
457 `(let [g# *graphics*
458 old-stroke# (.getStroke g#)]
459 (try
460 (.setStroke g# ~stroke)
461 ~@body
462 (finally
463 (.setStroke g# old-stroke#)))))
465 (defmacro with-hints
466 [hints & body]
467 `(let [h# ~hints
468 g# *graphics*
469 old# (.getRenderingHints g#)]
470 (try
471 (.addRenderingHints g# h#)
472 ~@body
473 (finally
474 (.setRenderingHints g# old#)))))
476 (defn with-hints* [hints f & args]
477 (with-hints hints
478 (apply f args)))
480 ;; TODO: constructor for AffineTransform.
481 ;; (transform :scale 0.3 0.5
482 ;; :translate 5 10
483 ;; :rotate (/ Math/PI 2))
485 (defmacro with-transform [transform & body]
486 `(let [g# *graphics*
487 old-t# (.getTransform g#)]
488 (try
489 (.transform g# ~transform)
490 ~@body
491 (finally
492 (.setTransform g# old-t#)))))
494 (defmacro with-rotate [theta ax ay & body]
495 `(let [transform# (AffineTransform/getRotateInstance ~theta ~ax ~ay)]
496 (with-transform transform# ~@body)))
498 (defmacro with-translate [x y & body]
499 `(let [x# ~x
500 y# ~y
501 g# *graphics*]
502 (try
503 (.translate g# x# y#)
504 ~@body
505 (finally
506 (.translate g# (- x#) (- y#))))))
508 (defn draw!
509 "Draws the View."
510 ([view]
511 (let [graphics (create-graphics)]
512 (try
513 (binding [*graphics* graphics]
514 (render! view))
515 (finally
516 (.dispose graphics)))))
517 ([view x y]
518 (draw! view x y true))
519 ([view x y clip?]
520 (let [geom (geometry view)]
521 (draw! view x y (width geom) (height geom) clip?)))
522 ([view x y width height]
523 (draw! view x y width height true))
524 ([view x y width height clip?]
525 (if clip?
526 (with-bounds* x y width height render! view)
527 (with-bounds-noclip* x y width height render! view))))
529 (defn draw-aligned!
530 "Draws the View. Location is relative to the view's anchor point
531 for the specified alignment."
532 ([view h-align v-align x y]
533 (let [geom (geometry view)
534 w (width geom)
535 h (height geom)]
536 (draw! view
537 (- x (anchor-x geom h-align w))
538 (- y (anchor-y geom v-align h))
539 w h)))
540 ([view h-align v-align x y w h]
541 (let [geom (geometry view)]
542 (draw! view
543 (- x (anchor-x geom h-align w))
544 (- y (anchor-y geom v-align h))
545 w h))))
547 ;;
548 ;; Event handling.
549 ;;
551 (defn with-handlers*
552 [handle handlers f & args]
553 (binding [*event-dispatcher* (create-dispatcher
554 *event-dispatcher* handle handlers)]
555 (apply f args)))
557 (defmacro with-handlers
558 "specs => (:event-id name & handler-body)*
560 Execute form with the specified event handlers."
561 [handle form & specs]
562 `(with-handlers* ~handle
563 ~(reduce (fn [m spec]
564 (assoc m (first spec)
565 `(fn [~(second spec)]
566 ~@(nnext spec)))) {}
567 specs)
568 (fn [] ~form)))
570 (defn picked? [handle]
571 (handle-picked? *event-dispatcher* handle))
573 (defn hovered? [handle]
574 (handle-hovered? *event-dispatcher* handle))
576 ;;
577 ;; EventDispatcher implementation
578 ;;
580 (def awt-events
581 {java.awt.event.MouseEvent/MOUSE_CLICKED :mouse-clicked
582 java.awt.event.MouseEvent/MOUSE_DRAGGED :mouse-dragged
583 java.awt.event.MouseEvent/MOUSE_ENTERED :mouse-entered
584 java.awt.event.MouseEvent/MOUSE_EXITED :mouse-exited
585 java.awt.event.MouseEvent/MOUSE_MOVED :mouse-moved
586 java.awt.event.MouseEvent/MOUSE_PRESSED :mouse-pressed
587 java.awt.event.MouseEvent/MOUSE_RELEASED :mouse-released
588 java.awt.event.MouseEvent/MOUSE_WHEEL :mouse-wheel})
590 (def dummy-event-dispatcher
591 (reify EventDispatcher
592 (listen! [_ _])
593 (create-dispatcher [this _ _] this)
594 (commit [_])
595 (handle-picked? [_ _])
596 (handle-hovered? [_ _])))
598 ;; Not using defrecord to avoid unacceptable overhead of recursive
599 ;; hash code calculation.
600 (deftype DispatcherNode [handle handlers parent
601 ^Shape clip ^AffineTransform transform
602 bindings]
603 EventDispatcher
604 (listen! [this component]
605 (listen! parent component))
606 (create-dispatcher [this handle handlers]
607 (create-dispatcher parent handle handlers))
608 (commit [this]
609 (commit parent))
610 (handle-picked? [this handle]
611 (handle-picked? parent handle))
612 (handle-hovered? [this handle]
613 (handle-hovered? parent handle)))
615 (defn- make-node [handle handlers]
616 (let [clip (if *input-clip*
617 (clip *input-clip*)
618 *clip*)
619 bindings (-> (get-thread-bindings)
620 (dissoc (var *graphics*))
621 (assoc (var *font-context*) (font-context)))]
622 (DispatcherNode. handle handlers *event-dispatcher* clip
623 (relative-transform)
624 bindings)))
626 (defn- add-node [tree ^DispatcherNode node]
627 (assoc-cons tree (.parent node) node))
629 (defn- nodes [tree]
630 (apply concat (vals tree)))
632 (defn- under-cursor
633 "Returns a vector of child nodes under cursor."
634 [node tree ^long x ^long y]
635 (some (fn [^DispatcherNode n]
636 (if (and (.clip n) (.contains ^Shape (.clip n) x y))
637 (conj (vec (under-cursor n tree x y)) n)))
638 (get tree node)))
640 (defn- translate-mouse-event [^java.awt.event.MouseEvent event
641 ^AffineTransform tr id]
642 (let [[x y] (inverse-transform-point tr (.getX event) (.getY event))
643 rotation (if (instance? MouseWheelEvent event)
644 (.getWheelRotation ^MouseWheelEvent event)
645 nil)]
646 (->MouseEvent id (.getWhen event) x y
647 (.getXOnScreen event) (.getYOnScreen event)
648 (.getButton event)
649 rotation
650 tr
651 (.getComponent event))))
653 (defn- translate-and-dispatch
654 ([nodes first-only ^java.awt.event.MouseEvent event]
655 (translate-and-dispatch nodes first-only
656 event (awt-events (.getID event))))
657 ([nodes first-only event id]
658 (if-let [^DispatcherNode node (first nodes)]
659 (let [handlers (.handlers node)
660 handler (get handlers id)]
661 (if handler
662 (do
663 (with-bindings* (.bindings node)
664 handler
665 (translate-mouse-event event (.transform node) id))
666 (when-not first-only
667 (recur (rest nodes) false event id)))
668 (when-not (and (= id :mouse-dragged)
669 (or (contains? handlers :mouse-pressed)
670 (contains? handlers :mouse-released)))
671 (recur (rest nodes) first-only event id)))))))
673 (defn- process-mouse-event
674 [dispatcher ^java.awt.event.MouseEvent source-event]
675 (let [{active-ref :active
676 hovered-ref :hovered
677 picked-ref :picked
678 last-ref :last-motion
679 tree-ref :tree} dispatcher
680 pressed (and source-event
681 (== (.getID source-event)
682 java.awt.event.MouseEvent/MOUSE_PRESSED))
683 released (and source-event
684 (== (.getID source-event)
685 java.awt.event.MouseEvent/MOUSE_RELEASED))
686 ^java.awt.event.MouseEvent last-event @last-ref
687 ^java.awt.event.MouseEvent event (or source-event last-event)]
688 (when event
689 (let [x (.getX event)
690 y (.getY event)
691 active @active-ref
692 active (if (and active
693 source-event
694 (== (.getX last-event) x)
695 (== (.getY last-event) y))
696 active
697 (ref-set active-ref
698 (under-cursor dispatcher @tree-ref x y)))
699 acted (cond
700 pressed (ref-set picked-ref active)
701 released (let [picked @picked-ref]
702 (ref-set picked-ref nil)
703 picked)
704 :else active)
705 picked (seq @picked-ref)
706 pred #(= (.handle ^DispatcherNode %1) (.handle ^DispatcherNode %2))
707 hovered (if picked
708 (filter #(some (partial pred %) picked) active)
709 active)
710 remove-all (fn [c1 c2]
711 (filter #(not (some (partial pred %) c2)) c1))
712 old-hovered @hovered-ref
713 exited (remove-all old-hovered hovered)
714 entered (remove-all hovered old-hovered)
715 moved (or picked (remove-all hovered entered))]
716 (ref-set hovered-ref hovered)
717 (ref-set last-ref event)
718 [exited entered moved acted event]))))
720 (defn- dispatch-mouse-event
721 [dispatcher source-event button?]
722 (when-let [[exited
723 entered
724 moved
725 acted
726 event] (dosync (process-mouse-event dispatcher source-event))]
727 (when button?
728 (translate-and-dispatch acted true event))
729 (translate-and-dispatch exited false event :mouse-exited)
730 (translate-and-dispatch entered false event :mouse-entered)
731 (when-not button?
732 (translate-and-dispatch moved true source-event))))
734 (defrecord RootEventDispatcher [tree-r ;; register
735 tree ;; dispatch
736 active ;; nodes under cursor
737 hovered ;; mouse entered
738 picked ;; mouse pressed
739 last-motion]
740 EventDispatcher
741 (listen! [dispatcher component]
742 (doto ^Component component
743 (.addMouseListener dispatcher)
744 (.addMouseWheelListener dispatcher)
745 (.addMouseMotionListener dispatcher)))
746 (create-dispatcher [dispatcher handle handlers]
747 (let [node (make-node handle handlers)]
748 (dosync (alter tree-r add-node node))
749 node))
750 (commit [dispatcher]
751 (let [[exited
752 entered
753 _ _
754 event] (dosync
755 ;; TODO: retain contexts that do
756 ;; not intersect graphics
757 ;; clipping area in tree.
758 (ref-set tree @tree-r)
759 (ref-set tree-r {})
760 (process-mouse-event dispatcher nil))]
761 ;; Send mouse entered and exited events if necessary due to
762 ;; updated layout.
763 (translate-and-dispatch exited false event :mouse-exited)
764 (translate-and-dispatch entered false event :mouse-entered)))
765 (handle-picked? [dispatcher handle]
766 (some #(= handle (.handle ^DispatcherNode %)) @picked))
767 (handle-hovered? [dispatcher handle]
768 (some #(= handle (.handle ^DispatcherNode %)) @hovered))
769 MouseListener
770 (mouseEntered [dispatcher event]
771 (dispatch-mouse-event dispatcher event false))
772 (mouseExited [dispatcher event]
773 (dispatch-mouse-event dispatcher event false))
774 (mouseClicked [dispatcher event]
775 (dispatch-mouse-event dispatcher event true))
776 (mousePressed [dispatcher event]
777 (dispatch-mouse-event dispatcher event true))
778 (mouseReleased [dispatcher event]
779 (dispatch-mouse-event dispatcher event true))
780 MouseWheelListener
781 (mouseWheelMoved [dispatcher event]
782 (dispatch-mouse-event dispatcher event true))
783 MouseMotionListener
784 (mouseDragged [dispatcher event]
785 (dispatch-mouse-event dispatcher event false))
786 (mouseMoved [dispatcher event]
787 (dispatch-mouse-event dispatcher event false)))
789 (defn root-event-dispatcher []
790 (->RootEventDispatcher
791 (ref {}) (ref {}) ;; trees
792 (ref nil) (ref nil) (ref nil) ;; node states
793 (ref nil))) ;; last event
795 ;;
796 ;; Scene
797 ;;
799 (defrecord Scene [view
800 event-dispatcher
801 component
802 rendering-hints
803 next-state])
805 ;; Define rendering hints that affect font metrics to make sure that
806 ;; Graphics and Scene FontRenderContexts are consistent.
807 (def ^:private default-rendering-hints
808 {RenderingHints/KEY_TEXT_ANTIALIASING
809 RenderingHints/VALUE_TEXT_ANTIALIAS_DEFAULT,
810 RenderingHints/KEY_FRACTIONALMETRICS
811 RenderingHints/VALUE_FRACTIONALMETRICS_DEFAULT})
813 (defn make-scene
814 ([view]
815 (make-scene view dummy-event-dispatcher nil))
816 ([view event-dispatcher]
817 (make-scene view event-dispatcher nil))
818 ([view event-dispatcher ^Component component]
819 (make-scene view event-dispatcher component nil))
820 ([view event-dispatcher ^Component component hints]
821 (let [hints (merge default-rendering-hints hints)]
822 (->Scene view
823 event-dispatcher
824 component
825 hints
826 (atom nil)))))
828 (defn- get-and-set!
829 "Atomically sets the value of atom to newval and returns the old
830 value."
831 [atom newval]
832 (loop [v @atom]
833 (if (compare-and-set! atom v newval)
834 v
835 (recur @atom))))
837 (defn draw-scene!
838 [scene ^Graphics2D graphics width height]
839 (.addRenderingHints graphics (:rendering-hints scene))
840 (binding [*states* (get-and-set! (:next-state scene) nil)
841 *scene* scene
842 *graphics* graphics
843 *initial-transform* (.getTransform graphics)
844 *inverse-initial-transform* (-> graphics
845 .getTransform
846 .createInverse)
847 *event-dispatcher* (:event-dispatcher scene)
848 *width* width
849 *height* height
850 *clip* (Rectangle2D$Double. 0.0 0.0 width height)
851 *input-clip* nil
852 *time* (System/nanoTime)]
853 (apply-theme)
854 (let [tmp-watcher (Object.)]
855 ;; Keep current context observers until the rendering is
856 ;; complete. Some observers may be invoked twice if they
857 ;; appear in both groups until tmp-watcher is removed.
858 (replace-observers-watcher scene tmp-watcher)
859 (try
860 (render! (:view scene))
861 (finally
862 (remove-observers tmp-watcher)
863 (commit (:event-dispatcher scene)))))))
865 (defn- scene-font-context [scene]
866 (let [hints (:rendering-hints scene)
867 ^Component c (:component scene)
868 t (if c (->> c
869 .getFont
870 (.getFontMetrics c)
871 .getFontRenderContext
872 .getTransform))]
873 (FontRenderContext.
874 t
875 (get hints RenderingHints/KEY_TEXT_ANTIALIASING)
876 (get hints RenderingHints/KEY_FRACTIONALMETRICS))))
878 (defn scene-geometry [scene]
879 (binding [*scene* scene
880 *font-context* (scene-font-context scene)]
881 (geometry (:view scene))))
883 (defn set-cursor! [^Cursor cursor]
884 (when-let [^Component component (:component *scene*)]
885 (EventQueue/invokeLater #(.setCursor component cursor))))