packages feed

cattrap (empty) → 0.1.0.0

raw patch · 17 files changed

+3387/−0 lines, 17 filesdep +GLUTdep +QuickCheckdep +balkonsetup-changed

Dependencies added: GLUT, QuickCheck, balkon, base, bytestring, cattrap, containers, css-syntax, fontconfig-pure, gl, harfbuzz-pure, hspec, scientific, stylist-traits, text, xml

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Revision history for cattrap++## 0.1.0.0 -- YYYY-mm-dd++* First version. Released on an unsuspecting world.
+ Graphics/Layout.hs view
@@ -0,0 +1,366 @@+{-# LANGUAGE OverloadedStrings, RecordWildCards #-}+-- | Generic layout logic, handling a hierarchy of varying formulas.+-- Unless callers have more specific needs they probably wish to use this abstraction.+-- Attempts to follow the CSS specs.+-- See `boxLayout` for a main entrypoint,+-- & `Graphics.Layout.CSS` to receive CSS input.+module Graphics.Layout(LayoutItem(..),+        layoutGetBox, layoutGetChilds, layoutGetInner,+        boxMinWidth, boxMaxWidth, boxNatWidth, boxWidth,+        boxNatHeight, boxMinHeight, boxMaxHeight, boxHeight,+        boxSplit, boxPaginate, boxPosition, boxLayout, glyphsPerFont) where++import Data.Text.ParagraphLayout (Paragraph(..), ParagraphOptions(..), Fragment(..),+        ParagraphLayout(..), PageOptions(..), PageContinuity(..), paginate, layoutPlain)+import Stylist (PropertyParser(..))++import Graphics.Layout.Box as B+import Graphics.Layout.Grid as G+import Graphics.Layout.Flow as F+import Graphics.Layout.Inline as I+import Graphics.Layout.CSS.Font (Font'(..))++import Data.Maybe (fromMaybe)++-- To gather glyphs for atlases.+import qualified Data.IntSet as IS+import qualified Data.Map.Strict as M+import qualified Data.Text.Glyphize as Hb+import Graphics.Text.Font.Choose (Pattern)++-- | A tree of different layout algorithms.+-- More to come...+data LayoutItem m n x =+    -- | A block element. With margins, borders, & padding.+    LayoutFlow x (PaddedBox m n) [LayoutItem m n x]+    -- | A grid or table element.+    | LayoutGrid x (Grid m n) [GridItem] [LayoutItem m n x]+    -- | Some richtext.+    | LayoutInline x Font' Paragraph PageOptions [x] -- Balkon holds children.+    -- | Results laying out richtext, has fixed width.+    -- Generated from `LayoutInline` for the sake of pagination.+    | LayoutInline' x Font' ParagraphLayout PageOptions [x]+    -- | Children of a `LayoutInline` or `LayoutInline'`.+    | LayoutSpan x Font' Fragment+-- | An empty box.+nullLayout :: (PropertyParser x, Zero m, Zero n) => LayoutItem m n x+nullLayout = LayoutFlow temp zero []++--- | Retrieve the surrounding box for a layout item.+layoutGetBox :: (Zero m, Zero n, CastDouble m, CastDouble n) =>+        LayoutItem m n x -> PaddedBox m n+layoutGetBox (LayoutFlow _ ret _) = ret+layoutGetBox (LayoutGrid _ self _ _) = zero {+    B.min = Size (fromDouble $ trackMin toDouble $ inline self)+            (fromDouble $ trackMin toDouble $ block self),+    B.size = Size (fromDouble $ trackNat toDouble $ inline self)+            (fromDouble $ trackNat toDouble $ block self),+    B.max = Size (fromDouble $ trackNat toDouble $ inline self)+            (fromDouble $ trackNat toDouble $ block self)+}+layoutGetBox (LayoutInline _ f self _ _) = zero {+    B.min = inlineMin f self, B.size = inlineSize f self, B.max = inlineSize f self+}+layoutGetBox (LayoutInline' _ f self _ _) = zero {+    B.min = layoutSize f self, B.size = layoutSize f self, B.max = layoutSize f self+}+layoutGetBox (LayoutSpan _ f self) = zero {+    B.min = fragmentSize f self, B.size = fragmentSize f self, B.max = fragmentSize f self+}+-- | Retrieve the subtree under a node.+layoutGetChilds (LayoutFlow _ _ ret) = ret+layoutGetChilds (LayoutGrid _ _ _ ret) = ret+layoutGetChilds (LayoutSpan _ _ _) = []+layoutGetChilds (LayoutInline _ font self _ vals) = map inner $ inlineChildren vals self+  where inner (val, fragment) = LayoutSpan val font fragment+layoutGetChilds (LayoutInline' _ font self _ vals) = map inner $ layoutChildren vals self+  where inner (val, fragment) = LayoutSpan val font fragment+-- | Retrieve the caller-specified data attached to a layout node.+layoutGetInner (LayoutFlow ret _ _) = ret+layoutGetInner (LayoutGrid ret _ _ _) = ret+layoutGetInner (LayoutInline ret _ _ _ _) = ret+layoutGetInner (LayoutInline' ret _ _ _ _) = ret+layoutGetInner (LayoutSpan ret _ _) = ret++-- | map-ready wrapper around `setCellBox` sourcing from a child node.+setCellBox' (child, cell) = setCellBox cell $ layoutGetBox child++-- | Update a (sub)tree to compute & cache minimum legible sizes.+boxMinWidth :: (Zero y, CastDouble y) =>+        Maybe Double -> LayoutItem y Length x -> LayoutItem y Length x+boxMinWidth parent (LayoutFlow val self childs) = LayoutFlow val self' childs'+  where+    self' = self { B.min = mapSizeX (B.mapAuto min') (B.min self) }+    min' = flowMinWidth parent' self childs''+    childs'' = map (mapX' $ lowerLength selfWidth) $ map layoutGetBox childs'+    childs' = map (boxMinWidth $ Just selfWidth) childs+    selfWidth = width $ mapX' (lowerLength parent') self+    parent' = fromMaybe 0 parent+boxMinWidth parent (LayoutGrid val self cells0 childs) = LayoutGrid val self' cells' childs'+  where+    self' = Size (inline self) { trackMins = cells } (block self)+    cells = sizeTrackMins parent' (inline self) $ map inline cells'+    cells' = map setCellBox' $ zip childs' cells0 -- Flatten subgrids+    childs'' = map (mapX' $ lowerLength selfWidth) $ map layoutGetBox childs'+    childs' = map (boxMinWidth $ Just selfWidth) childs+    selfWidth = trackNat (lowerLength parent') $ inline self+    parent' = fromMaybe (gridEstWidth self cells0) parent+    zeroBox :: PaddedBox Double Double+    zeroBox = zero+boxMinWidth _ self@(LayoutInline _ _ _ _ _) = self+boxMinWidth _ self@(LayoutInline' _ _ _ _ _) = self+boxMinWidth _ self@(LayoutSpan _ _ _) = self+-- | Update a (sub)tree to compute & cache ideal width.+boxNatWidth :: (Zero y, CastDouble y) =>+        Maybe Double -> LayoutItem y Length x -> LayoutItem y Length x+boxNatWidth parent (LayoutFlow val self childs) = LayoutFlow val self' childs'+  where+    self' = self { B.nat = Size size' $ block $ B.nat self }+    size' = flowNatWidth parent' self childs''+    childs'' = map (mapX' $ lowerLength selfWidth) $ map layoutGetBox childs'+    childs' = map (boxNatWidth $ Just selfWidth) childs+    selfWidth = width $ mapX' (lowerLength parent') self+    parent' = fromMaybe 0 parent+boxNatWidth parent (LayoutGrid val self cells0 childs) = LayoutGrid val self' cells' childs'+  where+    self' = Size (inline self) { trackNats = cells } (block self)+    cells = sizeTrackNats parent' (inline $ self) $ map inline cells'+    cells' = map setCellBox' $ zip childs' cells0 -- Flatten subgrids+    childs'' = map (mapX' $ lowerLength selfWidth) $ map layoutGetBox childs'+    childs' = map (boxNatWidth $ Just selfWidth) childs+    selfWidth = trackNat (lowerLength parent') $ inline self+    parent' = fromMaybe (gridEstWidth self cells0) parent+    zeroBox :: PaddedBox Double Double+    zeroBox = zero+boxNatWidth _ self@(LayoutInline _ _ _ _ _) = self+boxNatWidth _ self@(LayoutInline' _ _ _ _ _) = self+boxNatWidth _ self@(LayoutSpan _ _ _) = self+-- | Update a (sub)tree to compute & cache maximum legible width.+boxMaxWidth :: CastDouble y => PaddedBox a Double -> LayoutItem y Length x -> LayoutItem y Length x+boxMaxWidth parent (LayoutFlow val self childs) = LayoutFlow val self' childs'+  where+    childs' = map (boxMaxWidth self'') childs+    self'' = mapX' (lowerLength $ inline $ B.size parent) self'+    self' = self { B.max = Size (Pixels max') (block $ B.max self) }+    max' = flowMaxWidth parent self+boxMaxWidth parent (LayoutGrid val self cells childs) = LayoutGrid val self cells childs'+  where -- Propagate parent track as default.+    childs' = map inner $ zip cells childs+    inner (Size cellx celly, child) =+        boxMaxWidth (cellSize (inline self) cellx `size2box` cellSize (block self) celly) child+    size2box x y = zeroBox { B.min = Size x y, B.max = Size x y, B.size = Size x y }+boxMaxWidth parent self@(LayoutInline _ _ _ _ _) = self+boxMaxWidth parent self@(LayoutInline' _ _ _ _ _) = self+boxMaxWidth parent self@(LayoutSpan _ f self') = self+-- | Update a (sub)tree to compute & cache final width.+boxWidth :: (Zero y, CastDouble y) => PaddedBox b Double -> LayoutItem y Length x ->+        LayoutItem y Double x+boxWidth parent (LayoutFlow val self childs) = LayoutFlow val self' childs'+  where+    childs' = map (boxWidth self') childs+    self' = (mapX' (lowerLength $ inline $ size parent) self) {+        size = Size size' $ block $ B.max self+      }+    size' = flowWidth parent self+boxWidth parent (LayoutGrid val self cells childs) = LayoutGrid val self' cells' childs'+  where -- Propagate parent track as default+    (cells', childs') = unzip $ map recurse $ zip cells childs+    recurse (cell, child) = (cell', child')+      where+        cell' = setCellBox cell $ layoutGetBox child'+        child' = boxWidth (gridItemBox self cell) child+    self' = flip Size (block self) Track {+        cells = map Left widths,+        trackMins = trackMins $ inline self, trackNats = trackNats $ inline self,+        gap = lowerLength outerwidth $ gap $ inline self+    }+    outerwidth = inline $ size parent+    widths = sizeTrackMaxs (inline $ size parent) $ inline self+boxWidth parent (LayoutInline val font (Paragraph a b c d) paging vals) =+    LayoutInline val font (Paragraph a b c d { paragraphMaxWidth = round width }) paging vals+  where width = B.inline $ B.size parent+boxWidth _ (LayoutInline' a b c d e) = LayoutInline' a b c d e+boxWidth parent (LayoutSpan val font self') = LayoutSpan val font self'++-- | Update a (sub)tree to compute & cache ideal legible height.+boxNatHeight :: Double -> LayoutItem Length Double x -> LayoutItem Length Double x+boxNatHeight parent (LayoutFlow val self childs) = LayoutFlow val self' childs'+  where+    self' = self { size = mapSizeY (mapAuto size') (size self) }+    size' = flowNatHeight parent self childs''+    childs'' = map (mapY' (lowerLength parent)) $ map layoutGetBox childs'+    childs' = map (boxNatHeight $ inline $ size self) childs+boxNatHeight parent (LayoutGrid val self cells childs) = LayoutGrid val self' cells childs'+  where+    self' = Size (inline self) (block self) { trackNats = heights }+    heights = sizeTrackNats parent (block self) $ map block cells'+    cells' = map setCellBox' $ zip childs' cells -- Flatten subgrids+    childs' = map (boxNatHeight width) childs+    width = trackNat id $ inline self+boxNatHeight parent self@(LayoutInline _ _ _ _ _) = self+boxNatHeight parent self@(LayoutInline' _ _ _ _ _) = self+boxNatHeight parent self@(LayoutSpan _ _ _) = self+-- | Update a (sub)tree to compute & cache minimum legible height.+boxMinHeight :: Double -> LayoutItem Length Double x -> LayoutItem Length Double x+boxMinHeight parent (LayoutFlow val self childs) = LayoutFlow val self' childs'+  where+    childs' = map (boxMinHeight $ inline $ size self) childs+    self' = self { B.min = Size (inline $ B.min self) (Pixels min') }+    min' = flowMinHeight parent self+boxMinHeight parent (LayoutGrid val self cells childs) = LayoutGrid val self' cells' childs'+  where+    (cells', childs') = unzip $ map recurse $ zip cells childs+    recurse (cell, child) = (cell', child') -- Propagate track into subgrids.+      where+        cell' = setCellBox cell (layoutGetBox child')+        child' = boxMinHeight width child+    self' = Size (inline self) (block self) { trackMins = heights }+    heights = sizeTrackMins width (block self) $ map block cells+    width = trackNat id $ inline self+boxMinHeight parent self@(LayoutInline _ _ _ _ _) = self+boxMinHeight _ self@(LayoutInline' _ _ _ _ _) = self+boxMinHeight parent self@(LayoutSpan _ font self') = self+-- | Update a subtree to compute & cache maximum legible height.+boxMaxHeight :: PaddedBox Double Double -> LayoutItem Length Double x ->+        LayoutItem Length Double x+boxMaxHeight parent (LayoutFlow val self childs) = LayoutFlow val self' childs'+  where+    childs' = map (boxMaxHeight $ mapY' (lowerLength width) self') childs+    self' = self { B.max = Size (inline $ B.max self) (Pixels max') }+    max' = flowMaxHeight (inline $ size parent) self+    width = inline $ size self+boxMaxHeight parent (LayoutGrid val self cells childs) = LayoutGrid val self cells' childs'+  where+    (cells', childs') = unzip $ map recurse $ zip cells childs+    recurse (cell, child) = (cell', child') -- Propagate track into subgrids+      where+        cell' = setCellBox cell (layoutGetBox child')+        child' = boxMaxHeight (gridItemBox self cell) child+    heights = sizeTrackMaxs (inline $ size parent) (block self)+    width = inline $ size parent+boxMaxHeight parent (LayoutInline val font self' paging vals) =+    LayoutInline val font self' paging vals+boxMaxHeight parent (LayoutInline' val font self' paging vals) =+    LayoutInline' val font self' paging vals+boxMaxHeight parent (LayoutSpan val font self') = LayoutSpan val font self'+-- | Update a (sub)tree to compute & cache final height.+boxHeight :: PaddedBox Double Double -> LayoutItem Length Double x -> LayoutItem Double Double x+boxHeight parent (LayoutFlow val self childs) = LayoutFlow val self' childs'+  where+    childs' = map (boxHeight self') childs+    self' = (mapY' (lowerLength $ inline $ size parent) self) {+        size = Size (inline $ size self) size'+      }+    size' = flowHeight parent self+    width = inline $ size self+boxHeight parent (LayoutGrid val self cells0 childs) = LayoutGrid val self' cells' childs'+  where+    (cells', childs') = unzip $ map recurse $ zip cells0 childs+    recurse (cell, child) = (cell', child') -- Propagate track into subgrids.+      where+        cell' = setCellBox cell (layoutGetBox child')+        child' = boxHeight (layoutGetBox $ LayoutGrid val self' [] []) child+    self' = Size (inline self) Track {+        gap = lowerLength width $ gap $ block self,+        cells = map lowerSize $ cells $ block self,+        trackMins = trackMins $ block self, trackNats = trackNats $ block self+      }+    heights = sizeTrackMaxs (inline $ size parent) $ block self+    lowerSize (Left x) = Left $ lowerLength width x+    lowerSize (Right x) = Right x+    width = inline $ size parent+boxHeight parent (LayoutInline val font self' paging vals) =+    LayoutInline val font self' paging vals+boxHeight _ (LayoutInline' val font self' paging vals) =+    LayoutInline' val font self' paging vals+boxHeight _ (LayoutSpan val font self') = LayoutSpan val font self'++-- | Split a (sub)tree to fit within max-height.+-- May take full page height into account.+boxSplit :: PropertyParser x => Double -> Double -> LayoutItem Double Double x ->+    (LayoutItem Double Double x, Maybe (LayoutItem Double Double x))+boxSplit maxheight _ node | height (layoutGetBox node) <= maxheight = (node, Nothing)+boxSplit maxheight pageheight (LayoutFlow val self childs)+    | (next:_) <- childs1, ((y,_):_) <- childs0',+        (tail,Just nextpage) <- boxSplit (maxheight - y) pageheight next =+            (LayoutFlow val self {+                size = (size self) { B.block = y }+            } (childs0 ++ [tail]),+             Just $ LayoutFlow val self {+                size = (size self) { B.block = B.block (size self) - y }+             } (nextpage:childs1))+    | otherwise =+        (LayoutFlow val self { size = (size self) { B.block = maxheight } } childs0,+         Just $ LayoutFlow val self childs1) -- TODO recompute height+  where+    childs0 = map snd childs0'+    childs1 = map snd childs1'+    (childs0', childs1') = break overflowed $ inner 0 childs+    overflowed (y, _) = y >= maxheight+    inner start (child:childs) = (start', child):inner start' childs -- TODO margin collapse?+        where start' = start + height (layoutGetBox child)+    inner _ [] = []+boxSplit _ _ self@(LayoutGrid _ _ _ _) = (self, Nothing) -- TODO+boxSplit maxheight pageheight (LayoutInline a b self c d) =+    boxSplit maxheight pageheight $ LayoutInline' a b (layoutPlain self) c d+boxSplit maxheight pageheight (LayoutInline' a b self paging c) =+    case paginate paging {+            pageCurrentHeight = toEnum $ fromEnum maxheight,+            pageNextHeight = toEnum $ fromEnum pageheight+      } self of+        (Continue, self', next) -> (wrap self', wrap <$> next)+        (Break, _, _) -> (nullLayout, Just $ wrap self)+  where+    wrap self' = LayoutInline' a b self' paging c+boxSplit _ _ self@(LayoutSpan _ _ _) = (self, Nothing) -- Can't split!+-- | Generate a list of pages from a node, splitting subtrees where necessary.+boxPaginate pageheight node+    | (page, Just overflow) <- boxSplit pageheight pageheight node =+        page:boxPaginate pageheight overflow+    | otherwise = [node]++-- | Compute position of all nodes in the (sub)tree relative to a base coordinate.+boxPosition :: PropertyParser x => (Double, Double) -> LayoutItem Double Double x ->+    LayoutItem Double Double ((Double, Double), x)+boxPosition pos@(x, y) (LayoutFlow val self childs) = LayoutFlow (pos, val) self childs'+  where+    childs' = map recurse $ zip pos' childs+    recurse ((Size x' y'), child) = boxPosition (x + x', y + y') child+    pos' = positionFlow $ map layoutGetBox childs+boxPosition pos@(x, y) (LayoutGrid val self cells childs) = LayoutGrid (pos, val) self cells childs'+  where+    childs' = map recurse $ zip pos' childs+    recurse ((x', y'), child) = boxPosition (x + x', y + y') child+    pos' = gridPosition self cells+boxPosition pos@(x, y) (LayoutInline val font self paging vals) =+    LayoutInline (pos, val) font self paging $ map (\(x, y) -> (fragmentPos font pos y, x)) $+            inlineChildren vals self+boxPosition pos@(x, y) (LayoutInline' val font self paging vals) =+    LayoutInline' (pos, val) font self paging $ map (\(x, y) -> (fragmentPos font pos y, x)) $+            layoutChildren vals self+boxPosition pos (LayoutSpan val f self) = LayoutSpan (pos, val) f self -- No children...+-- | Compute sizes & position information for all nodes in the (sub)tree.+boxLayout :: PropertyParser x => PaddedBox Double Double -> LayoutItem Length Length x ->+        Bool -> [LayoutItem Double Double ((Double, Double), x)]+boxLayout parent self paginate = self9+  where+    self0 = boxMinWidth Nothing self+    self1 = boxNatWidth Nothing self0+    self2 = boxMaxWidth parent self1+    self3 = boxWidth parent self2+    self4 = boxNatHeight (inline $ size parent) self3+    self5 = boxMinHeight (inline $ size parent) self4+    self6 = boxMaxHeight parent self5+    self7 = boxHeight parent self6+    self8 | paginate = boxPaginate (block $ size parent) self7+        | otherwise = [self7]+    self9 = map (boxPosition (0, 0)) self8++-- | Compute a mapping from a layout tree indicating which glyphs for which fonts+-- are required.+-- Useful for assembling glyph atlases.+glyphsPerFont :: LayoutItem x y z -> M.Map (Pattern, Double) IS.IntSet+glyphsPerFont (LayoutSpan _ font self) =+    (pattern font, fontSize font) `M.singleton` IS.fromList glyphs+  where glyphs = map fromEnum $ map Hb.codepoint $ map fst $ fragmentGlyphs self+glyphsPerFont node = M.unionsWith IS.union $ map glyphsPerFont $ layoutGetChilds node
+ Graphics/Layout/Arithmetic.hs view
@@ -0,0 +1,141 @@+{-# LANGUAGE OverloadedStrings #-}+-- | (Unused) Parses & evaluates calc() expressions.+-- Implemented using The Shunting Yard Algorithm.+module Graphics.Layout.Arithmetic(Opcode(..), parseCalc, verifyCalc,+        evalCalc, mapCalc) where++import Data.CSS.Syntax.Tokens (Token(..), NumericValue(..))+import Data.Scientific (toRealFloat)+import GHC.Real (infinity)+import Data.Text (unpack, Text)+import qualified Data.Text as Txt+import Debug.Trace (trace) -- For error reporting.++-- | Parsed calc() expression. As a postfix arithmatic expression.+data Opcode n = Seq | Add | Subtract | Multiply | Divide | Func Text | Num n deriving Show+-- | Parse a calc() expression.+parseCalc :: [Token] -> [Opcode (Float, String)] -> [Opcode (Float, String)]+parseCalc (Number _ n:toks) stack = Num (val2float n, ""):parseCalc toks stack+parseCalc (Percentage _ n:toks) stack = Num (val2float n, "%"):parseCalc toks stack+parseCalc (Dimension _ n unit:toks) stack =+    Num (val2float n, unpack unit):parseCalc toks stack+parseCalc (Ident "e":toks) stack = Num (exp 1, ""):parseCalc toks stack+parseCalc (Ident "pi":toks) stack = Num (pi, ""):parseCalc toks stack+parseCalc (Ident "infinity":toks) stack = Num (f infinity, ""):parseCalc toks stack+parseCalc (Ident "-infinity":toks) stack =+    Num (negate $ f infinity, ""):parseCalc toks stack+parseCalc (Ident "NaN":toks) stack = Num (0/0, ""):parseCalc toks stack++parseCalc (Function x:toks) stack = parseCalc toks (Func x:stack)+parseCalc (LeftParen:toks) stack = parseCalc toks (Func "calc":stack)+parseCalc toks'@(Delim c:toks) (stack:stacks)+    | prec stack >= prec (op c) = stack:parseCalc toks' stacks+    | otherwise = parseCalc toks (op c:stack:stacks)+  where+    prec :: Opcode n -> Int+    prec Seq = 1+    prec Add = 2+    prec Subtract = 2+    prec Multiply = 3+    prec Divide = 3+    prec (Func _) = 0+    prec (Num _) = error "Unexpected number on operand stack!"+parseCalc (Delim c:toks) [] = parseCalc toks [op c]+parseCalc (Comma:toks) stack = parseCalc (Delim ',':toks) stack+parseCalc (RightParen:toks) (Func "calc":stack) = parseCalc toks stack+parseCalc (RightParen:toks) (op'@(Func _):stack) = op':parseCalc toks stack+parseCalc toks@(RightParen:_) (op':stack) = op':parseCalc toks stack+parseCalc (RightParen:toks) [] = parseCalc toks []+parseCalc [] [] = []+parseCalc [] stack = parseCalc [RightParen] stack+parseCalc _ _ = [Func "invalid"]++-- | Parse an operator char.+op :: Char -> Opcode n+op '+' = Add+op '-' = Subtract+op '*' = Multiply+op '/' = Divide+op ',' = Seq -- For function-calls.+op _ = Func "invalid"++-- Do operands counts line up? Are we dividing by 0?+-- Also I see concerns about whether units line up. Not bothering verifying that.+-- | Verify that a parsed math expression can be properly evaluated.+verifyCalc :: [Opcode (Float, String)] -> [Bool] -> Bool+verifyCalc (Seq:expr) stack = verifyCalc expr stack+verifyCalc (Add:expr) (_:_:stack) = verifyCalc expr (True:stack)+verifyCalc (Subtract:expr) (_:_:stack) = verifyCalc expr (True:stack)+verifyCalc (Multiply:expr) (_:_:stack) = verifyCalc expr (True:stack)+verifyCalc (Divide:_) (False:_) = False+verifyCalc (Divide:expr) (_:_:stack) = verifyCalc expr (True:stack)+verifyCalc (Num (n, _):expr) stack = verifyCalc expr ((n == 0):stack)+verifyCalc (Func x:expr) (_:stack)+    | x `elem` Txt.words "abs acos asin atan cos exp log sign sin sqrt tan" =+        verifyCalc expr (True:stack)+verifyCalc (Func x:expr) (_:_:stack)+    | x `elem` Txt.words "atan2 max min mod pow rem" = verifyCalc expr (True:stack)+verifyCalc (Func "clamp":expr) (_:_:_:stack) = verifyCalc expr (True:stack)+verifyCalc [] [_] = True+verifyCalc _ _ = False++-- | Evaluate a parsed calc() expression.+evalCalc :: [Opcode Float] -> [Float] -> Float+evalCalc (Seq:expr) stack = evalCalc expr stack -- The function args off+evalCalc (Add:expr) (y:x:stack) = evalCalc expr ((x + y):stack)+evalCalc (Subtract:expr) (y:x:stack) = evalCalc expr ((x - y):stack)+evalCalc (Multiply:expr) (y:x:stack) = evalCalc expr ((x*y):stack)+evalCalc (Divide:expr) (y:x:stack) = evalCalc expr ((x/y):stack)+evalCalc (Num n:expr) stack = evalCalc expr (n:stack)++evalCalc (Func "abs":expr) (x:stack) = evalCalc expr (abs x:stack)+evalCalc (Func "acos":expr) (x:stack) = evalCalc expr (acos x:stack)+evalCalc (Func "asin":expr) (x:stack) = evalCalc expr (asin x:stack)+evalCalc (Func "atan":expr) (x:stack) = evalCalc expr (atan x:stack)+evalCalc (Func "atan2":expr) (y:x:stack) = evalCalc expr (atan2 x y:stack)+evalCalc (Func "clamp":expr) (high:x:low:stack) =+    evalCalc expr (min high (max low x):stack)+evalCalc (Func "cos":expr) (x:stack) = evalCalc expr (cos x:stack)+evalCalc (Func "exp":expr) (x:stack) = evalCalc expr (exp x:stack)+evalCalc (Func "log":expr) (x:stack) = evalCalc expr (log x:stack)+evalCalc (Func "max":expr) (y:x:stack) = evalCalc expr (max x y:stack)+evalCalc (Func "min":expr) (y:x:stack) = evalCalc expr (min x y:stack)+evalCalc (Func "mod":expr) (y:x:stack) =+    evalCalc expr (toEnum (round x `mod` round y):stack)+evalCalc (Func "pow":expr) (y:x:stack) = evalCalc expr (x ** y:stack)+evalCalc (Func "rem":expr) (y:x:stack) =+    evalCalc expr (toEnum (round x `rem` round y):stack)+evalCalc (Func "sign":expr) (x:stack) = evalCalc expr (signum x:stack)+evalCalc (Func "sin":expr) (x:stack) = evalCalc expr (sin x:stack)+evalCalc (Func "sqrt":expr) (x:stack) = evalCalc expr (sqrt x:stack)+evalCalc (Func "tan":expr) (x:stack) = evalCalc expr (tan x:stack)++evalCalc [] [ret] = ret+evalCalc [] stack@(ret:_) =+    trace ("Verification should have caught this error! " ++ show stack) ret+evalCalc [] [] = trace "Verification should have caught this error! Stack underflow!" 0+evalCalc (op:_) (ret:_) =+    trace ("Verification should have caught this error! Unsupported op " ++ show op) ret+evalCalc (op:_) [] =+    trace ("Verification should have caught this error! Unsupported op " ++ show op) 0++-- | Convert all numbers in an expression via the given callback.+mapCalc :: (a -> b) -> [Opcode a] -> [Opcode b]+mapCalc cb (Num x:toks) = Num (cb x):mapCalc cb toks+-- GHC demanded more verbosity...+mapCalc cb (Seq:toks) = mapCalc cb toks -- we can drop these while we're at it...+mapCalc cb (Add:toks) = Add:mapCalc cb toks+mapCalc cb (Subtract:toks) = Subtract:mapCalc cb toks+mapCalc cb (Multiply:toks) = Multiply:mapCalc cb toks+mapCalc cb (Divide:toks) = Divide:mapCalc cb toks+mapCalc cb (Func f':toks) = Func f':mapCalc cb toks+mapCalc _ [] = []++-- | Convert from a tokenized NumericValue to a Float.+val2float :: NumericValue -> Float+val2float (NVInteger n) = fromIntegral n+val2float (NVNumber n) = toRealFloat n++-- | Convert from a rational value to a float.+f :: Rational -> Float+f = fromRational
+ Graphics/Layout/Box.hs view
@@ -0,0 +1,164 @@+{-# LANGUAGE RecordWildCards #-}+-- | Datastructures representing the CSS box model,+-- & utilities for operating on them.+module Graphics.Layout.Box(Border(..), mapX, mapY,+        Size(..), mapSizeX, mapSizeY,+        PaddedBox(..), zeroBox, lengthBox, mapX', mapY',+        width, height, minWidth, minHeight, maxWidth, maxHeight,+        Length(..), mapAuto, lowerLength, Zero(..), CastDouble(..)) where++-- | Amount of space surrounding the box.+data Border m n = Border {+    top :: m, bottom :: m, left :: n, right :: n+}+-- | Convert horizontal spacing via given callback.+mapX :: (n -> nn) -> Border m n -> Border m nn+-- | Convert vertical spacing via given callback.+mapY :: (m -> mm) -> Border m n -> Border mm n+mapX cb self = self { left = cb $ left self, right = cb $ right self }+mapY cb self = self { top = cb $ top self, bottom = cb $ bottom self }++-- | 2D size of a box. Typically inline is width & block is height.+-- This may change as support for vertical layout is added.+data Size m n = Size {inline :: n, block :: m} deriving (Eq, Show)+-- | Convert inline size via given callback+mapSizeY :: (m -> mm) -> Size m n -> Size mm n+mapSizeY cb self = Size (inline self) (cb $ block self)+-- | Convert block size via given callback+mapSizeX :: (n -> nn) -> Size m n -> Size m nn+mapSizeX cb self = Size (cb $ inline self) (block self)++-- | A box with min & max bounds & surrounding borders. The CSS Box Model.+data PaddedBox m n = PaddedBox {+    -- | The minimum amount of pixels this box should take.+    min :: Size m n,+    -- | The maximum amount of pixels this box should take.+    max :: Size m n,+    -- | The ideal number of pixels this box should take.+    nat :: Size Double Double,+    -- | The amount of pixels this box should take.+    size :: Size m n,+    -- | The amount of space between the box & the border.+    padding :: Border m n,+    -- | The amount of space for the border.+    border :: Border m n,+    -- | The amount of space between the border & anything else.+    margin :: Border m n+}+-- | An empty box, takes up nospace onscreen.+zeroBox :: PaddedBox Double Double+zeroBox = PaddedBox {+    min = Size 0 0,+    max = Size 0 0,+    nat = Size 0 0,+    size = Size 0 0,+    padding = Border 0 0 0 0,+    border = Border 0 0 0 0,+    margin = Border 0 0 0 0+  }+-- | A box which takes up all available space with no borders.+lengthBox :: PaddedBox Length Length+lengthBox = PaddedBox {+    min = Size Auto Auto,+    max = Size Auto Auto,+    nat = Size 0 0,+    size = Size Auto Auto,+    padding = Border zero zero zero zero,+    border = Border zero zero zero zero,+    margin = Border zero zero zero zero+  }++-- | Convert all sizes along the inline axis via given callback.+mapX' :: (n -> nn) -> PaddedBox m n -> PaddedBox m nn+mapX' cb PaddedBox {..} = PaddedBox {+    min = Size (cb $ inline min) (block min),+    size = Size (cb $ inline size) (block size),+    nat = Size 0 0,+    max = Size (cb $ inline max) (block max),+    padding = mapX cb padding,+    border = mapX cb border,+    margin = mapX cb margin+  }+-- | Convert all sizes along the block axis via given callback.+mapY' :: (m -> mm) -> PaddedBox m n -> PaddedBox mm n+mapY' cb PaddedBox {..} = PaddedBox {+    min = Size (inline min) (cb $ block min),+    size = Size (inline size) (cb $ block size),+    nat = Size 0 0,+    max = Size (inline max) (cb $ block max),+    padding = mapY cb padding,+    border = mapY cb border,+    margin = mapY cb margin+  }++-- | The total size along the inline axis including borders, etc.+width PaddedBox {..} = left margin + left border + left padding ++    inline size + right padding + right border + right margin+-- | The total size along the block axis, including borders, etc.+height PaddedBox {..} = top margin + top border + top padding ++    block size + bottom padding + bottom border + bottom margin+-- | The total minimum size along the inline axis.+minWidth PaddedBox {..} = left margin + left border + left padding ++    inline min + right padding + right border + right margin+-- | The total minimum size along the block axis.+minHeight PaddedBox {..} = top margin + top border + top padding ++    block min + bottom padding + bottom border + bottom margin+-- | The total maximum size along the inline axis.+maxWidth PaddedBox {..} = left margin + left border + left padding ++    inline max + right padding + right border + right margin+-- | The total maximum size along the block axis.+maxHeight PaddedBox {..} = top margin + top border + top padding ++    block max + bottom padding + bottom border + bottom margin++-- | A partially-computed length value.+data Length = Pixels Double -- ^ Absolute number of device pixels.+        | Percent Double -- ^ Multiplier by container width.+        | Auto -- ^ Use normal layout computations.+        | Preferred -- ^ Use computed preferred width.+        | Min -- ^ Use minimum legible width.+        deriving Eq++-- | Convert a length given the container's width. Filling in 0 for keywords.+-- If you wish for keywords to be handled differently, callers need to compute+-- that themselves.+lowerLength :: Double -> Length -> Double+lowerLength _ (Pixels x) = x+lowerLength outerwidth (Percent x) = x * outerwidth+lowerLength _ _ = 0++-- | Replace keywords with a given number of pixels.+-- Useful for avoiding messing up percentage calculations in later processing.+mapAuto x Auto = Pixels x+mapAuto x Preferred = Pixels x+mapAuto x Min = Pixels x+mapAuto _ x = x++class Zero a where+    -- | Return the empty (or zero) value for a CatTrap geometric type.+    zero :: a++instance Zero Double where zero = 0+instance Zero Length where zero = Pixels 0+instance (Zero m, Zero n) => Zero (PaddedBox m n) where+    zero = PaddedBox {+        min = Size zero zero,+        max = Size zero zero,+        nat = Size 0 0,+        size = Size zero zero,+        padding = Border zero zero zero zero,+        border = Border zero zero zero zero,+        margin = Border zero zero zero zero+    }++class CastDouble a where+    -- | Convert a double to a double or length.+    fromDouble :: Double -> a+    -- | Convert a double or length to a double.+    toDouble :: a -> Double++instance CastDouble Double where+    fromDouble = id+    toDouble = id+instance CastDouble Length where+    fromDouble = Pixels+    toDouble = lowerLength 0
+ Graphics/Layout/CSS.hs view
@@ -0,0 +1,295 @@+{-# LANGUAGE OverloadedStrings #-}+-- | Parses & desugars CSS properties to general CatTrap datastructures.+module Graphics.Layout.CSS(CSSBox(..), BoxSizing(..), Display(..),+        finalizeCSS, finalizeCSS') where++import Data.CSS.Syntax.Tokens (Token(..), NumericValue(..))+import qualified Data.Text as Txt+import Stylist (PropertyParser(..), TrivialPropertyParser)+import Stylist.Tree (StyleTree(..))+import Data.Text.ParagraphLayout (PageOptions(..))++import Graphics.Layout.Box as B+import Graphics.Layout+import Graphics.Text.Font.Choose (Pattern(..), unset)+import Graphics.Layout.CSS.Length+import Graphics.Layout.CSS.Font+import Graphics.Layout.Grid.CSS+import Graphics.Layout.Inline.CSS++-- | Parsed CSS properties relevant to layout.+data CSSBox a = CSSBox {+    -- | Which layout formula to use, a.k.a. parsed CSS display property.+    display :: Display,+    -- | (Unused) Parsed CSS box-sizing+    boxSizing :: BoxSizing,+    -- | sizing, margins, border-width, & padding CSS properties.+    -- Stores units in case they're needed for font-related units.+    cssBox :: PaddedBox Unitted Unitted, -- calc()?+    -- | Query parameters describing desired font.+    font :: Pattern,+    -- | Additional font-related CSS properties.+    font' :: CSSFont,+    -- | Caller-specified data, to parse additional CSS properties.+    inner :: a,+    -- | Grid-related CSS properties.+    gridStyles :: CSSGrid,+    -- | Grid item related CSS properties.+    cellStyles :: CSSCell,+    -- | inline-related CSS properties.+    inlineStyles :: CSSInline,+    -- | Parsed CSS caption-side.+    captionBelow :: Bool,+    -- | Parsed widows & orphans controlling pagination.+    pageOptions :: PageOptions+}+-- | Possible values for CSS box-sizing.+data BoxSizing = BorderBox | ContentBox+-- | Empty border, to use as default value.+noborder = Border (0,"px") (0,"px") (0,"px") (0,"px")++-- | Possibly values for CSS display property.+data Display = Block | Grid | Inline | Table | None |+    TableRow | TableHeaderGroup | TableRowGroup | TableFooterGroup | TableCell |+    TableColumn | TableColumnGroup | TableCaption deriving Eq+-- | Can the display value contain table-rows?+rowContainer CSSBox { display = d } =+    d `elem` [Table, TableHeaderGroup, TableRowGroup, TableFooterGroup]++instance PropertyParser a => PropertyParser (CSSBox a) where+    temp = CSSBox {+        boxSizing = ContentBox,+        display = Inline,+        cssBox = PaddedBox {+            B.min = Size auto auto,+            size = Size auto auto,+            nat = Size 0 0,+            B.max = Size auto auto,+            padding = noborder,+            border = noborder,+            margin = noborder+        },+        font = temp,+        font' = temp,+        inner = temp,+        gridStyles = temp,+        cellStyles = temp,+        inlineStyles = temp,+        captionBelow = False,+        pageOptions = PageOptions 0 0 2 2+      }+    inherit parent = CSSBox {+        boxSizing = boxSizing parent,+        display = Inline,+        cssBox = cssBox (temp :: CSSBox TrivialPropertyParser),+        font = inherit $ font parent,+        font' = inherit $ font' parent,+        inner = inherit $ inner parent,+        gridStyles = inherit $ gridStyles parent,+        cellStyles = inherit $ cellStyles parent,+        inlineStyles = inherit $ inlineStyles parent,+        captionBelow = captionBelow parent,+        pageOptions = pageOptions parent+      }++    -- Wasn't sure how to implement in FontConfig-Pure+    longhand _ self "font-family" [Ident "initial"] =+        Just self { font = unset "family" $ font self}++    longhand _ self "box-sizing" [Ident "content-box"] = Just self {boxSizing = ContentBox}+    longhand _ self "box-sizing" [Ident "border-box"] = Just self {boxSizing = BorderBox}+    longhand _ self "box-sizing" [Ident "initial"] = Just self {boxSizing = ContentBox}++    longhand _ self@CSSBox {cssBox = box} "padding-top" toks | Just x <- parseLength toks =+        Just self { cssBox = box { padding = (padding box) { top = x } } }+    longhand _ self@CSSBox {cssBox = box} "padding-bottom" toks | Just x <- parseLength toks =+        Just self { cssBox = box { padding = (padding box) { bottom = x } } }+    longhand _ self@CSSBox {cssBox = box} "padding-left" toks | Just x <- parseLength toks =+        Just self { cssBox = box { padding = (padding box) { left = x } } }+    longhand _ self@CSSBox {cssBox = box} "padding-right" toks | Just x <- parseLength toks =+        Just self { cssBox = box { padding = (padding box) { right = x } } }+    longhand _ self@CSSBox {cssBox = box} "border-top-width" toks | Just x <- parseLength toks =+        Just self { cssBox = box { border = (border box) { top = x } } }+    longhand _ self@CSSBox {cssBox = box} "border-bottom-width" toks | Just x <- parseLength toks =+        Just self { cssBox = box { border = (border box) { bottom = x } } }+    longhand _ self@CSSBox {cssBox = box} "border-left-width" toks | Just x <- parseLength toks =+        Just self { cssBox = box { border = (border box) { left = x } } }+    longhand _ self@CSSBox {cssBox = box} "border-right-width" toks | Just x <- parseLength toks =+        Just self { cssBox = box { border = (border box) { right = x } } }+    longhand _ self@CSSBox {cssBox = box} "margin-top" toks | Just x <- parseLength toks =+        Just self { cssBox = box { margin = (margin box) { top = x } } }+    longhand _ self@CSSBox {cssBox = box} "margin-bottom" toks | Just x <- parseLength toks =+        Just self { cssBox = box { margin = (margin box) { bottom = x } } }+    longhand _ self@CSSBox {cssBox = box} "margin-left" toks | Just x <- parseLength toks =+        Just self { cssBox = box { margin = (margin box) { left = x } } }+    longhand _ self@CSSBox {cssBox = box} "margin-right" toks | Just x <- parseLength toks =+        Just self { cssBox = box { margin = (margin box) { right = x } } }++    longhand _ self@CSSBox {cssBox = box} "width" toks | Just x <- parseLength' toks =+        Just self { cssBox = box { size = (size box) { inline = x } } }+    longhand _ self@CSSBox {cssBox = box} "height" toks | Just x <- parseLength' toks =+        Just self { cssBox = box { size = (size box) { block = x } } }+    longhand _ self@CSSBox {cssBox = box} "max-width" toks | Just x <- parseLength' toks =+        Just self { cssBox = box { B.max = (B.max box) { inline = x } } }+    longhand _ self@CSSBox {cssBox = box} "min-width" toks | Just x <- parseLength' toks =+        Just self { cssBox = box { B.min = (B.min box) { inline = x } } }+    longhand _ self@CSSBox {cssBox = box} "max-height" toks | Just x <- parseLength' toks =+        Just self { cssBox = box { B.max = (B.max box) { block = x } } }+    longhand _ self@CSSBox {cssBox = box} "min-height" toks | Just x <- parseLength' toks =+        Just self { cssBox = box { B.min = (B.min box) { block = x } } }++    longhand _ self "display" [Ident "block"] = Just self { display = Block }+    longhand _ self "display" [Ident "none"] = Just self { display = None }+    longhand _ self "display" [Ident "grid"] = Just self { display = Grid }+    {-longhand _ self "display" [Ident "table"] = Just self { display = Table }+    longhand CSSBox { display = Table } self "display" [Ident "table-row-group"] =+        Just self { display=TableRowGroup }+    longhand CSSBox { display = Table } self "display" [Ident "table-header-group"] =+        Just self { display = TableHeaderGroup }+    longhand CSSBox { display = Table } self "display" [Ident "table-footer-group"] =+        Just self { display = TableFooterGroup }+    longhand parent self "display" [Ident "table-row"] | rowContainer parent =+        Just self { display = TableRow }+    longhand CSSBox { display = TableRow } self "display" [Ident "table-cell"] =+        Just self { display = TableCell }+    longhand CSSBox { display = Table } self "display" [Ident "table-column-group"] =+        Just self { display = TableColumnGroup }+    longhand CSSBox { display = TableColumnGroup } self "display" [Ident "table-column"] =+        Just self { display = TableColumn }+    longhand CSSBox { display = Table } self "display" [Ident "table-caption"] =+        Just self { display=TableCaption } -}+    longhand _ self "display" [Ident "inline"] = Just self { display = Inline }+    longhand _ self "display" [Ident "initial"] = Just self { display = Inline }++    longhand _ self "caption-side" [Ident "top"] = Just self { captionBelow = False }+    longhand _ self "caption-side" [Ident "bottom"] = Just self { captionBelow = True }+    longhand _ self "caption-side" [Ident "initial"] = Just self {captionBelow = False}++    longhand _ self "orphans" [Number _ (NVInteger x)] =+        Just self { pageOptions = (pageOptions self) { pageOrphans = fromInteger x } }+    longhand _ self "widows" [Number _ (NVInteger x)] =+        Just self { pageOptions = (pageOptions self) { pageWidows = fromInteger x } }++    longhand a b c d | Just x <- longhand (font a) (font b) c d,+        Just y <- longhand (font' a) (font' b) c d =+            Just b { font = x, font' = y } -- Those properties can overlap!+    longhand a b c d | Just font' <- longhand (font a) (font b) c d = Just b {+        font = font'+      }+    longhand a b c d | Just font <- longhand (font' a) (font' b) c d = Just b {+        font' = font+      }+    longhand a b c d | Just inline' <- longhand (inlineStyles a) (inlineStyles b) c d =+        Just b { inlineStyles = inline' }+    longhand a b c d | Just grid' <- longhand (gridStyles a) (gridStyles b) c d =+        Just b { gridStyles = grid' }+    longhand a b c d | Just cell' <- longhand (cellStyles a) (cellStyles b) c d =+        Just b { cellStyles = cell' }+    longhand a b c d | Just inner' <- longhand (inner a) (inner b) c d = Just b {+        inner = inner'+      }+    longhand _ _ _ _ = Nothing++-- | Desugar parsed CSS into more generic layout parameters.+finalizeCSS :: PropertyParser x => Font' -> Font' -> StyleTree (CSSBox x) ->+        LayoutItem Length Length x+finalizeCSS root parent StyleTree { style = self'@CSSBox { display = None } } =+    LayoutFlow (inner self') lengthBox []+finalizeCSS root parent self@StyleTree {+    style = self'@CSSBox { display = Grid, inner = val }, children = childs+  } = LayoutFlow val (finalizeBox self' font_) [+        finalizeGrid (gridStyles self') font_ (map cellStyles $ map style childs)+            (finalizeChilds root font_ (inner self') childs)]+  where+    font_ = pattern2font (font self') (font' self') parent root+finalizeCSS root parent self@StyleTree {+        style = self'@CSSBox { display = Table, captionBelow = False }, children = childs+    } = LayoutFlow (inner self') (finalizeBox self' font_)+        ([finalizeCSS root font_ child { style = child' { display = Block } }+            | child@StyleTree { style = child'@CSSBox { display = TableCaption } } <- childs] +++        [finalizeTable root font_ (inner self') childs])+  where+    font_ = pattern2font (font self') (font' self') parent root+finalizeCSS root parent self@StyleTree {+        style = self'@CSSBox { display = Table, captionBelow = True }, children = childs+    } = LayoutFlow (inner self') (finalizeBox self' font_)+        (finalizeTable root font_ temp childs:+        [finalizeCSS root font_ child { style = child' { display = Block } }+            | child@StyleTree { style = child'@CSSBox { display = TableCaption } } <- childs])+  where+    font_ = pattern2font (font self') (font' self') parent root+finalizeCSS root parent self@StyleTree {+    style = self'@CSSBox { inner = val }, children = childs+  } = LayoutFlow val (finalizeBox self' font_) (finalizeChilds root font_ val childs)+  where+    font_ = pattern2font (font self') (font' self') parent root+finalizeCSS' sysfont self@StyleTree { style = self' } =+    finalizeCSS (pattern2font (font self') (font' self') sysfont sysfont) sysfont self++-- | Desugar a sequence of child nodes, taking care to capture runs of inlines.+finalizeChilds :: PropertyParser x => Font' -> Font' -> x -> [StyleTree (CSSBox x)] ->+        [LayoutItem Length Length x]+finalizeChilds root parent style' (StyleTree { style = CSSBox { display = None } }:childs) =+    finalizeChilds root parent style' childs+finalizeChilds root parent style' childs@(child:childs')+    | isInlineTree childs, Just self <- finalizeParagraph (flattenTree childs) parent =+        -- FIXME propagate display properties, how to handle the hierarchy.+        -- NOTE: Playing around in firefox, it appears the CSS borders should cover+        -- their entire span, doubling up on borders where needed.+        [LayoutInline (inherit style') parent self paging (repeat $ inherit style')]+    | (inlines@(_:_), blocks) <- spanInlines childs,+        Just self <- finalizeParagraph (flattenTree inlines) parent  =+            LayoutInline (inherit style') parent self paging (repeat $ inherit style') :+                finalizeChilds root parent style' blocks+    | (StyleTree { style = CSSBox { display = Inline } }:childs') <- childs =+        finalizeChilds root parent style' childs' -- Inline's all whitespace...+    | otherwise = finalizeCSS root parent child : finalizeChilds root parent style' childs'+  where+    paging = pageOptions $ style child+    isInlineTree = all isInlineTree0+    isInlineTree0 StyleTree { style = CSSBox { display = Inline }, children = childs } =+        isInlineTree childs+    isInlineTree0 _ = False+    spanInlines childs = case span isInlineTree0 childs of+        (inlines, (StyleTree {+            style = CSSBox { display = Inline }, children = tail+          }:blocks)) -> let (inlines', blocks') = spanInlines tail+            in (inlines ++ inlines', blocks' ++ blocks)+        ret -> ret+    flattenTree (StyleTree { children = child@(_:_) }:childs) =+        flattenTree child `concatParagraph` flattenTree childs+    flattenTree (child:childs) =+        buildParagraph (inlineStyles $ style child) `concatParagraph` flattenTree childs+    flattenTree [] = ParagraphBuilder "" []+finalizeChilds _ _ _ [] = []++-- | Desugar most units, possibly in reference to given font.+finalizeBox self@CSSBox { cssBox = box } font_ =+    mapY' (flip finalizeLength font_) $ mapX' (flip finalizeLength font_) box++-- | (Unused, incomplete) Desugar a styletree of table elements to a grid layout.+finalizeTable root parent val childs = LayoutFlow val lengthBox [] -- Placeholder!+{- finalizeTable root parent val childs = LayoutGrid val grid $ zip cells' childs'+  where -- FIXME? How to handle non-table items in <table>?+    grid = Grid {+        rows = take width $ repeat ("", (0,"auto")),+        rowBounds = [],+        subgridRows = 0,+        columns = take height $ repeat ("", (0,"auto")),+        colBounds = [],+        subgridCols = 0,+        gap = Size (0,"px") (0,"px"), -- FIXME where to get this from?+        containerSize = Size Auto Auto, -- Proper size is set on parent.+        containerMin = Size Auto Auto,+        containerMax = Size Auto Auto+    }+    cells' = adjustWidths cells+    +    (cells, width, height) = lowerCells childs+    lowerCells (StyleTree self@CSSBox { display = TableRow } cells:rest) =+        (row:rows, max rowwidth width', succ height)+      where+        (row, rowwidth) = lowerRow cells 0 -- FIXME: How to dodge colspans?+        (rows, width', height') = lowerCells rest+    lowerCells (StyleTree self@CSSBox { display = TableHeaderGroup } childs ) =+        -}
+ Graphics/Layout/CSS/Font.hs view
@@ -0,0 +1,228 @@+{-# LANGUAGE OverloadedStrings #-}+-- | Infrastructure for parsing & desugaring CSS properties related to fonts.+module Graphics.Layout.CSS.Font(Font'(..), placeholderFont, hbScale, hbUnit,+        pattern2hbfont, pattern2font, CSSFont(..), variations') where++import Data.CSS.Syntax.Tokens (Token(..), NumericValue(..), serialize)+import Stylist (PropertyParser(..))+import qualified Data.Text as Txt+import Data.Maybe (fromMaybe)++import Graphics.Layout.Box+import Graphics.Layout.CSS.Length++import Data.Text.Glyphize as HB+import Graphics.Text.Font.Choose (Pattern(..), Value(..), normalizePattern,+                                  getValue', getValue0, setValue, Binding(..),+                                  configSubstitute', defaultSubstitute,+                                  fontSort', MatchKind(..), fontRenderPrepare')+import qualified Data.ByteString as B+import System.IO.Unsafe (unsafePerformIO)++-- | zero'd `Font'` to serve as the root's parent in a font heirarchy.+placeholderFont = Font' undefined [] (const 0) (const 0) 0 0 0 0  0 0 0 0  1+-- | Scale-factor for text-shaping APIs.+hbScale :: Font' -> Double+hbScale f = fontSize f*hbUnit+-- | Magic number informing the value of `hbScale`.+hbUnit = 64 :: Double++-- | Convert from FontConfig query result to a Harfbuzz font.+pattern2hbfont :: Pattern -> Int -> [Variation] -> Font+pattern2hbfont pat scale variations = createFontWithOptions options face+  where+    bytes = unsafePerformIO $ B.readFile $ getValue0 "file" pat+    face = createFace bytes $ toEnum $ fromMaybe 0 $ getValue' "index" pat+    options = foldl value2opt defaultFontOptions { optionScale = Just (scale, scale) } $+                normalizePattern pat++    value2opt opts ("slant", (_, ValueInt x):_) = opts {+        optionSynthSlant = Just $ realToFrac x+      }+    value2opt opts ("fontvariations", _:_) = opts {optionVariations = variations}+    value2opt opts _ = opts++-- | Convert Parsed CSS to a `Font'`.+-- Includes sizing parameters derived from a root & parent `Font'`.+pattern2font :: Pattern -> CSSFont -> Font' -> Font' -> Font'+pattern2font pat styles@CSSFont { cssFontSize = (x,"initial") } parent root =+    pattern2font pat styles { cssFontSize = (x*fontSize root," ") } parent root+pattern2font pat styles parent root = Font' {+        hbFont = font',+        pattern = font,+        fontHeight = height' . fontGlyphExtents font' . fontGlyph',+        fontAdvance = fromIntegral . fontGlyphHAdvance font' . fontGlyph',+        fontSize = fontSize',+        rootEm = fontSize root,+        lineheight = lineheight',+        rlh = lineheight root,++        vh = vh root,+        vw = vw root,+        vmax = vmax root,+        vmin = vmin root,+        scale = scale root+    } where+        height' (Just x) = fromIntegral $ HB.height x+        height' Nothing = fontSize'+        lineheight' | snd (cssLineheight styles) == "normal",+            Just extents <- fontHExtents font' = (fromIntegral $ lineGap extents)/scale'+            | otherwise = lowerLength' (cssLineheight styles) parent+        fontSize' = lowerLength' (cssFontSize styles) parent+        lowerLength' a = lowerLength (fontSize parent) . finalizeLength a+        fontGlyph' ch = fromMaybe 0 $ fontGlyph font' ch Nothing+        q | Nothing <- lookup "family" pat, Just val <- lookup "family" $ pattern root =+                ("family", val):setValue "size" Weak (px2pt root fontSize') pat+            | otherwise = setValue "size" Weak (px2pt root fontSize') pat+        font = case fontSort' (defaultSubstitute $ configSubstitute' q MatchPattern) False of+            Just (font:_, _) -> fontRenderPrepare' q font+            _ -> error "TODO: Set fallback font!"+        font' = pattern2hbfont font (round scale') $ variations' fontSize' styles+        scale' = fontSize'*hbUnit++-- | Parsed CSS font properties, excluding the FontConfig query.+data CSSFont = CSSFont {+    -- | Parsed CSS font-size.+    cssFontSize :: Unitted,+    -- | Parsed CSS line-height.+    cssLineheight :: Unitted,+    -- | Parsed CSS font-variation-settings.+    variations :: [Variation],+    -- | Parsed CSS font-weight.+    weightVariation :: Variation,+    -- | Parsed CSS font-stretch.+    widthVariation :: Variation,+    -- | Parsed CSS font-style.+    slantVariation :: Variation,+    -- | Parsed CSS font-optical-sizing.+    opticalSize :: Bool+}+-- | All font-variations from the parsed CSS properties.+-- | Requires the resolved font-size in case font-optical-sizing is set.+variations' :: Double -> CSSFont -> [Variation]+variations' fontsize self =+    (if opticalSize self then (Variation opsz (realToFrac fontsize):) else id)+    (slantVariation self:widthVariation self:weightVariation self:variations self)++-- | Represents a multiple of the initial font-size.+-- Resolved by `pattern2font`.+fracDefault :: CSSFont -> Double -> Maybe CSSFont+fracDefault self frac = Just self {+    cssFontSize = (frac,"initial")+}+instance PropertyParser CSSFont where+    temp = CSSFont {+        cssFontSize = (12,"pt"),+        cssLineheight = (1,""),+        variations = [],+        weightVariation = Variation wght 400,+        widthVariation = Variation wdth 100,+        slantVariation = Variation ital 0,+        opticalSize = True+    }+    inherit parent = parent++    longhand _ self "font-size" [Ident "xx-small"] = fracDefault self $ 3/5+    longhand _ self "font-size" [Ident "x-small"] = fracDefault self $ 3/4+    longhand _ self "font-size" [Ident "small"] = fracDefault self $ 8/9+    longhand _ self "font-size" [Ident "medium"] = fracDefault self 1+    longhand _ self "font-size" [Ident "initial"] = fracDefault self 1+    longhand _ self "font-size" [Ident "large"] = fracDefault self $ 6/5+    longhand _ self "font-size" [Ident "x-large"] = fracDefault self $ 3/2+    longhand _ self "font-size" [Ident "xx-large"] = fracDefault self 2+    longhand _ self "font-size" [Ident "xxx-large"] = fracDefault self 3+    longhand parent self "font-size" [Ident "larger"] =+        Just self { cssFontSize = (x*1.2,unit) }+      where (x,unit) = cssFontSize parent+    longhand parent self "font-size" [Ident "smaller"] =+        Just self { cssFontSize = (x/1.2,unit) }+      where (x, unit) = cssFontSize parent+    longhand _ self "font-size" toks+        | Just x <- parseLength toks = Just self { cssFontSize = x }++    longhand _ self "line-height" [Ident "normal"] = Just self { cssLineheight = (0,"normal") }+    longhand _ self "line-height" [Number _ x] = Just self { cssLineheight = (n2f x,"em") }+    longhand _ self "line-height" toks+        | Just x <- parseLength toks = Just self { cssLineheight = x }++    longhand _ self "font-variation-settings" [Ident "normal"] = Just self { variations = [] }+    longhand _ self "font-variation-settings" [Ident "initial"] = Just self {variations = []}+    longhand _ self "font-variation-settings" toks+        | Just x <- parseVariations toks = Just self { variations = x }++    longhand _ self "font-weight" [Ident "normal"] =+        Just self { weightVariation = Variation wght 400 }+    longhand _ self "font-weight" [Ident "initial"] =+        Just self { weightVariation = Variation wght 400 }+    longhand _ self "font-weight" [Ident "bold"] =+        Just self { weightVariation = Variation wght 700 }+    longhand _ self "font-weight" [Number _ (NVInteger x)] | x >= 100 && x < 1000 =+        Just self { weightVariation = Variation wght $ fromIntegral x }+    longhand parent self "font-weight" [Ident "bolder"]+        | varValue (weightVariation parent) < 400 =+            Just self { weightVariation = Variation wght 400 }+        | varValue (weightVariation parent) < 600 =+            Just self { weightVariation = Variation wght 700 }+        | otherwise = Just self { weightVariation = Variation wght 900 }+    longhand parent self "font-weight" [Ident "lighter"]+        | varValue (weightVariation parent) < 600 =+            Just self { weightVariation = Variation wght 100 }+        | varValue (weightVariation parent) < 800 =+            Just self { weightVariation = Variation wght 400 }+        | otherwise = Just self { weightVariation = Variation wght 700 }++    longhand _ self "font-stretch" [Ident "ultra-condensed"] =+        Just self { widthVariation = Variation wdth 50 }+    longhand _ self "font-stretch" [Ident "extra-condensed"] =+        Just self { widthVariation = Variation wdth 62.5 }+    longhand _ self "font-stretch" [Ident "condensed"] =+        Just self { widthVariation = Variation wdth 75 }+    longhand _ self "font-stretch" [Ident "semi-condensed"] =+        Just self { widthVariation = Variation wdth 87.5 }+    longhand _ self "font-stretch" [Ident k] | k `elem` ["initial", "normal"] =+        Just self { widthVariation = Variation wdth 100 }+    longhand _ self "font-stretch" [Ident "semi-expanded"] =+        Just self { widthVariation = Variation wdth 112.5 }+    longhand _ self "font-stretch" [Ident "expanded"] =+        Just self { widthVariation = Variation wdth 125 }+    longhand _ self "font-stretch" [Ident "extra-expanded"] =+        Just self { widthVariation = Variation wdth 150 }+    longhand _ self "font-stretch" [Ident "ultra-expanded"] =+        Just self { widthVariation = Variation wdth 200 }+    longhand _ self "font-stretch" [Percentage _ x] =+        Just self { widthVariation = Variation wdth $ n2f x }++    longhand _ self "font-style" [Ident "oblique", Dimension _ x "deg"] =+        Just self { slantVariation = Variation slnt $ n2f x }+    longhand _ self "font-style" [Ident "oblique", Dimension _ x "grad"] =+        Just self { slantVariation = Variation slnt (n2f x/400*360) }+    longhand _ self "font-style" [Ident "oblique", Dimension _ x "rad"] =+        Just self { slantVariation = Variation slnt (n2f x*180/pi) }+    longhand _ self "font-style" [Ident "oblique", Dimension _ x "turn"] =+        Just self { slantVariation = Variation slnt (n2f x*360) }+    longhand _ self "font-style" [Ident "italic"] =+        Just self { slantVariation = Variation ital 1 }+    longhand _ self "font-style" [Ident "normal"] =+        Just self { slantVariation = Variation ital 0 }+    longhand _ self "font-style" [Ident "initial"] =+        Just self { slantVariation = Variation ital 0 }++    longhand _ s "font-optical-sizing" [Ident "auto"] = Just s {opticalSize = True}+    longhand _ s "font-optical-sizing" [Ident "initial"] = Just s {opticalSize = True}+    longhand _ s "font-optical-sizing" [Ident "none"] = Just s {opticalSize = False}++    longhand _ _ _ _ = Nothing++-- | Utility for parsing multiple font variations (via Harfbuzz).+parseVariations (x@(String _):y@(Number _ _):Comma:toks)+    | Just var <- parseVariation $ Txt.unpack $ serialize [x, y],+        Just vars <- parseVariations toks = Just $ var:vars+parseVariations toks@[String _, Number _ _]+    | Just var <- parseVariation $ Txt.unpack $ serialize toks = Just [var]+parseVariations _ = Nothing++wght = tag_from_string "wght"+wdth = tag_from_string "wdth"+slnt = tag_from_string "slnt"+ital = tag_from_string "ital"+opsz = tag_from_string "opsz"
+ Graphics/Layout/CSS/Length.hs view
@@ -0,0 +1,106 @@+{-# LANGUAGE OverloadedStrings #-}+-- | Infrastructure for parsing & desugaring length units & keywords,+-- in reference to the selected font.+module Graphics.Layout.CSS.Length(Unitted, auto, parseLength, parseLength',+        n2f, finalizeLength, px2pt, Font'(..)) where++import Data.CSS.Syntax.Tokens (Token(..), NumericValue(..))+import qualified Data.Text as Txt+import Data.Scientific (toRealFloat)+import Debug.Trace (trace) -- For warnings.+import Data.Text.Glyphize (Font)+import Graphics.Text.Font.Choose (Pattern(..))++import Graphics.Layout.Box++-- | A number+unit, prior to resolving side units.+-- The unit may alternately represent a keyword, in which case the number is+-- ignored & typically set to 0.+type Unitted = (Double, Txt.Text)+-- | The CSS `auto` keyword.+auto :: Unitted+auto = (0,"auto")++-- | Parse a pre-tokenized CSS length value.+parseLength :: [Token] -> Maybe Unitted+parseLength [Percentage _ x] = Just (n2f x,"%")+parseLength [Dimension _ x unit]+    | n2f x == 0 && unit == "" = Just (0,"px")+    | unit `elem` units = Just (n2f x,unit)+parseLength [Ident "auto"] = Just (0,"auto")+parseLength [Ident "initial"] = Just (0,"auto")+parseLength _ = Nothing+-- | Variant of `parseLength` which supports min-content & max-content keywords.+parseLength' [Ident "min-content"] = Just (0,"min-content")+parseLength' [Ident "max-content"] = Just (0,"max-content")+parseLength' toks = parseLength toks++-- | Supported length units.+units = Txt.words "cap ch em ex ic lh rem rlh vh vw vmax vmin px cm mm Q in pc pt %"++-- | Convert a lexed number to a Double.+n2f :: (Fractional x, RealFloat x) => NumericValue -> x+n2f (NVInteger x) = realToFrac x+n2f (NVNumber x) = toRealFloat x++-- | Resolve a parsed length according to the sizing parameters in a given `Font'`.+finalizeLength :: Unitted -> Font' -> Length+finalizeLength (x,"cap") f = Pixels $ x*fontHeight f 'A'+finalizeLength (x,"ch") f = Pixels $ x*fontAdvance f '0'+finalizeLength (x,"em") f = Pixels $ x*fontSize f+finalizeLength (x,"") f = Pixels $ x*fontSize f -- For line-height.+finalizeLength (x,"ex") f = Pixels $ x*fontHeight f 'x'+finalizeLength (x,"ic") f = Pixels $ x*fontHeight f '水' -- CJK water ideograph+finalizeLength (x,"lh") f = Pixels $ x*lineheight f+finalizeLength (x,"rem") f = Pixels $ x*rootEm f+finalizeLength (x,"rlh") f = Pixels $ x*rlh f+finalizeLength (x,"vh") f = Pixels $ x*vh f+finalizeLength (x,"vw") f = Pixels $ x*vw f+finalizeLength (x,"vmax") f = Percent $ x*vmax f+finalizeLength (x,"vmin") f = Percent $ x*vmin f+finalizeLength (x,"px") f = Pixels $ x*scale f+finalizeLength (x,"cm") f = Pixels $ x*scale f*96/2.54+finalizeLength (x,"in") f = Pixels $ x*96*scale f+finalizeLength (x,"mm") f | Pixels x' <- finalizeLength (x,"cm") f = Pixels $ x'/10+finalizeLength (x,"Q") f | Pixels x' <- finalizeLength (x,"cm") f = Pixels $ x'/40+finalizeLength (x,"pc") f | Pixels x' <- finalizeLength (x,"in") f = Pixels $ x'/6+finalizeLength (x,"pt") f | Pixels x' <- finalizeLength (x,"in") f = Pixels $ x'/72+finalizeLength (x,"%") _ = Percent $ x/100+finalizeLength (_,"auto") _ = Auto+finalizeLength (_,"min-content") _ = Min+finalizeLength (_,"max-content") _ = Preferred+finalizeLength (x, " ") _ = Pixels x -- Internal constant value...+finalizeLength (_,unit) _ = trace ("Invalid unit " ++ Txt.unpack unit) $ Pixels 0+-- | Convert from a computed length to the "pt" unit.+px2pt f x = x / scale f / 96 * 72++-- | A Harfbuzz font with sizing parameters.+data Font' = Font' {+    -- | The Harfbuzz font used to shape text & query character-size information.+    hbFont :: Font,+    -- | The FontConfig query result. Useful to incorporate into output rendering.+    pattern :: Pattern,+    -- | Query the height of a character.+    -- Used for cap, ex, or ic units.+    fontHeight :: Char -> Double,+    -- | Query the width of a character, used for ch unit.+    fontAdvance :: Char -> Double,+    -- | The desired font-size, used for em unit.+    fontSize :: Double,+    -- | The root font's size, used for rem unit.+    rootEm :: Double,+    -- | The desired line-height, used for lh unit.+    lineheight :: Double,+    -- | The root font's line-height, used for rlh unit.+    rlh :: Double,+    -- | Scale-factor for vh unit.+    vh :: Double,+    -- | Scale-factor for vw unit.+    vw :: Double,+    -- | Scale-factor for vmax unit.+    vmax :: Double,+    -- | Scale-factor for vmin unit.+    vmin :: Double,+    -- | How many device pixels in a CSS px?+    scale :: Double+}
+ Graphics/Layout/Flow.hs view
@@ -0,0 +1,148 @@+-- | Sizes a block element & positions their children.+-- Taking into account size bounds.+module Graphics.Layout.Flow(flowMinWidth, flowNatWidth, flowMaxWidth, flowWidth,+        flowNatHeight, flowMinHeight, flowMaxHeight, flowHeight,+        positionFlow, layoutFlow) where++import Graphics.Layout.Box as B++-- | Compute the minimum width of a block element with children of the given sizes.+flowMinWidth :: Double -> PaddedBox a Length -> [PaddedBox b Double] -> Double+flowMinWidth _ PaddedBox {B.min = Size (Pixels x) _} _ = x+flowMinWidth parent PaddedBox {B.min = Size (Percent x) _} _ = x * parent+flowMinWidth parent self@PaddedBox {B.min = Size Preferred _} childs =+    flowNatWidth parent self childs+flowMinWidth _ _ childs = maximum $ (0:) $ map minWidth childs+-- | Compute the natural width of a block element with children of the given sizes.+flowNatWidth :: Double -> PaddedBox a Length -> [PaddedBox b Double] -> Double+flowNatWidth _ PaddedBox {size = Size (Pixels x) _} _ = x+flowNatWidth parent PaddedBox {size = Size (Percent x) _} _ = x * parent+flowNatWidth parent self@PaddedBox {size = Size Min _, B.min = Size x _} childs+    -- Avoid infinite loops!+    | x /= Preferred = flowMinWidth parent self childs+flowNatWidth parent _ childs = maximum $ (0:) $ map maxWidth childs+-- | Compute the maximum width of a block element inside the given parent size.+flowMaxWidth :: PaddedBox a Double -> PaddedBox b Length -> Double+flowMaxWidth _ PaddedBox {B.max = Size (Pixels x) _} = x+flowMaxWidth parent PaddedBox {B.max = Size (Percent x) _} = x * (inline $ size parent)+flowMaxWidth parent self@PaddedBox {B.max = Size Auto _} = inline (size parent) - ws+    where+        ws = l2d (left $ margin self) + l2d (left $ border self) + l2d (left $ padding self) ++            l2d (right $ padding self) + l2d (right $ border self) + l2d (right $ margin self)+        l2d = lowerLength $ inline $ size parent+flowMaxWidth parent self@PaddedBox {B.max = Size Preferred _} =+    flowNatWidth (inline $ size parent) self []+flowMaxWidth parent self@PaddedBox {B.max = Size Min _} =+    flowMinWidth (inline $ B.min parent) self []+-- | Compute final block element width based on cached width computations &+-- parent size.+flowWidth :: PaddedBox a Double -> PaddedBox b Length -> Double+flowWidth parent self+    | small > large = small+    | natural > large = large+    | inline (size self) == Auto = large -- specialcase+    | natural >= small = natural+    | otherwise = small+  where+    small = flowMinWidth (inline $ B.min parent) self []+    natural = flowNatWidth (inline $ size parent) self []+    large = flowMaxWidth parent self++-- | Compute natural block element height at cached width.+flowNatHeight :: Double -> PaddedBox Length Double -> [PaddedBox Double Double] -> Double+flowNatHeight _ PaddedBox {size = Size _ (Pixels y)} _ = y+flowNatHeight parent PaddedBox {size = Size _ (Percent y)} _ = y * parent+flowNatHeight _ PaddedBox {size = Size _ Min} childs =+    sum $ map minHeight $ marginCollapse childs+flowNatHeight _ PaddedBox {size = Size owidth _} childs =+    sum $ map height $ marginCollapse childs+-- | Compute minimum block height at cached width.+flowMinHeight :: Double -> PaddedBox Length Double -> Double+flowMinHeight _ PaddedBox {B.min = Size _ (Pixels y)} = y+flowMinHeight parent PaddedBox {B.min = Size _ (Percent y)} = y * parent+flowMinHeight parent self = flowNatHeight parent self []+-- | Compute maximum block height at cached width.+flowMaxHeight :: Double -> PaddedBox Length Double -> Double+flowMaxHeight _ PaddedBox {B.max = Size _ (Pixels y)} = y+flowMaxHeight parent PaddedBox {B.max = Size _ (Percent y)} = y * parent+flowMaxHeight parent PaddedBox {B.max = Size _ Auto} = parent+flowMaxHeight parent self@PaddedBox {B.max = Size _ Preferred} = flowNatHeight parent self []+flowMaxHeight parent self@PaddedBox {B.max = Size _ Min} = flowMinHeight parent self+-- | Compute final block height at cached width.+flowHeight :: PaddedBox Double Double -> PaddedBox Length Double -> Double+flowHeight parent self+    | small > large = small+    | natural > large = large+    | natural >= small = natural+    | otherwise = small+  where+    small = flowMinHeight (block $ B.min parent) self+    natural = flowNatHeight (block $ B.nat parent) self []+    large = flowMaxHeight (block $ B.max parent) self++-- | Compute position of all children relative to this block element.+positionFlow :: [PaddedBox Double Double] -> [Size Double Double]+positionFlow childs = scanl inner (Size 0 0) $ marginCollapse childs+  where inner (Size x y) self = Size x $ height self+-- | Compute size given block element in given parent,+-- & position of given children.+layoutFlow :: PaddedBox Double Double -> PaddedBox Length Length ->+        [PaddedBox Length Double] ->+        (PaddedBox Double Double, [(Size Double Double, PaddedBox Double Double)])+layoutFlow parent self childs = (self', zip positions' childs')+  where+    positions' = positionFlow childs'+    childs' = map layoutZooko childs+    self' = self0 {+        B.min = (B.min self0) { block = flowMinHeight (block $ B.min parent) self0 },+        size = (size self0) { block = flowHeight parent self0 },+        B.max = (B.max self0) { block = flowMaxHeight (block $ B.max parent) self0 },+        padding = mapY (lowerLength owidth) $ padding self0,+        border = mapY (lowerLength owidth) $ border self0,+        margin = mapY (lowerLength owidth) $ margin self0+      }+    self0 = self1 {+        size = (size self1) { block = Pixels $ flowNatHeight oheight self1 childs'}+      }+    self1 = self2 {+        size = (size self2) { inline = width' },+        B.max = (B.max self2) { inline = flowMaxWidth parent self2 },+        B.min = (B.min self2) { inline = flowMinWidth owidth self2 [] },+        padding = mapX (lowerLength owidth) $ padding self2,+        border = mapX (lowerLength owidth) $ border self2,+        margin = lowerMargin owidth (owidth - width') $ margin self2+      }+    width' = flowWidth parent self+    self2 = self {+        size = (size self) { inline = Pixels $ flowNatWidth owidth self childs },+        B.min = (B.min self) { inline = Pixels $ flowMinWidth owidth self childs }+      }+    owidth = inline $ size parent+    oheight = block $ size parent+    layoutZooko child = child {+        B.min = Size (inline $ B.min child) (flowMinHeight (block $ B.min self') child),+        size = Size (inline $ size child) (flowHeight self' child),+        B.max = Size (inline $ B.max child) (flowMaxHeight (block $ size self') child),+        padding = mapY (lowerLength owidth) $ padding child,+        border = mapY (lowerLength owidth) $ border child,+        margin = mapY (lowerLength owidth) $ margin child+      }++-- | Removes overlapping margins.+marginCollapse :: [PaddedBox Double n] -> [PaddedBox Double n]+marginCollapse (x'@PaddedBox {margin = xm@Border { bottom = x }}:+        y'@PaddedBox {margin = ym@Border { top = y}}:rest)+    | x > y = x':marginCollapse (y' {margin = ym { top = 0 }}:rest)+    | otherwise = x' { margin = xm { bottom = 0 }}:marginCollapse (y':rest)+marginCollapse rest = rest++-- | Resolves auto paddings or margins to fill given width.+lowerMargin :: Double -> Double -> Border m Length -> Border m Double+lowerMargin _ available (Border top' bottom' Auto Auto) =+    Border top' bottom' (available/2) (available/2)+lowerMargin outerwidth available (Border top' bottom' Auto right') =+    Border top' bottom' available $ lowerLength outerwidth right'+lowerMargin outerwidth available (Border top' bottom' left' Auto) =+    Border top' bottom' (lowerLength outerwidth left') available+lowerMargin outerwidth _ (Border top' bottom' left' right') =+    Border top' bottom' (lowerLength outerwidth left') (lowerLength outerwidth right')
+ Graphics/Layout/Grid.hs view
@@ -0,0 +1,202 @@+{-# LANGUAGE RecordWildCards, OverloadedStrings #-}+-- | Sizes grid cells & positions elements to them.+module Graphics.Layout.Grid(Grid(..), Track(..), GridItem(..), GridItem'(..), Alignment(..),+        buildTrack, buildGrid, setCellBox, enumerate, gridItemBox, cellSize,+        trackMin, trackNat, gridEstWidth, sizeTrackMins, sizeTrackNats, sizeTrackMaxs,+        trackPosition, gridPosition, trackLayout, gridLayout) where++import Data.Either (fromRight)+import Data.Text (Text)+import Data.List (intersperse)+import Graphics.Layout.Box as B++import Debug.Trace (trace)++-- | An element which positions it's children within a grid.+type Grid m n = Size (Track m) (Track n)+-- | The sizes to which children are alonged on a single axis.+data Track x = Track {+    -- | The desired size of each cell.+    -- If Left specifies ratio of excess space to use.+    cells :: [Either x Double],+    -- | The minimum amount of space each cell should take.+    trackMins :: [Double],+    -- | The ideal amount of space each cell should take.+    trackNats :: [Double],+    -- | How much space to add between cells.+    gap :: x+}+-- | Which cells a child should be aligned to.+type GridItem = Size GridItem' GridItem'+-- | How a grid child should be aligned per-axis.+data GridItem' = GridItem {+    -- | On which cell should this child start.+    cellStart :: Int,+    -- | Before which cell should this child end.+    cellEnd :: Int,+    -- | How to redistribute excess space.+    alignment :: Alignment,+    -- | The minimum amount of space to allocate to this child.+    minSize :: Double,+    -- | The maximum aount of space to allocate to this child.+    natSize :: Double+}+-- | How to redistribute excess space.+data Alignment = Start | Mid | End++-- | Constructs a track with default (to-be-computed) values & given cell sizes.+buildTrack :: CastDouble x => [Either x Double] -> Track x+buildTrack cells = Track cells [] [] $ fromDouble 0+-- | Constructs a grid with default (to-be-computed) values & given cell sizes.+buildGrid :: (CastDouble m, CastDouble n) =>+        [Either m Double] -> [Either n Double] -> Grid m n+buildGrid rows cols = Size (buildTrack cols) (buildTrack rows)++-- | Verify that the track is properly formed & can be validly processed.+verifyTrack :: Track x -> [GridItem'] -> Bool+verifyTrack track cells' = and [+    cellStart cell < length (cells track) && cellStart cell >= 0 &&+    cellEnd cell < length (cells track) && cellEnd cell > cellStart cell+  | cell <- cells']+-- | Verify that the grid is properly formed & can be validly processed.+verifyGrid :: Grid m n -> [GridItem] -> Bool+verifyGrid grid cells =+    verifyTrack (inline grid) (map inline cells) && verifyTrack (block grid) (map block cells)++-- | Compute the minimum size for the track given cell sizes.+-- Refers to computed min sizes if cached.+trackMin :: (n -> Double) -> Track n -> Double+trackMin cb self@Track { trackMins = [] } =+    sum $ intersperse (cb $ gap self) [cb x | Left x <- cells self]+trackMin cb self = sum $ intersperse (cb $ gap self) $ trackMins self+-- | Compute the natural size for the track given cell sizes.+-- Refers to compute natural sizes if cached.+trackNat :: (n -> Double) -> Track n -> Double+trackNat cb self@Track { trackNats = [] } =+    sum $ intersperse (cb $ gap self) [cb x | Left x <- cells self]+trackNat cb self = sum $ intersperse (cb $ gap self) $ trackNats self++-- | Selects all children entirely on the specified cell.+cellsForIndex :: [GridItem'] -> Int -> [GridItem']+cellsForIndex cells ix =+    [cell | cell <- cells, cellStart cell == ix, cellStart cell == pred (cellEnd cell)]+-- | Sets minimum & natural sizes from the given padded box.+setCellBox :: (CastDouble m, CastDouble n) => GridItem -> PaddedBox m n -> GridItem+setCellBox (Size x y) box = Size x {+    minSize = B.minWidth $ mapX' toDouble box,+    natSize = B.width $ mapX' toDouble box+  } y {+    minSize = B.minHeight $ mapY' toDouble box,+    natSize = B.height $ mapY' toDouble box+  }++-- | Estimate grid width to inform proper width calculation.+gridEstWidth :: Grid y Length -> [GridItem] -> Double+gridEstWidth (Size cols _) childs = trackNat toDouble cols {+    trackMins = sizeTrackMins 0 cols $ map inline childs,+    trackNats = sizeTrackNats 0 cols $ map inline childs+  }+-- | Calculate minimum sizes for all cells in the track.+-- Sized to fit given children.+sizeTrackMins :: Double -> Track Length -> [GridItem'] -> [Double]+sizeTrackMins parent track childs = map inner $ enumerate $ cells track+  where+    inner (_, Left (Pixels x)) = x+    inner (_, Left (Percent x)) = x * parent+    inner arg@(ix, Left Preferred) =+        maximum $ (0:) $ map natSize $ cellsForIndex childs ix+    inner (ix, _) =+        maximum $ (0:) $ map minSize $ cellsForIndex childs ix+-- | Compute natural sizes for all cells in the track.+-- Sized to fit given children.+sizeTrackNats :: Double -> Track Length -> [GridItem'] -> [Double]+sizeTrackNats parent track childs = map inner $ enumerate $ cells track+  where+    inner (_, Left (Pixels x)) = x+    inner (_, Left (Percent x)) = x * parent+    inner arg@(ix, Left Min) =+        maximum $ (0:) $ map minSize $ cellsForIndex childs ix+    inner (ix, _) =+        maximum $ (0:) $ map natSize $ cellsForIndex childs ix+-- | Compute maximum sizes for all cells in the track, sized to the parent element.+sizeTrackMaxs :: Double -> Track Length -> [Double]+sizeTrackMaxs parent track = map (inner fr) $ zip subsizes $ cells track+  where+    subsizes = zip (trackMins track) (trackNats track)+    fr = Prelude.max 0 fr'+    fr' = (parent - estimate)/(countFRs $ cells track)+    estimate = sum $ intersperse (lowerLength parent $ gap track) $+            map (inner 0) $ zip subsizes $ cells track+    inner _ (_, Left (Pixels x)) = x+    inner _ (_, Left (Percent x)) = x*parent+    inner _ ((_, nat), Left Preferred) = nat+    inner _ ((min, _), Left Min) = min+    inner fr ((_, nat), Left Auto) = Prelude.min nat fr+    inner fr (_, Right x) = x*fr++-- | Compute the position of all children within the grid.+trackPosition :: Track Double -> [GridItem'] -> [Double]+trackPosition self childs = map gridCellPosition childs+  where+    gridCellPosition child = track (cellStart child) + align whitespace (alignment child)+      where+        whitespace = track (cellEnd child) - track (cellStart child) - natSize child+    track = flip track' $ cells self+    track' ix (size:sizes) = fromRight 0 size + track' (pred ix) sizes+    track' 0 _ = 0+    track' ix [] = trace "WARNING! Malformed input table!" 0+    align _ Start = 0+    align excess Mid = excess/2+    align excess End = excess+-- Compute the maximum size along an axis of a child, for it to be sized to.+cellSize :: CastDouble x => Track x -> GridItem' -> Double+cellSize self child = track (cellEnd child) - track (cellStart child)+  where+    track = flip track' $ cells self+    track' ix (size:sizes) =+        (toDouble $ fromRight (fromDouble 0) size) + track' (pred ix) sizes+    track' 0 _ = 0+    track' ix [] = trace "WARNING! Malformed input table!" 0+-- | Compute the maximum size as a PaddedBox of a child, for it to be sized to.+gridItemBox :: (CastDouble x, CastDouble y) => Grid y x -> GridItem -> PaddedBox Double Double+gridItemBox (Size cols rows) cell =+    size2box (cellSize cols (inline cell) `Size` cellSize rows (block cell))+  where+    size2box size = zero { B.min = size, B.max = size, B.size = size }+-- | Compute the position of all children in a grid.+gridPosition :: Grid Double Double -> [GridItem] -> [(Double, Double)]+gridPosition (Size cols rows) childs =+    trackPosition rows (map inline childs) `zip` trackPosition cols (map block childs)+-- | Compute the track sizes & child positions along a single axis.+trackLayout :: Double -> Double -> Track Length -> [GridItem'] ->+        (Track Double, [(Double, GridItem')])+trackLayout parent width self childs = (self', zip positions childs)+  where+    positions = trackPosition self' childs+    self' = self {+        cells = map Left sizes,+        trackMins = mins, trackNats = nats,+        gap = lowerLength width $ gap self+      }+    sizes = sizeTrackMaxs parent self { trackMins = mins, trackNats = nats }+    mins = sizeTrackMins parent self childs+    nats = sizeTrackNats parent self childs+-- | Compute the track sizes & child positions along both axes.+gridLayout :: Size Double Double -> Grid Length Length -> [GridItem] ->+        (Grid Double Double, [((Double, Double), GridItem)])+gridLayout parent (Size cols rows) childs = (self', zip positions childs)+  where+    positions = gridPosition self' childs+    self' = Size cols' { gap = lowerLength width $ gap cols } rows'+    (rows', _) = trackLayout (block parent) width rows $ map block childs+    width = trackNat id cols'+    (cols', _) = trackLayout (inline parent) 0 cols $ map inline childs++-- | Utility for associate an index with each item in a list.+enumerate = zip [0..]++-- | Utility for summing the divisor used to compute the fr unit.+countFRs (Left Auto:rest) = succ $ countFRs rest+countFRs (Right x:rest) = x + countFRs rest+countFRs (_:rest) = countFRs rest+countFRs [] = 0
+ Graphics/Layout/Grid/CSS.hs view
@@ -0,0 +1,359 @@+{-# LANGUAGE OverloadedStrings #-}+-- | Infrastructure for parsing & desugaring grid-layout related CSS properties.+module Graphics.Layout.Grid.CSS(CSSGrid(..), Axis(..), CSSCell(..), Placement(..), finalizeGrid) where++import Stylist (PropertyParser(..))+import Data.CSS.Syntax.Tokens (Token(..), NumericValue(..))+import Data.Text (Text)+import qualified Data.Text as Txt+import Data.Char (isAlphaNum)+import Data.Maybe (fromMaybe)++import Graphics.Layout.CSS.Length+import Graphics.Layout.Box+import Graphics.Layout.Grid+import Graphics.Layout++-- | Parsed CSS Grid properties+data CSSGrid = CSSGrid {+    -- | Parsed CSS grid-auto-columns+    autoColumns :: Unitted,+    -- | Parsed grid-auto-flow+    autoFlow :: Axis,+    -- | Whether grid-auto-flow: dense was specified.+    autoFlowDense :: Bool,+    -- | Parsed CSS grid-auto-rows+    autoRows :: Unitted,+    -- | Parsed CSS grid-template-areas+    templateAreas :: [[Text]],+    -- | Parsed CSS grid-template-columns+    templateColumns :: [([Text], Unitted)],+    -- | Parsed CSS grid-template-rows+    templateRows :: [([Text], Unitted)],+    -- | Parsed CSS row-gap & column-gap+    cssGap :: Size Unitted Unitted,+    -- | Parsed CSS justify-items & align-items+    alignItems :: Size Alignment Alignment+}+-- | A grid axis.+data Axis = Row | Col deriving Eq+-- | Parsed CSS grid item properties.+data CSSCell = CSSCell {+    -- | Parsed CSS grid-column-start+    columnStart :: Placement,+    -- | Parsed CSS grid-column-end+    columnEnd :: Placement,+    -- | Parsed CSS grid-row-start+    rowStart :: Placement,+    -- | Parsed CSS grid-row-end+    rowEnd :: Placement,+    -- | Parsed CSS align-self & justify-self+    alignSelf :: Size (Maybe Alignment) (Maybe Alignment)+}+-- | Identifies a cell in the CSS grid.+data Placement = Autoplace | Named Text | Numbered Int (Maybe Text) |+        Span Int (Maybe Text)++instance PropertyParser CSSGrid where+    temp = CSSGrid {+        autoColumns = auto,+        autoFlow = Row,+        autoFlowDense = False,+        autoRows = auto,+        templateAreas = [],+        templateColumns = [],+        templateRows = [],+        cssGap = Size (0,"px") (0,"px"),+        alignItems = Size Start Start -- FIXME: Should be stretch, unsupported.+    }+    inherit _ = temp++    longhand _ s "grid-auto-columns" toks | Just x <- parseFR toks = Just s {autoColumns=x}+    longhand _ s "grid-auto-rows" toks | Just x <- parseFR toks = Just s { autoRows = x }++    longhand _ self "grid-auto-flow" [Ident "row"] = Just self {+        autoFlow = Row, autoFlowDense = False+      }+    longhand _ self "grid-auto-flow" [Ident "column"] = Just self {+        autoFlow = Col, autoFlowDense = False+      }+    longhand _ self "grid-auto-flow" [Ident "row", Ident "dense"] = Just self {+        autoFlow = Row, autoFlowDense = True+      }+    longhand _ self "grid-auto-flow" [Ident "column", Ident "dense"] = Just self {+        autoFlow = Col, autoFlowDense = True+      }++    longhand _ self "grid-template-areas" [Ident "none"] = Just self {templateAreas = []}+    longhand _ self "grid-template-areas" [Ident "initial"] = Just self {templateAreas=[]}+    longhand _ self "grid-template-areas" toks+        | all isString toks, validate [Txt.words x | String x <- toks] =+            Just self { templateAreas = [Txt.words x | String x <- toks] }+      where+        isString (String _) = True+        isString _ = False+        validate grid@(row:rows) =+            all isValidName (concat grid) && all (\x -> length row == length x) rows+        validate [] = False+        isValidName name = Txt.all (\c -> isAlphaNum c || c == '-') name++    longhand _ self "grid-template-columns" toks | Just x <- parseTemplate toks =+        Just self { templateColumns = x }+    longhand _ self "grid-template-rows" toks | Just x <- parseTemplate toks =+        Just self { templateRows = x}++    longhand _ self "row-gap" toks | Just x <- parseLength toks =+        Just self { cssGap = (cssGap self) { inline = x } }+    longhand _ self "column-gap" toks | Just x <- parseLength toks =+        Just self { cssGap = (cssGap self) { block = x } }++    longhand _ self "justify-items" [Ident "start"] =+        Just self { alignItems = (alignItems self) { inline = Start } }+    longhand _ self "justify-items" [Ident "flex-start"] =+        Just self { alignItems = (alignItems self) { inline = Start } }+    longhand _ self "justify-items" [Ident "self-start"] =+        Just self { alignItems = (alignItems self) { inline = Start } }+    longhand _ self "justify-items" [Ident "left"] =+        Just self { alignItems = (alignItems self) { inline = Start } }+    longhand _ self "justify-items" [Ident "center"] =+        Just self { alignItems = (alignItems self) { inline = Mid } }+    longhand _ self "justify-items" [Ident "end"] =+        Just self { alignItems = (alignItems self) { inline = End } }+    longhand _ self "justify-items" [Ident "flex-end"] =+        Just self { alignItems = (alignItems self) { inline = End } }+    longhand _ self "justify-items" [Ident "self-end"] =+        Just self { alignItems = (alignItems self) { inline = End } }+    longhand _ self "justify-items" [Ident "right"] =+        Just self { alignItems = (alignItems self) { inline = End } }+    longhand parent self "justify-items" (Ident "unsafe":toks) =+        longhand parent self "justify-items" toks+    longhand _ self "justify-items" [Ident "normal"] = -- FIXME Should be stretch, unsupported.+        Just self { alignItems = (alignItems self) { inline = Start } }+    longhand _ self "justify-items" [Ident "initial"] = -- FIXME Should be stretch, unsupported.+        Just self { alignItems = (alignItems self) { inline = Start } }++    longhand _ self "align-items" [Ident "start"] =+        Just self { alignItems = (alignItems self) { block = Start } }+    longhand _ self "align-items" [Ident "flex-start"] =+        Just self { alignItems = (alignItems self) { block = Start } }+    longhand _ self "align-items" [Ident "self-start"] =+        Just self { alignItems = (alignItems self) { block = Start } }+    longhand _ self "align-items" [Ident "center"] =+        Just self { alignItems = (alignItems self) { block = Mid } }+    longhand _ self "align-items" [Ident "end"] =+        Just self { alignItems = (alignItems self) { block = End } }+    longhand _ self "align-items" [Ident "flex-end"] =+        Just self { alignItems = (alignItems self) { block = End } }+    longhand _ self "align-items" [Ident "self-end"] =+        Just self { alignItems = (alignItems self) { block = End } }+    longhand parent self "align-items" (Ident "unsafe":toks) =+        longhand parent self "align-items" toks+    longhand _ self "align-items" [Ident "normal"] = -- FIXME Should be stretch, unsupported.+        Just self { alignItems = (alignItems self) { block = Start } }+    longhand _ self "align-items" [Ident "initial"] = -- FIXME Should be stretch, unsupported.+        Just self { alignItems = (alignItems self) { block = Start } }++    longhand _ _ _ _ = Nothing++instance PropertyParser CSSCell where+    temp = CSSCell {+        columnStart = Autoplace,+        columnEnd = Autoplace,+        rowStart = Autoplace,+        rowEnd = Autoplace,+        alignSelf = Size Nothing Nothing+    }+    inherit _ = temp++    longhand _ self "grid-column-start" toks | Just x <- placement toks =+        Just self { columnStart = x}+    longhand _ s "grid-column-end" toks | Just x <- placement toks = Just s {columnEnd=x}+    longhand _ s "grid-row-start" toks | Just x <- placement toks = Just s {rowStart = x}+    longhand _ s "grid-row-end" toks | Just x <- placement toks = Just s { rowEnd = x }++    longhand _ self "align-self" [Ident "start"] =+        Just self { alignSelf = (alignSelf self) { block = Just Start } }+    longhand _ self "align-self" [Ident "self-start"] =+        Just self { alignSelf = (alignSelf self) { block = Just Start } }+    longhand _ self "align-self" [Ident "flex-start"] =+        Just self { alignSelf = (alignSelf self) { block = Just Start } }+    longhand _ self "align-self" [Ident "center"] =+        Just self { alignSelf = (alignSelf self) { block = Just Mid } }+    longhand _ self "align-self" [Ident "end"] =+        Just self { alignSelf = (alignSelf self) { block = Just End } }+    longhand _ self "align-self" [Ident "self-end"] =+        Just self { alignSelf = (alignSelf self) { block = Just End } }+    longhand _ self "align-self" [Ident "flex-end"] =+        Just self { alignSelf = (alignSelf self) { block = Just End } }+    longhand _ self "align-self" [Ident "normal"] = -- FIXME should be stretch, unsupported+        Just self { alignSelf = (alignSelf self) { block = Just Start } }+    longhand parent self "align-self" (Ident "unsafe":toks) =+        longhand parent self "align-self" toks+    longhand _ self "align-self" [Ident "auto"] =+        Just self { alignSelf = (alignSelf self) { block = Nothing } }+    longhand _ self "align-self" [Ident "initial"] =+        Just self { alignSelf = (alignSelf self) { block = Nothing } }++    longhand _ self "justify-self" [Ident "start"] =+        Just self { alignSelf = (alignSelf self) { inline = Just Start } }+    longhand _ self "justify-self" [Ident "self-start"] =+        Just self { alignSelf = (alignSelf self) { inline = Just Start } }+    longhand _ self "justify-self" [Ident "flex-start"] =+        Just self { alignSelf = (alignSelf self) { inline = Just Start } }+    longhand _ self "justify-self" [Ident "left"] =+        Just self { alignSelf = (alignSelf self) { inline = Just Start } }+    longhand _ self "justify-self" [Ident "center"] =+        Just self { alignSelf = (alignSelf self) { inline = Just Mid } }+    longhand _ self "justify-self" [Ident "end"] =+        Just self { alignSelf = (alignSelf self) { inline = Just End } }+    longhand _ self "justify-self" [Ident "self-end"] =+        Just self { alignSelf = (alignSelf self) { inline = Just End } }+    longhand _ self "justify-self" [Ident "flex-end"] =+        Just self { alignSelf = (alignSelf self) { inline = Just End } }+    longhand _ self "justify-self" [Ident "right"] =+        Just self { alignSelf = (alignSelf self) { inline = Just End } }+    longhand _ self "justify-self" [Ident "normal"] = -- FIXME should be stretch, unsupported+        Just self { alignSelf = (alignSelf self) { inline = Just Start } }+    longhand parent self "justify-self" (Ident "unsafe":toks) =+        longhand parent self "justify-self" toks+    longhand _ self "justify-self" [Ident "auto"] =+        Just self { alignSelf = (alignSelf self) { inline = Nothing } }+    longhand _ self "justify-self" [Ident "initial"] =+        Just self { alignSelf = (alignSelf self) { inline = Nothing } }++    longhand _ _ _ _ = Nothing++-- | Parse a length or FR unit.+parseFR [Dimension _ x "fr"] = Just (n2f x,"fr")+parseFR toks = parseLength toks+-- | Parse a length or FR unit, including extended keywords.+parseFR' [Dimension _ x "fr"] = Just (n2f x,"fr")+parseFR' toks = parseLength' toks++-- | Parse an identifier for a grid cell.+placement [Ident "auto"] = Just $ Autoplace+placement [Ident x] = Just $ Named x+placement [Number _ (NVInteger x)] = Just $ Numbered (fromEnum x) Nothing+placement [Number _ (NVInteger x), Ident y] = Just $ Numbered (fromEnum x) (Just y)+placement [Ident "span", Number _ (NVInteger x)]+    | x > 0 = Just $ Span (fromEnum x) Nothing+placement [Ident "span", Ident x] = Just $ Span 1 $ Just x+placement [Ident "span", Number _ (NVInteger x), Ident y]+    | x > 0 = Just $ Span (fromEnum x) (Just y)+placement [Ident "span", Ident y, Number _ (NVInteger x)]+    | x > 0 = Just $ Span (fromEnum x) (Just y)+placement _ = Nothing++-- | Parse grid-template-*+parseTemplate [Ident "none"] = Just []+parseTemplate [Ident "initial"] = Just []+parseTemplate toks | (tracks@(_:_), []) <- parseTrack toks = Just tracks+parseTemplate _ = Nothing+-- | Parse an individual track specified by grid-template-*+parseTrack (LeftSquareBracket:toks)+    | Just (names', toks') <- parseNames toks,+        ((names,size):cells,toks) <- parseTrack toks' = ((names' ++ names,size):cells,toks)+    | Just (names', toks') <- parseNames toks = ([(names',(0,"end"))],toks')+parseTrack (tok:toks) | Just x <- parseFR' [tok] =+    (([], x):fst (parseTrack toks), snd $ parseTrack toks)+parseTrack (Function "repeat":Number _ (NVInteger x):Comma:toks)+    | x > 0, (tracks@(_:_), RightParen:toks') <- parseTrack toks =+        (concat $ replicate (fromEnum x) tracks, toks')+parseTrack toks = ([], toks)+-- | (UNUSED) Parse a subgrid specified by grid-template-*+parseSubgrid (LeftSquareBracket:toks)+    | Just (names', toks') <- parseNames toks, (names,toks'') <- parseSubgrid toks' =+        (names' : names, toks')+parseSubgrid (Function "repeat":Number _ (NVInteger x):Comma:toks)+    | x > 0, (names@(_:_), RightParen:toks') <- parseSubgrid toks =+        (concat $ replicate (fromEnum x) names, toks')+parseSubgrid toks = ([], toks)+-- | Parse a track's names.+parseNames (Ident x:toks)+    | Just (names,toks') <- parseNames toks = Just (x:names,toks')+parseNames (RightSquareBracket:toks) = Just ([], toks)+parseNames _ = Nothing++-- | Desugar grid properties to a grid layout.+finalizeGrid :: PropertyParser x => CSSGrid -> Font' ->+    [CSSCell] -> [LayoutItem Length Length x] -> LayoutItem Length Length x+finalizeGrid self@CSSGrid {+        templateColumns = cols', templateRows = rows'+    } font cells childs = LayoutGrid temp self' cells' childs+  where+    self' = Size Track {+        cells = map finalizeFR $ map snd rows0,+        trackMins = [], trackNats = [],+        gap = finalizeLength (inline $ cssGap self) font+      } Track {+        cells = map finalizeFR $ map snd cols0,+        trackMins = [], trackNats = [],+        gap = finalizeLength (block $ cssGap self) font+      }++    (cells', rows0, cols0) = finalizeCells cells rows' cols'+    finalizeCells :: [CSSCell] -> [([Text], Unitted)] -> [([Text], Unitted)] ->+            ([GridItem], [([Text], Unitted)], [([Text], Unitted)])+    finalizeCells (cell:cells) rows cols = (cell':cells', rows_, cols_)+      where+        (cell', rows0, cols0) = finalizeCell cell rows cols+        (cells', rows_, cols_) = finalizeCells cells rows0 cols0+    finalizeCells [] rows cols = ([], rows, cols)+    finalizeCell :: CSSCell -> [([Text], Unitted)] -> [([Text], Unitted)] ->+            (GridItem, [([Text], Unitted)], [([Text], Unitted)])+    finalizeCell cell@CSSCell {+            rowStart = Autoplace, columnStart = Autoplace+        } rows cols | autoFlow self == Row =+            finalizeCell cell { columnStart = Numbered 1 Nothing } rows cols+        | autoFlow self == Col =+            finalizeCell cell { rowStart = Numbered 1 Nothing } rows cols+    finalizeCell cell rows cols = (Size GridItem {+            cellStart = startCol', cellEnd = endCol',+            minSize = 0, natSize = 0,+            alignment = fromMaybe (inline $ alignItems self) (inline $ alignSelf cell)+        } GridItem {+            cellStart = startRow', cellEnd = endRow',+            minSize = 0, natSize = 0,+            alignment = fromMaybe (inline $ alignItems self) (inline $ alignSelf cell)+        }, rows', cols')+      where+        (startRow', endRow', rows') = lowerTrack2 rows ([], autoRows self)+                (rowStart cell) (rowEnd cell)+        (startCol', endCol', cols') = lowerTrack2 cols ([], autoColumns self) +                (columnStart cell) (columnEnd cell)++    lowerTrack2 tracks auto start Autoplace = lowerTrack2 tracks auto start $ Span 1 Nothing+    lowerTrack2 tracks auto start@(Span _ _) end@(Span _ _) =+        lowerTrack2 tracks auto start $ Numbered (pred $ length tracks) Nothing+    lowerTrack2 tracks auto start@(Span _ _) end = (start', end', tracks')+      where+        (end', tracks0) = lowerTrack tracks auto 0 end -- Already checked for spans.+        (start', tracks') = lowerTrack tracks auto (negate end') start+    lowerTrack2 tracks auto start end = (start', end', tracks')+      where+        (start', tracks0) = lowerTrack tracks auto 0 start -- already checked for spans.+        (end', tracks') = lowerTrack tracks auto start' end+    lowerTrack tracks auto _ (Named name)+        | ix:_ <- [ix | (ix, (names, _)) <- enumerate tracks, name `elem` names] = (ix, tracks)+        | otherwise = (length tracks, tracks ++ [auto])++    -- TODO Take into account placement strategy.+    lowerTrack tracks auto _ Autoplace = (length tracks, tracks ++ [auto])+    lowerTrack tracks _ _ (Numbered ix Nothing) = (ix, tracks)+    lowerTrack tracks auto _ (Numbered ix (Just name))+        | ix < length tracks' = (tracks' !! ix, tracks)+        | otherwise = (length tracks, tracks ++ [auto])+      where tracks' = [ix | (ix, (names, _)) <- enumerate tracks, name `elem` names]+    lowerTrack tracks _ start (Span x Nothing)+        | start > 0 = (start + x,tracks)+        | otherwise = (-start - x,tracks)+    lowerTrack tracks (_, auto) start (Span x (Just name)) = (tracks' !! x,tracks)+      where+        tracks0 | start < 0 = reverse tracks+            | otherwise = tracks+        tracks' = [ix | (ix, (names, _)) <-+            drop (abs start) $ enumerate (tracks0 ++ repeat ([name],auto)),+            name `elem` names]++    finalizeFR (x,"fr") = Right x+    finalizeFR x = Left $ finalizeLength x font
+ Graphics/Layout/Inline.hs view
@@ -0,0 +1,74 @@+{-# LANGUAGE TupleSections #-}+-- | Sizes inline text & extracts positioned children,+-- wraps Balkón for the actual logic.+module Graphics.Layout.Inline(inlineMinWidth, inlineMin, inlineNatWidth, inlineHeight,+    inlineSize, inlineChildren, layoutSize, layoutChildren,+    fragmentSize, fragmentSize', fragmentPos) where++import Data.Text.ParagraphLayout (Paragraph(..), ParagraphOptions(..),+                                    SpanLayout(..), Fragment(..),+                                    ParagraphLayout(..), layoutPlain, Span(..))+import Data.Text.ParagraphLayout.Rect (Rect(..), width, height, x_min, y_min)+import Data.Text.Internal (Text(..))+import qualified Data.Text as Txt+import Data.Char (isSpace)+import Data.Int (Int32)++import Graphics.Layout.Box (Size(..), CastDouble(..), fromDouble)+import Graphics.Layout.CSS.Font (Font', hbScale)++-- | Convert from Harfbuzz units to device pixels as a Double+hbScale' font = (/hbScale font) . fromIntegral+-- | Convert from Harfbuzz units to device pixels as a Double or Length.+c font = fromDouble . hbScale' font++-- | Compute minimum width for some richtext.+inlineMinWidth :: Font' -> Paragraph -> Double+inlineMinWidth font self = hbScale' font $ width $ layoutPlain' self 0+-- | Compute minimum width & height for some richtext.+inlineMin :: (CastDouble x, CastDouble y) => Font' -> Paragraph -> Size x y+inlineMin font self = Size (c font $ width rect) (c font $ height rect)+    where rect = layoutPlain' self 0+-- | Compute natural (single-line) width for some richtext.+inlineNatWidth :: Font' -> Paragraph -> Double+inlineNatWidth font self = hbScale' font $ width $ layoutPlain' self maxBound+-- | Compute height for rich text at given width.+inlineHeight :: Font' -> Double -> Paragraph -> Double+inlineHeight font width self =+    hbScale' font $ height $ layoutPlain' self $ round (hbScale font * width)++-- | Compute width & height of some richtext at configured width.+inlineSize :: (CastDouble x, CastDouble y) => Font' -> Paragraph -> Size x y+inlineSize font self = layoutSize font $ layoutPlain self+-- | Retrieve children out of some richtext,+-- associating given userdata with them.+inlineChildren :: [x] -> Paragraph -> [(x, Fragment)]+inlineChildren vals self = layoutChildren vals $ layoutPlain self++-- | Retrieve a laid-out paragraph's rect & convert to CatTrap types.+layoutSize :: (CastDouble x, CastDouble y) => Font' -> ParagraphLayout -> Size x y+layoutSize font self = Size (c font $ width r) (c font $ height r)+  where r = paragraphRect self+-- | Retrieve a laid-out paragraph's children & associate with given userdata.+layoutChildren :: [x] -> ParagraphLayout -> [(x, Fragment)]+layoutChildren vals self = zip vals $ concat $ map inner $ spanLayouts self+  where inner (SpanLayout y) = y++-- | Layout a paragraph at given width & retrieve resulting rect.+layoutPlain' :: Paragraph -> Int32 -> Rect Int32+layoutPlain' (Paragraph a b c d) width =+    paragraphRect $ layoutPlain $ Paragraph a b c d { paragraphMaxWidth = width }++-- | Retrieve the rect for a fragment & convert to CatTrap types.+fragmentSize :: (CastDouble x, CastDouble y) => Font' -> Fragment -> Size x y+fragmentSize font self = Size (c font $ width r) (c font $ height r)+    where r = fragmentRect self+-- | Variant of `fragmentSize` asserting to the typesystem that both fields+-- of the resulting `Size` are of the same type.+fragmentSize' :: CastDouble x => Font' -> Fragment -> Size x x+fragmentSize' = fragmentSize -- Work around for typesystem.+-- | Retrieve the position of a fragment.+fragmentPos :: Font' -> (Double, Double) -> Fragment -> (Double, Double)+fragmentPos font (x, y) self =+        (x + hbScale' font (x_min r), y + hbScale' font (y_min r))+    where r = fragmentRect self
+ Graphics/Layout/Inline/CSS.hs view
@@ -0,0 +1,60 @@+{-# LANGUAGE OverloadedStrings #-}+-- | Infrastructure for parsing & desugaring text related CSS properties.+module Graphics.Layout.Inline.CSS(CSSInline(..), ParagraphBuilder(..),+    buildParagraph, concatParagraph, finalizeParagraph) where++import Data.CSS.Syntax.Tokens (Token(..))+import Stylist (PropertyParser(..))+import qualified Data.Text.Lazy as Lz+import qualified Data.Text as Txt+import Data.Text.Internal (Text(..))+import Data.Text.ParagraphLayout (Span(..), SpanOptions(..), LineHeight(..),+                                Paragraph(..), ParagraphOptions(..))++import Graphics.Layout.CSS.Font (Font'(..), hbScale)+import Data.Char (isSpace)++-- | Document text with Balkón styling options, CSS stylable.+data CSSInline = CSSInline Lz.Text SpanOptions++instance PropertyParser CSSInline where+    temp = CSSInline "" SpanOptions {+        spanLanguage = "Zxx"+    }+    inherit (CSSInline _ opts) = CSSInline "" opts++    longhand _ (CSSInline _ opts) "content" toks+        | all isString toks =+            Just $ CSSInline (Lz.concat [Lz.fromStrict x | String x <- toks]) opts+      where+        isString (String _) = True+        isString _ = False+    longhand _ (CSSInline txt opts) "-argo-lang" [String x] =+        Just $ CSSInline txt opts { spanLanguage = Txt.unpack x }+    longhand _ _ _ _ = Nothing++-- | Helper datastructure for concatenating CSSInlines.+data ParagraphBuilder = ParagraphBuilder Lz.Text [Span]++-- | Convert a CSSInline to a paragraph builder, with a span covering the entire text.+buildParagraph :: CSSInline -> ParagraphBuilder+buildParagraph (CSSInline txt opts) =+    ParagraphBuilder txt [flip Span opts $ fromEnum $ Lz.length txt]+-- | Concatenate two `ParagraphBuilder`s, adjusting the spans appropriately.+concatParagraph :: ParagraphBuilder -> ParagraphBuilder -> ParagraphBuilder+concatParagraph (ParagraphBuilder aTxt aOpts) (ParagraphBuilder bTxt bOps) =+    ParagraphBuilder (aTxt `Lz.append` bTxt)+                    (aOpts ++ [Span (toEnum (fromEnum $ Lz.length aTxt) + off) opts+                                | Span off opts <- bOps])+-- | Convert a builder + font to a Balkón paragraph.+finalizeParagraph :: ParagraphBuilder -> Font' -> Maybe Paragraph+finalizeParagraph (ParagraphBuilder txt _) _ | Lz.all isSpace txt || Lz.null txt = Nothing+finalizeParagraph (ParagraphBuilder txt ops) font' = Just $ Paragraph txt' 0 ops pOps+    where+        Text txt' _ _ = Lz.toStrict txt+        pOps = ParagraphOptions {+            paragraphFont = hbFont font',+            paragraphLineHeight = Absolute $ round (lineheight font' * hbScale font'),+            -- This is what we're computing! Configure to give natural width.+            paragraphMaxWidth = maxBound -- i.e. has all the space it needs...+        }
+ LICENSE view
@@ -0,0 +1,674 @@+              GNU GENERAL PUBLIC LICENSE+                Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++                     Preamble++  The GNU General Public License is a free, copyleft license for+software and other kinds of works.++  The licenses for most software and other practical works are designed+to take away your freedom to share and change the works.  By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users.  We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors.  You can apply it to+your programs, too.++  When we speak of free software, we are referring to freedom, not+price.  Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++  To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights.  Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++  For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received.  You must make sure that they, too, receive+or can get the source code.  And you must show them these terms so they+know their rights.++  Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++  For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software.  For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++  Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so.  This is fundamentally incompatible with the aim of+protecting users' freedom to change the software.  The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable.  Therefore, we+have designed this version of the GPL to prohibit the practice for those+products.  If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++  Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary.  To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++  The precise terms and conditions for copying, distribution and+modification follow.++                TERMS AND CONDITIONS++  0. Definitions.++  "This License" refers to version 3 of the GNU General Public License.++  "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++  "The Program" refers to any copyrightable work licensed under this+License.  Each licensee is addressed as "you".  "Licensees" and+"recipients" may be individuals or organizations.++  To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy.  The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++  A "covered work" means either the unmodified Program or a work based+on the Program.++  To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy.  Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++  To "convey" a work means any kind of propagation that enables other+parties to make or receive copies.  Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++  An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License.  If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++  1. Source Code.++  The "source code" for a work means the preferred form of the work+for making modifications to it.  "Object code" means any non-source+form of a work.++  A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++  The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form.  A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++  The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities.  However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work.  For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++  The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++  The Corresponding Source for a work in source code form is that+same work.++  2. Basic Permissions.++  All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met.  This License explicitly affirms your unlimited+permission to run the unmodified Program.  The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work.  This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++  You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force.  You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright.  Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++  Conveying under any other circumstances is permitted solely under+the conditions stated below.  Sublicensing is not allowed; section 10+makes it unnecessary.++  3. Protecting Users' Legal Rights From Anti-Circumvention Law.++  No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++  When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++  4. Conveying Verbatim Copies.++  You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++  You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++  5. Conveying Modified Source Versions.++  You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++    a) The work must carry prominent notices stating that you modified+    it, and giving a relevant date.++    b) The work must carry prominent notices stating that it is+    released under this License and any conditions added under section+    7.  This requirement modifies the requirement in section 4 to+    "keep intact all notices".++    c) You must license the entire work, as a whole, under this+    License to anyone who comes into possession of a copy.  This+    License will therefore apply, along with any applicable section 7+    additional terms, to the whole of the work, and all its parts,+    regardless of how they are packaged.  This License gives no+    permission to license the work in any other way, but it does not+    invalidate such permission if you have separately received it.++    d) If the work has interactive user interfaces, each must display+    Appropriate Legal Notices; however, if the Program has interactive+    interfaces that do not display Appropriate Legal Notices, your+    work need not make them do so.++  A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit.  Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++  6. Conveying Non-Source Forms.++  You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++    a) Convey the object code in, or embodied in, a physical product+    (including a physical distribution medium), accompanied by the+    Corresponding Source fixed on a durable physical medium+    customarily used for software interchange.++    b) Convey the object code in, or embodied in, a physical product+    (including a physical distribution medium), accompanied by a+    written offer, valid for at least three years and valid for as+    long as you offer spare parts or customer support for that product+    model, to give anyone who possesses the object code either (1) a+    copy of the Corresponding Source for all the software in the+    product that is covered by this License, on a durable physical+    medium customarily used for software interchange, for a price no+    more than your reasonable cost of physically performing this+    conveying of source, or (2) access to copy the+    Corresponding Source from a network server at no charge.++    c) Convey individual copies of the object code with a copy of the+    written offer to provide the Corresponding Source.  This+    alternative is allowed only occasionally and noncommercially, and+    only if you received the object code with such an offer, in accord+    with subsection 6b.++    d) Convey the object code by offering access from a designated+    place (gratis or for a charge), and offer equivalent access to the+    Corresponding Source in the same way through the same place at no+    further charge.  You need not require recipients to copy the+    Corresponding Source along with the object code.  If the place to+    copy the object code is a network server, the Corresponding Source+    may be on a different server (operated by you or a third party)+    that supports equivalent copying facilities, provided you maintain+    clear directions next to the object code saying where to find the+    Corresponding Source.  Regardless of what server hosts the+    Corresponding Source, you remain obligated to ensure that it is+    available for as long as needed to satisfy these requirements.++    e) Convey the object code using peer-to-peer transmission, provided+    you inform other peers where the object code and Corresponding+    Source of the work are being offered to the general public at no+    charge under subsection 6d.++  A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++  A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling.  In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage.  For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product.  A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++  "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source.  The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++  If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information.  But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++  The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed.  Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++  Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++  7. Additional Terms.++  "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law.  If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++  When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it.  (Additional permissions may be written to require their own+removal in certain cases when you modify the work.)  You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++  Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++    a) Disclaiming warranty or limiting liability differently from the+    terms of sections 15 and 16 of this License; or++    b) Requiring preservation of specified reasonable legal notices or+    author attributions in that material or in the Appropriate Legal+    Notices displayed by works containing it; or++    c) Prohibiting misrepresentation of the origin of that material, or+    requiring that modified versions of such material be marked in+    reasonable ways as different from the original version; or++    d) Limiting the use for publicity purposes of names of licensors or+    authors of the material; or++    e) Declining to grant rights under trademark law for use of some+    trade names, trademarks, or service marks; or++    f) Requiring indemnification of licensors and authors of that+    material by anyone who conveys the material (or modified versions of+    it) with contractual assumptions of liability to the recipient, for+    any liability that these contractual assumptions directly impose on+    those licensors and authors.++  All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10.  If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term.  If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++  If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++  Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++  8. Termination.++  You may not propagate or modify a covered work except as expressly+provided under this License.  Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++  However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++  Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++  Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License.  If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++  9. Acceptance Not Required for Having Copies.++  You are not required to accept this License in order to receive or+run a copy of the Program.  Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance.  However,+nothing other than this License grants you permission to propagate or+modify any covered work.  These actions infringe copyright if you do+not accept this License.  Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++  10. Automatic Licensing of Downstream Recipients.++  Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License.  You are not responsible+for enforcing compliance by third parties with this License.++  An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations.  If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++  You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License.  For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++  11. Patents.++  A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based.  The+work thus licensed is called the contributor's "contributor version".++  A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version.  For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++  Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++  In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement).  To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++  If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients.  "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++  If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++  A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License.  You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++  Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++  12. No Surrender of Others' Freedom.++  If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License.  If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all.  For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++  13. Use with the GNU Affero General Public License.++  Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work.  The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++  14. Revised Versions of this License.++  The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time.  Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++  Each version is given a distinguishing version number.  If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation.  If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++  If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++  Later license versions may give you additional or different+permissions.  However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++  15. Disclaimer of Warranty.++  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++  16. Limitation of Liability.++  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++  17. Interpretation of Sections 15 and 16.++  If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++              END OF TERMS AND CONDITIONS++     How to Apply These Terms to Your New Programs++  If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++  To do so, attach the following notices to the program.  It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++    <one line to give the program's name and a brief idea of what it does.>+    Copyright (C) <year>  <name of author>++    This program is free software: you can redistribute it and/or modify+    it under the terms of the GNU General Public License as published by+    the Free Software Foundation, either version 3 of the License, or+    (at your option) any later version.++    This program is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+    GNU General Public License for more details.++    You should have received a copy of the GNU General Public License+    along with this program.  If not, see <http://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++  If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++    <program>  Copyright (C) <year>  <name of author>+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+    This is free software, and you are welcome to redistribute it+    under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License.  Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++  You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<http://www.gnu.org/licenses/>.++  The GNU General Public License does not permit incorporating your program+into proprietary programs.  If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library.  If this is what you want to do, use the GNU Lesser General+Public License instead of this License.  But first, please read+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ app/Main.hs view
@@ -0,0 +1,214 @@+module Main where++import Text.XML.Light.Input (parseXMLDoc)+import qualified Text.XML.Light.Types as X+import Data.Maybe (fromJust, fromMaybe)+import qualified Data.Text as Txt+import Control.Monad (forM_, mapM)++import Graphics.Layout.CSS (CSSBox(..), finalizeCSS')+import Graphics.Layout.CSS.Font (placeholderFont)+import Graphics.Layout (LayoutItem, boxLayout,+                        layoutGetBox, layoutGetChilds, layoutGetInner)+import Graphics.Layout.Box (zeroBox)+import qualified Graphics.Layout.Box as B++import Stylist.Tree (StyleTree(..))+import Stylist (PropertyParser(..))+import Data.CSS.Syntax.Tokens (Token(..), tokenize)++import Graphics.UI.GLUT+import Graphics.GL.Core32++import Foreign.Ptr (castPtr, nullPtr)+import Foreign.Storable (Storable(..))+import Foreign.Marshal.Array (withArrayLen, allocaArray, peekArray)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Marshal.Utils (with)+import Foreign.C.String (withCString)++main :: IO ()+main = do+    (progname, args) <- getArgsAndInitialize+    source <- readFile $ case args of+        (filename:_) -> filename+        [] -> "styletree.xml"+    let xml = fromJust $ parseXMLDoc source+    let styles = xml2styles temp xml+    let layout = finalizeCSS' placeholderFont styles++    w <- createWindow progname++    vertexShader <- compileOGLShader vertexSource GL_VERTEX_SHADER+    fragmentShader <- compileOGLShader fragmentSource GL_FRAGMENT_SHADER+    shader <- compileOGLProgram [] [vertexShader, fragmentShader]+    glDetachShader shader vertexShader+    glDetachShader shader fragmentShader+    glDeleteShader vertexShader+    glDeleteShader fragmentShader++    displayCallback $= do+        clear [ ColorBuffer ]+        Size x y <- get windowSize+        let (display:_) = boxLayout zeroBox {+            B.size = B.Size (fromIntegral x) (fromIntegral y)+          } layout False++        glUseProgram shader+        attribScale <- withCString "windowsize" $ glGetUniformLocation shader+        glUniform3f attribScale (realToFrac x) (realToFrac y) 1++        renderDisplay shader display+        flush+    mainLoop++xml2styles :: CSSBox Nil -> X.Element -> StyleTree (CSSBox Nil)+xml2styles parent el = StyleTree {+    style = self',+    children = [xml2styles self' child | X.Elem child <- X.elContent el]+  } where self' = foldl (applyStyle parent) temp $ X.elAttribs el++applyStyle parent style (X.Attr (X.QName name _ _) val) =+    fromMaybe style $ longhand parent style (Txt.pack name) $+        filter (/= Whitespace) $ tokenize $ Txt.pack val++data Nil = Nil+instance PropertyParser Nil where+    temp = Nil+    inherit _ = Nil+    longhand _ _ _ _ = Nothing++renderDisplay :: GLuint -> LayoutItem Double Double ((Double, Double), a) -> IO ()+renderDisplay shader display = do+    let ((x, y), _) = layoutGetInner display+    let box = layoutGetBox display+    attribColour <- withCString "fill" $ glGetUniformLocation shader++    glUniform3f attribColour 1 0 0+    drawBox x y (B.width box) (B.height box)+    glUniform3f attribColour 0 1 0+    drawBox (x + B.left (B.margin box)) (y + B.top (B.margin box))+            (B.width box - B.left (B.margin box) - B.right (B.margin box))+            (B.height box - B.top (B.margin box) - B.bottom (B.margin box))+    glUniform3f attribColour 0 0 1+    drawBox (x + B.left (B.margin box) + B.left (B.border box))+            (y + B.top (B.margin box) + B.top (B.border box))+            (B.inline (B.size box) + B.left (B.padding box) + B.right (B.padding box))+            (B.block (B.size box) + B.top (B.padding box) + B.bottom (B.padding box))+    glUniform3f attribColour 1 1 0+    drawBox (x + B.left (B.margin box) + B.left (B.border box) + B.left (B.padding box))+            (y + B.top (B.margin box) + B.top (B.border box) + B.top (B.padding box))+            (B.inline $ B.size box) (B.block $ B.size box)++    mapM (renderDisplay shader) $ layoutGetChilds display+    return ()++drawBox x y width height = do+    buf <- withPointer $ glGenBuffers 1+    glBindBuffer GL_ARRAY_BUFFER buf+    glBufferData' GL_ARRAY_BUFFER [+        x, y, 0,+        x + width, y, 0,+        x, y + height, 0,++        x + width, y, 0,+        x + width, y + height, 0,+        x, y + height, 0+      ] GL_STATIC_DRAW++    glEnableVertexAttribArray 0+    glBindBuffer GL_ARRAY_BUFFER buf+    glVertexAttribPointer 0 3 GL_FLOAT GL_FALSE 0 nullPtr++    glDrawArrays GL_TRIANGLES 0 6+    glDisableVertexAttribArray 0++withPointer cb = alloca $ \ret' -> do+    cb ret'+    peek ret'++glBufferData' _ [] _ = return ()+glBufferData' target dat usage =+    withArrayLen (map realToFrac dat :: [Float]) $ \len dat' -> do+        glBufferData target (toEnum $ len*sizeOf (head dat)) (castPtr dat') usage++compileOGLShader :: String -> GLenum -> IO GLuint+compileOGLShader src shType = do+  shader <- glCreateShader shType+  if shader == 0+    then error "Could not create shader"+    else do+      success <-do+        withCString (src) $ \ptr ->+          with ptr $ \ptrptr -> glShaderSource shader 1 ptrptr nullPtr++        glCompileShader shader+        with (0 :: GLint) $ \ptr -> do+          glGetShaderiv shader GL_COMPILE_STATUS ptr+          peek ptr++      if success == GL_FALSE+        then do+          err <- do+            infoLog <- with (0 :: GLint) $ \ptr -> do+                glGetShaderiv shader GL_INFO_LOG_LENGTH ptr+                logsize <- peek ptr+                allocaArray (fromIntegral logsize) $ \logptr -> do+                    glGetShaderInfoLog shader logsize nullPtr logptr+                    peekArray (fromIntegral logsize) logptr++            return $ unlines [ "Could not compile shader:"+                             , src+                             , map (toEnum . fromEnum) infoLog+                             ]+          error err+        else return shader++compileOGLProgram :: [(String, Integer)] -> [GLuint] -> IO GLuint+compileOGLProgram attribs shaders = do+  (program, success) <- do+     program <- glCreateProgram+     forM_ shaders (glAttachShader program)+     forM_ attribs+       $ \(name, loc) ->+         withCString name+           $ glBindAttribLocation program+           $ fromIntegral loc+     glLinkProgram program++     success <- with (0 :: GLint) $ \ptr -> do+       glGetProgramiv program GL_LINK_STATUS ptr+       peek ptr+     return (program, success)++  if success == GL_FALSE+  then with (0 :: GLint) $ \ptr -> do+    glGetProgramiv program GL_INFO_LOG_LENGTH ptr+    logsize <- peek ptr+    infoLog <- allocaArray (fromIntegral logsize) $ \logptr -> do+      glGetProgramInfoLog program logsize nullPtr logptr+      peekArray (fromIntegral logsize) logptr+    error $ unlines+          [ "Could not link program"+          , map (toEnum . fromEnum) infoLog+          ]+  else do+    forM_ shaders glDeleteShader+    return program++vertexSource = unlines [+    "#version 330 core",+    "layout(location = 0) in vec3 vertexPositionModelSpace;",+    "uniform vec3 windowsize;",+    "void main() {",+    "gl_Position.xyz = vertexPositionModelSpace/windowsize - 1;",+    "gl_Position.y = -gl_Position.y;",+    "gl_Position.w = 1.0;",+    "}"+  ]+fragmentSource = unlines [+    "#version 330 core",+    "uniform vec3 fill;",+    "out vec3 colour;",+    "void main() { colour = fill; }"+  ]
+ cattrap.cabal view
@@ -0,0 +1,56 @@+-- Initial cattrap.cabal generated by cabal init.  For further+-- documentation, see http://haskell.org/cabal/users-guide/++name:                cattrap+version:             0.1.0.0+synopsis:            Lays out boxes according to the CSS Box Model.+description:         Computes where to place e.g. images, paragraphs, containers, tables, etc onscreen given desired amounts of whitespace.+homepage:            https://argonaut-constellation.org/+license:             GPL-3+license-file:        LICENSE+author:              Adrian Cochrane+maintainer:          ~alcinnz/cattrap@todo.argonaut-constellation.org+bug-reports:         https://todo.argonaut-constellation.org/~alcinnz/cattrap+copyright:           Adrian Cochrane 2023+category:            Graphics+build-type:          Simple+extra-source-files:  CHANGELOG.md+cabal-version:       >=1.10++source-repository head+  type:     git+  location: https://git.argonaut-constellation.org/~alcinnz/cattrap++library+  exposed-modules:     Graphics.Layout, Graphics.Layout.CSS, Graphics.Layout.Flow,+                        Graphics.Layout.Grid, Graphics.Layout.Grid.CSS,+                        Graphics.Layout.Box, Graphics.Layout.Arithmetic,+                        Graphics.Layout.CSS.Length, Graphics.Layout.CSS.Font,+                        Graphics.Layout.Inline, Graphics.Layout.Inline.CSS+  -- other-modules:+  -- other-extensions:+  build-depends:       base >=4.12 && <4.16, containers,+                        css-syntax, scientific, text,+                        stylist-traits >= 0.1.1.0 && < 1,+                        fontconfig-pure >= 0.2 && < 0.3,+                        harfbuzz-pure >= 1.0.3.2 && < 1.1, bytestring,+                        balkon >= 0.2.1 && < 1+  -- hs-source-dirs:+  default-language:    Haskell2010+  ghc-options:         -Wincomplete-patterns++executable cattrap+  main-is:             Main.hs+  -- other-modules:+  -- other-extensions:+  build-depends:       base >=4.12 && <4.16, cattrap, xml, text, css-syntax, stylist-traits, GLUT, gl+  hs-source-dirs:      app+  default-language:    Haskell2010++test-suite test-cattrap+  hs-source-dirs:      test+  default-language:    Haskell2010+  type:                exitcode-stdio-1.0+  main-is:             Test.hs+  build-depends:       base, cattrap, hspec >= 2 && < 3, QuickCheck >= 2 && < 3,+                        css-syntax, stylist-traits
+ test/Test.hs view
@@ -0,0 +1,293 @@+{-# LANGUAGE OverloadedStrings #-}+module Main where++import Test.Hspec++import Graphics.Layout.Arithmetic+import Data.CSS.Syntax.Tokens (tokenize, Token(..))+import Stylist (PropertyParser(..))++import Graphics.Layout.Box as B+import Graphics.Layout.Grid+import Graphics.Layout.Flow+import Graphics.Layout++main :: IO ()+main = hspec spec++spec :: Spec+spec = do+    describe "canary" $ do+        it "test framework works" $ do+            True `shouldBe` True+    describe "calc()" $ do+        it "Can perform basic arithmatic" $ do+            runMath "42" `shouldBe` 42+            runMath "6 * 9" `shouldBe` 54+            runMath "6 * 9 - 42" `shouldBe` 12+            runMath "6 * (9 - 42)" `shouldBe` -198+            runMath "6 * calc(9 - 42)" `shouldBe` -198+            runMath "6 * abs(9 - 42)" `shouldBe` 198+    describe "Flow sizing" $ do+        -- Based on http://hixie.ch/tests/adhoc/css/box/block/+        it "Can overflow parent" $ do+            width (fst $ layoutFlow zeroBox {+                    size = Size 3 1+                } lengthBox {+                    border = Border (Pixels 0) (Pixels 0) (Pixels 2) (Pixels 2)+                } []) `shouldBe` 4+            width (fst $ layoutFlow zeroBox {+                    size = Size 3 1+                } lengthBox {+                    padding = Border (Pixels 0) (Pixels 0) (Pixels 2) (Pixels 2)+                } []) `shouldBe` 4+            width (fst $ layoutFlow zeroBox {+                    size = Size 3 1+                } lengthBox {+                    margin = Border (Pixels 0) (Pixels 0) (Pixels 2) (Pixels 2)+                } []) `shouldBe` 4+        it "Fits to parent" $ do+            width (fst $ layoutFlow zeroBox {+                    size = Size 5 1+                } lengthBox {+                    border = Border (Pixels 0) (Pixels 0) (Pixels 2) (Pixels 2),+                    size = Size Auto $ Pixels 1+                } []) `shouldBe` 5+            width (fst $ layoutFlow zeroBox {+                    size = Size 5 1+                } lengthBox {+                    padding = Border (Pixels 0) (Pixels 0) (Pixels 2) (Pixels 2),+                    size = Size Auto $ Pixels 1+                } []) `shouldBe` 5+            width (fst $ layoutFlow zeroBox {+                    size = Size 5 1+                } lengthBox {+                    margin = Border (Pixels 0) (Pixels 0) (Pixels 2) (Pixels 2),+                    size = Size Auto $ Pixels 1+                } []) `shouldBe` 5+        it "Fits children" $ do+            let child = mapX' (lowerLength 100) $ lengthBox {+                size = Size (Pixels 10) (Pixels 10)+              }+            height (fst $ layoutFlow zeroBox {+                size = Size 100 100+              } lengthBox [child, child]) `shouldBe` 20+        it "Collapses margins" $ do+            let a :: PaddedBox Length Double+                a = PaddedBox {+                    B.min = Size 0 Auto,+                    size = Size 0 Auto,+                    B.nat = Size 0 0,+                    B.max = Size 0 Auto,+                    padding = Border (Pixels 0) (Pixels 0) 0 0,+                    border = Border (Pixels 0) (Pixels 0) 0 0,+                    margin = Border (Pixels 5) (Pixels 10) 0 0+                  }+                b :: PaddedBox Length Double+                b = PaddedBox {+                    B.min = Size 0 Auto,+                    size = Size 0 Auto,+                    B.nat = Size 0 0,+                    B.max = Size 0 Auto,+                    padding = Border (Pixels 0) (Pixels 0) 0 0,+                    border = Border (Pixels 0) (Pixels 0) 0 0,+                    margin = Border (Pixels 10) (Pixels 5) 0 0+                  }+            height (fst $ layoutFlow zeroBox {+                    size = Size 100 100+                } lengthBox [a, a]) `shouldBe` 25+            height (fst $ layoutFlow zeroBox {+                    size = Size 100 100+                } lengthBox [b, b]) `shouldBe` 25+            height (fst $ layoutFlow zeroBox {+                    size = Size 100 100+                } lengthBox [a, b]) `shouldBe` 20+            height (fst $ layoutFlow zeroBox {+                    size = Size 100 100+                } lengthBox [b, a]) `shouldBe` 25+    {-describe "Grid" $ do+        it "computes single-columns widths/heights" $ do+            let (pxGrid, pxCells) = gridLayout zeroBox {+                    size = Size 100 100+                  } (buildGrid [Left $ Pixels 10] [Left $ Pixels 10])+                    [GridItem 0 1 0 1 (Size Start Start) zeroBox] True+            containerSize pxGrid `shouldBe` Size 10 10+            fst (head pxCells) `shouldBe` Size 0 0+            let (pcGrid, pcCells) = gridLayout zeroBox {+                    size = Size 100 100+                  } (buildGrid [Left $ Percent 0.5] [Left $ Percent 0.5])+                    [GridItem 0 1 0 1 (Size Start Start) zeroBox] True+            containerSize pcGrid `shouldBe` Size 50 50+            fst (head pcCells) `shouldBe` Size 0 0+            let (autoGrid, autoCells) = gridLayout zeroBox {+                    size = Size 100 100+                  } (buildGrid [Left Auto] [Left Auto])+                    [GridItem 0 1 0 1 (Size Start Start) zeroBox {+                        B.min = Size 10 10,+                        size = Size 20 20+                    }] True+            containerSize autoGrid `shouldBe` Size 20 20+            fst (head autoCells) `shouldBe` Size 0 0+            let (prefGrid, prefCells) = gridLayout zeroBox {+                    size = Size 100 100+                  } (buildGrid [Left Preferred] [Left Preferred])+                    [GridItem 0 1 0 1 (Size Start Start) zeroBox {+                        B.min = Size 10 10,+                        size = Size 15 15+                    }] True+            containerSize prefGrid `shouldBe` Size 15 15+            fst (head prefCells) `shouldBe` Size 0 0+            let (minGrid, minCells) = gridLayout zeroBox {+                    size = Size 100 100+                  } (buildGrid [Left Min] [Left Min])+                    [GridItem 0 1 0 1 (Size Start Start) zeroBox {+                        B.min = Size 10 10,+                        size = Size 15 15+                    }] True+            containerSize minGrid `shouldBe` Size 10 10+            fst (head minCells) `shouldBe` Size 0 0-}+    describe "Abstract layout" $ do+        it "Can overflow parent" $ do+            width (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 3 1+                } (LayoutFlow () lengthBox {+                    border = Border (Pixels 0) (Pixels 0) (Pixels 2) (Pixels 2)+                } []) False) `shouldBe` 4+            height (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 3 1+                } (LayoutFlow () lengthBox {+                    border = Border (Pixels 2) (Pixels 2) (Pixels 2) (Pixels 2)+                } []) False) `shouldBe` 4+            width (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 3 1+                } (LayoutFlow () lengthBox {+                    padding = Border (Pixels 0) (Pixels 0) (Pixels 2) (Pixels 2)+                } []) False) `shouldBe` 4+            height (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 3 1+                } (LayoutFlow () lengthBox {+                    padding = Border (Pixels 2) (Pixels 2) (Pixels 2) (Pixels 2)+                } []) False) `shouldBe` 4+            width (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 3 1+                } (LayoutFlow () lengthBox {+                    margin = Border (Pixels 0) (Pixels 0) (Pixels 2) (Pixels 2)+                } []) False) `shouldBe` 4+            height (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 3 1+                } (LayoutFlow () lengthBox {+                    margin = Border (Pixels 2) (Pixels 2) (Pixels 2) (Pixels 2)+                } []) False) `shouldBe` 4+        it "Fits to parent" $ do+            width (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 5 1+                } (LayoutFlow () lengthBox {+                    border = Border (Pixels 0) (Pixels 0) (Pixels 2) (Pixels 2),+                    size = Size Auto $ Pixels 1+                } []) False) `shouldBe` 5+            width (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 5 1+                } (LayoutFlow () lengthBox {+                    padding = Border (Pixels 0) (Pixels 0) (Pixels 2) (Pixels 2),+                    size = Size Auto $ Pixels 1+                } []) False) `shouldBe` 5+            width (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 5 1+                } (LayoutFlow () lengthBox {+                    margin = Border (Pixels 0) (Pixels 0) (Pixels 2) (Pixels 2),+                    size = Size Auto $ Pixels 1+                } []) False) `shouldBe` 5+        it "Fits children" $ do+            let child = LayoutFlow () lengthBox {+                size = Size (Pixels 10) (Pixels 10),+                B.max = Size (Pixels 10) (Pixels 10)+              } []+            height (layoutGetBox $ head $ boxLayout zeroBox {+                size = Size 100 100+              } child False) `shouldBe` 10+            height (layoutGetBox $ head $ boxLayout zeroBox {+                size = Size 100 100+              } (LayoutFlow () lengthBox [child, child]) False) `shouldBe` 20+        it "Collapses margins" $ do+            let a :: LayoutItem Length Length ()+                a = LayoutFlow () PaddedBox {+                    B.min = Size Auto Auto,+                    size = Size Auto Auto,+                    B.nat = Size 0 0,+                    B.max = Size Auto Auto,+                    padding = Border (Pixels 0) (Pixels 0) (Pixels 0) (Pixels 0),+                    border = Border (Pixels 0) (Pixels 0) (Pixels 0) (Pixels 0),+                    margin = Border (Pixels 5) (Pixels 10) (Pixels 0) (Pixels 0)+                  } []+                b :: LayoutItem Length Length ()+                b = LayoutFlow () PaddedBox {+                    B.min = Size Auto Auto,+                    size = Size Auto Auto,+                    B.nat = Size 0 0,+                    B.max = Size Auto Auto,+                    padding = Border (Pixels 0) (Pixels 0) (Pixels 0) (Pixels 0),+                    border = Border (Pixels 0) (Pixels 0) (Pixels 0) (Pixels 0),+                    margin = Border (Pixels 10) (Pixels 5) (Pixels 0) (Pixels 0)+                  } []+            height (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 100 100+                } (LayoutFlow () lengthBox [a, a]) False) `shouldBe` 25+            height (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 100 100+                } (LayoutFlow () lengthBox [b, b]) False) `shouldBe` 25+            height (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 100 100+                } (LayoutFlow () lengthBox [a, b]) False) `shouldBe` 20+            height (layoutGetBox $ head $ boxLayout zeroBox {+                    size = Size 100 100+                } (LayoutFlow () lengthBox [b, a]) False) `shouldBe` 25++        {-it "computes single-columns widths/heights" $ do+            let zeroCell = LayoutFlow () lengthBox []+            let nonzeroCell = LayoutFlow () lengthBox {+                B.min = Size (Pixels 10) (Pixels 10),+                size = Size (Pixels 20) (Pixels 20)+              } []++            let LayoutGrid (_, _) pxGrid pxCells = boxLayout zeroBox {+                    size = Size 100 100+                  } (LayoutGrid () (buildGrid [Left $ Pixels 10] [Left $ Pixels 10])+                    [(GridItem 0 1 0 1 (Size Start Start) lengthBox, zeroCell)]) True+            let LayoutFlow (pos, _) _ _ = snd $ head pxCells+            containerSize pxGrid `shouldBe` Size 10 10+            pos `shouldBe` (0, 0)+            let LayoutGrid (_, _) pxGrid pxCells = boxLayout zeroBox {+                    size = Size 100 100+                  } (LayoutGrid () (buildGrid [Left $ Percent 0.5] [Left $ Percent 0.5])+                    [(GridItem 0 1 0 1 (Size Start Start) lengthBox, zeroCell)]) True+            let LayoutFlow (pos, _) _ _ = snd $ head pxCells+            containerSize pxGrid `shouldBe` Size 50 50+            pos `shouldBe` (0, 0)+            let LayoutGrid (_, _) pxGrid pxCells = boxLayout zeroBox {+                    size = Size 100 100+                  } (LayoutGrid () (buildGrid [Left Auto] [Left Auto])+                    [(GridItem 0 1 0 1 (Size Start Start) lengthBox, nonzeroCell)]) True+            let LayoutFlow (pos, _) _ _ = snd $ head pxCells+            containerSize pxGrid `shouldBe` Size 20 10 -- FIXME Is the 10 correct?+            pos `shouldBe` (0, 0)+            let LayoutGrid (_, _) pxGrid pxCells = boxLayout zeroBox {+                    size = Size 100 100+                  } (LayoutGrid () (buildGrid [Left Preferred] [Left Preferred])+                    [(GridItem 0 1 0 1 (Size Start Start) lengthBox, nonzeroCell)]) True+            let LayoutFlow (pos, _) _ _ = snd $ head pxCells+            containerSize pxGrid `shouldBe` Size 20 0 -- FIXME Is the 0 correct?+            pos `shouldBe` (0, 0)+            let LayoutGrid (_, _) pxGrid pxCells = boxLayout zeroBox {+                    size = Size 100 100+                  } (LayoutGrid () (buildGrid [Left Min] [Left Min])+                    [(GridItem 0 1 0 1 (Size Start Start) lengthBox, nonzeroCell)]) True+            let LayoutFlow (pos, _) _ _ = snd $ head pxCells+            containerSize pxGrid `shouldBe` Size 10 10+            pos `shouldBe` (0, 0) -}++runMath = flip evalCalc [] . mapCalc fst . flip parseCalc [] . filter (/= Whitespace) . tokenize++instance PropertyParser () where+    temp = ()+    inherit _ = ()+    longhand _ _ _ _ = Nothing