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
|
{-# LANGUAGE OverloadedStrings #-}
module TextViewport
( Item(..)
, Buffer(..)
, WrapStrategy(..)
, RenderedLine(..)
, RenderedBuffer
, renderBuffer
, flatten
, modifyItem
, updateRenderedItem
, Viewport(..)
, defaultViewport
, scrollUp
, scrollDown
, visibleLines
, lookupPosition
) where
import Data.List (minimumBy)
import Data.Ord (comparing)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Text.Hyphenation as H
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Foldable as F
--------------------------------------------------------------------------------
-- Logical model
--------------------------------------------------------------------------------
data WrapStrategy
= NoWrap
| FixedWidthWrap
| HyphenateWrap H.Hyphenator
data Item = Item
{ itemText :: Text
, itemWrap :: WrapStrategy
}
newtype Buffer = Buffer { unBuffer :: Seq Item }
modifyItem :: Int -> (Item -> Item) -> Buffer -> Buffer
modifyItem ix f (Buffer xs) =
Buffer (Seq.adjust' f ix xs)
--------------------------------------------------------------------------------
-- Rendering with provenance
--------------------------------------------------------------------------------
data RenderedLine = RenderedLine
{ rlText :: !Text
, rlItemIx :: !Int
, rlLineIx :: !Int
, rlCharStart :: !Int
} deriving (Show)
type RenderedBuffer = Seq [RenderedLine]
flatten :: RenderedBuffer -> [RenderedLine]
flatten = concat . F.toList
renderBuffer :: Int -> Buffer -> RenderedBuffer
renderBuffer width (Buffer items) =
let itemsList = F.toList items
blocks = zipWith (renderItem width) [0..] itemsList
in Seq.fromList blocks
renderItem :: Int -> Int -> Item -> [RenderedLine]
renderItem width itemIx (Item txt strategy) =
zipWith mkLine [0..] (applyStrategy strategy width txt)
where
mkLine logicalIx (off, chunk) =
RenderedLine
{ rlText = chunk
, rlItemIx = itemIx
, rlLineIx = logicalIx
, rlCharStart = off
}
--------------------------------------------------------------------------------
-- Wrapping strategies
--------------------------------------------------------------------------------
applyStrategy :: WrapStrategy -> Int -> Text -> [(Int, Text)]
applyStrategy NoWrap w t =
[(0, T.take w t)]
applyStrategy FixedWidthWrap w t =
zip [0,w..] (chunkFixed w t)
applyStrategy (HyphenateWrap dict) w t =
hyphenateWrapped dict w t
chunkFixed :: Int -> Text -> [Text]
chunkFixed w t
| T.null t = [""]
| otherwise = go t
where
go s
| T.null s = []
| otherwise =
let (c, r) = T.splitAt w s
in c : go r
--------------------------------------------------------------------------------
-- Hyphenation-aware wrapping (TeX-lite)
--------------------------------------------------------------------------------
hyphenateWrapped :: H.Hyphenator -> Int -> Text -> [(Int, Text)]
hyphenateWrapped dict w txt =
let chunks = wrapWithHyphenationTeXLite dict w txt
offsets = scanOffsets chunks
in zip offsets chunks
scanOffsets :: [Text] -> [Int]
scanOffsets [] = []
scanOffsets (x:xs) = 0 : go (T.length x) xs
where
go _ [] = []
go acc (y:ys) = acc : go (acc + T.length y) ys
wrapWithHyphenationTeXLite :: H.Hyphenator -> Int -> Text -> [Text]
wrapWithHyphenationTeXLite dict width txt =
go (T.words txt)
where
go [] = []
go ws =
case lineCandidates dict width ws of
[] -> [T.unwords ws] -- fallback: everything on one line
cs ->
let (line, rest, _) =
minimumBy (comparing (scoreCandidate width)) cs
in line : go rest
type Candidate = (Text, [Text], Bool)
lineCandidates :: H.Hyphenator -> Int -> [Text] -> [Candidate]
lineCandidates dict width = go [] []
where
go :: [Text] -> [Candidate] -> [Text] -> [Candidate]
go _ acc [] = acc
go line acc (w:ws) =
let space = if null line then "" else " "
baseTxt = T.unwords line
-- whole word candidate (no hyphen)
wholeTxt = baseTxt <> space <> w
wholeLen = T.length wholeTxt
acc' =
if wholeLen <= width && not (T.null wholeTxt)
then (wholeTxt, ws, False) : acc
else acc
-- hyphenation candidates for this word
hyphs = hyphenateWord dict w
hyphCands =
[ let preTxt = baseTxt <> space <> pre <> "-"
preLen = T.length preTxt
in (preTxt, suf : ws, True)
| (pre, suf) <- hyphs
, not (T.null pre)
, let preTxt = baseTxt <> space <> pre <> "-"
, let preLen = T.length preTxt
, preLen <= width
]
acc'' = hyphCands ++ acc'
in if wholeLen <= width
then go (line ++ [w]) acc'' ws
else acc''
hyphenateWord :: H.Hyphenator -> Text -> [(Text, Text)]
hyphenateWord dict word =
let parts = H.hyphenate dict (T.unpack word)
in [ ( T.pack (concat (take i parts))
, T.pack (concat (drop i parts))
)
| i <- [1 .. length parts - 1]
]
scoreCandidate :: Int -> Candidate -> Int
scoreCandidate width (line, _, endsWithHyphen) =
let len = T.length line
remSpace = max 0 (width - len)
badness = remSpace * remSpace * remSpace
hyphenPenalty =
if endsWithHyphen then 50 else 0
shortPenalty =
if len < width `div` 2 then 200 else 0
in badness + hyphenPenalty + shortPenalty
--------------------------------------------------------------------------------
-- Incremental re-rendering
--------------------------------------------------------------------------------
updateRenderedItem :: Int -> Int -> Buffer -> RenderedBuffer -> RenderedBuffer
updateRenderedItem width itemIx (Buffer items) rb =
let item = Seq.index items itemIx
newBlock = renderItem width itemIx item
in Seq.update itemIx newBlock rb
--------------------------------------------------------------------------------
-- Viewport
--------------------------------------------------------------------------------
data Viewport = Viewport
{ vpWidth :: !Int
, vpHeight :: !Int
, vpOffset :: !Int
} deriving (Show)
defaultViewport :: Int -> Int -> [RenderedLine] -> Viewport
defaultViewport w h rendered =
let total = length rendered
off = max 0 (total - h)
in Viewport w h off
scrollUp :: Int -> Viewport -> Viewport
scrollUp k vp =
vp { vpOffset = max 0 (vpOffset vp - k) }
scrollDown :: Int -> [RenderedLine] -> Viewport -> Viewport
scrollDown k rendered vp =
let total = length rendered
maxOff = max 0 (total - vpHeight vp)
newOff = min maxOff (vpOffset vp + k)
in vp { vpOffset = newOff }
visibleLines :: [RenderedLine] -> Viewport -> [RenderedLine]
visibleLines rendered vp =
take (vpHeight vp) . drop (vpOffset vp) $ rendered
--------------------------------------------------------------------------------
-- Coordinate lookup
--------------------------------------------------------------------------------
lookupPosition
:: Int
-> Int
-> Viewport
-> [RenderedLine]
-> Maybe (Int, Int)
lookupPosition x y vp rendered = do
let lineIx = vpOffset vp + y
rl <- renderedAt lineIx rendered
pure (rlItemIx rl, rlCharStart rl + x)
where
renderedAt ix rs
| ix < 0 || ix >= length rs = Nothing
| otherwise = Just (rs !! ix)
|