view src/indyvon/core.clj @ 11:ea6fc44f19c8

Rename render-layer! to draw!
author Mikhail Kryshen <mikhail@kryshen.net>
date Mon, 14 Jun 2010 04:38:00 +0400
parents 9af27ccccfac
children c6009a144727
line wrap: on
line source

;;
;; Copyright (C) 2010 Mikhail Kryshen <mikhail@kryshen.net>
;;
;; This file is part of Indyvon.
;;

(ns indyvon.core)

(defprotocol Layer
  (render! [this context graphics])
  (size [this context])
  (anchor [this context]))

(defrecord LayerContext [layer parent x y width height update-fn dispatcher])

(defn default-context []
  (LayerContext. nil nil 0 0 0 0 nil nil))

(defmacro reify-layer [& fns]
  (let [method-map {'size [['_ '_] [0 0]]
                    'anchor [['_ '_] [0 0]]}
        method-map (loop [fns fns
                          mm method-map]
                     (if-let [form (first fns)]
                       (recur (next fns)
                              (conj mm [(first form) (next form)]))
                       mm))
        methods (for [m method-map]
                  (cons (first m) (second m)))]
    `(reify Layer ~@methods)))

(defn- make-graphics [g x y w h clip]
  (if clip
    (.create g x y w h)
    (doto (.create g)
      (.translate x y))))

(defn draw!
  "Render layer in a new graphics context."
  ([context layer graphics]
     (draw! context layer graphics
                    0 0 (:width context) (:height context)))
  ([context layer graphics x y]
     (draw! context layer graphics x y true))
  ([context layer graphics x y clip]
     (let [s (size layer context)]
       (draw! context layer graphics
                      x y (s 0) (s 1) clip)))
  ([context layer graphics x y w h]
     (draw! context layer graphics
                    x y w h true))
  ([context layer graphics x y w h clip]
     (let [graphics (make-graphics graphics x y w h clip)]
       (try
         (render! layer
                  (assoc context
                    :layer layer
                    :parent context
                    :x (+ (:x context) x)
                    :y (+ (:y context) y)
                    :width w
                    :height h)
                  graphics)
         (finally
          (.dispose graphics))))))