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 : if-one-line ( paragraph true false -- )
20 [ dup lines>> 1list? ] 2dip if ; inline
22 TYPED: top-fits? ( paragraph: paragraph -- ? )
24 [ [ line-ideal>> ] [ line-max>> ] if-one-line ] bi <= ; inline
26 TYPED: fits? ( paragraph: paragraph -- ? )
27 ! Make this not count spaces at end
28 { [ lines>> car 1list? ] [ top-fits? ] } 1|| ; inline
30 TYPED: paragraph-cost ( paragraph: paragraph -- cost )
32 [ head-width>> ] [ line-ideal>> - sq ] [ tail-cost>> ] tri +
33 ] if-one-line ; inline
35 : min-cost ( paragraphs -- paragraph )
36 [ paragraph-cost ] infimum-by ; inline
38 TYPED: new-line ( paragraph: paragraph element: element -- paragraph )
40 [ drop [ line-max>> ] [ line-ideal>> ] bi ]
41 [ [ lines>> ] [ 1list ] bi* swons ]
43 [ drop paragraph-cost ]
44 } 2cleave <paragraph> ; inline
46 TYPED: add-element ( paragraph: paragraph element: element -- )
47 [ '[ _ element-length + ] change-head-width ]
48 [ '[ unswons _ swons swons ] change-lines ] bi drop ; inline
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
56 : 1paragraph ( line-max line-ideal element -- paragraph )
57 [ 1list 1list ] [ black>> ] bi 0 <paragraph> ;
59 : post-process ( paragraph -- array )
60 lines>> [ [ contents>> ] lmap>array ] lmap>array ;
62 : initial-step ( line-max line-ideal elements -- elements paragraph )
63 reverse unclip [ -rot ] dip 1paragraph 1array ;
67 : wrap ( elements line-max line-ideal -- array )