]> gitweb.factorcode.org Git - factor.git/blob - basis/wrap/wrap.factor
wrap: some cleanup.
[factor.git] / basis / wrap / wrap.factor
1 ! Copyright (C) 2009 Daniel Ehrenberg
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays combinators combinators.short-circuit
4 fry kernel kernel.private lists locals math sequences typed ;
5 IN: wrap
6
7 ! black is the text length, white is the whitespace length
8 TUPLE: element contents black white ;
9 C: <element> element
10
11 <PRIVATE
12
13 : element-length ( element -- n )
14     [ black>> ] [ white>> ] bi + ; inline
15
16 TUPLE: paragraph line-max line-ideal lines head-width tail-cost ;
17 C: <paragraph> paragraph
18
19 : if-one-line ( paragraph true false -- )
20     [ dup lines>> 1list? ] 2dip if ; inline
21
22 TYPED: top-fits? ( paragraph: paragraph -- ? )
23     [ head-width>> ]
24     [ [ line-ideal>> ] [ line-max>> ] if-one-line ] bi <= ; inline
25
26 TYPED: fits? ( paragraph: paragraph -- ? )
27     ! Make this not count spaces at end
28     { [ lines>> car 1list? ] [ top-fits? ] } 1|| ; inline
29
30 TYPED: paragraph-cost ( paragraph: paragraph -- cost )
31     [ drop 0 ] [
32         [ head-width>> ] [ line-ideal>> - sq ] [ tail-cost>> ] tri +
33     ] if-one-line ; inline
34
35 : min-cost ( paragraphs -- paragraph )
36     [ paragraph-cost ] infimum-by ; inline
37
38 TYPED: new-line ( paragraph: paragraph element: element -- paragraph )
39     {
40         [ drop [ line-max>> ] [ line-ideal>> ] bi ]
41         [ [ lines>> ] [ 1list ] bi* swons ]
42         [ nip black>> ]
43         [ drop paragraph-cost ]
44     } 2cleave <paragraph> ; inline
45
46 TYPED: add-element ( paragraph: paragraph element: element -- )
47     [ '[ _ element-length + ] change-head-width ]
48     [ '[ unswons _ swons swons ] change-lines ] bi drop ; inline
49
50 TYPED: wrap-step ( paragraphs: array element: element -- paragraphs )
51     [ [ min-cost ] dip new-line ]
52     [ dupd '[ _ add-element ] each ]
53     2bi swap prefix { array } declare
54     [ fits? ] filter ; inline
55
56 : 1paragraph ( line-max line-ideal element -- paragraph )
57     [ 1list 1list ] [ black>> ] bi 0 <paragraph> ;
58
59 : post-process ( paragraph -- array )
60     lines>> [ [ contents>> ] lmap>array ] lmap>array ;
61
62 : initial-step ( line-max line-ideal elements -- elements paragraph )
63     reverse unclip [ -rot ] dip 1paragraph 1array ;
64
65 PRIVATE>
66
67 : wrap ( elements line-max line-ideal -- array )
68     rot [ 2drop { } ] [
69         initial-step
70         [ wrap-step ] reduce
71         min-cost
72         post-process
73     ] if-empty ;