{-# LANGUAGE OverloadedStrings #-}
{- |
   Module      : Text.Pandoc.Readers.OOXML.Charts
   Copyright   : © 2026 Nacho García
   License     : GNU GPL, version 2 or above

   Maintainer  : Nacho García <hello@nachogarcia.dev>
   Stability   : alpha
   Portability : portable

Reading of DrawingML charts (in PPTX slides and XLSX sheets), from the
values cached in the chart part.
-}
module Text.Pandoc.Readers.OOXML.Charts
  ( Chart(..)
  , ChartSeries(..)
  , readChart
  , chartToBlocks
  ) where

import Codec.Archive.Zip (Archive, findEntryByPath, fromEntry)
import Data.List (find, nub, transpose)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe, listToMaybe, mapMaybe)
import qualified Data.Text as T
import qualified Data.Text.Lazy.Encoding as TL
import Data.Text (Text)
import qualified Text.Pandoc.Builder as B
import Text.Pandoc.Definition
import Text.Pandoc.Readers.OOXML.Shared
import Text.Pandoc.XML.Light
import Text.Read (readMaybe)

-- | A chart's data, as cached in its chart part
data Chart = Chart
  { Chart -> Text
chartTitle  :: Text     -- ^ Empty if the chart has no title
  , Chart -> [Text]
chartTypes  :: [Text]   -- ^ Such as @bar@ or @line@, one per plot
  , Chart -> [ChartSeries]
chartSeries :: [ChartSeries]
  } deriving (Int -> Chart -> ShowS
[Chart] -> ShowS
Chart -> String
(Int -> Chart -> ShowS)
-> (Chart -> String) -> ([Chart] -> ShowS) -> Show Chart
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Chart -> ShowS
showsPrec :: Int -> Chart -> ShowS
$cshow :: Chart -> String
show :: Chart -> String
$cshowList :: [Chart] -> ShowS
showList :: [Chart] -> ShowS
Show)

-- | One series: its name, and its points as (category, value)
data ChartSeries = ChartSeries
  { ChartSeries -> Text
seriesName   :: Text
  , ChartSeries -> [(Text, Text)]
seriesPoints :: [(Text, Text)]
  } deriving (Int -> ChartSeries -> ShowS
[ChartSeries] -> ShowS
ChartSeries -> String
(Int -> ChartSeries -> ShowS)
-> (ChartSeries -> String)
-> ([ChartSeries] -> ShowS)
-> Show ChartSeries
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ChartSeries -> ShowS
showsPrec :: Int -> ChartSeries -> ShowS
$cshow :: ChartSeries -> String
show :: ChartSeries -> String
$cshowList :: [ChartSeries] -> ShowS
showList :: [ChartSeries] -> ShowS
Show)

-- | Read a chart part (@c:chartSpace@)
readChart :: Archive -> FilePath -> Either Text Chart
readChart :: Archive -> String -> Either Text Chart
readChart Archive
archive String
path = do
  entry <- Either Text Entry
-> (Entry -> Either Text Entry) -> Maybe Entry -> Either Text Entry
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Text -> Either Text Entry
forall a b. a -> Either a b
Left (Text -> Either Text Entry) -> Text -> Either Text Entry
forall a b. (a -> b) -> a -> b
$ Text
"Entry not found: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> String -> Text
T.pack String
path) Entry -> Either Text Entry
forall a b. b -> Either a b
Right (Maybe Entry -> Either Text Entry)
-> Maybe Entry -> Either Text Entry
forall a b. (a -> b) -> a -> b
$
           String -> Archive -> Maybe Entry
findEntryByPath String
path Archive
archive
  chartSpace <- parseXMLElement (TL.decodeUtf8 (fromEntry entry))
  chart <- maybe (Left "Missing c:chart") Right $ child "chart" chartSpace
  plotArea <- maybe (Left "Missing c:plotArea") Right $
              child "plotArea" chart
  let plots = (Element -> Bool) -> [Element] -> [Element]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Text
"Chart" Text -> Text -> Bool
`T.isSuffixOf`) (Text -> Bool) -> (Element -> Text) -> Element -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. QName -> Text
qName (QName -> Text) -> (Element -> QName) -> Element -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Element -> QName
elName)
                     (Element -> [Element]
elChildren Element
plotArea)
      series = (Int -> Element -> ChartSeries)
-> [Int] -> [Element] -> [ChartSeries]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Int -> Element -> ChartSeries
parseSeries [Int
1..] ((Element -> [Element]) -> [Element] -> [Element]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Text -> Element -> [Element]
children Text
"ser") [Element]
plots)
      title = Text -> (Element -> Text) -> Maybe Element -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Element -> Text
titleText (Text -> Element -> Maybe Element
child Text
"title" Element
chart)
  if all (all (T.null . snd) . seriesPoints) series
     then Left "Chart has no cached values"
     else Right Chart
            { chartTitle = title
            , chartTypes = nub $ map (T.dropEnd 5 . qName . elName) plots
            , chartSeries = series
            }

-- | Text of a chart title: rich text, or a cached cell reference
titleText :: Element -> Text
titleText :: Element -> Text
titleText Element
title =
  case Text -> Element -> Maybe Element
child Text
"tx" Element
title of
    Just Element
tx | Just Element
rich <- Text -> Element -> Maybe Element
child Text
"rich" Element
tx -> Element -> Text
drawingMLText Element
rich
            | Bool
otherwise -> [Text] -> Text
T.unwords (Element -> [Text]
cachedValues Element
tx)
    Maybe Element
Nothing -> Text
""

-- | Parse a series (@c:ser@). Its categories come from @c:cat@, or
-- @c:xVal@ in a scatter or bubble chart, and its values from @c:val@ or
-- @c:yVal@. A series without categories is numbered from 1, as in
-- PowerPoint.
parseSeries :: Int -> Element -> ChartSeries
parseSeries :: Int -> Element -> ChartSeries
parseSeries Int
n Element
ser =
  ChartSeries
    { seriesName :: Text
seriesName = case Text -> Element -> Maybe Element
child Text
"tx" Element
ser of
        Just Element
tx -> [Text] -> Text
T.unwords (Element -> [Text]
cachedValues Element
tx)
        Maybe Element
Nothing -> Text
"Series" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> String -> Text
T.pack (Int -> String
forall a. Show a => a -> String
show Int
n)
    , seriesPoints :: [(Text, Text)]
seriesPoints =
        [ (Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe (String -> Text
T.pack (Int -> String
forall a. Show a => a -> String
show (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1))) (Int -> Map Int Text -> Maybe Text
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Int
i Map Int Text
categories), Text
v)
        | Int
i <- [Int
0 .. Int
count Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1]
        , let v :: Text
v = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
"" (Int -> Map Int Text -> Maybe Text
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Int
i Map Int Text
values)
        ]
    }
  where
    points :: [Text] -> (Int, Map Int Text)
points [Text]
names = (Int, Map Int Text)
-> (Element -> (Int, Map Int Text))
-> Maybe Element
-> (Int, Map Int Text)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Int
0, Map Int Text
forall k a. Map k a
M.empty) Element -> (Int, Map Int Text)
cachedPoints (Maybe Element -> (Int, Map Int Text))
-> Maybe Element -> (Int, Map Int Text)
forall a b. (a -> b) -> a -> b
$
      [Element] -> Maybe Element
forall a. [a] -> Maybe a
listToMaybe ((Text -> Maybe Element) -> [Text] -> [Element]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (Text -> Element -> Maybe Element
`child` Element
ser) [Text]
names)
    (Int
catCount, Map Int Text
categories) = [Text] -> (Int, Map Int Text)
points [Text
"cat", Text
"xVal"]
    (Int
valCount, Map Int Text
values) = [Text] -> (Int, Map Int Text)
points [Text
"val", Text
"yVal"]
    count :: Int
count = [Int] -> Int
forall a. Ord a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
maximum [Int
catCount, Int
valCount, Map Int Text -> Int
forall {b} {b}. Num b => Map b b -> b
size Map Int Text
values, Map Int Text -> Int
forall {b} {b}. Num b => Map b b -> b
size Map Int Text
categories]
    size :: Map b b -> b
size Map b b
m = b -> ((b, b) -> b) -> Maybe (b, b) -> b
forall b a. b -> (a -> b) -> Maybe a -> b
maybe b
0 ((b -> b -> b
forall a. Num a => a -> a -> a
+ b
1) (b -> b) -> ((b, b) -> b) -> (b, b) -> b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (b, b) -> b
forall a b. (a, b) -> a
fst) (Map b b -> Maybe (b, b)
forall k a. Map k a -> Maybe (k, a)
M.lookupMax Map b b
m)

-- | The cached points of a data source (@c:cat@, @c:val@, ...): the
-- point count and the value of each point by index. In multi-level
-- categories only the innermost level is read.
cachedPoints :: Element -> (Int, M.Map Int Text)
cachedPoints :: Element -> (Int, Map Int Text)
cachedPoints Element
source =
  case [Element] -> Maybe Element
forall a. [a] -> Maybe a
listToMaybe ((Element -> Maybe Element) -> [Element] -> [Element]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe Element -> Maybe Element
cache (Element -> [Element]
elChildren Element
source)) of
    Just Element
c ->
      ( Int -> Maybe Int -> Int
forall a. a -> Maybe a -> a
fromMaybe Int
0 (Maybe Int -> Int) -> Maybe Int -> Int
forall a b. (a -> b) -> a -> b
$ Text -> Element -> Maybe Element
child Text
"ptCount" Element
c Maybe Element -> (Element -> Maybe Text) -> Maybe Text
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"val") Maybe Text -> (Text -> Maybe Int) -> Maybe Int
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>=
                        String -> Maybe Int
forall a. Read a => String -> Maybe a
readMaybe (String -> Maybe Int) -> (Text -> String) -> Text -> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> String
T.unpack
      , [(Int, Text)] -> Map Int Text
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList
          [ (Int
i, Text -> (Element -> Text) -> Maybe Element -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Element -> Text
strContent (Text -> Element -> Maybe Element
child Text
"v" Element
pt))
          | Element
pt <- Text -> Element -> [Element]
children Text
"pt" Element
c
          , Just Int
i <- [QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"idx") Element
pt Maybe Text -> (Text -> Maybe Int) -> Maybe Int
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= String -> Maybe Int
forall a. Read a => String -> Maybe a
readMaybe (String -> Maybe Int) -> (Text -> String) -> Text -> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> String
T.unpack]
          ]
      )
    Maybe Element
Nothing -> (Int
0, Map Int Text
forall k a. Map k a
M.empty)
  where
    cache :: Element -> Maybe Element
cache Element
el = case QName -> Text
qName (Element -> QName
elName Element
el) of
      Text
name | Text
name Text -> [Text] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Text
"strLit", Text
"numLit"] -> Element -> Maybe Element
forall a. a -> Maybe a
Just Element
el
           | Text
name Text -> [Text] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Text
"strRef", Text
"numRef"] ->
               (Element -> Bool) -> [Element] -> Maybe Element
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((Text -> [Text] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Text
"strCache", Text
"numCache"]) (Text -> Bool) -> (Element -> Text) -> Element -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. QName -> Text
qName (QName -> Text) -> (Element -> QName) -> Element -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Element -> QName
elName)
                    (Element -> [Element]
elChildren Element
el)
           | Text
name Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"multiLvlStrRef" ->
               Text -> Element -> Maybe Element
child Text
"multiLvlStrCache" Element
el Maybe Element -> (Element -> Maybe Element) -> Maybe Element
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Element -> Maybe Element
child Text
"lvl"
           | Bool
otherwise -> Maybe Element
forall a. Maybe a
Nothing

-- | The cached values of a text source such as a series name (@c:tx@),
-- which is either a cell reference with its cache or a literal @c:v@
cachedValues :: Element -> [Text]
cachedValues :: Element -> [Text]
cachedValues Element
tx =
  case Text -> Element -> Maybe Element
child Text
"v" Element
tx of
    Just Element
v -> [Element -> Text
strContent Element
v]
    Maybe Element
Nothing -> Map Int Text -> [Text]
forall k a. Map k a -> [a]
M.elems ((Int, Map Int Text) -> Map Int Text
forall a b. (a, b) -> b
snd (Element -> (Int, Map Int Text)
cachedPoints Element
tx))

-- | A chart as a table, in a @chart@ div with the chart types as its
-- @type@ attribute. Series that share their categories go in one table,
-- one column per series; otherwise each series gets its own table.
chartToBlocks :: Chart -> [Block]
chartToBlocks :: Chart -> [Block]
chartToBlocks Chart
chart =
  [Attr -> [Block] -> Block
Div (Text
"", [Text
"chart"], [(Text
"type", [Text] -> Text
T.unwords (Chart -> [Text]
chartTypes Chart
chart))])
       (([ChartSeries] -> Block) -> [[ChartSeries]] -> [Block]
forall a b. (a -> b) -> [a] -> [b]
map [ChartSeries] -> Block
table [[ChartSeries]]
groups)]
  where
    series :: [ChartSeries]
series = Chart -> [ChartSeries]
chartSeries Chart
chart
    categoriesOf :: ChartSeries -> [Text]
categoriesOf = ((Text, Text) -> Text) -> [(Text, Text)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text, Text) -> Text
forall a b. (a, b) -> a
fst ([(Text, Text)] -> [Text])
-> (ChartSeries -> [(Text, Text)]) -> ChartSeries -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ChartSeries -> [(Text, Text)]
seriesPoints
    groups :: [[ChartSeries]]
groups = case [ChartSeries]
series of
      ChartSeries
s:[ChartSeries]
rest | (ChartSeries -> Bool) -> [ChartSeries] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (([Text] -> [Text] -> Bool
forall a. Eq a => a -> a -> Bool
== ChartSeries -> [Text]
categoriesOf ChartSeries
s) ([Text] -> Bool) -> (ChartSeries -> [Text]) -> ChartSeries -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ChartSeries -> [Text]
categoriesOf) [ChartSeries]
rest -> [[ChartSeries]
series]
      [ChartSeries]
_ -> (ChartSeries -> [ChartSeries]) -> [ChartSeries] -> [[ChartSeries]]
forall a b. (a -> b) -> [a] -> [b]
map (ChartSeries -> [ChartSeries] -> [ChartSeries]
forall a. a -> [a] -> [a]
: []) [ChartSeries]
series
    caption :: Caption
caption = if Text -> Bool
T.null (Chart -> Text
chartTitle Chart
chart)
                 then Maybe ShortCaption -> [Block] -> Caption
Caption Maybe ShortCaption
forall a. Maybe a
Nothing []
                 else Maybe ShortCaption -> [Block] -> Caption
Caption Maybe ShortCaption
forall a. Maybe a
Nothing [ShortCaption -> Block
Plain (Many Inline -> ShortCaption
forall a. Many a -> [a]
B.toList (Text -> Many Inline
B.text
                                               (Chart -> Text
chartTitle Chart
chart)))]
    table :: [ChartSeries] -> Block
table [ChartSeries]
group =
      let cell :: Text -> Cell
cell Text
t = Attr -> Alignment -> RowSpan -> ColSpan -> [Block] -> Cell
Cell Attr
nullAttr Alignment
AlignDefault (Int -> RowSpan
RowSpan Int
1) (Int -> ColSpan
ColSpan Int
1)
                     [ShortCaption -> Block
Plain (Many Inline -> ShortCaption
forall a. Many a -> [a]
B.toList (Text -> Many Inline
B.text Text
t))]
          headerRow :: Row
headerRow = Attr -> [Cell] -> Row
Row Attr
nullAttr ([Cell] -> Row) -> [Cell] -> Row
forall a b. (a -> b) -> a -> b
$ Text -> Cell
cell Text
"" Cell -> [Cell] -> [Cell]
forall a. a -> [a] -> [a]
: (ChartSeries -> Cell) -> [ChartSeries] -> [Cell]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> Cell
cell (Text -> Cell) -> (ChartSeries -> Text) -> ChartSeries -> Cell
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ChartSeries -> Text
seriesName) [ChartSeries]
group
          categories :: [Text]
categories = [Text] -> (ChartSeries -> [Text]) -> Maybe ChartSeries -> [Text]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ChartSeries -> [Text]
categoriesOf ([ChartSeries] -> Maybe ChartSeries
forall a. [a] -> Maybe a
listToMaybe [ChartSeries]
group)
          values :: [[Text]]
values = [[Text]] -> [[Text]]
forall a. [[a]] -> [[a]]
transpose ((ChartSeries -> [Text]) -> [ChartSeries] -> [[Text]]
forall a b. (a -> b) -> [a] -> [b]
map (((Text, Text) -> Text) -> [(Text, Text)] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text, Text) -> Text
forall a b. (a, b) -> b
snd ([(Text, Text)] -> [Text])
-> (ChartSeries -> [(Text, Text)]) -> ChartSeries -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ChartSeries -> [(Text, Text)]
seriesPoints) [ChartSeries]
group)
          bodyRows :: [Row]
bodyRows = (Text -> [Text] -> Row) -> [Text] -> [[Text]] -> [Row]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith (\Text
category [Text]
vs -> Attr -> [Cell] -> Row
Row Attr
nullAttr
                                              ((Text -> Cell) -> [Text] -> [Cell]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Cell
cell (Text
category Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: [Text]
vs)))
                             [Text]
categories [[Text]]
values
       in Attr
-> Caption
-> [ColSpec]
-> TableHead
-> [TableBody]
-> TableFoot
-> Block
Table Attr
nullAttr Caption
caption
            (Int -> ColSpec -> [ColSpec]
forall a. Int -> a -> [a]
replicate ([ChartSeries] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [ChartSeries]
group Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) (Alignment
AlignDefault, ColWidth
ColWidthDefault))
            (Attr -> [Row] -> TableHead
TableHead Attr
nullAttr [Row
headerRow])
            [Attr -> RowHeadColumns -> [Row] -> [Row] -> TableBody
TableBody Attr
nullAttr RowHeadColumns
0 [] [Row]
bodyRows]
            (Attr -> [Row] -> TableFoot
TableFoot Attr
nullAttr [])

-- Chart elements are matched by local name, as the c prefix can vary.
child :: Text -> Element -> Maybe Element
child :: Text -> Element -> Maybe Element
child Text
name = (Element -> Bool) -> [Element] -> Maybe Element
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
name) (Text -> Bool) -> (Element -> Text) -> Element -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. QName -> Text
qName (QName -> Text) -> (Element -> QName) -> Element -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Element -> QName
elName) ([Element] -> Maybe Element)
-> (Element -> [Element]) -> Element -> Maybe Element
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Element -> [Element]
elChildren

children :: Text -> Element -> [Element]
children :: Text -> Element -> [Element]
children Text
name = (Element -> Bool) -> [Element] -> [Element]
forall a. (a -> Bool) -> [a] -> [a]
filter ((Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
name) (Text -> Bool) -> (Element -> Text) -> Element -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. QName -> Text
qName (QName -> Text) -> (Element -> QName) -> Element -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Element -> QName
elName) ([Element] -> [Element])
-> (Element -> [Element]) -> Element -> [Element]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Element -> [Element]
elChildren