view src/indyvon/core.clj @ 157:4fea68ec12f4

Applying theme correctly.
author Mikhail Kryshen <mikhail@kryshen.net>
date Wed, 12 Nov 2014 15:44:17 +0300
parents dc13cacf3a43
children e0063c1d0f7f
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 (.setBackground (:back-color theme))
393 (.setFont (:font theme)))))
395 (defn- ^Graphics2D create-graphics
396 ([]
397 (apply-theme (.create *graphics*) *theme*))
398 ([^long x ^long y ^long w ^long h]
399 (apply-theme (.create *graphics* x y w h) *theme*)))
401 (defn- with-bounds-noclip*
402 [x y w h f & args]
403 (let [graphics (create-graphics)]
404 (try
405 (.translate graphics (double x) (double y))
406 (binding [*width* w
407 *height* h
408 *input-clip* (Rectangle2D$Double. 0.0 0.0 w h)
409 *graphics* graphics]
410 (apply f args))
411 (finally
412 (.dispose graphics)))))
414 (defn with-bounds*
415 [x y w h f & args]
416 (let [x (double x)
417 y (double y)
418 bounds (Rectangle2D$Double. x y w h)]
419 (when-let [clip (clip bounds)]
420 (let [^Graphics2D graphics (create-graphics)]
421 (try
422 (.clip graphics bounds)
423 (.translate graphics x y)
424 (binding [*width* w
425 *height* h
426 *clip* clip
427 *input-clip* nil
428 *graphics* graphics]
429 (apply f args))
430 (finally
431 (.dispose graphics)))))))
433 (defmacro with-bounds
434 [x y w h & body]
435 `(with-bounds* ~x ~y ~w ~h (fn [] ~@body)))
437 (defmacro with-theme
438 [theme & body]
439 `(binding [*theme* (merge *theme* ~theme)]
440 ~@body))
442 (defn with-theme* [theme f & args]
443 (with-theme theme
444 (apply f args)))
446 (defmacro with-color [color-or-key & body]
447 `(let [color# ~color-or-key
448 color# (get *theme* color# color#)
449 g# *graphics*
450 old-color# (.getColor g#)]
451 (try
452 (.setColor g# color#)
453 ~@body
454 (finally
455 (.setColor g# old-color#)))))
457 (defmacro with-stroke [stroke & body]
458 `(let [g# *graphics*
459 old-stroke# (.getStroke g#)]
460 (try
461 (.setStroke g# ~stroke)
462 ~@body
463 (finally
464 (.setStroke g# old-stroke#)))))
466 (defmacro with-hints
467 [hints & body]
468 `(let [h# ~hints
469 g# *graphics*
470 old# (.getRenderingHints g#)]
471 (try
472 (.addRenderingHints g# h#)
473 ~@body
474 (finally
475 (.setRenderingHints g# old#)))))
477 (defn with-hints* [hints f & args]
478 (with-hints hints
479 (apply f args)))
481 ;; TODO: constructor for AffineTransform.
482 ;; (transform :scale 0.3 0.5
483 ;; :translate 5 10
484 ;; :rotate (/ Math/PI 2))
486 (defmacro with-transform [transform & body]
487 `(let [g# *graphics*
488 old-t# (.getTransform g#)]
489 (try
490 (.transform g# ~transform)
491 ~@body
492 (finally
493 (.setTransform g# old-t#)))))
495 (defmacro with-rotate [theta ax ay & body]
496 `(let [transform# (AffineTransform/getRotateInstance ~theta ~ax ~ay)]
497 (with-transform transform# ~@body)))
499 (defmacro with-translate [x y & body]
500 `(let [x# ~x
501 y# ~y
502 g# *graphics*]
503 (try
504 (.translate g# x# y#)
505 ~@body
506 (finally
507 (.translate g# (- x#) (- y#))))))
509 (defn draw!
510 "Draws the View."
511 ([view]
512 (let [graphics (create-graphics)]
513 (try
514 (binding [*graphics* graphics]
515 (render! view))
516 (finally
517 (.dispose graphics)))))
518 ([view x y]
519 (draw! view x y true))
520 ([view x y clip?]
521 (let [geom (geometry view)]
522 (draw! view x y (width geom) (height geom) clip?)))
523 ([view x y width height]
524 (draw! view x y width height true))
525 ([view x y width height clip?]
526 (if clip?
527 (with-bounds* x y width height render! view)
528 (with-bounds-noclip* x y width height render! view))))
530 (defn draw-aligned!
531 "Draws the View. Location is relative to the view's anchor point
532 for the specified alignment."
533 ([view h-align v-align x y]
534 (let [geom (geometry view)
535 w (width geom)
536 h (height geom)]
537 (draw! view
538 (- x (anchor-x geom h-align w))
539 (- y (anchor-y geom v-align h))
540 w h)))
541 ([view h-align v-align x y w h]
542 (let [geom (geometry view)]
543 (draw! view
544 (- x (anchor-x geom h-align w))
545 (- y (anchor-y geom v-align h))
546 w h))))
548 ;;
549 ;; Event handling.
550 ;;
552 (defn with-handlers*
553 [handle handlers f & args]
554 (binding [*event-dispatcher* (create-dispatcher
555 *event-dispatcher* handle handlers)]
556 (apply f args)))
558 (defmacro with-handlers
559 "specs => (:event-id name & handler-body)*
561 Execute form with the specified event handlers."
562 [handle form & specs]
563 `(with-handlers* ~handle
564 ~(reduce (fn [m spec]
565 (assoc m (first spec)
566 `(fn [~(second spec)]
567 ~@(nnext spec)))) {}
568 specs)
569 (fn [] ~form)))
571 (defn picked? [handle]
572 (handle-picked? *event-dispatcher* handle))
574 (defn hovered? [handle]
575 (handle-hovered? *event-dispatcher* handle))
577 ;;
578 ;; EventDispatcher implementation
579 ;;
581 (def awt-events
582 {java.awt.event.MouseEvent/MOUSE_CLICKED :mouse-clicked
583 java.awt.event.MouseEvent/MOUSE_DRAGGED :mouse-dragged
584 java.awt.event.MouseEvent/MOUSE_ENTERED :mouse-entered
585 java.awt.event.MouseEvent/MOUSE_EXITED :mouse-exited
586 java.awt.event.MouseEvent/MOUSE_MOVED :mouse-moved
587 java.awt.event.MouseEvent/MOUSE_PRESSED :mouse-pressed
588 java.awt.event.MouseEvent/MOUSE_RELEASED :mouse-released
589 java.awt.event.MouseEvent/MOUSE_WHEEL :mouse-wheel})
591 (def dummy-event-dispatcher
592 (reify EventDispatcher
593 (listen! [_ _])
594 (create-dispatcher [this _ _] this)
595 (commit [_])
596 (handle-picked? [_ _])
597 (handle-hovered? [_ _])))
599 ;; Not using defrecord to avoid unacceptable overhead of recursive
600 ;; hash code calculation.
601 (deftype DispatcherNode [handle handlers parent
602 ^Shape clip ^AffineTransform transform
603 bindings]
604 EventDispatcher
605 (listen! [this component]
606 (listen! parent component))
607 (create-dispatcher [this handle handlers]
608 (create-dispatcher parent handle handlers))
609 (commit [this]
610 (commit parent))
611 (handle-picked? [this handle]
612 (handle-picked? parent handle))
613 (handle-hovered? [this handle]
614 (handle-hovered? parent handle)))
616 (defn- make-node [handle handlers]
617 (let [clip (if *input-clip*
618 (clip *input-clip*)
619 *clip*)
620 bindings (-> (get-thread-bindings)
621 (dissoc (var *graphics*))
622 (assoc (var *font-context*) (font-context)))]
623 (DispatcherNode. handle handlers *event-dispatcher* clip
624 (relative-transform)
625 bindings)))
627 (defn- add-node [tree ^DispatcherNode node]
628 (assoc-cons tree (.parent node) node))
630 (defn- nodes [tree]
631 (apply concat (vals tree)))
633 (defn- under-cursor
634 "Returns a vector of child nodes under cursor."
635 [node tree ^long x ^long y]
636 (some (fn [^DispatcherNode n]
637 (if (and (.clip n) (.contains ^Shape (.clip n) x y))
638 (conj (vec (under-cursor n tree x y)) n)))
639 (get tree node)))
641 (defn- translate-mouse-event [^java.awt.event.MouseEvent event
642 ^AffineTransform tr id]
643 (let [[x y] (inverse-transform-point tr (.getX event) (.getY event))
644 rotation (if (instance? MouseWheelEvent event)
645 (.getWheelRotation ^MouseWheelEvent event)
646 nil)]
647 (->MouseEvent id (.getWhen event) x y
648 (.getXOnScreen event) (.getYOnScreen event)
649 (.getButton event)
650 rotation
651 tr
652 (.getComponent event))))
654 (defn- translate-and-dispatch
655 ([nodes first-only ^java.awt.event.MouseEvent event]
656 (translate-and-dispatch nodes first-only
657 event (awt-events (.getID event))))
658 ([nodes first-only event id]
659 (if-let [^DispatcherNode node (first nodes)]
660 (let [handlers (.handlers node)
661 handler (get handlers id)]
662 (if handler
663 (do
664 (with-bindings* (.bindings node)
665 handler
666 (translate-mouse-event event (.transform node) id))
667 (when-not first-only
668 (recur (rest nodes) false event id)))
669 (when-not (and (= id :mouse-dragged)
670 (or (contains? handlers :mouse-pressed)
671 (contains? handlers :mouse-released)))
672 (recur (rest nodes) first-only event id)))))))
674 (defn- process-mouse-event
675 [dispatcher ^java.awt.event.MouseEvent source-event]
676 (let [{active-ref :active
677 hovered-ref :hovered
678 picked-ref :picked
679 last-ref :last-motion
680 tree-ref :tree} dispatcher
681 pressed (and source-event
682 (== (.getID source-event)
683 java.awt.event.MouseEvent/MOUSE_PRESSED))
684 released (and source-event
685 (== (.getID source-event)
686 java.awt.event.MouseEvent/MOUSE_RELEASED))
687 ^java.awt.event.MouseEvent last-event @last-ref
688 ^java.awt.event.MouseEvent event (or source-event last-event)]
689 (when event
690 (let [x (.getX event)
691 y (.getY event)
692 active @active-ref
693 active (if (and active
694 source-event
695 (== (.getX last-event) x)
696 (== (.getY last-event) y))
697 active
698 (ref-set active-ref
699 (under-cursor dispatcher @tree-ref x y)))
700 acted (cond
701 pressed (ref-set picked-ref active)
702 released (let [picked @picked-ref]
703 (ref-set picked-ref nil)
704 picked)
705 :else active)
706 picked (seq @picked-ref)
707 pred #(= (.handle ^DispatcherNode %1) (.handle ^DispatcherNode %2))
708 hovered (if picked
709 (filter #(some (partial pred %) picked) active)
710 active)
711 remove-all (fn [c1 c2]
712 (filter #(not (some (partial pred %) c2)) c1))
713 old-hovered @hovered-ref
714 exited (remove-all old-hovered hovered)
715 entered (remove-all hovered old-hovered)
716 moved (or picked (remove-all hovered entered))]
717 (ref-set hovered-ref hovered)
718 (ref-set last-ref event)
719 [exited entered moved acted event]))))
721 (defn- dispatch-mouse-event
722 [dispatcher source-event button?]
723 (when-let [[exited
724 entered
725 moved
726 acted
727 event] (dosync (process-mouse-event dispatcher source-event))]
728 (when button?
729 (translate-and-dispatch acted true event))
730 (translate-and-dispatch exited false event :mouse-exited)
731 (translate-and-dispatch entered false event :mouse-entered)
732 (when-not button?
733 (translate-and-dispatch moved true source-event))))
735 (defrecord RootEventDispatcher [tree-r ;; register
736 tree ;; dispatch
737 active ;; nodes under cursor
738 hovered ;; mouse entered
739 picked ;; mouse pressed
740 last-motion]
741 EventDispatcher
742 (listen! [dispatcher component]
743 (doto ^Component component
744 (.addMouseListener dispatcher)
745 (.addMouseWheelListener dispatcher)
746 (.addMouseMotionListener dispatcher)))
747 (create-dispatcher [dispatcher handle handlers]
748 (let [node (make-node handle handlers)]
749 (dosync (alter tree-r add-node node))
750 node))
751 (commit [dispatcher]
752 (let [[exited
753 entered
754 _ _
755 event] (dosync
756 ;; TODO: retain contexts that do
757 ;; not intersect graphics
758 ;; clipping area in tree.
759 (ref-set tree @tree-r)
760 (ref-set tree-r {})
761 (process-mouse-event dispatcher nil))]
762 ;; Send mouse entered and exited events if necessary due to
763 ;; updated layout.
764 (translate-and-dispatch exited false event :mouse-exited)
765 (translate-and-dispatch entered false event :mouse-entered)))
766 (handle-picked? [dispatcher handle]
767 (some #(= handle (.handle ^DispatcherNode %)) @picked))
768 (handle-hovered? [dispatcher handle]
769 (some #(= handle (.handle ^DispatcherNode %)) @hovered))
770 MouseListener
771 (mouseEntered [dispatcher event]
772 (dispatch-mouse-event dispatcher event false))
773 (mouseExited [dispatcher event]
774 (dispatch-mouse-event dispatcher event false))
775 (mouseClicked [dispatcher event]
776 (dispatch-mouse-event dispatcher event true))
777 (mousePressed [dispatcher event]
778 (dispatch-mouse-event dispatcher event true))
779 (mouseReleased [dispatcher event]
780 (dispatch-mouse-event dispatcher event true))
781 MouseWheelListener
782 (mouseWheelMoved [dispatcher event]
783 (dispatch-mouse-event dispatcher event true))
784 MouseMotionListener
785 (mouseDragged [dispatcher event]
786 (dispatch-mouse-event dispatcher event false))
787 (mouseMoved [dispatcher event]
788 (dispatch-mouse-event dispatcher event false)))
790 (defn root-event-dispatcher []
791 (->RootEventDispatcher
792 (ref {}) (ref {}) ;; trees
793 (ref nil) (ref nil) (ref nil) ;; node states
794 (ref nil))) ;; last event
796 ;;
797 ;; Scene
798 ;;
800 (defrecord Scene [view
801 event-dispatcher
802 component
803 rendering-hints
804 next-state])
806 ;; Define rendering hints that affect font metrics to make sure that
807 ;; Graphics and Scene FontRenderContexts are consistent.
808 (def ^:private default-rendering-hints
809 {RenderingHints/KEY_TEXT_ANTIALIASING
810 RenderingHints/VALUE_TEXT_ANTIALIAS_DEFAULT,
811 RenderingHints/KEY_FRACTIONALMETRICS
812 RenderingHints/VALUE_FRACTIONALMETRICS_DEFAULT})
814 (defn make-scene
815 ([view]
816 (make-scene view dummy-event-dispatcher nil))
817 ([view event-dispatcher]
818 (make-scene view event-dispatcher nil))
819 ([view event-dispatcher ^Component component]
820 (make-scene view event-dispatcher component nil))
821 ([view event-dispatcher ^Component component hints]
822 (let [hints (merge default-rendering-hints hints)]
823 (->Scene view
824 event-dispatcher
825 component
826 hints
827 (atom nil)))))
829 (defn- get-and-set!
830 "Atomically sets the value of atom to newval and returns the old
831 value."
832 [atom newval]
833 (loop [v @atom]
834 (if (compare-and-set! atom v newval)
835 v
836 (recur @atom))))
838 (defn draw-scene!
839 [scene ^Graphics2D graphics width height]
840 (.addRenderingHints graphics (:rendering-hints scene))
841 (binding [*states* (get-and-set! (:next-state scene) nil)
842 *scene* scene
843 *graphics* graphics
844 *initial-transform* (.getTransform graphics)
845 *inverse-initial-transform* (-> graphics
846 .getTransform
847 .createInverse)
848 *event-dispatcher* (:event-dispatcher scene)
849 *width* width
850 *height* height
851 *clip* (Rectangle2D$Double. 0.0 0.0 width height)
852 *input-clip* nil
853 *time* (System/nanoTime)]
854 (apply-theme)
855 (let [tmp-watcher (Object.)]
856 ;; Keep current context observers until the rendering is
857 ;; complete. Some observers may be invoked twice if they
858 ;; appear in both groups until tmp-watcher is removed.
859 (replace-observers-watcher scene tmp-watcher)
860 (try
861 (render! (:view scene))
862 (finally
863 (remove-observers tmp-watcher)
864 (commit (:event-dispatcher scene)))))))
866 (defn- scene-font-context [scene]
867 (let [hints (:rendering-hints scene)
868 ^Component c (:component scene)
869 t (if c (->> c
870 .getFont
871 (.getFontMetrics c)
872 .getFontRenderContext
873 .getTransform))]
874 (FontRenderContext.
875 t
876 (get hints RenderingHints/KEY_TEXT_ANTIALIASING)
877 (get hints RenderingHints/KEY_FRACTIONALMETRICS))))
879 (defn scene-geometry [scene]
880 (binding [*scene* scene
881 *font-context* (scene-font-context scene)]
882 (geometry (:view scene))))
884 (defn set-cursor! [^Cursor cursor]
885 (when-let [^Component component (:component *scene*)]
886 (EventQueue/invokeLater #(.setCursor component cursor))))