{-# LANGUAGE OverloadedStrings #-}
{- |
   Module      : Text.Pandoc.Readers.Xlsx.Parse
   Copyright   : © 2025 Anton Antic
   License     : GNU GPL, version 2 or above

   Maintainer  : Anton Antic <anton@everworker.ai>
   Stability   : alpha
   Portability : portable

Parsing of XLSX archive to intermediate representation.
-}
module Text.Pandoc.Readers.Xlsx.Parse
  ( Xlsx(..)
  , XlsxWorkbook(..)
  , XlsxSheet(..)
  , SheetId(..)
  , SharedStrings
  , Styles(..)
  , FontInfo(..)
  , archiveToXlsx
  ) where

import Codec.Archive.Zip (Archive, Entry, findEntryByPath, fromEntry)
import Control.Monad (join)
import Data.Char (toLower)
import Data.List (find)
import qualified Data.Map.Strict as M
import Data.Maybe (mapMaybe, fromMaybe)
import qualified Data.Text as T
import qualified Data.Text.Lazy.Encoding as TL
import Data.Text (Text)
import Data.Time.Calendar (Day, addDays, fromGregorian, showGregorian)
import qualified Data.Vector as V
import System.FilePath (splitFileName)
import qualified System.FilePath.Posix as Posix
import Text.Pandoc.Readers.OOXML.Charts (Chart, readChart)
import Text.Pandoc.Readers.OOXML.Shared
import Text.Pandoc.Readers.Xlsx.Cells
import Text.Pandoc.Shared (collapseFilePath)
import Text.Pandoc.XML.Light
import Text.Read (readMaybe)

-- | Sheet identifier
newtype SheetId = SheetId Int deriving (Int -> SheetId -> ShowS
[SheetId] -> ShowS
SheetId -> [Char]
(Int -> SheetId -> ShowS)
-> (SheetId -> [Char]) -> ([SheetId] -> ShowS) -> Show SheetId
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SheetId -> ShowS
showsPrec :: Int -> SheetId -> ShowS
$cshow :: SheetId -> [Char]
show :: SheetId -> [Char]
$cshowList :: [SheetId] -> ShowS
showList :: [SheetId] -> ShowS
Show, SheetId -> SheetId -> Bool
(SheetId -> SheetId -> Bool)
-> (SheetId -> SheetId -> Bool) -> Eq SheetId
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SheetId -> SheetId -> Bool
== :: SheetId -> SheetId -> Bool
$c/= :: SheetId -> SheetId -> Bool
/= :: SheetId -> SheetId -> Bool
Eq, Eq SheetId
Eq SheetId =>
(SheetId -> SheetId -> Ordering)
-> (SheetId -> SheetId -> Bool)
-> (SheetId -> SheetId -> Bool)
-> (SheetId -> SheetId -> Bool)
-> (SheetId -> SheetId -> Bool)
-> (SheetId -> SheetId -> SheetId)
-> (SheetId -> SheetId -> SheetId)
-> Ord SheetId
SheetId -> SheetId -> Bool
SheetId -> SheetId -> Ordering
SheetId -> SheetId -> SheetId
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: SheetId -> SheetId -> Ordering
compare :: SheetId -> SheetId -> Ordering
$c< :: SheetId -> SheetId -> Bool
< :: SheetId -> SheetId -> Bool
$c<= :: SheetId -> SheetId -> Bool
<= :: SheetId -> SheetId -> Bool
$c> :: SheetId -> SheetId -> Bool
> :: SheetId -> SheetId -> Bool
$c>= :: SheetId -> SheetId -> Bool
>= :: SheetId -> SheetId -> Bool
$cmax :: SheetId -> SheetId -> SheetId
max :: SheetId -> SheetId -> SheetId
$cmin :: SheetId -> SheetId -> SheetId
min :: SheetId -> SheetId -> SheetId
Ord)

-- | Shared strings table (Vector for O(1) lookup)
type SharedStrings = V.Vector Text

-- | Font information
data FontInfo = FontInfo
  { FontInfo -> Bool
fontBold :: Bool
  , FontInfo -> Bool
fontItalic :: Bool
  , FontInfo -> Bool
fontUnderline :: Bool
  } deriving (Int -> FontInfo -> ShowS
[FontInfo] -> ShowS
FontInfo -> [Char]
(Int -> FontInfo -> ShowS)
-> (FontInfo -> [Char]) -> ([FontInfo] -> ShowS) -> Show FontInfo
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> FontInfo -> ShowS
showsPrec :: Int -> FontInfo -> ShowS
$cshow :: FontInfo -> [Char]
show :: FontInfo -> [Char]
$cshowList :: [FontInfo] -> ShowS
showList :: [FontInfo] -> ShowS
Show)

-- | Style information
data Styles = Styles
  { Styles -> Vector FontInfo
styleFonts :: V.Vector FontInfo
  , Styles -> Vector Int
styleCellFonts :: V.Vector Int
    -- ^ For each cell format (@cellXfs@), the index of its font
  , Styles -> Vector (Maybe DateFormat)
styleDateFormats :: V.Vector (Maybe DateFormat)
    -- ^ For each cell format (@cellXfs@), what it shows of a date
  } deriving (Int -> Styles -> ShowS
[Styles] -> ShowS
Styles -> [Char]
(Int -> Styles -> ShowS)
-> (Styles -> [Char]) -> ([Styles] -> ShowS) -> Show Styles
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Styles -> ShowS
showsPrec :: Int -> Styles -> ShowS
$cshow :: Styles -> [Char]
show :: Styles -> [Char]
$cshowList :: [Styles] -> ShowS
showList :: [Styles] -> ShowS
Show)

-- | What a date or time number format shows
data DateFormat = DateFormat
  { DateFormat -> Bool
dateShowsDate :: Bool
  , DateFormat -> Bool
dateShowsTime :: Bool
  , DateFormat -> Bool
dateShowsSeconds :: Bool
  } deriving (Int -> DateFormat -> ShowS
[DateFormat] -> ShowS
DateFormat -> [Char]
(Int -> DateFormat -> ShowS)
-> (DateFormat -> [Char])
-> ([DateFormat] -> ShowS)
-> Show DateFormat
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DateFormat -> ShowS
showsPrec :: Int -> DateFormat -> ShowS
$cshow :: DateFormat -> [Char]
show :: DateFormat -> [Char]
$cshowList :: [DateFormat] -> ShowS
showList :: [DateFormat] -> ShowS
Show)

-- | Complete XLSX document
data Xlsx = Xlsx
  { Xlsx -> XlsxWorkbook
xlsxWorkbook :: XlsxWorkbook
  , Xlsx -> [XlsxSheet]
xlsxSheets :: [XlsxSheet]
  , Xlsx -> SharedStrings
xlsxSharedStrings :: SharedStrings
  , Xlsx -> Styles
xlsxStyles :: Styles
  } deriving (Int -> Xlsx -> ShowS
[Xlsx] -> ShowS
Xlsx -> [Char]
(Int -> Xlsx -> ShowS)
-> (Xlsx -> [Char]) -> ([Xlsx] -> ShowS) -> Show Xlsx
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Xlsx -> ShowS
showsPrec :: Int -> Xlsx -> ShowS
$cshow :: Xlsx -> [Char]
show :: Xlsx -> [Char]
$cshowList :: [Xlsx] -> ShowS
showList :: [Xlsx] -> ShowS
Show)

-- | Workbook information
data XlsxWorkbook = XlsxWorkbook
  { XlsxWorkbook -> [(SheetId, Text, Text)]
workbookSheetNames :: [(SheetId, Text, Text)]  -- (id, name, relId)
  , XlsxWorkbook -> Bool
workbookDate1904 :: Bool  -- ^ Dates count from 1904 rather than 1900
  } deriving (Int -> XlsxWorkbook -> ShowS
[XlsxWorkbook] -> ShowS
XlsxWorkbook -> [Char]
(Int -> XlsxWorkbook -> ShowS)
-> (XlsxWorkbook -> [Char])
-> ([XlsxWorkbook] -> ShowS)
-> Show XlsxWorkbook
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> XlsxWorkbook -> ShowS
showsPrec :: Int -> XlsxWorkbook -> ShowS
$cshow :: XlsxWorkbook -> [Char]
show :: XlsxWorkbook -> [Char]
$cshowList :: [XlsxWorkbook] -> ShowS
showList :: [XlsxWorkbook] -> ShowS
Show)

-- | Individual worksheet
data XlsxSheet = XlsxSheet
  { XlsxSheet -> SheetId
sheetId :: SheetId
  , XlsxSheet -> Text
sheetName :: Text
  , XlsxSheet -> Map CellRef XlsxCell
sheetCells :: M.Map CellRef XlsxCell
  , XlsxSheet -> [(CellRef, CellRef)]
sheetMerges :: [(CellRef, CellRef)]
    -- ^ Merged ranges, as their top-left and bottom-right cells
  , XlsxSheet -> [Chart]
sheetCharts :: [Chart]  -- ^ In the order they are drawn
  } deriving (Int -> XlsxSheet -> ShowS
[XlsxSheet] -> ShowS
XlsxSheet -> [Char]
(Int -> XlsxSheet -> ShowS)
-> (XlsxSheet -> [Char])
-> ([XlsxSheet] -> ShowS)
-> Show XlsxSheet
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> XlsxSheet -> ShowS
showsPrec :: Int -> XlsxSheet -> ShowS
$cshow :: XlsxSheet -> [Char]
show :: XlsxSheet -> [Char]
$cshowList :: [XlsxSheet] -> ShowS
showList :: [XlsxSheet] -> ShowS
Show)

-- | Parse XLSX archive
archiveToXlsx :: Archive -> Either Text Xlsx
archiveToXlsx :: Archive -> Either Text Xlsx
archiveToXlsx Archive
archive = do
  -- Find and parse workbook.xml
  workbookPath <- Archive -> Either Text [Char]
getWorkbookXmlPath Archive
archive
  workbookElem <- loadXMLFromArchive archive workbookPath
  workbook <- parseWorkbook workbookElem
    `addContext` ("Parsing workbook.xml from: " <> T.pack workbookPath)

  -- Load workbook relationships
  workbookRels <- loadRelationships archive (relsPathFor workbookPath)

  -- Parse shared strings (look for sharedStrings relationship)
  sharedStrings <- case findRelWithTarget workbookRels "sharedStrings" of
    Just (Text
_, Text
target) -> do
      el <- Archive -> [Char] -> Either Text Element
loadXMLFromArchive Archive
archive ([Char] -> Text -> [Char]
resolveTarget [Char]
workbookPath Text
target)
      parseSharedStrings el
    Maybe (Text, Text)
Nothing -> SharedStrings -> Either Text SharedStrings
forall a b. b -> Either a b
Right SharedStrings
forall a. Vector a
V.empty

  -- Parse styles
  styles <- case findRelWithTarget workbookRels "styles" of
    Just (Text
_, Text
target) -> do
      el <- Archive -> [Char] -> Either Text Element
loadXMLFromArchive Archive
archive ([Char] -> Text -> [Char]
resolveTarget [Char]
workbookPath Text
target)
      parseStyles el
    Maybe (Text, Text)
Nothing -> Styles -> Either Text Styles
forall a b. b -> Either a b
Right (Styles -> Either Text Styles) -> Styles -> Either Text Styles
forall a b. (a -> b) -> a -> b
$ Vector FontInfo
-> Vector Int -> Vector (Maybe DateFormat) -> Styles
Styles Vector FontInfo
forall a. Vector a
V.empty Vector Int
forall a. Vector a
V.empty Vector (Maybe DateFormat)
forall a. Vector a
V.empty

  -- Parse worksheets
  sheets <- mapM (parseSheet archive workbookPath workbookRels sharedStrings
                    styles (workbookDate1904 workbook))
                 (workbookSheetNames workbook)

  return $ Xlsx workbook sheets sharedStrings styles

-- | Find workbook.xml via root relationships
getWorkbookXmlPath :: Archive -> Either Text FilePath
getWorkbookXmlPath :: Archive -> Either Text [Char]
getWorkbookXmlPath Archive
archive = do
  relsEntry <- Text -> Maybe Entry -> Either Text Entry
forall a. Text -> Maybe a -> Either Text a
maybeToEither Text
"Missing _rels/.rels" (Maybe Entry -> Either Text Entry)
-> Maybe Entry -> Either Text Entry
forall a b. (a -> b) -> a -> b
$
               [Char] -> Archive -> Maybe Entry
findEntryByPath [Char]
"_rels/.rels" Archive
archive
  relsElem <- parseXMLFromEntry relsEntry

  let relElems = [Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
relsElem
  case find isOfficeDocRel relElems of
    Maybe Element
Nothing -> Text -> Either Text [Char]
forall a b. a -> Either a b
Left Text
"No workbook.xml relationship found"
    Just Element
rel -> do
      target <- Text -> Maybe Text -> Either Text Text
forall a. Text -> Maybe a -> Either Text a
maybeToEither Text
"Missing Target" (Maybe Text -> Either Text Text) -> Maybe Text -> Either Text Text
forall a b. (a -> b) -> a -> b
$ QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"Target") Element
rel
      -- The root relationships belong to the package itself.
      return $ resolveTarget "" target
  where
    isOfficeDocRel :: Element -> Bool
isOfficeDocRel Element
el =
      case (QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"Type") Element
el, QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"Target") Element
el) of
        (Just Text
relType, Just Text
target) ->
          Text
"officeDocument" Text -> Text -> Bool
`T.isInfixOf` Text
relType Bool -> Bool -> Bool
&& Text
"workbook" Text -> Text -> Bool
`T.isInfixOf` Text
target
        (Maybe Text, Maybe Text)
_ -> Bool
False

-- | Parse workbook.xml
parseWorkbook :: Element -> Either Text XlsxWorkbook
parseWorkbook :: Element -> Either Text XlsxWorkbook
parseWorkbook Element
wbElem = do
  let ns :: NameSpaces
ns = Element -> NameSpaces
elemToNameSpaces Element
wbElem

  -- Find sheets element (match by local name only)
  sheets <- Text -> Maybe Element -> Either Text Element
forall a. Text -> Maybe a -> Either Text a
maybeToEither Text
"Missing <sheets>" (Maybe Element -> Either Text Element)
-> Maybe Element -> Either Text Element
forall a b. (a -> b) -> a -> b
$
            (Element -> Bool) -> [Element] -> Maybe Element
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"sheets") ([Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
wbElem)

  let sheetElems = (Element -> Bool) -> [Element] -> [Element]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"sheet") ([Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
sheets)
  sheetRefs <- mapM (parseSheetRef ns) (zip [1..] sheetElems)

  let date1904 = Bool -> (Text -> Bool) -> Maybe Text -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (Text -> [Text] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Text
"1", Text
"true"]) (Maybe Text -> Bool) -> Maybe Text -> Bool
forall a b. (a -> b) -> a -> b
$
        (Element -> Bool) -> [Element] -> Maybe Element
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"workbookPr") (Element -> [Element]
elChildren Element
wbElem)
          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
"date1904")

  return $ XlsxWorkbook sheetRefs date1904

parseSheetRef :: NameSpaces -> (Int, Element) -> Either Text (SheetId, Text, Text)
parseSheetRef :: NameSpaces -> (Int, Element) -> Either Text (SheetId, Text, Text)
parseSheetRef NameSpaces
ns (Int
idx, Element
sheetElem) = do
  let name :: Text
name = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe (Text
"Sheet" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> [Char] -> Text
T.pack (Int -> [Char]
forall a. Show a => a -> [Char]
show Int
idx)) (Maybe Text -> Text) -> Maybe Text -> Text
forall a b. (a -> b) -> a -> b
$
             QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"name") Element
sheetElem
  relId <- Text -> Maybe Text -> Either Text Text
forall a. Text -> Maybe a -> Either Text a
maybeToEither Text
"Missing r:id" (Maybe Text -> Either Text Text) -> Maybe Text -> Either Text Text
forall a b. (a -> b) -> a -> b
$
           NameSpaces -> Text -> Text -> Element -> Maybe Text
findAttrByName NameSpaces
ns Text
"r" Text
"id" Element
sheetElem
  return (SheetId idx, name, relId)

-- | Parse shared strings
parseSharedStrings :: Element -> Either Text SharedStrings
parseSharedStrings :: Element -> Either Text SharedStrings
parseSharedStrings Element
sstElem = do
  let siElems :: [Element]
siElems = (Element -> Bool) -> [Element] -> [Element]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"si") ([Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
sstElem)
      strings :: [Text]
strings = (Element -> Text) -> [Element] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Element -> Text
stringItemText [Element]
siElems
  SharedStrings -> Either Text SharedStrings
forall a. a -> Either Text a
forall (m :: * -> *) a. Monad m => a -> m a
return (SharedStrings -> Either Text SharedStrings)
-> SharedStrings -> Either Text SharedStrings
forall a b. (a -> b) -> a -> b
$ [Text] -> SharedStrings
forall a. [a] -> Vector a
V.fromList [Text]
strings

-- | Text of a string item (@si@ in the shared strings, @is@ in an inline
-- string cell): its @t@, or the @t@ of its rich-text runs (@r@)
-- concatenated as written. Phonetic runs (@rPh@) are skipped.
stringItemText :: Element -> Text
stringItemText :: Element -> Text
stringItemText Element
el = [Text] -> Text
T.concat
  [ Element -> Text
strContent Element
t
  | Element
child <- Element -> [Element]
elChildren Element
el
  , Element
t <- case QName -> Text
qName (Element -> QName
elName Element
child) of
           Text
"t" -> [Element
child]
           Text
"r" -> (Element -> Bool) -> [Element] -> [Element]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"t") (Element -> [Element]
elChildren Element
child)
           Text
_   -> []
  ]

-- | Parse styles (fonts only for MVP)
parseStyles :: Element -> Either Text Styles
parseStyles :: Element -> Either Text Styles
parseStyles Element
stylesElem = do
  -- Parse fonts (match by local name)
  let fontsElem :: Maybe Element
fontsElem = (Element -> Bool) -> [Element] -> Maybe Element
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"fonts") ([Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
stylesElem)
      fontElems :: [Element]
fontElems = [Element] -> (Element -> [Element]) -> Maybe Element -> [Element]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] (\Element
fe -> (Element -> Bool) -> [Element] -> [Element]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"font") ([Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
fe)) Maybe Element
fontsElem
      fonts :: Vector FontInfo
fonts = [FontInfo] -> Vector FontInfo
forall a. [a] -> Vector a
V.fromList ([FontInfo] -> Vector FontInfo) -> [FontInfo] -> Vector FontInfo
forall a b. (a -> b) -> a -> b
$ (Element -> FontInfo) -> [Element] -> [FontInfo]
forall a b. (a -> b) -> [a] -> [b]
map (NameSpaces -> Element -> FontInfo
parseFont NameSpaces
forall a. Monoid a => a
mempty) [Element]
fontElems

      -- A cell's style index (@s@) refers to a cell format in <cellXfs>,
      -- which refers to its font by @fontId@ and its number format by
      -- @numFmtId@.
      children :: Text -> Element -> [Element]
children Text
name Element
el = (Element -> Bool) -> [Element] -> [Element]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
name) (Element -> [Element]
elChildren Element
el)
      cellFormats :: [Element]
cellFormats =
        [ Element
xf
        | Element
cellXfs <- Text -> Element -> [Element]
children Text
"cellXfs" Element
stylesElem
        , Element
xf <- Text -> Element -> [Element]
children Text
"xf" Element
cellXfs
        ]
      cellFonts :: Vector Int
cellFonts = [Int] -> Vector Int
forall a. [a] -> Vector a
V.fromList
        [ 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
$ QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"fontId") Element
xf 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
>>= [Char] -> Maybe Int
forall a. Read a => [Char] -> Maybe a
readMaybe ([Char] -> Maybe Int) -> (Text -> [Char]) -> Text -> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Char]
T.unpack
        | Element
xf <- [Element]
cellFormats
        ]

      -- Number formats: custom ones from <numFmts>, by id
      customFormats :: Map Int Text
customFormats = [(Int, Text)] -> Map Int Text
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList
        [ (Int
fmtId, Text
code)
        | Element
numFmts <- Text -> Element -> [Element]
children Text
"numFmts" Element
stylesElem
        , Element
numFmt <- Text -> Element -> [Element]
children Text
"numFmt" Element
numFmts
        , Just Int
fmtId <- [QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"numFmtId") Element
numFmt 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
>>=
                           [Char] -> Maybe Int
forall a. Read a => [Char] -> Maybe a
readMaybe ([Char] -> Maybe Int) -> (Text -> [Char]) -> Text -> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Char]
T.unpack]
        , Just Text
code <- [QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"formatCode") Element
numFmt]
        ]
      xfDateFormat :: Element -> Maybe DateFormat
xfDateFormat Element
xf = do
        fmtId <- QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"numFmtId") Element
xf 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
>>= [Char] -> Maybe Int
forall a. Read a => [Char] -> Maybe a
readMaybe ([Char] -> Maybe Int) -> (Text -> [Char]) -> Text -> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Char]
T.unpack
        maybe (builtinDateFormat fmtId) customDateFormat
          (M.lookup fmtId customFormats)
      dateFormats :: Vector (Maybe DateFormat)
dateFormats = [Maybe DateFormat] -> Vector (Maybe DateFormat)
forall a. [a] -> Vector a
V.fromList ([Maybe DateFormat] -> Vector (Maybe DateFormat))
-> [Maybe DateFormat] -> Vector (Maybe DateFormat)
forall a b. (a -> b) -> a -> b
$ (Element -> Maybe DateFormat) -> [Element] -> [Maybe DateFormat]
forall a b. (a -> b) -> [a] -> [b]
map Element -> Maybe DateFormat
xfDateFormat [Element]
cellFormats

  Styles -> Either Text Styles
forall a. a -> Either Text a
forall (m :: * -> *) a. Monad m => a -> m a
return (Styles -> Either Text Styles) -> Styles -> Either Text Styles
forall a b. (a -> b) -> a -> b
$ Vector FontInfo
-> Vector Int -> Vector (Maybe DateFormat) -> Styles
Styles Vector FontInfo
fonts Vector Int
cellFonts Vector (Maybe DateFormat)
dateFormats

-- | The built-in number formats that show dates or times. Format 46,
-- @[h]:mm:ss@, shows a duration rather than a time of day.
builtinDateFormat :: Int -> Maybe DateFormat
builtinDateFormat :: Int -> Maybe DateFormat
builtinDateFormat Int
fmtId
  | Int
fmtId Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
14 Bool -> Bool -> Bool
&& Int
fmtId Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
17 = DateFormat -> Maybe DateFormat
forall a. a -> Maybe a
Just (DateFormat -> Maybe DateFormat) -> DateFormat -> Maybe DateFormat
forall a b. (a -> b) -> a -> b
$ Bool -> Bool -> Bool -> DateFormat
DateFormat Bool
True Bool
False Bool
False
  | Int
fmtId Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
18 Bool -> Bool -> Bool
|| Int
fmtId Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
20 = DateFormat -> Maybe DateFormat
forall a. a -> Maybe a
Just (DateFormat -> Maybe DateFormat) -> DateFormat -> Maybe DateFormat
forall a b. (a -> b) -> a -> b
$ Bool -> Bool -> Bool -> DateFormat
DateFormat Bool
False Bool
True Bool
False
  | Int
fmtId Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
19 Bool -> Bool -> Bool
|| Int
fmtId Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
21 Bool -> Bool -> Bool
|| Int
fmtId Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
45 Bool -> Bool -> Bool
|| Int
fmtId Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
47
                               = DateFormat -> Maybe DateFormat
forall a. a -> Maybe a
Just (DateFormat -> Maybe DateFormat) -> DateFormat -> Maybe DateFormat
forall a b. (a -> b) -> a -> b
$ Bool -> Bool -> Bool -> DateFormat
DateFormat Bool
False Bool
True Bool
True
  | Int
fmtId Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
22                = DateFormat -> Maybe DateFormat
forall a. a -> Maybe a
Just (DateFormat -> Maybe DateFormat) -> DateFormat -> Maybe DateFormat
forall a b. (a -> b) -> a -> b
$ Bool -> Bool -> Bool -> DateFormat
DateFormat Bool
True Bool
True Bool
False
  | Bool
otherwise                  = Maybe DateFormat
forall a. Maybe a
Nothing

-- | Whether a custom format code shows a date or a time: whether its
-- first section has a date or time token (y, m, d, h, s) outside quoted
-- text, escaped characters and brackets. A bracketed elapsed-time token
-- such as @[h]@ makes it a duration, which isn't treated as a date.
customDateFormat :: Text -> Maybe DateFormat
customDateFormat :: Text -> Maybe DateFormat
customDateFormat Text
code
  | Bool
elapsed = Maybe DateFormat
forall a. Maybe a
Nothing
  | Bool
showsDate Bool -> Bool -> Bool
|| Bool
showsTime = DateFormat -> Maybe DateFormat
forall a. a -> Maybe a
Just (DateFormat -> Maybe DateFormat) -> DateFormat -> Maybe DateFormat
forall a b. (a -> b) -> a -> b
$ Bool -> Bool -> Bool -> DateFormat
DateFormat Bool
showsDate Bool
showsTime Bool
hasS
  | Bool
otherwise = Maybe DateFormat
forall a. Maybe a
Nothing
  where
    ([Char]
tokens, [[Char]]
brackets) = [Char] -> [Char] -> [[Char]] -> ([Char], [[Char]])
scan (Text -> [Char]
T.unpack ((Char -> Bool) -> Text -> Text
T.takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
';') Text
code)) [] []
    has :: Char -> Bool
has Char
c = Char
c Char -> [Char] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Char]
tokens
    hasS :: Bool
hasS = Char -> Bool
has Char
's'
    showsTime :: Bool
showsTime = Char -> Bool
has Char
'h' Bool -> Bool -> Bool
|| Bool
hasS
    showsDate :: Bool
showsDate = Char -> Bool
has Char
'y' Bool -> Bool -> Bool
|| Char -> Bool
has Char
'd' Bool -> Bool -> Bool
|| (Char -> Bool
has Char
'm' Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
showsTime)
    elapsed :: Bool
elapsed = ([Char] -> Bool) -> [[Char]] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\[Char]
b -> Bool -> Bool
not ([Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
b) Bool -> Bool -> Bool
&& (Char -> Bool) -> [Char] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Char -> [Char] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` ([Char]
"hms" :: String)) [Char]
b)
                  [[Char]]
brackets
    -- Collect the letters outside quotes, escapes and brackets, and the
    -- contents of brackets.
    scan :: [Char] -> [Char] -> [[Char]] -> ([Char], [[Char]])
scan [] [Char]
ts [[Char]]
bs = ([Char]
ts, [[Char]]
bs)
    scan (Char
'"':[Char]
cs) [Char]
ts [[Char]]
bs = [Char] -> [Char] -> [[Char]] -> ([Char], [[Char]])
scan (Int -> ShowS
forall a. Int -> [a] -> [a]
drop Int
1 ((Char -> Bool) -> ShowS
forall a. (a -> Bool) -> [a] -> [a]
dropWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'"') [Char]
cs)) [Char]
ts [[Char]]
bs
    scan (Char
'\\':Char
_:[Char]
cs) [Char]
ts [[Char]]
bs = [Char] -> [Char] -> [[Char]] -> ([Char], [[Char]])
scan [Char]
cs [Char]
ts [[Char]]
bs
    scan (Char
'_':Char
_:[Char]
cs) [Char]
ts [[Char]]
bs = [Char] -> [Char] -> [[Char]] -> ([Char], [[Char]])
scan [Char]
cs [Char]
ts [[Char]]
bs
    scan (Char
'*':Char
_:[Char]
cs) [Char]
ts [[Char]]
bs = [Char] -> [Char] -> [[Char]] -> ([Char], [[Char]])
scan [Char]
cs [Char]
ts [[Char]]
bs
    scan (Char
'[':[Char]
cs) [Char]
ts [[Char]]
bs =
      let ([Char]
inside, [Char]
rest) = (Char -> Bool) -> [Char] -> ([Char], [Char])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
']') [Char]
cs
       in [Char] -> [Char] -> [[Char]] -> ([Char], [[Char]])
scan (Int -> ShowS
forall a. Int -> [a] -> [a]
drop Int
1 [Char]
rest) [Char]
ts ((Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower [Char]
inside [Char] -> [[Char]] -> [[Char]]
forall a. a -> [a] -> [a]
: [[Char]]
bs)
    scan (Char
c:[Char]
cs) [Char]
ts [[Char]]
bs = [Char] -> [Char] -> [[Char]] -> ([Char], [[Char]])
scan [Char]
cs (Char -> Char
toLower Char
c Char -> ShowS
forall a. a -> [a] -> [a]
: [Char]
ts) [[Char]]
bs

-- | Render a date serial number under a date or time format, as an ISO
-- 8601 date (@2023-11-01@), time (@14:30@ or @14:30:05@), or both joined
-- by a space. Nothing if the number isn't a date the format can show:
-- negative, or before the first day of the date system for a format
-- that shows the date.
formatDate :: Bool -> DateFormat -> Double -> Maybe Text
formatDate :: Bool -> DateFormat -> Double -> Maybe Text
formatDate Bool
date1904 DateFormat
fmt Double
serial
  | Double
serial Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
< Double
0 = Maybe Text
forall a. Maybe a
Nothing
  | Bool
otherwise = do
      dateText <- if DateFormat -> Bool
dateShowsDate DateFormat
fmt
                    then (\Day
d -> [Day -> [Char]
showGregorian Day
d]) (Day -> [[Char]]) -> Maybe Day -> Maybe [[Char]]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Day
day
                    else [[Char]] -> Maybe [[Char]]
forall a. a -> Maybe a
Just []
      let timeText = [ [Char]
showTime | DateFormat -> Bool
dateShowsTime DateFormat
fmt ]
      return $ T.pack $ unwords (dateText ++ timeText)
  where
    seconds :: Integer
seconds = Double -> Integer
forall b. Integral b => Double -> b
forall a b. (RealFrac a, Integral b) => a -> b
round (Double
serial Double -> Double -> Double
forall a. Num a => a -> a -> a
* Double
86400) :: Integer
    (Integer
days, Integer
secs) = Integer
seconds Integer -> Integer -> (Integer, Integer)
forall a. Integral a => a -> a -> (a, a)
`divMod` Integer
86400
    day :: Maybe Day
    day :: Maybe Day
day
      | Bool
date1904 = Day -> Maybe Day
forall a. a -> Maybe a
Just (Day -> Maybe Day) -> Day -> Maybe Day
forall a b. (a -> b) -> a -> b
$ Integer -> Day -> Day
addDays Integer
days (Integer -> Int -> Int -> Day
fromGregorian Integer
1904 Int
1 Int
1)
      -- 1900 system: day 1 is 1900-01-01, and day 60 is the 29 February
      -- 1900 that Excel counts but that didn't exist.
      | Integer
days Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
1 Bool -> Bool -> Bool
|| Integer
days Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
== Integer
60 = Maybe Day
forall a. Maybe a
Nothing
      | Integer
days Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
60 = Day -> Maybe Day
forall a. a -> Maybe a
Just (Day -> Maybe Day) -> Day -> Maybe Day
forall a b. (a -> b) -> a -> b
$ Integer -> Day -> Day
addDays Integer
days (Integer -> Int -> Int -> Day
fromGregorian Integer
1899 Int
12 Int
31)
      | Bool
otherwise = Day -> Maybe Day
forall a. a -> Maybe a
Just (Day -> Maybe Day) -> Day -> Maybe Day
forall a b. (a -> b) -> a -> b
$ Integer -> Day -> Day
addDays Integer
days (Integer -> Int -> Int -> Day
fromGregorian Integer
1899 Int
12 Int
30)
    (Integer
h, Integer
rest) = Integer
secs Integer -> Integer -> (Integer, Integer)
forall a. Integral a => a -> a -> (a, a)
`divMod` Integer
3600
    (Integer
m, Integer
s) = Integer
rest Integer -> Integer -> (Integer, Integer)
forall a. Integral a => a -> a -> (a, a)
`divMod` Integer
60
    pad :: a -> [Char]
pad a
n = (if a
n a -> a -> Bool
forall a. Ord a => a -> a -> Bool
< a
10 then (Char
'0' Char -> ShowS
forall a. a -> [a] -> [a]
:) else ShowS
forall a. a -> a
id) (a -> [Char]
forall a. Show a => a -> [Char]
show a
n)
    showTime :: [Char]
showTime = Integer -> [Char]
forall {a}. (Ord a, Num a, Show a) => a -> [Char]
pad Integer
h [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
":" [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ Integer -> [Char]
forall {a}. (Ord a, Num a, Show a) => a -> [Char]
pad Integer
m [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++
               (if DateFormat -> Bool
dateShowsSeconds DateFormat
fmt then [Char]
":" [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ Integer -> [Char]
forall {a}. (Ord a, Num a, Show a) => a -> [Char]
pad Integer
s else [Char]
"")

parseFont :: NameSpaces -> Element -> FontInfo
parseFont :: NameSpaces -> Element -> FontInfo
parseFont NameSpaces
_ns Element
fontElem =
  FontInfo
    { fontBold :: Bool
fontBold = (Element -> Bool) -> [Element] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"b") ([Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
fontElem)
    , fontItalic :: Bool
fontItalic = (Element -> Bool) -> [Element] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"i") ([Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
fontElem)
    , fontUnderline :: Bool
fontUnderline = (Element -> Bool) -> [Element] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"u") ([Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
fontElem)
    }

-- | Parse individual worksheet
parseSheet :: Archive -> FilePath -> [(Text, Text)] -> SharedStrings -> Styles
           -> Bool -> (SheetId, Text, Text) -> Either Text XlsxSheet
parseSheet :: Archive
-> [Char]
-> [(Text, Text)]
-> SharedStrings
-> Styles
-> Bool
-> (SheetId, Text, Text)
-> Either Text XlsxSheet
parseSheet Archive
archive [Char]
wbPath [(Text, Text)]
rels SharedStrings
sharedStrings Styles
styles Bool
date1904
           (SheetId
sid, Text
name, Text
relId) = do
  target <- Text -> Maybe Text -> Either Text Text
forall a. Text -> Maybe a -> Either Text a
maybeToEither (Text
"Sheet relationship not found: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
relId) (Maybe Text -> Either Text Text) -> Maybe Text -> Either Text Text
forall a b. (a -> b) -> a -> b
$
            Text -> [(Text, Text)] -> Maybe Text
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Text
relId [(Text, Text)]
rels

  let sheetPath = [Char] -> Text -> [Char]
resolveTarget [Char]
wbPath Text
target
  sheetElem <- loadXMLFromArchive archive sheetPath

  cells <- parseSheetCells sheetElem sharedStrings styles date1904

  let merges =
        [ (CellRef
from, CellRef
to)
        | Element
mergeCells <- (Element -> Bool) -> [Element] -> [Element]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"mergeCells")
                               (Element -> [Element]
elChildren Element
sheetElem)
        , Element
mergeCell <- (Element -> Bool) -> [Element] -> [Element]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"mergeCell")
                              (Element -> [Element]
elChildren Element
mergeCells)
        , Just Text
ref <- [QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"ref") Element
mergeCell]
        , (Text
fromText, Text
toText) <- [HasCallStack => Text -> Text -> (Text, Text)
Text -> Text -> (Text, Text)
T.breakOn Text
":" Text
ref]
        , Right CellRef
from <- [Text -> Either Text CellRef
parseCellRef Text
fromText]
        , Right CellRef
to <- [Text -> Either Text CellRef
parseCellRef (Int -> Text -> Text
T.drop Int
1 Text
toText)]
        ]

  return $ XlsxSheet sid name cells merges
           (sheetChartsOf archive sheetPath)

-- | The charts on a worksheet or chart sheet: those its drawing refers
-- to, in document order. A drawing or chart that can't be read is left
-- out.
sheetChartsOf :: Archive -> FilePath -> [Chart]
sheetChartsOf :: Archive -> [Char] -> [Chart]
sheetChartsOf Archive
archive [Char]
sheetPath = [Chart] -> Maybe [Chart] -> [Chart]
forall a. a -> Maybe a -> a
fromMaybe [] (Maybe [Chart] -> [Chart]) -> Maybe [Chart] -> [Chart]
forall a b. (a -> b) -> a -> b
$ do
  drawingTarget <- Archive -> [Char] -> Text -> Maybe Text
findRelTargetByType Archive
archive (ShowS
relsPathFor [Char]
sheetPath)
                     Text
"drawing"
  let drawingPath = [Char] -> Text -> [Char]
resolveTarget [Char]
sheetPath Text
drawingTarget
  drawing <- either (const Nothing) Just $
             loadXMLFromArchive archive drawingPath
  drawingRels <- either (const Nothing) Just $
                 loadRelationships archive (relsPathFor drawingPath)
  return
    [ chart
    | chartElem <- filterElementsName ((== "chart") . qName) drawing
    , Just relId <- [lookupRelId chartElem]
    , Just chartTarget <- [lookup relId drawingRels]
    , Right chart <- [readChart archive
                        (resolveTarget drawingPath chartTarget)]
    ]
  where
    lookupRelId :: Element -> Maybe Text
lookupRelId Element
el = Attr -> Text
attrVal (Attr -> Text) -> Maybe Attr -> Maybe Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Attr -> Bool) -> [Attr] -> Maybe Attr
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find Attr -> Bool
isRelId (Element -> [Attr]
elAttribs Element
el)
    isRelId :: Attr -> Bool
isRelId Attr
a = QName -> Text
qName (Attr -> QName
attrKey Attr
a) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"id" Bool -> Bool -> Bool
&& QName -> Maybe Text
qURI (Attr -> QName
attrKey Attr
a) Maybe Text -> Maybe Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text -> Maybe Text
forall a. a -> Maybe a
Just
      Text
"http://schemas.openxmlformats.org/officeDocument/2006/relationships"

-- | Find the target of the first relationship in a .rels part whose Type
-- ends with the given name, such as @drawing@
findRelTargetByType :: Archive -> FilePath -> Text -> Maybe Text
findRelTargetByType :: Archive -> [Char] -> Text -> Maybe Text
findRelTargetByType Archive
archive [Char]
relsPath Text
typeName = do
  entry <- [Char] -> Archive -> Maybe Entry
findEntryByPath [Char]
relsPath Archive
archive
  relsElem <- either (const Nothing) Just $ parseXMLFromEntry entry
  rel <- find hasType (onlyElems $ elContent relsElem)
  findAttr (unqual "Target") rel
  where
    hasType :: Element -> Bool
hasType Element
el = Bool -> (Text -> Bool) -> Maybe Text -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False ((Text
"/" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
typeName) Text -> Text -> Bool
`T.isSuffixOf`) (Maybe Text -> Bool) -> Maybe Text -> Bool
forall a b. (a -> b) -> a -> b
$
                 QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"Type") Element
el

-- | Parse sheet cells
parseSheetCells :: Element -> SharedStrings -> Styles -> Bool
                -> Either Text (M.Map CellRef XlsxCell)
parseSheetCells :: Element
-> SharedStrings
-> Styles
-> Bool
-> Either Text (Map CellRef XlsxCell)
parseSheetCells Element
sheetElem SharedStrings
sharedStrings Styles
styles Bool
date1904 = do
  -- Find sheetData by local name
  case (Element -> Bool) -> [Element] -> Maybe Element
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"sheetData") ([Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
sheetElem) of
    Maybe Element
Nothing -> Map CellRef XlsxCell -> Either Text (Map CellRef XlsxCell)
forall a. a -> Either Text a
forall (m :: * -> *) a. Monad m => a -> m a
return Map CellRef XlsxCell
forall k a. Map k a
M.empty
    Just Element
sheetData -> do
      let rowElems :: [Element]
rowElems = (Element -> Bool) -> [Element] -> [Element]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"row") ([Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
sheetData)
          cellElems :: [Element]
cellElems = (Element -> [Element]) -> [Element] -> [Element]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\Element
r -> (Element -> Bool) -> [Element] -> [Element]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"c") ([Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
r)) [Element]
rowElems
          cells :: [XlsxCell]
cells = (Element -> Maybe XlsxCell) -> [Element] -> [XlsxCell]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (SharedStrings -> Styles -> Bool -> Element -> Maybe XlsxCell
parseCell SharedStrings
sharedStrings Styles
styles Bool
date1904) [Element]
cellElems
      Map CellRef XlsxCell -> Either Text (Map CellRef XlsxCell)
forall a. a -> Either Text a
forall (m :: * -> *) a. Monad m => a -> m a
return (Map CellRef XlsxCell -> Either Text (Map CellRef XlsxCell))
-> Map CellRef XlsxCell -> Either Text (Map CellRef XlsxCell)
forall a b. (a -> b) -> a -> b
$ [(CellRef, XlsxCell)] -> Map CellRef XlsxCell
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [(XlsxCell -> CellRef
cellRef XlsxCell
c, XlsxCell
c) | XlsxCell
c <- [XlsxCell]
cells]

-- | Parse individual cell
parseCell :: SharedStrings -> Styles -> Bool -> Element -> Maybe XlsxCell
parseCell :: SharedStrings -> Styles -> Bool -> Element -> Maybe XlsxCell
parseCell SharedStrings
sharedStrings Styles
styles Bool
date1904 Element
cElem = do
  -- Get cell reference
  refText <- QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"r") Element
cElem
  cellRefParsed <- either (const Nothing) Just $ parseCellRef refText

  -- Get cell type (default to number if missing)
  let cellType = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
"" (Maybe Text -> Text) -> Maybe Text -> Text
forall a b. (a -> b) -> a -> b
$ QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"t") Element
cElem
      styleIdx = QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"s") Element
cElem 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
>>= [Char] -> Maybe Int
forall a. Read a => [Char] -> Maybe a
readMaybe ([Char] -> Maybe Int) -> (Text -> [Char]) -> Text -> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Char]
T.unpack

  -- Get value (match by local name)
  let vElem = (Element -> Bool) -> [Element] -> Maybe Element
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"v") ([Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
cElem)
      vText = Text -> (Element -> Text) -> Maybe Element -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" Element -> Text
strContent Maybe Element
vElem

  -- Parse value based on type
  let value = if Text
cellType Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"s"
              then
                -- Shared string
                case [Char] -> Maybe Int
forall a. Read a => [Char] -> Maybe a
readMaybe (Text -> [Char]
T.unpack Text
vText) of
                  Just Int
idx | Int
idx Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
0 Bool -> Bool -> Bool
&& Int
idx Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< SharedStrings -> Int
forall a. Vector a -> Int
V.length SharedStrings
sharedStrings ->
                    Text -> CellValue
TextValue (SharedStrings
sharedStrings SharedStrings -> Int -> Text
forall a. Vector a -> Int -> a
V.! Int
idx)
                  Maybe Int
_ -> CellValue
EmptyValue
              else if Text
cellType Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"inlineStr"
                then
                  -- Inline string, held in the cell itself rather than in <v>
                  CellValue -> (Element -> CellValue) -> Maybe Element -> CellValue
forall b a. b -> (a -> b) -> Maybe a -> b
maybe CellValue
EmptyValue (Text -> CellValue
TextValue (Text -> CellValue) -> (Element -> Text) -> Element -> CellValue
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Element -> Text
stringItemText) (Maybe Element -> CellValue) -> Maybe Element -> CellValue
forall a b. (a -> b) -> a -> b
$
                    (Element -> Bool) -> [Element] -> Maybe Element
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (\Element
e -> QName -> Text
qName (Element -> QName
elName Element
e) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"is") (Element -> [Element]
elChildren Element
cElem)
              else if Text -> Bool
T.null Text
vText
                then CellValue
EmptyValue
              else if Text
cellType Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"b"
                then Bool -> CellValue
BoolValue (Text
vText Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"1")
                else
                  -- Number
                  case [Char] -> Maybe Double
forall a. Read a => [Char] -> Maybe a
readMaybe (Text -> [Char]
T.unpack Text
vText) of
                    Just Double
n
                      | Just Text
txt <- Maybe DateFormat
dateFormat Maybe DateFormat -> (DateFormat -> 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
>>= \DateFormat
f -> Bool -> DateFormat -> Double -> Maybe Text
formatDate Bool
date1904 DateFormat
f Double
n
                      -> Text -> CellValue
TextValue Text
txt
                      | Bool
otherwise -> Double -> CellValue
NumberValue Double
n
                    Maybe Double
Nothing -> Text -> CellValue
TextValue Text
vText
      dateFormat = Maybe (Maybe DateFormat) -> Maybe DateFormat
forall (m :: * -> *) a. Monad m => m (m a) -> m a
join (Maybe (Maybe DateFormat) -> Maybe DateFormat)
-> Maybe (Maybe DateFormat) -> Maybe DateFormat
forall a b. (a -> b) -> a -> b
$ Maybe Int
styleIdx Maybe Int
-> (Int -> Maybe (Maybe DateFormat)) -> Maybe (Maybe DateFormat)
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Styles -> Vector (Maybe DateFormat)
styleDateFormats Styles
styles Vector (Maybe DateFormat) -> Int -> Maybe (Maybe DateFormat)
forall a. Vector a -> Int -> Maybe a
V.!?)

  -- Get formatting from style
  let font = do
        idx <- Maybe Int
styleIdx
        fontIdx <- styleCellFonts styles V.!? idx
        styleFonts styles V.!? fontIdx
      (bold, italic) = maybe (False, False)
                         (\FontInfo
f -> (FontInfo -> Bool
fontBold FontInfo
f, FontInfo -> Bool
fontItalic FontInfo
f)) font

  return $ XlsxCell cellRefParsed value bold italic

-- Helper functions
loadXMLFromArchive :: Archive -> FilePath -> Either Text Element
loadXMLFromArchive :: Archive -> [Char] -> Either Text Element
loadXMLFromArchive Archive
archive [Char]
path = do
  entry <- Text -> Maybe Entry -> Either Text Entry
forall a. Text -> Maybe a -> Either Text a
maybeToEither (Text
"Entry not found: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> [Char] -> Text
T.pack [Char]
path) (Maybe Entry -> Either Text Entry)
-> Maybe Entry -> Either Text Entry
forall a b. (a -> b) -> a -> b
$
           [Char] -> Archive -> Maybe Entry
findEntryByPath [Char]
path Archive
archive
  parseXMLFromEntry entry

parseXMLFromEntry :: Entry -> Either Text Element
parseXMLFromEntry :: Entry -> Either Text Element
parseXMLFromEntry Entry
entry =
  let lazyText :: Text
lazyText = ByteString -> Text
TL.decodeUtf8 (ByteString -> Text) -> ByteString -> Text
forall a b. (a -> b) -> a -> b
$ Entry -> ByteString
fromEntry Entry
entry
   in Text -> Either Text Element
parseXMLElement Text
lazyText

loadRelationships :: Archive -> FilePath -> Either Text [(Text, Text)]
loadRelationships :: Archive -> [Char] -> Either Text [(Text, Text)]
loadRelationships Archive
archive [Char]
relsPath =
  case [Char] -> Archive -> Maybe Entry
findEntryByPath [Char]
relsPath Archive
archive of
    Maybe Entry
Nothing -> [(Text, Text)] -> Either Text [(Text, Text)]
forall a b. b -> Either a b
Right []
    Just Entry
entry -> do
      relsElem <- Entry -> Either Text Element
parseXMLFromEntry Entry
entry
      let relElems = [Content] -> [Element]
onlyElems ([Content] -> [Element]) -> [Content] -> [Element]
forall a b. (a -> b) -> a -> b
$ Element -> [Content]
elContent Element
relsElem
      return $ mapMaybe extractRel relElems
  where
    extractRel :: Element -> Maybe (Text, Text)
extractRel Element
el = do
      relId <- QName -> Element -> Maybe Text
findAttr (Text -> QName
unqual Text
"Id") Element
el
      target <- findAttr (unqual "Target") el
      return (relId, target)

relsPathFor :: FilePath -> FilePath
relsPathFor :: ShowS
relsPathFor [Char]
path =
  let ([Char]
dir, [Char]
file) = [Char] -> ([Char], [Char])
splitFileName [Char]
path
   in [Char]
dir [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
"/_rels/" [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
file [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
".rels"

-- | Resolve a relationship target to an archive path. A target starting
-- with @/@ is relative to the package root; any other target is relative
-- to the folder of the part that holds the relationship.
resolveTarget :: FilePath -> Text -> FilePath
resolveTarget :: [Char] -> Text -> [Char]
resolveTarget [Char]
source Text
target =
  case Text -> [Char]
T.unpack Text
target of
    Char
'/':[Char]
path -> [Char]
path
    [Char]
path -> ShowS
collapseFilePath (ShowS
Posix.takeDirectory [Char]
source [Char] -> ShowS
Posix.</> [Char]
path)

findRelWithTarget :: [(Text, Text)] -> Text -> Maybe (Text, Text)
findRelWithTarget :: [(Text, Text)] -> Text -> Maybe (Text, Text)
findRelWithTarget [(Text, Text)]
rels Text
targetName =
  ((Text, Text) -> Bool) -> [(Text, Text)] -> Maybe (Text, Text)
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (\(Text
_, Text
target) -> Text
targetName Text -> Text -> Bool
`T.isInfixOf` Text
target) [(Text, Text)]
rels

maybeToEither :: Text -> Maybe a -> Either Text a
maybeToEither :: forall a. Text -> Maybe a -> Either Text a
maybeToEither Text
err Maybe a
Nothing = Text -> Either Text a
forall a b. a -> Either a b
Left Text
err
maybeToEither Text
_ (Just a
x) = a -> Either Text a
forall a b. b -> Either a b
Right a
x

addContext :: Either Text a -> Text -> Either Text a
addContext :: forall a. Either Text a -> Text -> Either Text a
addContext (Right a
x) Text
_ = a -> Either Text a
forall a b. b -> Either a b
Right a
x
addContext (Left Text
err) Text
ctx = Text -> Either Text a
forall a b. a -> Either a b
Left (Text
err Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" (context: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
ctx Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
")")