summaryrefslogtreecommitdiff
path: root/pict.scm
blob: dfa854ad1ea55068ac32d7b58a0996230d3662c8 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
;;; pict.scm --- A simple picture language for Guile

;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public License
;;; as published by the Free Software Foundation; either version 3 of
;;; the License, or (at your option) any later version.
;;; 
;;; This library is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;; Lesser General Public License for more details.
;;; 
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library.  If not, see
;;; <http://www.gnu.org/licenses/>.


(define-module (pict)
  #:use-module (sxml simple)
  #:use-module (sxml transform)
  #:use-module (sxml fold)
  #:use-module ((sxml xpath) #:hide (filter))
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-9 gnu)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-26)
  #:use-module (ice-9 match)
  #:export (pict?
            pict-sxml
            pict-width
            pict-height
            pict-rotation

            ;; modifiers
            fill
            colorize
            remove-outline
            scale
            expand
            grow
            shrink
            rotate
            blur
            cellophane

            frame

            ;; graphics primitives
            line
            polyline
            polygon
            circle
            ellipse
            rectangle

            ;; other graphics
            vline
            hline
            disk
            filled-ellipse
            filled-rectangle
            triangle
            filled-triangle
            octagon
            filled-octagon

            text

            ;; composition
            vl-append
            vc-append
            vr-append

            ht-append
            hc-append
            hb-append

            lt-superimpose
            lc-superimpose
            lb-superimpose

            ct-superimpose
            cc-superimpose
            cb-superimpose

            rt-superimpose
            rc-superimpose
            rb-superimpose

            pin-over
            pin-under
            ghost

            ;; colors
            rgb
            colors))


;;; Records

;; This is the main record for pictures, a simple wrapper around SXML.
;; We only use a record so that we can abuse the record type printer
;; facility (see below).  All operations are really performed on the
;; wrapped SXML.
(define-record-type <pict>
  (make-pict sxml)
  pict?
  (sxml pict-sxml))

;; XXX: This is a hack to let Geiser display the image.
;; Since Geiser only supports the display of images that are
;; associated with a file we write out the SVG to a temp file and
;; return #<Image: /path/to/svg>.
;; Hey, where are you going?  You haven't seen the rest...!
(set-record-type-printer! <pict>
 (lambda (record port)
   (let* ((xml  (with-output-to-string
                  (lambda _ (sxml->xml `(svg (@ (width ,(pict-width record))
                                                (height ,(pict-height record))
                                                (xmlns "http://www.w3.org/2000/svg"))
                                             ,(pict-sxml record))))))
          (name (string-append "/tmp/geiser-"
                               (number->string (string-hash xml))
                               ".svg")))
     (with-output-to-file name
       (lambda _ (display xml)))
     (format port "#<Image: ~a>" name))))


;;; Miscellaneous utilities

(define (scan vals)
  "Return a list of cumulative offsets for each numeric value in the
list VALS."
  (reverse
   (fold (lambda (val acc)
           (match acc
             ((last . lst)
              (let ((offset (+ val last)))
                (cons offset (cons offset lst))))))
         '(0 . ())
         (cons 0 vals))))


;;; SXML utilities

(define (modify-attribute search-key proc node)
  "Find an attribute with the key SEARCH-KEY in the attributes of
NODE.  Run PROC on the current value of the found attribute or create
the attribute by running PROC on #F."
  (let ((attributes (cdr node)))
    (cons '@
     (match (fold (lambda (attribute state)
                    (match attribute
                      ((key vals)
                       (if (eq? key search-key)
                           (cons #t     ; replaced!
                                 (cons (list key (proc vals))
                                       (cdr state)))
                           (cons (car state)
                                 (cons attribute (cdr state)))))))
                  '(#f . ())
                  attributes)
       ((#f . attrs)
        (cons (list search-key (proc #f))
              attrs))
       ((_ . attrs) attrs)))))

(define (attribute-modifier attribute proc)
  "Return a procedure that takes an SXML element and modifies or adds
ATTRIBUTE by applying PROC to the current value (or #F)."
  (match-lambda
    ((tag attrs . inner)
     `(,tag ,(modify-attribute attribute proc attrs)
            ,@inner))))

(define (transform-string->list ts)
  "Split the transform string TS into a list of lists from keys to
values."
  (map (compose (cut take <> 2)
                (cut string-split <> #\()
                (cut string-trim-both <>))
       (filter (negate string-null?) (string-split ts #\)))))

(define (transform-list->string lst)
  "Returns an SVG string of transforms that are built from the list
of transform lists LST."
  (string-join (map (match-lambda
                      ((key val)
                       (string-append key "(" val ")")))
                    lst)))

(define (transform-modifier key proc)
  "Return a function that replaces KEY in the transforms of a pict
with the return value of PROC applied to the current value.  If KEY
does not exist it is added with PROC applied to #F."
  (attribute-modifier
   'transform
   (lambda (transform-str)
     (transform-list->string
      (match (fold (lambda (item state)
                     (match item
                       ((k v)
                        (if (string=? k key)
                            (cons #t    ; replaced!
                                  (cons (list key (proc v))
                                        (cdr state)))
                            (cons (car state)
                                  (cons item (cdr state)))))))
                   '(#f . ())
                   (transform-string->list (or transform-str "")))
        ((#f . items)
         (cons (list key (proc #f))
               items))
        ((_ . items) items))))))

(define (rotation->values str)
  "Returns a list of three rotation values by converting the rotation
string STR."
  (if str
      (map string->number (string-split str #\space))
      (list 0 0 0)))

(define (style-string->list styles)
  "Split the styles string into a list of lists from keys to values."
  (map (cut string-split <> #\:)
       (string-split styles #\;)))

(define (style-list->string lst)
  "Returns a string of semicolon-separated pairs of colon-separated
strings that are built from the list of attributes LST."
  (string-join (map (cut string-join <> ":") lst) ";"))

(define (style-modifier key value)
  (attribute-modifier
   'style
   (lambda (style-str)
     (style-list->string
      (cons (list key value)
            (filter (match-lambda
                      ((k _)
                       (not (string=? k key)))
                      (_ '()))
                    (style-string->list (or style-str ""))))))))

(define (update-style key value sxml)
  ((style-modifier key value) sxml))


;;; Picture modifiers

;; Picts are wrapped in an SVG tag to allow us to record the width and
;; height (and any transformations).  Graphic primitives may be buried
;; deep inside wrapping SVG elements after composition and
;; transformations, so we use foldt to apply modifications to the
;; inner graphic primitives.
(define (pict-modify-primitives pict proc)
  "Apply PROC to all graphic primitives in PICT."
  (make-pict
   (foldt (lambda (thing)
            (let ((tag (car thing)))
              (if (member tag '(rect polygon polyline circle ellipse text))
                  (proc thing) thing)))
          identity
          (pict-sxml pict))))

(define (fill pict color)
  "Fill PICT with COLOR."
  (pict-modify-primitives pict
                          (lambda (inner)
                            (update-style "fill" color inner))))

(define (colorize pict color)
  "Set the outer COLOR of PICT."
  (pict-modify-primitives pict
                          (lambda (inner)
                            (update-style "stroke" color inner))))

(define remove-outline (cut colorize <> "none"))

(define pi (/ 355 113))
(define (deg->rad deg)
  (* deg (/ pi 180)))

;; Nested SVGs lose their transforms!  So we need to use "g" and SVG
;; for wrapping.  "g" for the transform and SVG for x, y, width, and
;; height (because "g" doesn't have those).

(define (rotate pict deg)
  "Rotate the PICT by DEG degrees."
  (define (compute-modifiers inner)
    (let* ((width  (pict-width inner))
           (height (pict-height inner))
           (cx     (exact->inexact (/ width 2)))
           (cy     (exact->inexact (/ height 2)))
           (vecx   (make-rectangular width 0))
           (vecy   (make-rectangular 0 height))
           (degs   (+ deg
                      ;; Current rotation
                      (pict-rotation pict)))
           (rot    (make-polar 1 (deg->rad degs)))
           (rotx   (* vecx rot))
           (roty   (* vecy rot))
           (new-height (+ (abs (imag-part rotx))
                          (abs (imag-part roty))))
           (new-width  (+ (abs (real-part rotx))
                          (abs (real-part roty)))))
      (values
       (compose (transform-modifier "translate"
                                    (const
                                     (format #f "~a ~a"
                                             (exact->inexact (/ (- new-width width) 2))
                                             (exact->inexact (/ (- new-height height) 2)))))
                (transform-modifier "rotate"
                                    (const
                                     (format #f "~a ~a ~a"
                                             degs cx cy))))
       new-height
       new-width)))
  ;; If pict has an svg.rotate + g.transform wrapper: modify that.
  ;; Only wrap it if there is no such wrapper.  Limiting the number of
  ;; wrappers to 1 ensures that the bounding box of the pict does not
  ;; grow on successive rotations.
  (make-pict
   (match (pict-sxml pict)
     (('svg attr ('g (and g-attrs
                          ('@ ('class "transform") rest))
                     ;; TODO: this should only be a single child
                     children))
      (let-values (((modifiers new-height new-width)
                    (compute-modifiers (make-pict children))))
        ((compose (attribute-modifier 'height (const new-height))
                  (attribute-modifier 'width (const new-width)))
         `(svg ,attr
               ,(modifiers `(g ,g-attrs ,children))))))
     (sxml
      (let-values (((modifiers new-height new-width)
                    (compute-modifiers pict)))
        `(svg (@ (height ,new-height)
                 (width ,new-width)
                 (class "rotate")
                 (x 0)
                 (y 0))
              ,(modifiers
                `(g (@ (class "transform")) ,sxml))))))))

(define (scale pict factor)
  "Scale the PICT by the given FACTOR."
  (make-pict
   `(svg (@ (height ,(* factor (pict-height pict)))
            (width ,(* factor (pict-width pict)))
            (class "scale")
            (x 0)
            (y 0))
         ,((transform-modifier "scale" (const (number->string factor)))
           `(g (@ (class "transform"))
               ,(pict-sxml pict))))))

(define* (expand pict
                 #:key
                 (amount 0)
                 (left amount) (right amount)
                 (top amount) (bottom amount))
  "Expand the bounding box of PICT."
  (let ((w (pict-width pict))
        (h (pict-height pict)))
    (make-pict
     `(svg (@ (width ,(+ w left right))
              (height ,(+ h top bottom)))
           ,((compose (attribute-modifier 'x (lambda (x) (+ left x)))
                      (attribute-modifier 'y (lambda (y) (+ top y))))
             (pict-sxml pict))))))

(define (grow pict amount)
  "Grow the bounding box of PICT."
  (expand pict #:amount amount))

(define (shrink pict amount)
  "Shrink the bounding box of PICT."
  (expand pict #:amount (- amount)))

;;; XXX: Emacs doesn't render filters when the image type is SVG.  It
;;; only does this when the image type is 'imagemagick, i.e. when the
;;; SVG is first fed to ImageMagick and the raster image is displayed.
(define (blur pict radius)
  "Apply a Gaussian blur with blur RADIUS to the PICT."
  (let ((new-height (+ (pict-height pict) (* 2 radius)))
        (new-width (+ (pict-width pict) (* 2 radius))))
    (make-pict
     `(svg (@ (width ,new-width)
              (height ,new-height)
              (class "blur"))
           (g (defs
                (filter
                 (@ (id "blur")
                    (width ,new-width)
                    (height ,new-height))
                 (feGaussianBlur
                  (@ (stdDeviation ,(number->string radius)))))))
           ,((compose (style-modifier "filter" "url(#blur)")
                      (attribute-modifier 'x (const (/ (- new-width
                                                          (pict-width pict))
                                                       2)))
                      (attribute-modifier 'y (const (/ (- new-height
                                                          (pict-height pict))
                                                       2))))
             (pict-sxml pict))))))

(define (cellophane pict opacity)
  "Set the opacity of PICT to OPACITY, a numeric value between 0 (for
full transparency) and 1 (for full opacity)."
  (make-pict
   `(svg (@ (height ,(pict-height pict))
            (width ,(pict-width pict))
            (class "opacity")
            (x 0)
            (y 0))
         ,((attribute-modifier 'opacity (const opacity))
           `(g (@ (class "opacity")
                  (opacity ,opacity))
               ,(pict-sxml pict))))))

(define* (frame pict #:key (color "black") (stroke-width 1))
  "Draw a box around PICT."
  (cc-superimpose pict
                  (rectangle (pict-width pict)
                             (pict-height pict)
                             #:border-color color
                             #:border-width stroke-width)))

(define (ghost pict)
  "Create an empty picture with the same size as PICT."
  (make-pict
   `(svg (@ (height ,(pict-height pict))
            (width  ,(pict-width pict))
            (class "ghost")
            (x 0)
            (y 0)))))


;;; SVG graphics primitives.

;;; Each shape is wrapped in an SVG tag that records the width,
;;; height, and the coordinates.

(define* (line x1 y1 x2 y2
               #:optional (maxw 0) (maxh 0)
               #:key
               (color "black")
               (stroke-width 1))
  (make-pict
   `(svg (@ (width ,(max maxw (let ((new-width (+ (min x1 x2)
                                                  (abs (- x2 x1)))))
                                (if (zero? new-width)
                                    stroke-width new-width))))
            (height ,(max maxh (let ((new-height (+ (min y1 y2)
                                                    (abs (- y2 y1)))))
                                 (if (zero? new-height)
                                     stroke-width new-height))))
            (x 0)
            (y 0))
         (line (@ (x1 ,x1)
                  (y1 ,y1)
                  (x2 ,x2)
                  (y2 ,y2)
                  (style ,(style-list->string
                           `(("stroke" ,color)
                             ("stroke-width"
                              ,(number->string stroke-width))))))))))

(define* (hline w h
               #:key
               (color "black")
               (stroke-width 1))
  (let ((vcenter (exact->inexact (/ h 2))))
    (line 0 vcenter w vcenter w h
          #:color color #:stroke-width stroke-width)))

(define* (vline w h
               #:key
               (color "black")
               (stroke-width 1))
  (let ((hcenter (exact->inexact (/ w 2))))
    (line hcenter 0 hcenter h w h
          #:color color #:stroke-width stroke-width)))

(define* (polyline points
               #:key
               (color "black")
               (stroke-width 1))
  "Draw a polyline from POINTS, a list of x and y coordinate pairs."
  (let* ((xs (map car points))
         (ys (map cdr points)))
    (make-pict
     `(svg (@ (width ,(+ (apply min xs)
                         (apply max xs)))
              (height ,(+ (apply min ys)
                          (apply max ys)))
              (x 0)
              (y 0))
           (polyline (@ (points ,(string-join
                                  (map (match-lambda
                                         ((x . y)
                                          (string-append (number->string x)
                                                         ","
                                                         (number->string y))))
                                       points)))
                        (style ,(style-list->string
                                 `(("fill" "none")
                                   ("stroke" ,color)
                                   ("stroke-width"
                                    ,(number->string stroke-width)))))))))))

(define* (polygon points
               #:key
               (border-color "black")
               (border-width 1))
  "Draw a polygon from POINTS, a list of x and y coordinate pairs."
  (let* ((xs (map car points))
         (ys (map cdr points)))
    (make-pict
     `(svg (@ (width ,(+ (apply min xs)
                         (apply max xs)))
              (height ,(+ (apply min ys)
                          (apply max ys)))
              (x 0)
              (y 0))
           (polygon (@ (points ,(string-join
                                 (map (match-lambda
                                        ((x . y)
                                         (string-append (number->string x)
                                                        ","
                                                        (number->string y))))
                                      points)))
                       (style ,(style-list->string
                                `(("fill" "none")
                                  ("stroke" ,border-color)
                                  ("stroke-width"
                                   ,(number->string border-width)))))))))))

;; An isosceles triangle
(define* (triangle w h
                   #:key
                   (border-color "black")
                   (border-width 1))
  (polygon `((0 . ,h)
             (,w . ,h)
             (,(/ w 2) . 0))
           #:border-color border-color
           #:border-width border-width))

(define* (filled-triangle w h #:key (color "black"))
  (remove-outline (fill (triangle w h) color)))

;; A boring p8 symmetric isogonal octagon
(define* (octagon size
                  #:key
                  (border-color "black")
                  (border-width 1))
  (let ((third (exact->inexact (/ size 3))))
    (polygon `((0 . ,(* 2 third))
               (0 . ,third)
               (,third . 0)
               (,(* 2 third) . 0)
               (,size . ,third)
               (,size . ,(* 2 third))
               (,(* 2 third) . ,size)
               (,third . ,size))
             #:border-color border-color
             #:border-width border-width)))

(define* (filled-octagon size #:key (color "black"))
  (remove-outline (fill (octagon size) color)))

(define* (circle size
                 #:key
                 (border-color "black")
                 (border-width 1))
  (let* ((border-width (min border-width (/ size 2)))
         (radius (exact->inexact
                  (/ (- size border-width) 2))))
    (make-pict
     `(svg (@ (width ,size)
              (height ,size)
              (x 0)
              (y 0))
           (circle (@ (style ,(style-list->string
                               `(("fill" "none")
                                 ("stroke" ,border-color)
                                 ("stroke-width"
                                  ,(number->string border-width)))))
                      (cx ,(+ radius (/ border-width 2)))
                      (cy ,(+ radius (/ border-width 2)))
                      (r  ,radius)))))))

(define* (disk size
               #:key
               (color "black"))
  (fill (circle size #:border-width 0 #:border-color "none") color))

(define* (ellipse w h
                  #:key
                  (border-color "black")
                  (border-width 1))
  (make-pict
   `(svg (@ (width ,w)
            (height ,h)
            (x 0)
            (y 0))
         (ellipse (@ (style ,(style-list->string
                              `(("fill" "none")
                                ("stroke" ,border-color)
                                ("stroke-width"
                                 ,(number->string border-width)))))
                     (cx ,(/ w 2))
                     (cy ,(/ h 2))
                     (rx ,(/ w 2))
                     (ry ,(/ h 2)))))))

(define* (filled-ellipse w h #:key (color "black"))
  (remove-outline (fill (ellipse w h) color)))

(define* (rectangle w h
                    #:key
                    (border-color "black")
                    (border-width 1)
                    (rx 0)
                    (ry 0))
  (make-pict
   `(svg (@ (width ,w)
            (height ,h)
            (x 0)
            (y 0))
         (rect (@ (style ,(style-list->string
                           `(("fill" "none")
                             ("stroke" ,border-color)
                             ("stroke-width"
                              ,(number->string border-width)))))
                  (x 0)
                  (y 0)
                  (width ,w)
                  (height ,h)
                  (rx ,rx)
                  (ry ,ry))))))

(define* (filled-rectangle w h #:key
                           (color "black")
                           (border-color "none")
                           (border-width 1)
                           (rx 0)
                           (ry 0))
  (fill (rectangle w h
                   #:border-color border-color
                   #:border-width border-width
                   #:rx rx
                   #:ry ry) color))

;; XXX: We need to ask the user to provide width and height, because
;; we cannot determine these dimensions without rendering the text.
;; Even so, the text is cut off in some cases when letters go below
;; the baseline.  This needs more work.
(define* (text txt w h
               #:key
               (color "black"))
  (make-pict
   `(svg (@ (width ,w)
            (height ,h)
            (x 0)
            (y 0))
         (text (@ (style ,(style-list->string
                           `(("fill" ,color)
                             ("font-family" "sans-serif")
                             ("font-size" ,(number->string h))
                             ("text-anchor" "middle"))))
                  (x ,(/ w 2)) (y ,h))
               ,txt))))


(define* (pict-attr attr pict #:key (path '()))
  "Return the value of the selected ATTRIBUTE of the outermost element
of the SVG of PICT or #F."
  (and=> ((sxpath `(,@path @ ,attr *any*))
          (pict-sxml pict))
         (lambda (m) (and (pair? m)
                          (car m)))))

(define (pict-height pict)
  "Return the height of PICT."
  (pict-attr 'height pict))

(define (pict-width pict)
  "Return the width of PICT."
  (pict-attr 'width pict))

(define (pict-rotation pict)
  "Return the rotation of PICT."
  (let ((m (assoc-ref (transform-string->list
                       (or (pict-attr 'transform pict #:path '(g)) ""))
                      "rotate")))
    (or (and (pair? m)
             (and=> (first m)
                    (lambda (m) (first (rotation->values m)))))
        0)))

(define (append-align xalign yalign picts)
  "Append PICTS and align them vertically to the top, center, bottom,
or spread by an offset according to the symbol YALIGN and horizontally
to the left, center, right, or spread them with an offset according to
the symbol XALIGN.  When the first element of PICTS is a number, use
it as a gap between PICTS."
  (let-values (((gap picts) (match picts
                              (((? number? gap) . picts)
                               (values gap picts))
                              (_ (values 0 picts)))))
    (let* ((heights    (map pict-height picts))
           (widths     (map pict-width picts))
           (gaps       (* (- (length picts) 1) gap))
           (new-height (if (eq? yalign 'offset)
                           (+ (apply + heights) gaps)
                           (apply max heights)))
           (new-width  (if (eq? xalign 'offset)
                           (+ (apply + widths) gaps)
                           (apply max widths)))
           (x-offsets  (if (eq? xalign 'offset)
                           (map + (scan widths)
                                  (scan (list-tabulate (length picts) (const gap))))
                           (list-tabulate (length picts) (const gap))))
           (y-offsets  (if (eq? yalign 'offset)
                           (map + (scan heights)
                                  (scan (list-tabulate (length picts) (const gap))))
                           (list-tabulate (length picts) (const gap))))
           (aligner    (match-lambda
                         ((xoffset yoffset pict)
                          ((compose
                            (attribute-modifier
                             'x (match xalign
                                  ('left   identity)
                                  ('center (lambda _
                                             (exact->inexact
                                              (- (/ new-width 2)
                                                 (/ (pict-width pict) 2)))))
                                  ('right  (lambda _
                                             (exact->inexact
                                              (- new-width
                                                 (pict-width pict)))))
                                  ('offset (const xoffset))))
                            (attribute-modifier
                             'y (match yalign
                                  ('top    identity)
                                  ('center (lambda _
                                             (exact->inexact
                                              (- (/ new-height 2)
                                                 (/ (pict-height pict) 2)))))
                                  ('bottom (lambda _
                                             (exact->inexact
                                              (- new-height
                                                 (pict-height pict)))))
                                  ('offset (const yoffset)))))
                           (pict-sxml pict))))))
      (make-pict
       `(svg (@ (height ,new-height)
                (width  ,new-width)
                (class ,(string-append "aligned-"
                                       (symbol->string xalign)
                                       "-"
                                       (symbol->string yalign)))
                (x 0)
                (y 0))
             ,@(map aligner (zip x-offsets y-offsets picts)))))))

(define (ht-append . picts)
  "Line up the given PICTS horizontally on the top."
  (append-align 'offset 'top picts))

(define (hc-append . picts)
  "Line up the given PICTS horizontally and center them."
  (append-align 'offset 'center picts))

(define (hb-append . picts)
  "Line up the given PICTS horizontally on the top."
  (append-align 'offset 'bottom picts))

(define (vl-append . picts)
  "Line up the given PICTS vertically and left-align them."
  (append-align 'left 'offset picts))

(define (vc-append . picts)
  "Line up the given PICTS vertically and center them."
  (append-align 'center 'offset picts))

(define (vr-append . picts)
  "Line up the given PICTS vertically and right-align them."
  (append-align 'right 'offset picts))

(define (lt-superimpose . picts)
  "Stack the given PICTS and align them left and at the top."
  (append-align 'left 'top picts))
(define (lc-superimpose . picts)
  "Stack the given PICTS and align them left and center them
vertically."
  (append-align 'left 'center picts))
(define (lb-superimpose . picts)
  "Stack the given PICTS and align them left and at the bottom."
  (append-align 'left 'bottom picts))

(define (ct-superimpose . picts)
  "Stack the given PICTS and center them horizontally and align at the
top."
  (append-align 'center 'top picts))
(define (cc-superimpose . picts)
  "Stack the given PICTS and center them horizontally and vertically."
  (append-align 'center 'center picts))
(define (cb-superimpose . picts)
  "Stack the given PICTS and center them horizontally and align at the
bottom."
  (append-align 'center 'bottom picts))

(define (rt-superimpose . picts)
  "Stack the given PICTS and align them right and at the top."
  (append-align 'right 'top picts))
(define (rc-superimpose . picts)
  "Stack the given PICTS and align them right and center them vertically."
  (append-align 'right 'center picts))
(define (rb-superimpose . picts)
  "Stack the given PICTS and align them right and at the bottom."
  (append-align 'right 'bottom picts))

(define (pin-over base dx dy pict)
  "Create a pict with the same dimensions as BASE, but with PICT
placed on top.  PICT is offset from the top left corner of BASE by DX
and DY."
  (make-pict
   `(svg (@ (height ,(pict-height base))
            (width  ,(pict-width base))
            (class "pinned")
            (x 0)
            (y 0))
         ,(pict-sxml base)
         ,((compose (attribute-modifier 'y (const dy))
                    (attribute-modifier 'x (const dx)))
           (pict-sxml pict)))))

(define (pin-under base dx dy pict)
  "Create a pict with the same dimensions as BASE, but with PICT
placed underneath.  PICT is offset from the top left corner of BASE by
DX and DY."
  (make-pict
   `(svg (@ (height ,(pict-height base))
            (width  ,(pict-width base))
            (class "pinned")
            (x 0)
            (y 0))
         ,((compose (attribute-modifier 'y (const dy))
                    (attribute-modifier 'x (const dx)))
           (pict-sxml pict))
         ,(pict-sxml base))))


;;; Colors

(define (rgb r g b)
  (when (any (lambda (comp)
               (or (> comp 255)
                   (negative? comp)))
             (list r g b))
    (error "Color component values must be between 0 and 255."))
  (format #f "rgb(~a,~a,~a)" r g b))

;; List of defined SVG color names
(define colors
  (list "aliceblue" "antiquewhite" "aqua" "aquamarine" "azure" "beige"
        "bisque" "black" "blanchedalmond" "blue" "blueviolet" "brown"
        "burlywood" "cadetblue" "chartreuse" "chocolate" "coral"
        "cornflowerblue" "cornsilk" "crimson" "cyan" "darkblue"
        "darkcyan" "darkgoldenrod" "darkgray" "darkgreen" "darkgrey"
        "darkkhaki" "darkmagenta" "darkolivegreen" "darkorange"
        "darkorchid" "darkred" "darksalmon" "darkseagreen"
        "darkslateblue" "darkslategray" "darkslategrey" "darkturquoise"
        "darkviolet" "deeppink" "deepskyblue" "dimgray" "dimgrey"
        "dodgerblue" "firebrick" "floralwhite" "forestgreen" "fuchsia"
        "gainsboro" "ghostwhite" "gold" "goldenrod" "gray" "grey"
        "green" "greenyellow" "honeydew" "hotpink" "indianred" "indigo"
        "ivory" "khaki" "lavender" "lavenderblush" "lawngreen"
        "lemonchiffon" "lightblue" "lightcoral" "lightcyan"
        "lightgoldenrodyellow" "lightgray" "lightgreen" "lightgrey"
        "lightpink" "lightsalmon" "lightseagreen" "lightskyblue"
        "lightslategray" "lightslategrey" "lightsteelblue"
        "lightyellow" "lime" "limegreen" "linen" "magenta" "maroon"
        "mediumaquamarine" "mediumblue" "mediumorchid" "mediumpurple"
        "mediumseagreen" "mediumslateblue" "mediumspringgreen"
        "mediumturquoise" "mediumvioletred" "midnightblue" "mintcream"
        "mistyrose" "moccasin" "navajowhite" "navy" "oldlace" "olive"
        "olivedrab" "orange" "orangered" "orchid" "palegoldenrod"
        "palegreen" "paleturquoise" "palevioletred" "papayawhip"
        "peachpuff" "peru" "pink" "plum" "powderblue" "purple" "red"
        "rosybrown" "royalblue" "saddlebrown" "salmon" "sandybrown"
        "seagreen" "seashell" "sienna" "silver" "skyblue" "slateblue"
        "slategray" "slategrey" "snow" "springgreen" "steelblue" "tan"
        "teal" "thistle" "tomato" "turquoise" "violet" "wheat" "white"
        "whitesmoke" "yellow" "yellowgreen"))