-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathOutput.hs
2844 lines (2587 loc) · 117 KB
/
Output.hs
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{- |
Module : Text.Pandoc.Writers.Powerpoint.Output
Copyright : Copyright (C) 2017-2020 Jesse Rosenthal
License : GNU GPL, version 2 or above
Maintainer : Jesse Rosenthal <jrosenthal@jhu.edu>
Stability : alpha
Portability : portable
Conversion of Presentation datatype (defined in
Text.Pandoc.Writers.Powerpoint.Presentation) to a zip archive.
-}
module Text.Pandoc.Writers.Powerpoint.Output ( presentationToArchive
) where
import Control.Monad ( MonadPlus(mplus), foldM, unless )
import Control.Monad.Except (throwError, catchError)
import Control.Monad.Reader
( asks, MonadReader(local), ReaderT(runReaderT) )
import Control.Monad.State
( StateT, gets, modify, evalStateT )
import Codec.Archive.Zip
import Data.List (intercalate, stripPrefix, nub, union, isPrefixOf, intersperse)
import Data.Bifunctor (bimap)
import Data.CaseInsensitive (CI)
import qualified Data.CaseInsensitive as CI
import Data.Default
import Data.Foldable (toList)
import Data.List.NonEmpty (nonEmpty, NonEmpty ((:|)))
import Data.Ratio ((%), Ratio)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Read (decimal)
import Data.Time (formatTime, defaultTimeLocale)
import Data.Time.Clock (UTCTime)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds, posixSecondsToUTCTime)
import Data.Traversable (for)
import System.FilePath.Posix (splitDirectories, splitExtension, takeExtension, takeFileName)
import Text.Pandoc.XML.Light as XML
import Text.Pandoc.Definition
import qualified Text.Pandoc.UTF8 as UTF8
import Text.Pandoc.Class.PandocMonad (PandocMonad)
import Text.Pandoc.Error (PandocError(..))
import qualified Text.Pandoc.Class.PandocMonad as P
import Text.Pandoc.Data (readDataFile, readDefaultDataFile)
import Text.Pandoc.Options
import Text.Pandoc.MIME
import qualified Data.ByteString.Lazy as BL
import Text.Pandoc.Writers.Shared (metaToContext)
import Text.Pandoc.Writers.OOXML
import qualified Data.Map as M
import Data.Maybe (mapMaybe, listToMaybe, fromMaybe, maybeToList, catMaybes, isJust)
import Text.Pandoc.ImageSize
import Control.Applicative ((<|>))
import System.FilePath.Glob
import Text.DocTemplates (FromContext(lookupContext), Context)
import Text.DocLayout (literal)
import Text.TeXMath
import Text.Pandoc.Logging (LogMessage(PowerpointTemplateWarning))
import Text.Pandoc.Writers.Math (convertMath)
import Text.Pandoc.Writers.Powerpoint.Presentation
import Text.Pandoc.Shared (tshow, stringify)
import Skylighting (fromColor)
-- |The 'EMU' type is used to specify sizes in English Metric Units.
type EMU = Integer
-- |The 'pixelsToEmu' function converts a size in pixels to one
-- in English Metric Units. It assumes a DPI of 72.
pixelsToEmu :: Pixels -> EMU
pixelsToEmu = (12700 *)
-- This populates the global ids map with images already in the
-- template, so the ids won't be used by images introduced by the
-- user.
initialGlobalIds :: Archive -> Archive -> M.Map FilePath Int
initialGlobalIds refArchive distArchive =
let archiveFiles = filesInArchive refArchive `union` filesInArchive distArchive
mediaPaths = filter (isPrefixOf "ppt/media/image") archiveFiles
go :: FilePath -> Maybe (FilePath, Int)
go fp = do
s <- stripPrefix "ppt/media/image" $ fst $ splitExtension fp
(n, _) <- listToMaybe $ reads s
return (fp, n)
in
M.fromList $ mapMaybe go mediaPaths
getPresentationSize :: Archive -> Archive -> Maybe (Integer, Integer)
getPresentationSize refArchive distArchive = do
entry <- findEntryByPath "ppt/presentation.xml" refArchive `mplus`
findEntryByPath "ppt/presentation.xml" distArchive
presElement <- either (const Nothing) return $
parseXMLElement $ UTF8.toTextLazy $ fromEntry entry
let ns = elemToNameSpaces presElement
sldSize <- findChild (elemName ns "p" "sldSz") presElement
cxS <- findAttr (QName "cx" Nothing Nothing) sldSize
cyS <- findAttr (QName "cy" Nothing Nothing) sldSize
cx <- readTextAsInteger cxS
cy <- readTextAsInteger cyS
return (cx `div` 12700, cy `div` 12700)
readTextAsInteger :: Text -> Maybe Integer
readTextAsInteger = either (const Nothing) (Just . fst) . Data.Text.Read.decimal
data WriterEnv = WriterEnv { envRefArchive :: Archive
, envDistArchive :: Archive
, envUTCTime :: UTCTime
, envOpts :: WriterOptions
, envContext :: Context Text
, envPresentationSize :: (Integer, Integer)
, envSlideHasHeader :: Bool
, envInList :: Bool
, envInNoteSlide :: Bool
, envCurSlideId :: Int
, envPlaceholder :: Placeholder
, envSlideIdMap :: M.Map SlideId Int
-- maps the slide number to the
-- corresponding notes id number. If there
-- are no notes for a slide, there will be
-- no entry in the map for it.
, envSpeakerNotesIdMap :: M.Map Int Int
, envInSpeakerNotes :: Bool
, envSlideLayouts :: Maybe SlideLayouts
, envOtherStyleIndents :: Maybe Indents
}
deriving (Show)
instance Default WriterEnv where
def = WriterEnv { envRefArchive = emptyArchive
, envDistArchive = emptyArchive
, envUTCTime = posixSecondsToUTCTime 0
, envOpts = def
, envContext = mempty
, envPresentationSize = (720, 540)
, envSlideHasHeader = False
, envInList = False
, envInNoteSlide = False
, envCurSlideId = 1
, envPlaceholder = Placeholder ObjType 0
, envSlideIdMap = mempty
, envSpeakerNotesIdMap = mempty
, envInSpeakerNotes = False
, envSlideLayouts = Nothing
, envOtherStyleIndents = Nothing
}
type SlideLayouts = SlideLayoutsOf SlideLayout
data SlideLayoutsOf a = SlideLayouts
{ metadata :: a
, title :: a
, content :: a
, twoColumn :: a
, comparison :: a
, contentWithCaption :: a
, blank :: a
} deriving (Show, Eq, Functor, Foldable, Traversable)
data SlideLayout = SlideLayout
{ slElement :: Element
, slInReferenceDoc :: Bool
-- ^ True if the layout is in the provided reference doc, False if it's in
-- the default reference doc.
, slPath :: FilePath
, slEntry :: Entry
} deriving (Show)
getSlideLayouts :: PandocMonad m => P m SlideLayouts
getSlideLayouts = asks envSlideLayouts >>= maybe (throwError e) pure
where
e = PandocSomeError ("Slide layouts aren't defined, even though they should "
<> "always be. This is a bug in pandoc.")
-- | A placeholder within a layout, identified by type and index.
--
-- E.g., @Placeholder ObjType 2@ is the third placeholder of type 'ObjType' in
-- the layout.
data Placeholder = Placeholder
{ placeholderType :: PHType
, index :: Int
} deriving (Show, Eq)
-- | Paragraph indentation info.
data Indents = Indents
{ level1 :: Maybe LevelIndents
, level2 :: Maybe LevelIndents
, level3 :: Maybe LevelIndents
, level4 :: Maybe LevelIndents
, level5 :: Maybe LevelIndents
, level6 :: Maybe LevelIndents
, level7 :: Maybe LevelIndents
, level8 :: Maybe LevelIndents
, level9 :: Maybe LevelIndents
} deriving (Show, Eq)
levelIndent :: Indents -> Int -> Maybe LevelIndents
levelIndent is index = getter is
where
getter = case index of
0 -> level1
1 -> level2
2 -> level3
3 -> level4
4 -> level5
5 -> level6
6 -> level7
7 -> level8
8 -> level9
_ -> const Nothing
data LevelIndents = LevelIndents
{ marL :: EMU
, indent :: EMU
} deriving (Show, Eq)
data MediaInfo = MediaInfo { mInfoFilePath :: FilePath
, mInfoLocalId :: Int
, mInfoGlobalId :: Int
, mInfoMimeType :: Maybe MimeType
, mInfoExt :: Maybe T.Text
, mInfoCaption :: Bool
} deriving (Show, Eq)
data WriterState = WriterState { stLinkIds :: M.Map Int (M.Map Int LinkTarget)
-- (FP, Local ID, Global ID, Maybe Mime)
, stMediaIds :: M.Map Int [MediaInfo]
, stMediaGlobalIds :: M.Map FilePath Int
, stFooterInfo :: Maybe FooterInfo
} deriving (Show, Eq)
instance Default WriterState where
def = WriterState { stLinkIds = mempty
, stMediaIds = mempty
, stMediaGlobalIds = mempty
, stFooterInfo = Nothing
}
type P m = ReaderT WriterEnv (StateT WriterState m)
runP :: Monad m => WriterEnv -> WriterState -> P m a -> m a
runP env st p = evalStateT (runReaderT p env) st
--------------------------------------------------------------------
monospaceFont :: Monad m => P m T.Text
monospaceFont = do
vars <- asks envContext
case lookupContext "monofont" vars of
Just s -> return s
Nothing -> return "Courier"
fontSizeAttributes :: Monad m => RunProps -> P m [(Text, Text)]
fontSizeAttributes RunProps { rPropForceSize = Just sz } =
return [("sz", tshow $ sz * 100)]
fontSizeAttributes _ = return []
copyFileToArchive :: PandocMonad m => Archive -> FilePath -> P m Archive
copyFileToArchive arch fp = do
refArchive <- asks envRefArchive
distArchive <- asks envDistArchive
case findEntryByPath fp refArchive `mplus` findEntryByPath fp distArchive of
Nothing -> throwError $ PandocSomeError
$ T.pack
$ fp <> " missing in reference file"
Just e -> return $ addEntryToArchive e arch
alwaysInheritedPatterns :: [Pattern]
alwaysInheritedPatterns =
map compile [ "docProps/app.xml"
, "ppt/slideLayouts/slideLayout*.xml"
, "ppt/slideLayouts/_rels/slideLayout*.xml.rels"
, "ppt/slideMasters/slideMaster1.xml"
, "ppt/slideMasters/_rels/slideMaster1.xml.rels"
, "ppt/theme/theme*.xml"
, "ppt/theme/_rels/theme*.xml.rels"
, "ppt/presProps.xml"
, "ppt/tableStyles.xml"
, "ppt/media/image*"
, "ppt/fonts/*"
]
-- We only look for these under special conditions
contingentInheritedPatterns :: Presentation -> [Pattern]
contingentInheritedPatterns pres = [] <>
if presHasSpeakerNotes pres
then map compile [ "ppt/notesMasters/notesMaster*.xml"
, "ppt/notesMasters/_rels/notesMaster*.xml.rels"
]
else []
inheritedPatterns :: Presentation -> [Pattern]
inheritedPatterns pres =
alwaysInheritedPatterns <> contingentInheritedPatterns pres
patternToFilePaths :: PandocMonad m => Pattern -> P m [FilePath]
patternToFilePaths pat = do
refArchive <- asks envRefArchive
distArchive <- asks envDistArchive
let archiveFiles = filesInArchive refArchive `union` filesInArchive distArchive
return $ filter (match pat) archiveFiles
patternsToFilePaths :: PandocMonad m => [Pattern] -> P m [FilePath]
patternsToFilePaths pats = concat <$> mapM patternToFilePaths pats
-- Here are the files we'll require to make a Powerpoint document. If
-- any of these are missing, we should error out of our build.
requiredFiles :: [FilePath]
requiredFiles = [ "docProps/app.xml"
, "ppt/presProps.xml"
, "ppt/slideLayouts/slideLayout1.xml"
, "ppt/slideLayouts/_rels/slideLayout1.xml.rels"
, "ppt/slideLayouts/slideLayout2.xml"
, "ppt/slideLayouts/_rels/slideLayout2.xml.rels"
, "ppt/slideLayouts/slideLayout3.xml"
, "ppt/slideLayouts/_rels/slideLayout3.xml.rels"
, "ppt/slideLayouts/slideLayout4.xml"
, "ppt/slideLayouts/_rels/slideLayout4.xml.rels"
, "ppt/slideMasters/slideMaster1.xml"
, "ppt/slideMasters/_rels/slideMaster1.xml.rels"
, "ppt/theme/theme1.xml"
, "ppt/tableStyles.xml"
]
presentationToArchiveP :: PandocMonad m => Presentation -> P m Archive
presentationToArchiveP p@(Presentation docProps slides) = do
filePaths <- patternsToFilePaths $ inheritedPatterns p
-- make sure all required files are available:
let missingFiles = filter (`notElem` filePaths) requiredFiles
unless (null missingFiles)
(throwError $
PandocSomeError $
"The following required files are missing:\n" <>
T.unlines (map (T.pack . (" " <>)) missingFiles)
)
newArch <- foldM copyFileToArchive emptyArchive filePaths
-- Add any layouts taken from the default archive,
-- overwriting any already added.
slideLayouts <- getSlideLayouts
let f layout =
if not (slInReferenceDoc layout)
then addEntryToArchive (slEntry layout)
else id
let newArch' = foldr f newArch slideLayouts
master <- getMaster
refArchive <- asks envRefArchive
distArchive <- asks envDistArchive
presentationElement <- parseXml refArchive distArchive "ppt/presentation.xml"
modify (\s ->
s {stFooterInfo =
getFooterInfo (dcDate docProps) slideLayouts master presentationElement
})
-- Update the master to make sure it includes any layouts we've just added
masterRels <- getMasterRels
let (updatedMasterElem, updatedMasterRelElem) = updateMasterElems slideLayouts master masterRels
updatedMasterEntry <- elemToEntry "ppt/slideMasters/slideMaster1.xml" updatedMasterElem
updatedMasterRelEntry <- elemToEntry "ppt/slideMasters/_rels/slideMaster1.xml.rels" updatedMasterRelElem
-- we make a modified ppt/viewProps.xml out of the presentation viewProps
viewPropsEntry <- makeViewPropsEntry
-- we make a docProps/core.xml entry out of the presentation docprops
docPropsEntry <- docPropsToEntry docProps
-- we make a docProps/custom.xml entry out of the custom properties
docCustomPropsEntry <- docCustomPropsToEntry docProps
-- we make this ourself in case there's something unexpected in the
-- one in the reference doc.
relsEntry <- topLevelRelsEntry
-- presentation entry and rels.
(presentationRIdUpdateData, presRelsEntry) <- presentationToRelsEntry p
presEntry <- presentationToPresEntry presentationRIdUpdateData p
slideEntries <- mapM slideToEntry slides
slideRelEntries <- mapM slideToSlideRelEntry slides
spkNotesEntries <- catMaybes <$> mapM slideToSpeakerNotesEntry slides
spkNotesRelEntries <- catMaybes <$> mapM slideToSpeakerNotesRelEntry slides
-- These have to come after everything, because they need the info
-- built up in the state.
mediaEntries <- makeMediaEntries
contentTypesEntry <- presentationToContentTypes p >>= contentTypesToEntry
-- fold everything into our inherited archive and return it.
return $ foldr addEntryToArchive newArch' $
slideEntries <>
slideRelEntries <>
spkNotesEntries <>
spkNotesRelEntries <>
mediaEntries <>
[updatedMasterEntry, updatedMasterRelEntry] <>
[contentTypesEntry, docPropsEntry, docCustomPropsEntry, relsEntry,
presEntry, presRelsEntry, viewPropsEntry]
updateMasterElems :: SlideLayouts -> Element -> Element -> (Element, Element)
updateMasterElems layouts master masterRels = (updatedMaster, updatedMasterRels)
where
updatedMaster = master { elContent = updateSldLayoutIdLst <$> elContent master }
(updatedRelationshipIds, updatedMasterRels) = addLayoutRels masterRels
updateSldLayoutIdLst :: Content -> Content
updateSldLayoutIdLst (Elem e) = case elName e of
(QName "sldLayoutIdLst" _ _) -> let
mkChild relationshipId (lastId, children) = let
thisId = lastId + 1
newChild = Element
{ elName = QName "sldLayoutId" Nothing (Just "p")
, elAttribs =
[ Attr (QName "id" Nothing Nothing) (T.pack (show thisId))
, Attr (QName "id" Nothing (Just "r")) relationshipId
]
, elContent = []
, elLine = Nothing
}
in (thisId, Elem newChild : children)
newChildren = snd (foldr mkChild (maxIdNumber' e, []) updatedRelationshipIds)
in Elem e { elContent = elContent e <> newChildren }
_ -> Elem e
updateSldLayoutIdLst c = c
addLayoutRels ::
Element ->
([Text], Element)
addLayoutRels e = let
layoutsToAdd = filter (\l -> not (slInReferenceDoc l) && isNew e l)
(toList layouts)
newRelationships = snd (foldr mkRelationship (maxIdNumber e, []) layoutsToAdd)
newRelationshipIds =
mapMaybe (findElemAttr (QName "Id" Nothing Nothing)) newRelationships
mkRelationship layout (lastId, relationships) = let
thisId = lastId + 1
slideLayoutPath = "../slideLayouts/" <> T.pack (takeFileName (slPath layout))
newRelationship = Element
{ elName = QName "Relationship" Nothing Nothing
, elAttribs =
[ Attr (QName "Id" Nothing Nothing) ("rId" <> T.pack (show thisId))
, Attr (QName "Type" Nothing Nothing) "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"
, Attr (QName "Target" Nothing Nothing) slideLayoutPath
]
, elContent = []
, elLine = Nothing
}
in (thisId, Elem newRelationship : relationships)
in (newRelationshipIds, e {elContent = elContent e <> newRelationships})
-- Whether the layout needs to be added to the Relationships element.
isNew :: Element -> SlideLayout -> Bool
isNew relationships SlideLayout{..} = let
toDetails = fmap (takeFileName . T.unpack)
. findElemAttr (QName "Target" Nothing Nothing)
in takeFileName slPath `notElem` mapMaybe toDetails (elContent relationships)
findElemAttr :: QName -> Content -> Maybe Text
findElemAttr attr (Elem e) = findAttr attr e
findElemAttr _ _ = Nothing
maxIdNumber :: Element -> Integer
maxIdNumber relationships = maximum (0 : idNumbers)
where
idNumbers = mapMaybe (readTextAsInteger . T.drop 3) idAttributes
idAttributes = mapMaybe getIdAttribute (elContent relationships)
getIdAttribute (Elem e) = findAttr (QName "Id" Nothing Nothing) e
getIdAttribute _ = Nothing
maxIdNumber' :: Element -> Integer
maxIdNumber' sldLayouts = maximum (0 : idNumbers)
where
idNumbers = mapMaybe readTextAsInteger idAttributes
idAttributes = mapMaybe getIdAttribute (elContent sldLayouts)
getIdAttribute (Elem e) = findAttr (QName "id" Nothing Nothing) e
getIdAttribute _ = Nothing
data FooterInfo = FooterInfo
{ fiDate :: SlideLayoutsOf (Maybe Element)
, fiFooter :: SlideLayoutsOf (Maybe Element)
, fiSlideNumber :: SlideLayoutsOf (Maybe Element)
, fiShowOnFirstSlide :: Bool
} deriving (Show, Eq)
getFooterInfo :: Maybe Text -> SlideLayouts -> Element -> Element -> Maybe FooterInfo
getFooterInfo date layouts master presentation = do
let ns = elemToNameSpaces master
hf <- findChild (elemName ns "p" "hf") master
let fiDate = let
f layoutDate =
case date of
Nothing -> layoutDate
Just d ->
if dateIsAutomatic (elemToNameSpaces layoutDate) layoutDate
then layoutDate
else replaceDate d layoutDate
in fmap f . getShape "dt" hf . slElement <$> layouts
fiFooter = getShape "ftr" hf . slElement <$> layouts
fiSlideNumber = getShape "sldNum" hf . slElement <$> layouts
fiShowOnFirstSlide =
fromMaybe True
(getBooleanAttribute "showSpecialPlsOnTitleSld" presentation)
pure FooterInfo{..}
where
getShape t hf layout =
if fromMaybe True (getBooleanAttribute t hf)
then do
let ns = elemToNameSpaces layout
cSld <- findChild (elemName ns "p" "cSld") layout
spTree <- findChild (elemName ns "p" "spTree") cSld
let containsPlaceholder sp = fromMaybe False $ do
nvSpPr <- findChild (elemName ns "p" "nvSpPr") sp
nvPr <- findChild (elemName ns "p" "nvPr") nvSpPr
ph <- findChild (elemName ns "p" "ph") nvPr
placeholderType <- findAttr (QName "type" Nothing Nothing) ph
pure (placeholderType == t)
listToMaybe (filterChildren containsPlaceholder spTree)
else Nothing
dateIsAutomatic :: NameSpaces -> Element -> Bool
dateIsAutomatic ns shape = isJust $ do
txBody <- findChild (elemName ns "p" "txBody") shape
p <- findChild (elemName ns "a" "p") txBody
findChild (elemName ns "a" "fld") p
replaceDate :: Text -> Element -> Element
replaceDate newDate e =
e { elContent =
case (elName e) of
QName "t" _ (Just "a") ->
[ Text (CData { cdVerbatim = CDataText
, cdData = newDate
, cdLine = Nothing
})
]
_ -> ifElem (replaceDate newDate) <$> elContent e
}
ifElem :: (Element -> Element) -> (Content -> Content)
ifElem f (Elem e) = Elem (f e)
ifElem _ c = c
getBooleanAttribute t e =
(`elem` ["1", "true"]) <$>
(findAttr (QName t Nothing Nothing) e)
footerElements ::
PandocMonad m =>
(forall a. SlideLayoutsOf a -> a) ->
P m [Content]
footerElements layout = do
footerInfo <- gets stFooterInfo
pure
$ Elem <$>
(toList (footerInfo >>= layout . fiDate)
<> toList (footerInfo >>= layout . fiFooter)
<> toList (footerInfo >>= layout . fiSlideNumber))
makeSlideIdMap :: Presentation -> M.Map SlideId Int
makeSlideIdMap (Presentation _ slides) =
M.fromList $ map slideId slides `zip` [1..]
makeSpeakerNotesMap :: Presentation -> M.Map Int Int
makeSpeakerNotesMap (Presentation _ slides) =
M.fromList $
mapMaybe f (slides `zip` [1..]) `zip` [1..]
where f (Slide _ _ notes _, n) = if notes == mempty
then Nothing
else Just n
presentationToArchive :: PandocMonad m
=> WriterOptions -> Meta -> Presentation -> m Archive
presentationToArchive opts meta pres = do
distArchive <- toArchive . BL.fromStrict <$>
readDefaultDataFile "reference.pptx"
refArchive <- case writerReferenceDoc opts of
Just f -> toArchive . BL.fromStrict . fst
<$> P.fetchItem (T.pack f)
Nothing -> toArchive . BL.fromStrict <$>
readDataFile "reference.pptx"
let (referenceLayouts, defaultReferenceLayouts) =
(getLayoutsFromArchive refArchive, getLayoutsFromArchive distArchive)
let layoutTitles = SlideLayouts { metadata = "Title Slide" :: Text
, title = "Section Header"
, content = "Title and Content"
, twoColumn = "Two Content"
, comparison = "Comparison"
, contentWithCaption = "Content with Caption"
, blank = "Blank"
}
layouts <- for layoutTitles $ \layoutTitle -> do
let layout = M.lookup (CI.mk layoutTitle) referenceLayouts
let defaultLayout = M.lookup (CI.mk layoutTitle) defaultReferenceLayouts
case (layout, defaultLayout) of
(Nothing, Nothing) ->
throwError (PandocSomeError ("Couldn't find layout named \""
<> layoutTitle <> "\" in the provided "
<> "reference doc or in the default "
<> "reference doc included with pandoc."))
(Nothing, Just ((element, path, entry) :| _)) -> do
P.report (PowerpointTemplateWarning
("Couldn't find layout named \""
<> layoutTitle <> "\" in provided "
<> "reference doc. Falling back to "
<> "the default included with pandoc."))
pure SlideLayout { slElement = element
, slPath = path
, slEntry = entry
, slInReferenceDoc = False
}
(Just ((element, path, entry) :| _), _ ) ->
pure SlideLayout { slElement = element
, slPath = path
, slEntry = entry
, slInReferenceDoc = True
}
master <- getMaster' refArchive distArchive
let otherStyleIndents = do
let ns = elemToNameSpaces master
txStyles <- findChild (elemName ns "p" "txStyles") master
otherStyle <- findChild (elemName ns "p" "otherStyle") txStyles
let makeLevelIndents name = do
e <- findChild (elemName ns "a" name) otherStyle
pure LevelIndents
{ indent = fromMaybe (-342900)
(findAttr (QName "indent" Nothing Nothing) e
>>= readTextAsInteger)
, marL = fromMaybe 347663
(findAttr (QName "marL" Nothing Nothing) e
>>= readTextAsInteger)
}
pure Indents
{ level1 = makeLevelIndents "lvl1pPr"
, level2 = makeLevelIndents "lvl2pPr"
, level3 = makeLevelIndents "lvl3pPr"
, level4 = makeLevelIndents "lvl4pPr"
, level5 = makeLevelIndents "lvl5pPr"
, level6 = makeLevelIndents "lvl6pPr"
, level7 = makeLevelIndents "lvl7pPr"
, level8 = makeLevelIndents "lvl8pPr"
, level9 = makeLevelIndents "lvl9pPr"
}
utctime <- P.getTimestamp
presSize <- case getPresentationSize refArchive distArchive of
Just sz -> return sz
Nothing -> throwError $
PandocSomeError
"Could not determine presentation size"
-- note, we need writerTemplate to be Just _ or metaToContext does
-- nothing
context <- metaToContext opts{ writerTemplate =
writerTemplate opts <|> Just mempty }
(return . literal . stringify)
(return . literal . stringify) meta
let env = def { envRefArchive = refArchive
, envDistArchive = distArchive
, envUTCTime = utctime
, envOpts = opts
, envContext = context
, envPresentationSize = presSize
, envSlideIdMap = makeSlideIdMap pres
, envSpeakerNotesIdMap = makeSpeakerNotesMap pres
, envSlideLayouts = Just layouts
, envOtherStyleIndents = otherStyleIndents
}
let st = def { stMediaGlobalIds = initialGlobalIds refArchive distArchive
}
runP env st $ presentationToArchiveP pres
-- | Get all slide layouts from an archive, as a map where the layout's name
-- gives the map key.
--
-- For each layout, the map contains its XML representation, its path within
-- the archive, and the archive entry.
getLayoutsFromArchive :: Archive -> M.Map (CI Text) (NonEmpty (Element, FilePath, Entry))
getLayoutsFromArchive archive =
M.fromListWith (<>) ((\t@(e, _, _) -> (CI.mk (name e), pure t)) <$> layouts)
where
layouts :: [(Element, FilePath, Entry)]
layouts = mapMaybe findElementByPath paths
parseXml' entry = case parseXMLElement (UTF8.toTextLazy (fromEntry entry)) of
Left _ -> Nothing
Right element -> Just element
findElementByPath :: FilePath -> Maybe (Element, FilePath, Entry)
findElementByPath path = do
entry <- findEntryByPath path archive
element <- parseXml' entry
pure (element, path, entry)
paths = filter (match (compile "ppt/slideLayouts/slideLayout*.xml")) (filesInArchive archive)
name element = fromMaybe "Untitled layout" $ do
let ns = elemToNameSpaces element
cSld <- findChild (elemName ns "p" "cSld") element
findAttr (QName "name" Nothing Nothing) cSld
--------------------------------------------------
-- Check to see if the presentation has speaker notes. This will
-- influence whether we import the notesMaster template.
presHasSpeakerNotes :: Presentation -> Bool
presHasSpeakerNotes (Presentation _ slides) =
not $ all ((mempty ==) . slideSpeakerNotes) slides
curSlideHasSpeakerNotes :: PandocMonad m => P m Bool
curSlideHasSpeakerNotes =
M.member <$> asks envCurSlideId <*> asks envSpeakerNotesIdMap
--------------------------------------------------
getLayout :: PandocMonad m => Layout -> P m Element
getLayout layout = getElement <$> getSlideLayouts
where
getElement =
slElement . case layout of
MetadataSlide{} -> metadata
TitleSlide{} -> title
ContentSlide{} -> content
TwoColumnSlide{} -> twoColumn
ComparisonSlide{} -> comparison
ContentWithCaptionSlide{} -> contentWithCaption
BlankSlide{} -> blank
shapeHasId :: NameSpaces -> T.Text -> Element -> Bool
shapeHasId ns ident element = getShapeId ns element == Just ident
getShapeId :: NameSpaces -> Element -> Maybe Text
getShapeId ns element = do
nvSpPr <- findChild (elemName ns "p" "nvSpPr") element
cNvPr <- findChild (elemName ns "p" "cNvPr") nvSpPr
findAttr (QName "id" Nothing Nothing) cNvPr
type ShapeId = Integer
getContentShape :: PandocMonad m => NameSpaces -> Element -> P m (Maybe ShapeId, Element)
getContentShape ns spTreeElem
| isElem ns "p" "spTree" spTreeElem = do
ph@Placeholder{index, placeholderType} <- asks envPlaceholder
case drop index (getShapesByPlaceHolderType ns spTreeElem placeholderType) of
sp : _ -> let
shapeId = getShapeId ns sp >>= readTextAsInteger
in return (shapeId, sp)
[] -> throwError $ PandocSomeError $ missingPlaceholderMessage ph
getContentShape _ _ = throwError $ PandocSomeError
"Attempted to find content on non shapeTree"
missingPlaceholderMessage :: Placeholder -> Text
missingPlaceholderMessage Placeholder{..} =
"Could not find a " <> ordinal
<> " placeholder of type " <> placeholderText
where
ordinal = T.pack (show index) <>
case (index `mod` 100, index `mod` 10) of
(11, _) -> "th"
(12, _) -> "th"
(13, _) -> "th"
(_, 1) -> "st"
(_, 2) -> "nd"
(_, 3) -> "rd"
_ -> "th"
placeholderText = case placeholderType of
ObjType -> "obj (or nothing)"
PHType t -> t
getShapeDimensions :: NameSpaces
-> Element
-> Maybe ((Integer, Integer), (Integer, Integer))
getShapeDimensions ns element
| isElem ns "p" "sp" element = do
spPr <- findChild (elemName ns "p" "spPr") element
xfrm <- findChild (elemName ns "a" "xfrm") spPr
off <- findChild (elemName ns "a" "off") xfrm
xS <- findAttr (QName "x" Nothing Nothing) off
yS <- findAttr (QName "y" Nothing Nothing) off
ext <- findChild (elemName ns "a" "ext") xfrm
cxS <- findAttr (QName "cx" Nothing Nothing) ext
cyS <- findAttr (QName "cy" Nothing Nothing) ext
x <- readTextAsInteger xS
y <- readTextAsInteger yS
cx <- readTextAsInteger cxS
cy <- readTextAsInteger cyS
return ((x `div` 12700, y `div` 12700),
(cx `div` 12700, cy `div` 12700))
| otherwise = Nothing
getMasterShapeDimensionsById :: T.Text
-> Element
-> Maybe ((Integer, Integer), (Integer, Integer))
getMasterShapeDimensionsById ident master = do
let ns = elemToNameSpaces master
cSld <- findChild (elemName ns "p" "cSld") master
spTree <- findChild (elemName ns "p" "spTree") cSld
sp <- filterChild (\e -> isElem ns "p" "sp" e && shapeHasId ns ident e) spTree
getShapeDimensions ns sp
getContentShapeSize :: PandocMonad m
=> NameSpaces
-> Element
-> Element
-> P m ((Integer, Integer), (Integer, Integer))
getContentShapeSize ns layout master
| isElem ns "p" "sldLayout" layout
, Just cSld <- findChild (elemName ns "p" "cSld") layout
, Just spTree <- findChild (elemName ns "p" "spTree") cSld = do
(_, sp) <- getContentShape ns spTree
case getShapeDimensions ns sp of
Just sz -> return sz
Nothing -> do let mbSz =
findChild (elemName ns "p" "nvSpPr") sp >>=
findChild (elemName ns "p" "cNvPr") >>=
findAttr (QName "id" Nothing Nothing) >>=
flip getMasterShapeDimensionsById master
case mbSz of
Just sz' -> return sz'
Nothing -> throwError $ PandocSomeError
"Couldn't find necessary content shape size"
getContentShapeSize _ _ _ = throwError $ PandocSomeError
"Attempted to find content shape size in non-layout"
buildSpTree :: NameSpaces -> Element -> [Content] -> Element
buildSpTree ns spTreeElem newShapes =
emptySpTreeElem { elContent = newContent }
where newContent = elContent emptySpTreeElem <> newShapes
emptySpTreeElem = spTreeElem { elContent = filter fn (elContent spTreeElem) }
fn :: Content -> Bool
fn (Elem e) = isElem ns "p" "nvGrpSpPr" e ||
isElem ns "p" "grpSpPr" e
fn _ = True
replaceNamedChildren :: NameSpaces
-> Text
-> Text
-> [Element]
-> Element
-> Element
replaceNamedChildren ns prefix name newKids element =
element { elContent = concat $ fun True $ elContent element }
where
fun :: Bool -> [Content] -> [[Content]]
fun _ [] = []
fun switch (Elem e : conts) | isElem ns prefix name e =
if switch
then map Elem newKids : fun False conts
else fun False conts
fun switch (cont : conts) = [cont] : fun switch conts
----------------------------------------------------------------
registerLink :: PandocMonad m => LinkTarget -> P m Int
registerLink link = do
curSlideId <- asks envCurSlideId
linkReg <- gets stLinkIds
mediaReg <- gets stMediaIds
hasSpeakerNotes <- curSlideHasSpeakerNotes
let maxLinkId = case M.lookup curSlideId linkReg >>= nonEmpty . M.keys of
Just xs -> maximum xs
Nothing
| hasSpeakerNotes -> 2
| otherwise -> 1
maxMediaId = case M.lookup curSlideId mediaReg >>= nonEmpty of
Just mInfos -> maximum $ fmap mInfoLocalId mInfos
Nothing
| hasSpeakerNotes -> 2
| otherwise -> 1
maxId = max maxLinkId maxMediaId
slideLinks = case M.lookup curSlideId linkReg of
Just mp -> M.insert (maxId + 1) link mp
Nothing -> M.singleton (maxId + 1) link
modify $ \st -> st{ stLinkIds = M.insert curSlideId slideLinks linkReg}
return $ maxId + 1
registerMedia :: PandocMonad m => FilePath -> [ParaElem] -> P m MediaInfo
registerMedia fp caption = do
curSlideId <- asks envCurSlideId
linkReg <- gets stLinkIds
mediaReg <- gets stMediaIds
globalIds <- gets stMediaGlobalIds
hasSpeakerNotes <- curSlideHasSpeakerNotes
let maxLinkId = case M.lookup curSlideId linkReg >>= nonEmpty . M.keys of
Just ks -> maximum ks
Nothing
| hasSpeakerNotes -> 2
| otherwise -> 1
maxMediaId = case M.lookup curSlideId mediaReg >>= nonEmpty of
Just mInfos -> maximum $ fmap mInfoLocalId mInfos
Nothing
| hasSpeakerNotes -> 2
| otherwise -> 1
maxLocalId = max maxLinkId maxMediaId
maxGlobalId = maybe 0 maximum $ nonEmpty $ M.elems globalIds
(imgBytes, mbMt) <- P.fetchItem $ T.pack fp
let imgExt = (mbMt >>= extensionFromMimeType >>= (\x -> return $ "." <> x))
<|>
case imageType imgBytes of
Just Png -> Just ".png"
Just Jpeg -> Just ".jpeg"
Just Gif -> Just ".gif"
Just Pdf -> Just ".pdf"
Just Eps -> Just ".eps"
Just Svg -> Just ".svg"
Just Emf -> Just ".emf"
Just Tiff -> Just ".tiff"
Just Webp -> Just ".webp"
Nothing -> Nothing
let newGlobalId = fromMaybe (maxGlobalId + 1) (M.lookup fp globalIds)
let newGlobalIds = M.insert fp newGlobalId globalIds
let mediaInfo = MediaInfo { mInfoFilePath = fp
, mInfoLocalId = maxLocalId + 1
, mInfoGlobalId = newGlobalId
, mInfoMimeType =
case mbMt of
-- see #9113
Just t | ";base64" `T.isSuffixOf` t
-> T.stripSuffix ";base64" t
x -> x
, mInfoExt = imgExt
, mInfoCaption = (not . null) caption
}
let slideMediaInfos = case M.lookup curSlideId mediaReg of
Just minfos -> mediaInfo : minfos
Nothing -> [mediaInfo]
modify $ \st -> st{ stMediaIds = M.insert curSlideId slideMediaInfos mediaReg
, stMediaGlobalIds = newGlobalIds
}
return mediaInfo
makeMediaEntry :: PandocMonad m => MediaInfo -> P m Entry
makeMediaEntry mInfo = do
epochtime <- floor . utcTimeToPOSIXSeconds <$> asks envUTCTime
(imgBytes, _) <- P.fetchItem (T.pack $ mInfoFilePath mInfo)
let ext = fromMaybe "" (mInfoExt mInfo)
let fp = "ppt/media/image" <>
show (mInfoGlobalId mInfo) <> T.unpack ext
return $ toEntry fp epochtime $ BL.fromStrict imgBytes
makeMediaEntries :: PandocMonad m => P m [Entry]
makeMediaEntries = do
mediaInfos <- gets stMediaIds
let allInfos = mconcat $ M.elems mediaInfos
mapM makeMediaEntry allInfos
-- -- | Scales the image to fit the page
-- -- sizes are passed in emu
-- fitToPage' :: (Double, Double) -- image size in emu
-- -> Integer -- pageWidth
-- -> Integer -- pageHeight
-- -> (Integer, Integer) -- imagesize
-- fitToPage' (x, y) pageWidth pageHeight
-- -- Fixes width to the page width and scales the height
-- | x <= fromIntegral pageWidth && y <= fromIntegral pageHeight =
-- (floor x, floor y)
-- | x / fromIntegral pageWidth > y / fromIntegral pageWidth =
-- (pageWidth, floor $ ((fromIntegral pageWidth) / x) * y)
-- | otherwise =
-- (floor $ ((fromIntegral pageHeight) / y) * x, pageHeight)
-- positionImage :: (Double, Double) -> Integer -> Integer -> (Integer, Integer)
-- positionImage (x, y) pageWidth pageHeight =
-- let (x', y') = fitToPage' (x, y) pageWidth pageHeight
-- in
-- ((pageWidth - x') `div` 2, (pageHeight - y') `div` 2)
getMaster :: PandocMonad m => P m Element
getMaster = do
refArchive <- asks envRefArchive
distArchive <- asks envDistArchive
getMaster' refArchive distArchive
getMaster' :: PandocMonad m => Archive -> Archive -> m Element
getMaster' refArchive distArchive =
parseXml refArchive distArchive "ppt/slideMasters/slideMaster1.xml"
getMasterRels :: PandocMonad m => P m Element
getMasterRels = do
refArchive <- asks envRefArchive
distArchive <- asks envDistArchive
parseXml refArchive distArchive "ppt/slideMasters/_rels/slideMaster1.xml.rels"
-- We want to get the header dimensions, so we can make sure that the
-- image goes underneath it. We only use this in a content slide if it