factor/basis/wrap/wrap.factor

74 lines
2.3 KiB
Factor
Raw Normal View History

! Copyright (C) 2009 Daniel Ehrenberg
! See http://factorcode.org/license.txt for BSD license.
2012-08-29 12:20:55 -04:00
USING: accessors arrays combinators combinators.short-circuit
2012-09-19 20:08:41 -04:00
fry kernel kernel.private lists locals math sequences typed ;
2008-01-31 12:51:38 -05:00
IN: wrap
! black is the text length, white is the whitespace length
TUPLE: element contents black white ;
C: <element> element
2012-08-29 12:20:55 -04:00
<PRIVATE
2012-09-19 20:08:41 -04:00
: element-length ( element -- n )
[ black>> ] [ white>> ] bi + ; inline
TUPLE: paragraph line-max line-ideal lines head-width tail-cost ;
C: <paragraph> paragraph
2015-07-20 15:25:30 -04:00
: if-one-line ( paragraph true false -- )
[ dup lines>> 1list? ] 2dip if ; inline
2012-08-29 12:20:55 -04:00
TYPED: top-fits? ( paragraph: paragraph -- ? )
[ head-width>> ]
2015-07-20 15:25:30 -04:00
[ [ line-ideal>> ] [ line-max>> ] if-one-line ] bi <= ; inline
2012-08-29 12:20:55 -04:00
TYPED: fits? ( paragraph: paragraph -- ? )
! Make this not count spaces at end
2012-09-19 20:08:41 -04:00
{ [ lines>> car 1list? ] [ top-fits? ] } 1|| ; inline
2012-08-29 12:20:55 -04:00
TYPED: paragraph-cost ( paragraph: paragraph -- cost )
2015-07-20 15:25:30 -04:00
[ drop 0 ] [
[ head-width>> ] [ line-ideal>> - sq ] [ tail-cost>> ] tri +
] if-one-line ; inline
: min-cost ( paragraphs -- paragraph )
[ paragraph-cost ] infimum-by ; inline
2012-09-19 20:08:41 -04:00
TYPED: new-line ( paragraph: paragraph element: element -- paragraph )
{
[ drop [ line-max>> ] [ line-ideal>> ] bi ]
[ [ lines>> ] [ 1list ] bi* swons ]
[ nip black>> ]
[ drop paragraph-cost ]
2012-09-19 20:08:41 -04:00
} 2cleave <paragraph> ; inline
2008-01-31 12:51:38 -05:00
2012-08-29 12:20:55 -04:00
TYPED: add-element ( paragraph: paragraph element: element -- )
2015-07-20 15:25:30 -04:00
[ '[ _ element-length + ] change-head-width ]
[ '[ unswons _ swons swons ] change-lines ] bi drop ; inline
2008-01-31 12:51:38 -05:00
2012-09-19 20:08:41 -04:00
TYPED: wrap-step ( paragraphs: array element: element -- paragraphs )
[ [ min-cost ] dip new-line ]
2012-08-29 12:20:55 -04:00
[ dupd '[ _ add-element ] each ]
2012-09-19 20:08:41 -04:00
2bi swap prefix { array } declare
2015-07-20 15:25:30 -04:00
[ fits? ] filter ; inline
: 1paragraph ( line-max line-ideal element -- paragraph )
[ 1list 1list ] [ black>> ] bi 0 <paragraph> ;
2009-02-03 23:12:04 -05:00
: post-process ( paragraph -- array )
2009-05-16 14:34:39 -04:00
lines>> [ [ contents>> ] lmap>array ] lmap>array ;
2008-01-31 12:51:38 -05:00
2015-07-20 15:25:30 -04:00
: initial-step ( line-max line-ideal elements -- elements paragraph )
2012-08-29 12:20:55 -04:00
reverse unclip [ -rot ] dip 1paragraph 1array ;
PRIVATE>
2012-08-29 12:20:55 -04:00
: wrap ( elements line-max line-ideal -- array )
rot [ 2drop { } ] [
2015-07-20 15:25:30 -04:00
initial-step
[ wrap-step ] reduce
min-cost
post-process
] if-empty ;