view src/net/kryshen/indyvon/core.clj @ 68:9b511fe09867

Code cleanup, docstrings.
author Mikhail Kryshen <mikhail@kryshen.net>
date Sun, 29 Aug 2010 03:59:10 +0400
parents a19cf5007d14
children b2f6c78413d3
line source
1 ;;
2 ;; Copyright (C) 2010 Mikhail Kryshen <mikhail@kryshen.net>
3 ;;
4 ;; This file is part of Indyvon.
5 ;;
7 (ns net.kryshen.indyvon.core
8 (:import
9 (java.awt Graphics2D RenderingHints Component Color Font AWTEvent Shape)
10 (java.awt.geom AffineTransform Point2D$Double Rectangle2D$Double Area)
11 (java.awt.event MouseListener MouseMotionListener)
12 (java.awt.font FontRenderContext)))
14 ;;
15 ;; Layer context
16 ;;
18 (def ^Graphics2D *graphics*)
20 (def ^FontRenderContext *font-context*)
22 (def ^{:tag Component
23 :doc "Target AWT component, may be nil if drawing off-screen."}
24 *target*)
26 (def ^{:doc "Width of the rendering area."}
27 *width*)
29 (def ^{:doc "Height of the rendering area."}
30 *height*)
32 (def ^Shape *clip*)
34 (def *root*)
36 (def *event-dispatcher*)
38 (def ^{:tag AffineTransform
39 :doc "Initial transform associated with the graphics context."}
40 *initial-transform*)
42 (def ^{:tag AffineTransform
43 :doc "Inversion of the initial transform associated with
44 the graphics context."}
45 *inverse-initial-transform*)
47 (defrecord Theme [fore-color back-color alt-back-color border-color font])
49 ;; REMIND: use system colors, see java.awt.SystemColor.
50 (defn default-theme []
51 (Theme. Color/BLACK Color/WHITE Color/LIGHT_GRAY
52 Color/BLUE (Font. "Sans" Font/PLAIN 12)))
54 (def *theme* (default-theme))
56 (defrecord Location [x y])
57 (defrecord Size [width height])
58 (defrecord Bounds [x y width height])
60 ;;
61 ;; Core protocols and types
62 ;;
64 (defprotocol Layer
65 "Basic UI element."
66 (render! [this])
67 (layer-size [this]))
69 ;; TODO: modifiers
70 (defrecord MouseEvent [id when x y x-on-screen y-on-screen button])
72 (defprotocol EventDispatcher
73 (listen! [this ^Component component]
74 "Listen for events on the specified AWT Component.")
75 (create-dispatcher [this handle handlers]
76 "Returns new event dispatcher associated with the specified event
77 handlers (an event-id -> handler-fn map). Handle is used to
78 match the contexts between commits.")
79 (commit [this]
80 "Apply the registered handlers for event processing."))
82 (defprotocol Anchored
83 "Provide anchor point for Layers. Used by viewport."
84 (anchor [this h-align v-align]
85 "Anchor point: [x y], h-align could be :left, :center or :right,
86 v-align is :top, :center or :bottom"))
88 (defn default-anchor [layer h-align v-align]
89 (if (and (= h-align :left)
90 (= v-align :top))
91 (Location. 0 0)
92 (let [size (layer-size layer)]
93 (Location.
94 (case h-align
95 :top 0
96 :center (/ (:width size) 2)
97 :right (:width size))
98 (case v-align
99 :left 0
100 :center (/ (:height size) 2)
101 :bottom (:height size))))))
103 ;; Default implementation of Anchored for any Layer.
104 (extend-protocol Anchored
105 net.kryshen.indyvon.core.Layer
106 (anchor [this h-align v-align]
107 (default-anchor this h-align v-align)))
109 (defn- assoc-cons [m key val]
110 (->> (get m key) (cons val) (assoc m key)))
112 (defn- assoc-in-cons [m keys val]
113 (->> (get-in m keys) (cons val) (assoc-in m keys)))
115 ;;
116 ;; Observers
117 ;;
119 (def observers (atom nil))
121 ;; TODO: groups should be weakly referenced.
122 ;; Need persistent analog of java.util.WeakHashMap.
123 (defn add-observer
124 "Add observer fn for the target to the specified group."
125 [group target f]
126 (swap! observers assoc-in-cons [group target] f)
127 nil)
129 (defn remove-observer-group
130 "Remove group of observers."
131 [group]
132 (swap! observers dissoc group)
133 nil)
135 ;; (defn- replace-observer-group*
136 ;; [observers old-id new-id]
137 ;; (let [group (get observers old-id)]
138 ;; (assoc (dissoc observers old-id)
139 ;; new-id group)))
141 ;; (defn- replace-observer-group
142 ;; [old-id new-id]
143 ;; (swap! observers replace-observer-group* old-id new-id))
145 (defn update
146 "Notify observers."
147 [target & args]
148 (doseq [f (reduce #(concat %1 (get %2 target)) nil (vals @observers))]
149 (apply f target args)))
151 (defn add-context-observer
152 "Observer registered with this function will be automatically
153 removed after the next frame rendering is complete."
154 [target f]
155 (let [root *root*]
156 (add-observer root target f)))
158 (defn repaint-on-update
159 "Trigger repaint of the current scene when the target updates."
160 [target]
161 (let [root *root*]
162 (if (not= root target)
163 (add-observer root target (fn [_] (update root))))))
165 (defn repaint
166 "Repaint the current scene."
167 []
168 (update *root*))
170 ;;
171 ;; Rendering
172 ;;
174 (defn- relative-transform
175 "AffineTransform: layer context -> awt component."
176 []
177 (let [tr (.getTransform *graphics*)]
178 (.preConcatenate tr *inverse-initial-transform*)
179 tr))
181 (defn- inverse-relative-transform
182 "AffineTransform: awt component -> layer context."
183 []
184 (let [tr (.getTransform *graphics*)]
185 (.invert tr) ; absolute -> layer
186 (.concatenate tr *initial-transform*) ; component -> absolute
187 tr))
189 (defn- clip
190 "Intersect clipping area with the specified shape or bounds.
191 Returns new clip (Shape or nil if empty)."
192 ([x y w h]
193 (clip (Rectangle2D$Double. x y w h)))
194 ([shape]
195 (let [a1 (Area. shape)
196 a2 (if (instance? Area *clip*) *clip* (Area. *clip*))]
197 (.transform a1 (relative-transform))
198 (.intersect a1 a2)
199 (if (.isEmpty a1)
200 nil
201 a1))))
203 (defn- ^Graphics2D apply-theme
204 "Set graphics' color and font to match theme.
205 Modifies and returns the first argument."
206 ([]
207 (apply-theme *graphics* *theme*))
208 ([^Graphics2D graphics theme]
209 (doto graphics
210 (.setColor (:fore-color theme))
211 (.setFont (:font theme)))))
213 (defn- ^Graphics2D create-graphics
214 ([]
215 (create-graphics 0 0 *width* *height*))
216 ([x y w h]
217 (apply-theme (.create *graphics* x y w h) *theme*)))
219 (defn with-bounds*
220 [x y w h f & args]
221 (when-let [clip (clip x y w h)]
222 (let [graphics (create-graphics x y w h)]
223 (try
224 (binding [*width* w
225 *height* h
226 *clip* clip
227 *graphics* graphics]
228 (apply f args))
229 (finally
230 (.dispose graphics))))))
232 (defmacro with-bounds
233 [x y w h & body]
234 `(with-bounds* ~x ~y ~w ~h (fn [] ~@body)))
236 (defn with-handlers*
237 [handle handlers f & args]
238 (binding
239 [*event-dispatcher* (create-dispatcher
240 *event-dispatcher* handle handlers)]
241 (apply f args)))
243 (defmacro with-handlers
244 "specs => (:event-id name & handler-body)*
246 Execute form with the specified event handlers."
247 [handle form & specs]
248 `(with-handlers* ~handle
249 ~(reduce (fn [m spec]
250 (assoc m (first spec)
251 `(fn [~(second spec)]
252 ~@(nnext spec)))) {}
253 specs)
254 (fn [] ~form)))
256 (defmacro with-theme
257 [theme & body]
258 `(binding [*theme* (merge *theme* ~theme)]
259 ~@body))
261 (defmacro with-color
262 [color & body]
263 `(let [color# (.getColor *graphics*)]
264 (try
265 (.setColor *graphics* ~color)
266 ~@body
267 (finally
268 (.setColor *graphics* color#)))))
270 ;; TODO: constructor for AffineTransform.
271 ;; (transform :scale 0.3 0.5
272 ;; :translate 5 10
273 ;; :rotate (/ Math/PI 2))
275 (defmacro with-transform [transform & body]
276 `(let [old-t# (.getTransform *graphics*)]
277 (try
278 (.transform *graphics* ~transform)
279 ~@body
280 (finally
281 (.setTransform *graphics* old-t#)))))
283 (defmacro with-rotate [theta ax ay & body]
284 `(let [transform# (AffineTransform/getRotateInstance ~theta ~ax ~ay)]
285 (with-transform transform# ~@body)))
287 (defn draw!
288 "Draws layer."
289 ([layer]
290 (let [graphics (create-graphics)]
291 (try
292 (binding [*graphics* graphics]
293 (render! layer))
294 (finally
295 (.dispose graphics)))))
296 ([layer x y]
297 (let [size (layer-size layer)]
298 (draw! layer x y (:width size) (:height size))))
299 ([layer x y width height]
300 (with-bounds* x y width height render! layer)))
302 (defn draw-anchored!
303 "Draws layer. Location is relative to the layer's anchor point for
304 the specified alignment."
305 ([layer h-align v-align x y]
306 (let [anchor (anchor layer h-align v-align)]
307 (draw! layer (- x (:x anchor)) (- y (:y anchor)))))
308 ([layer h-align v-align x y w h]
309 (let [anchor (anchor layer h-align v-align)]
310 (draw! layer (- x (:x anchor)) (- y (:y anchor)) w h))))
312 (defn draw-root!
313 "Draws the root layer."
314 ([layer graphics width height event-dispatcher]
315 (draw-root! layer graphics width height event-dispatcher nil))
316 ([layer ^Graphics2D graphics width height event-dispatcher target]
317 (binding [*root* layer
318 *target* target
319 *graphics* graphics
320 *font-context* (.getFontRenderContext graphics)
321 *initial-transform* (.getTransform graphics)
322 *inverse-initial-transform*
323 (-> graphics .getTransform .createInverse)
324 *event-dispatcher* event-dispatcher
325 *width* width
326 *height* height
327 *clip* (Rectangle2D$Double. 0 0 width height)]
328 ;; (.setRenderingHint graphics
329 ;; RenderingHints/KEY_INTERPOLATION
330 ;; RenderingHints/VALUE_INTERPOLATION_BILINEAR)
331 ;; (.setRenderingHint graphics
332 ;; RenderingHints/KEY_ALPHA_INTERPOLATION
333 ;; RenderingHints/VALUE_ALPHA_INTERPOLATION_QUALITY)
334 ;; (.setRenderingHint graphics
335 ;; RenderingHints/KEY_ANTIALIASING
336 ;; RenderingHints/VALUE_ANTIALIAS_ON)
337 (apply-theme)
338 (with-color (:back-color *theme*)
339 (.fillRect graphics 0 0 width height))
340 (remove-observer-group layer)
341 (try
342 (render! layer)
343 (finally
344 (commit event-dispatcher))))))
346 (defn root-size
347 ([layer font-context]
348 (root-size layer font-context nil))
349 ([layer font-context target]
350 (binding [*root* layer
351 *target* target
352 *font-context* font-context]
353 (layer-size layer))))
355 ;;
356 ;; EventDispatcher implementation
357 ;;
359 (def awt-events
360 {java.awt.event.MouseEvent/MOUSE_CLICKED :mouse-clicked
361 java.awt.event.MouseEvent/MOUSE_DRAGGED :mouse-dragged
362 java.awt.event.MouseEvent/MOUSE_ENTERED :mouse-entered
363 java.awt.event.MouseEvent/MOUSE_EXITED :mouse-exited
364 java.awt.event.MouseEvent/MOUSE_MOVED :mouse-moved
365 java.awt.event.MouseEvent/MOUSE_PRESSED :mouse-pressed
366 java.awt.event.MouseEvent/MOUSE_RELEASED :mouse-released})
368 (def dummy-event-dispatcher
369 (reify
370 EventDispatcher
371 (listen! [this component])
372 (create-dispatcher [this handle handlers] this)
373 (commit [this])))
375 (defrecord DispatcherNode [handle handlers parent
376 ^Shape clip ^AffineTransform transform
377 bindings]
378 EventDispatcher
379 (listen! [this component]
380 (listen! parent component))
381 (create-dispatcher [this handle handlers]
382 (create-dispatcher parent handle handlers))
383 (commit [this]
384 (commit parent)))
386 (defn- make-node [handle handlers]
387 (DispatcherNode. handle handlers *event-dispatcher* *clip*
388 (inverse-relative-transform)
389 (get-thread-bindings)))
391 (defn- add-node [tree node]
392 (assoc-cons tree (:parent node) node))
394 (defn- under-cursor
395 "Returns a vector of child nodes under cursor."
396 [x y tree node]
397 (some #(if (.contains ^Shape (:clip %) x y)
398 (conj (vec (under-cursor x y tree %)) %))
399 (get tree node)))
401 (defn- remove-all [coll1 coll2 pred]
402 (filter #(not (some (partial pred %) coll2)) coll1))
404 (defn- transform [^AffineTransform tr x y]
405 (let [p (Point2D$Double. x y)]
406 (.transform tr p p)
407 [(.x p) (.y p)]))
409 (defn- translate-mouse-event [^java.awt.event.MouseEvent event
410 ^AffineTransform tr id]
411 (let [[x y] (transform tr (.getX event) (.getY event))]
412 (MouseEvent. id (.getWhen event) x y
413 (.getXOnScreen event) (.getYOnScreen event)
414 (.getButton event))))
416 (defn- translate-and-dispatch
417 ([nodes first-only ^java.awt.event.MouseEvent event]
418 (translate-and-dispatch nodes first-only
419 event (awt-events (.getID event))))
420 ([nodes first-only event id]
421 (if-let [node (first nodes)]
422 (if-let [handler (get (:handlers node) id)]
423 (do
424 (with-bindings* (:bindings node)
425 handler
426 (translate-mouse-event event (:transform node) id))
427 (if-not first-only
428 (recur (rest nodes) false event id)))
429 (recur (rest nodes) first-only event id)))))
431 (defn- dispatch-mouse-motion
432 "Dispatches mouse motion events."
433 [hovered-ref tree root ^java.awt.event.MouseEvent event]
434 (let [x (.getX event)
435 y (.getY event)
436 [hovered hovered2] (dosync
437 [@hovered-ref
438 (ref-set hovered-ref
439 (under-cursor x y tree root))])
440 pred #(= (:handle %1) (:handle %2))
441 exited (remove-all hovered hovered2 pred)
442 entered (remove-all hovered2 hovered pred)
443 moved (remove-all hovered2 entered pred)]
444 (translate-and-dispatch exited false event :mouse-exited)
445 (translate-and-dispatch entered false event :mouse-entered)
446 (translate-and-dispatch moved true event :mouse-moved)))
448 (defn- dispatch-mouse-button
449 [picked-ref hovered-ref ^java.awt.event.MouseEvent event]
450 (let [id (awt-events (.getID event))
451 hovered (if (= id :mouse-pressed)
452 (dosync (ref-set picked-ref @hovered-ref))
453 @hovered-ref)]
454 (translate-and-dispatch hovered true event id)))
456 (defn root-event-dispatcher []
457 (let [tree-r (ref {}) ; register
458 tree (ref {}) ; dispatch
459 hovered (ref '())
460 picked (ref '())]
461 (reify
462 EventDispatcher
463 (listen! [this component]
464 (doto component
465 (.addMouseListener this)
466 (.addMouseMotionListener this)))
467 (create-dispatcher [this handle handlers]
468 (let [node (make-node handle handlers)]
469 (dosync (alter tree-r add-node node))
470 node))
471 (commit [this]
472 (dosync (ref-set tree @tree-r)
473 (ref-set tree-r {})))
474 MouseListener
475 (mouseEntered [this event]
476 (dispatch-mouse-motion hovered @tree this event))
477 (mouseExited [this event]
478 (dispatch-mouse-motion hovered @tree this event))
479 (mouseClicked [this event]
480 (dispatch-mouse-button picked hovered event))
481 (mousePressed [this event]
482 (dispatch-mouse-button picked hovered event))
483 (mouseReleased [this event]
484 (translate-and-dispatch @picked true event))
485 ;;(dispatch-mouse-button picked hovered event))
486 MouseMotionListener
487 (mouseDragged [this event]
488 (translate-and-dispatch @picked true event))
489 (mouseMoved [this event]
490 (dispatch-mouse-motion hovered @tree this event)))))
492 ;;
493 ;; ИДЕИ:
494 ;;
495 ;; Контекст: биндинги или запись?
496 ;;
497 ;; Установка обработчиков (в контексте слоя):
498 ;;
499 ;; (listen
500 ;; (:mouse-entered e
501 ;; ...)
502 ;; (:mouse-exited e
503 ;; ...))
504 ;;
505 ;; Не надо IMGUI.
506 ;; Построение сцены путем декорирования слоев:
507 ;;
508 ;; (listener
509 ;; (:action e (println e))
510 ;; (:mouse-dragged e (println e))
511 ;; (theme :font "Helvetica-14"
512 ;; (vbox
513 ;; (button (text-layer "Button 1"))
514 ;; (button (text-layer "Button 2")))))
515 ;;