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 ;
7 ! black is the text length, white is the whitespace length
8 TUPLE: element contents black white ;
13 : element-length ( element -- n )
14 [ black>> ] [ white>> ] bi + ; inline
16 TUPLE: paragraph line-max line-ideal lines head-width tail-cost ;
17 C: <paragraph> paragraph
19 TYPED: top-fits? ( paragraph: paragraph -- ? )
21 [ dup lines>> 1list? [ line-ideal>> ] [ line-max>> ] if ] bi <= ; inline
23 TYPED: fits? ( paragraph: paragraph -- ? )
24 ! Make this not count spaces at end
25 { [ lines>> car 1list? ] [ top-fits? ] } 1|| ; inline
27 TYPED: paragraph-cost ( paragraph: paragraph -- cost )
28 dup lines>> 1list? [ drop 0 ] [
29 [ [ head-width>> ] [ line-ideal>> ] bi - sq ]
33 : min-cost ( paragraphs -- paragraph )
34 [ paragraph-cost ] infimum-by ; inline
36 TYPED: new-line ( paragraph: paragraph element: element -- paragraph )
38 [ drop [ line-max>> ] [ line-ideal>> ] bi ]
39 [ [ lines>> ] [ 1list ] bi* swons ]
41 [ drop paragraph-cost ]
42 } 2cleave <paragraph> ; inline
44 TYPED: add-element ( paragraph: paragraph element: element -- )
45 [ element-length [ + ] curry change-head-width ]
46 [ [ [ unswons ] dip swons swons ] curry change-lines ]
49 TYPED: wrap-step ( paragraphs: array element: element -- paragraphs )
50 [ [ min-cost ] dip new-line ]
51 [ dupd '[ _ add-element ] each ]
52 2bi swap prefix { array } declare
55 : 1paragraph ( line-max line-ideal element -- paragraph )
56 [ 1list 1list ] [ black>> ] bi 0 <paragraph> ;
58 : post-process ( paragraph -- array )
59 lines>> [ [ contents>> ] lmap>array ] lmap>array ;
61 : initialize ( line-max line-ideal elements -- elements paragraph )
62 reverse unclip [ -rot ] dip 1paragraph 1array ;
66 : wrap ( elements line-max line-ideal -- array )