summaryrefslogtreecommitdiff
path: root/src/Graphics/Fountainhead/Dumper.hs
blob: 647f159df0b5f8773cc614e7815c496169eb2093 (plain)
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
{- This Source Code Form is subject to the terms of the Mozilla Public License,
   v. 2.0. If a copy of the MPL was not distributed with this file, You can
   obtain one at https://mozilla.org/MPL/2.0/. -}

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE LambdaCase #-}

-- | Outputs information about a font as text.
module Graphics.Fountainhead.Dumper
    ( DumpError(..)
    , dumpCmap
    , dumpHead
    , dumpHmtx
    , dumpHhea
    , dumpLoca
    , dumpTrueType
    , dumpOffsetTable
    ) where

import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as Char8
import Data.Int (Int64)
import Data.Word (Word16, Word32)
import qualified Data.IntMap as IntMap
import qualified Data.Text.Encoding as Text
import qualified Data.Text.Lazy as Text.Lazy
import qualified Data.Text.Lazy.Builder as Text.Builder
import qualified Data.Text.Lazy.Builder.Int as Text.Builder
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Data.Void
import GHC.Records (HasField(..))
import Graphics.Fountainhead.TrueType
    ( CmapTable(..)
    , FontDirectory(..)
    , FontDirectionHint(..)
    , HeadTable(..)
    , HheaTable(..)
    , HmtxTable(..)
    , OffsetSubtable(..)
    , TableDirectory(..)
    , CmapEncoding(..)
    , CmapSubtable(..)
    , CmapFormat4Table(..)
    , FontStyle(..)
    , LongHorMetric(..)
    , LocaTable(..)
    , IndexToLocFormat(..)
    )
import qualified Text.Megaparsec as Megaparsec
import Graphics.Fountainhead.Parser
    ( fontDirectoryP
    , parseTable
    , cmapTableP
    , headTableP
    , hheaTableP
    , hmtxTableP
    , locaTableP
    )
import Graphics.Fountainhead.Type (Fixed32(..), ttfEpoch)
import Data.Foldable (Foldable(..), find)
import Data.Maybe (fromMaybe)
import Data.Time (LocalTime(..), NominalDiffTime, diffLocalTime, midnight)
import Data.Bits (Bits(..))
import Data.Bifunctor (Bifunctor(first))

data DumpError
    = DumpParseError (Megaparsec.ParseErrorBundle ByteString Void)
    | DumpRequiredTableMissingError String

data RequiredTables = RequiredTables
    { hheaTable :: HheaTable
    , headTable :: HeadTable
    } deriving (Eq, Show)

paddedHexadecimal :: Integral a => a -> Text.Builder.Builder
paddedHexadecimal = ("0x" <>)
    . Text.Builder.fromLazyText
    . Text.Lazy.justifyRight 8 '0'
    . Text.Builder.toLazyText
    . Text.Builder.hexadecimal

halfPaddedHexadecimal :: Integral a => a -> Text.Builder.Builder
halfPaddedHexadecimal = Text.Builder.fromLazyText
    . Text.Lazy.justifyRight 4 '0'
    . Text.Builder.toLazyText
    . Text.Builder.hexadecimal

justifyNumber :: Integral a => Int64 -> a -> Text.Builder.Builder
justifyNumber count = Text.Builder.fromLazyText
    . Text.Lazy.justifyRight count ' '
    . Text.Builder.toLazyText
    . Text.Builder.decimal

newlineBuilder :: Text.Builder.Builder
newlineBuilder = Text.Builder.singleton '\n'

dumpCaption :: String -> Text.Builder.Builder
dumpCaption headline = Text.Builder.fromString headline
    <> newlineBuilder
    <> Text.Builder.fromLazyText (Text.Lazy.replicate headlineLength "-")
    <> newlineBuilder
  where
    headlineLength = fromIntegral $ Prelude.length headline

dumpOffsetTable :: FontDirectory -> Text.Builder.Builder
dumpOffsetTable directory
    = dumpCaption "Offset Table"
    <> "         sfnt version:           1.0\n         number of tables: "
    <> Text.Builder.decimal (numTables $ offsetSubtable directory)
    <> newlineBuilder
    <> dumpOffsetSummary (tableDirectory directory)
  where
    dumpOffsetSummary = mconcat . fmap dumpOffsetRow . zip [0 :: Int ..]
    dumpOffsetRow (index, table) = justifyNumber 4 index
        <> ". '"
        <> Text.Builder.fromText (Text.decodeASCII $ tag table)
        <> "' - checksum = "
        <> paddedHexadecimal (getField @"checkSum" table)
        <> ", offset = "
        <> paddedHexadecimal (getField @"offset" table)
        <> ", len = "
        <> justifyNumber 9 (getField @"length" table)
        <> newlineBuilder

dumpFixed32 :: Fixed32 -> Text.Builder.Builder
dumpFixed32 (Fixed32 word)
    = Text.Builder.decimal (shiftR word 16)
    <> Text.Builder.singleton '.'
    <> Text.Builder.decimal (word .&. 0xff00)

dumpHmtx :: HmtxTable -> Text.Builder.Builder
dumpHmtx HmtxTable{..} =
    let caption = dumpCaption "'hmtx' Table - Horizontal Metrics"
        lastAccumulator = foldl' dumpHMetric (0 :: Int, caption) hMetrics
     in snd $ foldl' dumpLeftSideBear lastAccumulator leftSideBearing
  where
    dumpLeftSideBear (index, accumulator) leftSideBearing' =
        let withNewLine = dumpIndex index <> ". LSbear: "
                <> justifyNumber 4 leftSideBearing' <> newlineBuilder
         in (succ index, accumulator <> withNewLine)
    dumpHMetric (index, accumulator) metric =
        let LongHorMetric{ leftSideBearing = leftSideBearing', ..} = metric
            withNewLine = dumpIndex index <> ". advWid: "
                <> justifyNumber 4 advanceWidth <> ",  LSBear: "
                <> justifyNumber 4 leftSideBearing' <> newlineBuilder
         in (succ index, accumulator <> withNewLine)
    dumpIndex = justifyNumber 12

dumpHhea :: HheaTable -> Text.Builder.Builder
dumpHhea HheaTable{..}
    = dumpCaption "'hhea' Table - Horizontal Header"
    <> "         'hhea' version:         " <> dumpFixed32 version <> newlineBuilder
    <> "         yAscender:              " <> Text.Builder.decimal ascent <> newlineBuilder
    <> "         yDescender:             " <> Text.Builder.decimal descent <> newlineBuilder
    <> "         yLineGap:               " <> Text.Builder.decimal lineGap <> newlineBuilder
    <> "         advanceWidthMax:        " <> Text.Builder.decimal advanceWidthMax <> newlineBuilder
    <> "         minLeftSideBearing:     " <> Text.Builder.decimal minLeftSideBearing <> newlineBuilder
    <> "         minRightSideBearing:    " <> Text.Builder.decimal minRightSideBearing <> newlineBuilder
    <> "         xMaxExtent:             " <> Text.Builder.decimal xMaxExtent <> newlineBuilder
    <> "         caretSlopeRise:         " <> Text.Builder.decimal caretSlopeRise <> newlineBuilder
    <> "         caretSlopeRun:          " <> Text.Builder.decimal caretSlopeRun <> newlineBuilder
    <> "         reserved0:              0" <> newlineBuilder
    <> "         reserved1:              0" <> newlineBuilder
    <> "         reserved2:              0" <> newlineBuilder
    <> "         reserved3:              0" <> newlineBuilder
    <> "         reserved4:              0" <> newlineBuilder
    <> "         metricDataFormat:       " <> Text.Builder.decimal metricDataFormat <> newlineBuilder
    <> "         numberOfHMetrics:       " <> Text.Builder.decimal numOfLongHorMetrics <> newlineBuilder

dumpHead :: HeadTable -> Text.Builder.Builder
dumpHead HeadTable{..}
    = dumpCaption "'head' Table - Font Header"
    <> "         head version:           " <> dumpFixed32 version <> newlineBuilder
    <> "         fontRevision:           " <> dumpFixed32 fontRevision <> newlineBuilder
    <> "         checkSumAdjustment:     " <> paddedHexadecimal checkSumAdjustment <> newlineBuilder
    <> "         magicNumber:            " <> paddedHexadecimal magicNumber <> newlineBuilder
    <> "         flags:                  0x" <> halfPaddedHexadecimal flags <> newlineBuilder
    <> "         unitsPerEm:             " <> Text.Builder.decimal unitsPerEm <> newlineBuilder
    <> "         created:                " <> "0x" <> longDateTime created <> newlineBuilder
    <> "         modified:               " <> "0x" <> longDateTime modified <> newlineBuilder
    <> "         xMin:                   " <> Text.Builder.decimal xMin <> newlineBuilder
    <> "         yMin:                   " <> Text.Builder.decimal yMin <> newlineBuilder
    <> "         xMax:                   " <> Text.Builder.decimal xMax <> newlineBuilder
    <> "         yMax:                   " <> Text.Builder.decimal yMax <> newlineBuilder
    <> "         macStyle bits:          " <> "0x" <> dumpFontStyle macStyle <> newlineBuilder
    <> "         lowestRecPPEM           " <> Text.Builder.decimal lowestRecPPEM <> newlineBuilder
    <> "         fontDirectionHint       " <> dumpFontDirectionHint fontDirectionHint <> newlineBuilder
    <> "         indexToLocFormat        " <> dumpIndexToLocFormat indexToLocFormat <> newlineBuilder
    <> "         glyphDataFormat         " <> Text.Builder.decimal glyphDataFormat <> newlineBuilder

dumpIndexToLocFormat :: IndexToLocFormat -> Text.Builder.Builder
dumpIndexToLocFormat ShortOffsetIndexToLocFormat = "0"
dumpIndexToLocFormat LongOffsetIndexToLocFormat = "1"

dumpFontDirectionHint :: FontDirectionHint -> Text.Builder.Builder
dumpFontDirectionHint = \case
    MixedDirectionalGlyphs -> "0"
    StronglyLeftToRightGlyphs -> "1"
    LeftToRightGlyphsWithNeutrals -> "2"
    StronglyRightToLeftGlyphs -> "-1"
    RightToLeftGlyphsWithNeutrals -> "-2"

dumpFontStyle :: FontStyle -> Text.Builder.Builder
dumpFontStyle FontStyle{..} = halfPaddedHexadecimal
    $ foldr (go . fst) (zeroBits :: Int)
    $ filter snd
    $ zip [0..] [bold, italic, underline, outline, shadow, condensed, extended]
  where
    go bitNumber accumulator = setBit accumulator bitNumber

longDateTime :: LocalTime -> Text.Builder.Builder
longDateTime localTime = Text.Builder.fromLazyText
    $ Text.Lazy.justifyRight 16 '0'
    $ Text.Builder.toLazyText
    $ Text.Builder.hexadecimal
    $ (truncate :: NominalDiffTime -> Int)
    $ diffLocalTime localTime (LocalTime ttfEpoch midnight)

dumpCmap :: CmapTable -> Text.Builder.Builder
dumpCmap CmapTable{..}
    = dumpCaption "'cmap' Table - Character to Glyph Index Mapping Table"
    <> "        'cmap' version: " <> Text.Builder.decimal version <> newlineBuilder
    <> "        number of encodings: " <> Text.Builder.decimal encodingsLength <> newlineBuilder
    <> "        number of subtables: " <> Text.Builder.decimal (Prelude.length subtables) <> newlineBuilder
    <> newlineBuilder
    <> snd (foldr dumpCmapEncoding (pred encodingsLength, "") encodings) <> newlineBuilder
    <> snd (foldr dumpCmapSubTable (pred subTablesLength, "") subtables) <> newlineBuilder
  where
    encodingsLength = Prelude.length encodings
    subTablesLength = IntMap.size subtables
    dumpCmapEncoding CmapEncoding{..} (index, accumulator) =
        let findSubTableIndex = Text.Builder.decimal
                . Prelude.length
                . filter ((< offset) . fromIntegral)
                . IntMap.keys
            summary = "Encoding   " <> Text.Builder.decimal index
                <> ".    PlatformID:  " <> Text.Builder.decimal platformID <> newlineBuilder
                <> "                 EcodingID:   " <> Text.Builder.decimal platformSpecificID <> newlineBuilder
                <> "                 SubTable: " <> findSubTableIndex subtables
                <> ", Offset: " <> paddedHexadecimal offset <> newlineBuilder
         in (pred index, summary <> newlineBuilder <> accumulator)
    dumpCmapSubTable currentSubTable (index, accumulator) =
        let contents = "SubTable   " <> Text.Builder.decimal index
                <> ".    " <> dumpCmapSubTableFormat currentSubTable
         in (pred index, contents <> accumulator)
    dumpCmapSubTableFormat = \case
        (CmapFormat0 _) -> "Format 0"
        (CmapFormat2 _) -> "Format 2"
        (CmapFormat4 CmapFormat4Table{..}) ->
            let segCount = Vector.length startCode
                dumpSegment' = dumpSegment segCount glyphIndexArray
             in "Format 4 - Segment mapping to delta values\n\
                \                 Length:     994\n\
                \                 Version:      0\n\
                \                 segCount:       "
                <> Text.Builder.decimal segCount
                <> newlineBuilder <> "                 searchRange:    "
                <> Text.Builder.decimal searchRange
                <> newlineBuilder <> "                 entrySelector:  "
                <> Text.Builder.decimal entrySelector
                <> newlineBuilder <> "                 rangeShift:     "
                <> Text.Builder.decimal (segCount * 2 - fromIntegral searchRange)
                <> newlineBuilder
                <> fold (Vector.izipWith4 (dumpSegmentSummary segCount) startCode endCode idDelta idRangeOffset)
                <> "                 Number of glyphIndex "
                <> Text.Builder.decimal (Vector.length glyphIndexArray) <> newlineBuilder
                <> fold (Vector.imap dumpGlyphAtIndex glyphIndexArray)
                <> fold (Vector.izipWith4 dumpSegment' startCode endCode idDelta idRangeOffset)
        (CmapFormat6 _) -> "Format 6"
        (CmapFormat8 _) -> "Format 8"
        (CmapFormat10 _) -> "Format 10"
        (CmapFormat12 _) -> "Format 12"
        (CmapFormat13 _) -> "Format 13"
        (CmapFormat14 _) -> "Format 14"
    dumpSegment :: Int -> Vector Word16 -> Int -> Word16 -> Word16 -> Word16 -> Word16 -> Text.Builder.Builder
    dumpSegment segCount glyphIndexArray' segmentIndex startCode' endCode' idDelta' idRangeOffset' =
        let charRange = [startCode'..endCode']
            dumpSegmentCharIndex' =
                dumpSegmentCharIndex segCount glyphIndexArray' segmentIndex idDelta' idRangeOffset' startCode'
         in "Segment " <> Text.Builder.decimal segmentIndex <> ":\n"
            <> foldMap dumpSegmentCharIndex' charRange
    dumpSegmentCharIndex segCount glyphIndexArray' segmentIndex idDelta' idRangeOffset' startCode' charCode =
        let calculateGlyphIndex' =
                calculateGlyphIndex charCode segmentIndex segCount glyphIndexArray' idRangeOffset' idDelta' startCode'
         in "                 Char 0x"
            <> halfPaddedHexadecimal charCode <> " -> Index "
            <> Text.Builder.decimal calculateGlyphIndex'
            <> newlineBuilder
    dumpSegmentSummary segCount index startCode' endCode' idDelta' idRangeOffset'
        = "                 Seg " <> justifyNumber 5 index
        <> " : St = " <> halfPaddedHexadecimal startCode'
        <> ", En = " <> halfPaddedHexadecimal endCode'
        <> ", D = " <> justifyNumber 6 idDelta'
        <> ", RO = " <> justifyNumber 6 idRangeOffset'
        <> ", gId# = " <> dumpGlyphId index segCount idRangeOffset'
        <> newlineBuilder
    dumpGlyphId segmentIndex segCount idRangeOffset'
        = maybe "N/A" Text.Builder.decimal
        $ calculateGlyphId segmentIndex segCount idRangeOffset'
    calculateGlyphIndex :: Word16 -> Int -> Int -> Vector Word16 -> Word16 -> Word16 -> Word16 -> Int
    calculateGlyphIndex c segmentIndex segCount glyphIndexArray' idRangeOffset' idDelta' startCode' =
        let defaultIndex = fromIntegral $ c + idDelta'
            addOffset = fromIntegral
                . fromMaybe 0
                . (glyphIndexArray' Vector.!?)
                . (+ fromIntegral (c - startCode'))
         in maybe defaultIndex addOffset
            $ calculateGlyphId segmentIndex segCount idRangeOffset'
    calculateGlyphId segmentIndex segCount idRangeOffset'
        | idRangeOffset' == 0 = Nothing
        | otherwise = Just $ segmentIndex - segCount + (fromIntegral idRangeOffset' `div` 2)
    dumpGlyphAtIndex index element = "                 glyphIdArray[" <> Text.Builder.decimal index <> "] =  "
        <> Text.Builder.decimal element <> newlineBuilder

dumpLoca :: LocaTable -> Text.Builder.Builder
dumpLoca table =
    dumpCaption "'loca' Table - Index to Location"
    <> go table
  where
    go (LongLocaTable elements) = dumpElements elements
    go (ShortLocaTable elements) = dumpElements
        $ (* 2)
        . (fromIntegral :: Word16 -> Word32)
        <$> elements
    dumpElements elements =
        case Vector.unsnoc elements of
            Just (init', last')
                -> foldMap dumpLocaLine (Vector.indexed init')
                <> "         Ended at " <> paddedHexadecimal last'
            Nothing -> mempty
    dumpLocaLine :: Integral a => (Int, a) -> Text.Builder.Builder
    dumpLocaLine (index, element)
        = "         Idx " <> justifyNumber 6 index
        <> " -> GlyphOffset " <> paddedHexadecimal element <> newlineBuilder

dumpTables
    :: Megaparsec.State ByteString Void
    -> FontDirectory
    -> Either DumpError Text.Builder.Builder
dumpTables processedState directory@FontDirectory{..}
    = parseRequired >>= traverseDirectory
  where
    traverseDirectory parsedRequired =
        let initial = Right $ dumpOffsetTable directory
         in foldl' (go parsedRequired) initial tableDirectory
    parseRequired = RequiredTables
        <$> findRequired "hhea" hheaTableP
        <*> findRequired "head" headTableP
    findRequired tableName parser = 
        let missingError = Left $ DumpRequiredTableMissingError tableName
            parseFound tableEntry = parseTable tableEntry parser processedState
         in maybe missingError (first DumpParseError . parseFound)
            $ find ((== Char8.pack tableName) . getField @"tag") tableDirectory
    go _ (Left accumulator) _ = Left accumulator
    go parsedRequired (Right accumulator) tableEntry
        = maybe (Right accumulator) (concatDump accumulator . first DumpParseError)
        $ dumpSubTable parsedRequired tableEntry
    concatDump accumulator builderDump = ((accumulator <> newlineBuilder) <>)
        <$> builderDump
    dumpSubTable RequiredTables{..} tableEntry =
        case getField @"tag" tableEntry of
            "cmap" -> Just $ dumpCmap <$> parseTable tableEntry cmapTableP processedState
            "head" -> Just $ Right $ dumpHead headTable
            "hhea" -> Just $ Right $ dumpHhea hheaTable
            "hmtx" -> Just $ dumpHmtx
                <$> parseTable tableEntry (hmtxTableP $ getField @"numOfLongHorMetrics" hheaTable) processedState
            "loca" -> Just $ dumpLoca
                <$> parseTable tableEntry (locaTableP $ getField @"indexToLocFormat" headTable) processedState
            _ -> Nothing

dumpTrueType :: ByteString -> FilePath -> Either DumpError Text.Builder.Builder
dumpTrueType ttfContents fontFile =
    let initialState = Megaparsec.State
            { stateInput = ttfContents
            , stateOffset = 0
            , statePosState = Megaparsec.PosState
                { pstateInput = ttfContents
                , pstateOffset = 0
                , pstateSourcePos = Megaparsec.initialPos fontFile
                , pstateTabWidth = Megaparsec.defaultTabWidth
                , pstateLinePrefix = ""
                }
            , stateParseErrors = []
            }
        (processedState, initialResult) = Megaparsec.runParser' fontDirectoryP initialState 

     in first DumpParseError initialResult >>= dumpTables processedState