geomancy-layout-0.2.0: src/Geomancy/Layout/View.hs
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DefaultSignatures #-}
{-| SwiftUI-like view tree
The layout keeps the propose-report-place protocol, but chops some parts away.
* Views are abstracted and the 'View' constructor punches a hole in a tree (a hollow?) for a UI toolkit to fill in later.
* There's no "tree builder", so containers and modifiers are constructed directly. Although it is easy to recover modifier with the "Data.Function.(&)" operator.
* There's no "ideal size", "fixed size" etc. and the views are fully flexible. The UI tookit wrappers can instead self-wrap their Views in a 'Frame'/'FlexibleFrame' as needed.
-}
module Geomancy.Layout.View where
import Data.Bifunctor (Bifunctor(..))
import Data.Foldable (toList)
import Data.Foldable1 (foldMap1')
import Data.Traversable (foldMapDefault)
import Data.Functor.Identity (Identity)
import Data.List (mapAccumL, foldl', sortOn)
import Data.List.NonEmpty (nonEmpty)
import Data.List.NonEmpty qualified as NonEmpty
import Data.Maybe (fromMaybe)
import Geomancy ((^*))
import Geomancy.Gl.Funs (glClamp)
import Geomancy.Layout qualified as Layout
import Geomancy.Layout.Alignment (Alignment(..))
import Geomancy.Layout.Alignment qualified as Alignment
import Geomancy.Layout.Box (Box(..))
import Geomancy.Layout.Box qualified as Box
import Geomancy.Vec2 (Vec2, vec2, withVec2, pattern WithVec2)
import Geomancy.Vec4 (Vec4, vec4, withVec4)
import GHC.Arr (array)
-- | Run all the layout steps to annotate the nodes with their final placement boxes.
layout :: LayoutView stuff => Box -> View () stuff -> View Box (Placed stuff)
layout initialBox = place initialBox . measure
-- | Do all of the layout steps and fold placed views
--
-- Mostly an example. The better way is to cache intermediate steps.
--
-- (Actually a pun on "fold views".)
foldWith :: (LayoutView stuff, Monoid a) => (Placed stuff -> a) -> Box -> View () stuff -> a
foldWith f initialBox = foldMap f . place initialBox . measure
{- | An interface to plug UI toolkits into the layout.
Alternatively, convert them to `ViewFun`, which has the instance.
The "minimal: none" is a lie. Most likely you will need to adjust either 'ReportedCache ' or 'Placed' types and implement the other function accordingly.
The most gnarly code would be for "rendered text" widgets since they would be dynamically sized and have to be processed/cached on each step.
-}
class LayoutView stuff where
-- | Measurement pre-pass
viewFlexibility :: stuff -> ViewSize
-- XXX: argument order is optimized for \case
-- | Propose step: return the actual size and store intermediate data.
proposeView :: Vec2 -> stuff -> (Vec2, ReportedCache stuff)
type ReportedCache stuff
type ReportedCache stuff = stuff
-- | Placement step: get the reported size augmented with a final position, produce the result.
placeView :: Box -> ReportedCache stuff -> Placed stuff
type Placed stuff
type Placed stuff = stuff
-- | Default implementation is "the view *will* adapt to any size"
default viewFlexibility :: stuff -> ViewSize
viewFlexibility = const infinite_
-- | Default implementation for "accept everything" reporting
default proposeView :: (ReportedCache stuff ~ stuff) => Vec2 -> stuff -> (Vec2, ReportedCache stuff)
proposeView = (,)
-- | Default implementation for "box function" placement
default placeView :: (ReportedCache stuff ~ (Box -> Placed stuff)) => Box -> ReportedCache stuff -> Placed stuff
placeView placed f = f placed
{- | Do-nothing pass-through instance
You'll have to peek at the @View{ann}@ of the placement tree.
-}
instance LayoutView (Identity stuff) where
viewFlexibility = const infinite_
proposeView = (,)
placeView _placed = id
{- | A model type for the protocol
The fields correspond to the 3 steps:
* Measurement into ViewSize - static.
* Proposing and reporting - depends on parent size / caches size-related data.
* Placement - depends on placement ('Box' = reported size + position), can use cached data.
-}
data ViewFun stuff = ViewFun ViewSize (Vec2 -> (Vec2, Box -> stuff))
deriving (Functor)
-- | A wrapper to construct 'ViewFun'-based views
viewFun :: ViewSize -> (Vec2 -> (Vec2, Box -> stuff)) -> View () (ViewFun stuff)
viewFun flex steps = View{ann=(), stuff=ViewFun flex steps}
instance LayoutView (ViewFun stuff) where
type ReportedCache (ViewFun stuff) = Box -> stuff -- ^ Propose to resolve the outer
type Placed (ViewFun stuff) = stuff
viewFlexibility (ViewFun vs _) = vs
proposeView size (ViewFun _ f) = f size
placeView placed f = f placed
-- * View tree
{- | Layout skeleton
It is Functor-Foldable-Traversable on 'View' so you can use things like 'Control.Monad.void' to suppress payload and 'show' the intermediate structure.
-}
data View ann stuff
= View
{ ann :: ann
, stuff :: stuff
} -- ^ UI-specific payload
| Spacer
{ ann :: ann
}
-- "containers"
| HStack
{ ann :: ann
-- TODO: placement direction
, spacing :: Float
, align :: Alignment
, children :: [View ann stuff]
} -- ^ Place children side-by-side (LTR)
| VStack
{ ann :: ann
-- TODO: placement direction
, spacing :: Float
, align :: Alignment
, children :: [View ann stuff]
} -- ^ Place children top-to-bottom
| ZStack
{ ann :: ann
, align :: Alignment
, children :: [View ann stuff]
} -- ^ Place children atop of each other
| Grid
{ ann :: ann
, columnSpacing :: Float
, rowSpacing :: Float
, align :: Alignment
, rows :: [[View ann stuff]]
}
| Overlay
{ ann :: ann
, align :: Alignment
, secondary :: View ann stuff
, primary :: View ann stuff
} -- ^ Propose the size of the primary view to the secondary view
| Background
{ ann :: ann
, align :: Alignment
, secondary :: View ann stuff
, primary :: View ann stuff
}
-- "modifiers"
| Frame
{ ann :: ann
, size :: Vec2
, align :: Alignment
, inner :: View ann stuff
} -- ^ Propose/report size unconditionally
| FlexibleFrame
{ ann :: ann
, bounds :: FrameBounds -- ^ Acceptable size ranges
, align :: Alignment
, inner :: View ann stuff
} -- ^ Adjust measurement flex and clamp proposed/reported size
| AspectRatio
{ ann :: ann
, aspect :: Vec2 -- ^ Like 'Ratio Float', for example @vec2 16 9@ or @1@ (= @vec2 1 1@, i.e. square)
, align :: Alignment
-- TODO: fit/crop
, inner :: View ann stuff
} -- ^ Frame-like wrapper that fits
| Padding
{ ann :: ann
, trbl :: Box.TRBL
, inner :: View ann stuff
} -- ^ Subtracts a CSS-tyle padding (top/right/bottom/left) from parent
| Offset
{ ann :: ann
, xy :: Vec2
, inner :: View ann stuff
} -- ^ Adds offset when placing a view
| Span
{ ann :: ann
, columnSpan :: Int
, rowSpan :: Int
, inner :: View ann stuff
}
deriving (Eq, Show, Functor)
instance Foldable (View ann) where
foldMap = foldMapDefault
instance Traversable (View ann) where
traverse f = \case
View{ann, stuff} -> (\stuff' -> View{ann, stuff = stuff'}) <$> f stuff
Spacer{ann} -> pure Spacer{ann}
HStack{..} -> (\children' -> HStack{children = children', ..}) <$> traverse (traverse f) children
VStack{..} -> (\children' -> VStack{children = children', ..}) <$> traverse (traverse f) children
ZStack{..} -> (\children' -> ZStack{children = children', ..}) <$> traverse (traverse f) children
Grid{..} -> (\rows' -> Grid{rows = rows', ..}) <$> traverse (traverse (traverse f)) rows
Background{..} -> (\secondary' primary' -> Background{secondary = secondary', primary = primary', ..}) <$> traverse f secondary <*> traverse f primary
Overlay{..} -> (\primary' secondary' -> Overlay{primary = primary', secondary = secondary', ..}) <$> traverse f primary <*> traverse f secondary
Frame{..} -> (\inner' -> Frame{inner = inner', ..}) <$> traverse f inner
FlexibleFrame{..} -> (\inner' -> FlexibleFrame{inner = inner', ..}) <$> traverse f inner
AspectRatio{..} -> (\inner' -> AspectRatio{inner = inner', ..}) <$> traverse f inner
Padding{..} -> (\inner' -> Padding{inner = inner', ..}) <$> traverse f inner
Offset{..} -> (\inner' -> Offset{inner = inner', ..}) <$> traverse f inner
Span{..} -> (\inner' -> Span{inner = inner', ..}) <$> traverse f inner
instance Bifunctor View where
first f = \case
View{..} -> View{ann = f ann, stuff}
Spacer{..} -> Spacer{ann = f ann}
HStack{..} -> HStack{ann = f ann, children = map (first f) children, ..}
VStack{..} -> VStack{ann = f ann, children = map (first f) children, ..}
ZStack{..} -> ZStack{ann = f ann, children = map (first f) children, ..}
Grid{..} -> Grid{ann = f ann, rows = map (map (first f)) rows, ..}
Overlay{..} -> Overlay{ann = f ann, primary = first f primary, secondary = first f secondary, ..}
Background{..} -> Background{ann = f ann, primary = first f primary, secondary = first f secondary, ..}
Frame{..} -> Frame{ann = f ann, inner = first f inner, ..}
FlexibleFrame{..} -> FlexibleFrame{ann = f ann, inner = first f inner, ..}
Padding{..} -> Padding{ann = f ann, inner = first f inner, ..}
Offset{..} -> Offset{ann = f ann, inner = first f inner, ..}
Span{..} -> Span{ann = f ann, inner = first f inner, ..}
AspectRatio{..} -> AspectRatio{ann = f ann, inner = first f inner, ..}
second = fmap
-- ** Some shortcuts
view_ :: stuff -> View () stuff
view_ stuff = View{ann=(), ..}
spacer_ :: View () stuff
spacer_ = Spacer{ann=()}
-- *** Containers
hstack_ :: [View () stuff] -> View () stuff
hstack_ = hstack 0 Alignment.leftMiddle
vstack_ :: [View () stuff] -> View () stuff
vstack_ = vstack 0 Alignment.centerTop
hstack :: Float -> Alignment -> [View () stuff] -> View () stuff
hstack spacing align children = HStack{ann=(), ..}
vstack :: Float -> Alignment -> [View () stuff] -> View () stuff
vstack spacing align children = VStack{ann=(), ..}
zstack_ :: [View () stuff] -> View () stuff
zstack_ = zstack Alignment.center
zstack :: Alignment -> [View () stuff] -> View () stuff
zstack align children = ZStack{ann=(), ..}
grid_ :: [[View () stuff]] -> View () stuff
grid_ = grid 0 0 Alignment.center
grid :: Float -> Float -> Alignment -> [[View () stuff]] -> View () stuff
grid columnSpacing rowSpacing align rows = Grid{ann=(), ..}
overlay_ :: View () stuff -> View () stuff -> View () stuff
overlay_ = overlay Alignment.center
overlay :: Alignment -> View () stuff -> View () stuff -> View () stuff
overlay align secondary primary = Overlay{ann=(), ..}
background_ :: View () stuff -> View () stuff -> View () stuff
background_ = background Alignment.center
background :: Alignment -> View () stuff -> View () stuff -> View () stuff
background align secondary primary = Background{ann=(), ..}
-- *** Modifiers
frame_ :: Vec2 -> View () stuff -> View () stuff
frame_ size inner = Frame{ann=(), align = Alignment.center, ..}
flexible_ :: FrameBounds -> Alignment -> View () stuff -> View () stuff
flexible_ bounds align inner = FlexibleFrame{ann=(), ..}
aspect_ :: Vec2 -> View () stuff -> View () stuff
aspect_ ratio inner = AspectRatio{ann=(), aspect=ratio, align=Alignment.center, ..}
padding_ :: Vec4 -> View () stuff -> View () stuff
padding_ trbl inner = Padding{ann=(), trbl=Box.TRBL trbl, ..}
offset_ :: Vec2 -> View () stuff -> View () stuff
offset_ xy inner = Offset{ann=(), ..}
span_ :: Int -> Int -> View () stuff -> View () stuff
span_ columnSpan rowSpan inner = Span{ann=(), ..}
-- * Flexibility helper
-- | Represents size constraints and flexibility for a layout node.
data ViewSize = ViewSize
{ minWidth, maxWidth
, minHeight, maxHeight :: Maybe Float
-- XXX: put ideal size here?
, clearance :: !Box.TRBL
} deriving (Eq, Show)
noClearance :: Box.TRBL
noClearance = Box.TRBL 0
withClearance :: ViewSize -> Box.WithTRBL r -> r
withClearance size = withEdges size.clearance
withEdges :: Box.TRBL -> Box.WithTRBL r -> r
withEdges (Box.TRBL trbl) = withVec4 trbl
widerClearance :: Box.TRBL -> Box.TRBL -> Box.TRBL
widerClearance (Box.TRBL a) (Box.TRBL b) =
withVec4 a \at ar ab al ->
withVec4 b \bt br bb bl ->
Box.TRBL $ vec4 (max at bt) (max ar br) (max ab bb) (max al bl)
-- | Creates a ViewSize for a fixed-size view.
fixed_ :: Vec2 -> ViewSize
fixed_ size =
withVec2 size \w h ->
ViewSize
{ minWidth = Just w
, maxWidth = Just w
, minHeight = Just h
, maxHeight = Just h
, clearance = noClearance
}
-- | Creates a ViewSize for a fully flexible view.
infinite_ :: ViewSize
infinite_ = ViewSize
{ minWidth = Just 0
, maxWidth = Just inf
, minHeight = Just 0
, maxHeight = Just inf
, clearance = noClearance
}
range_ :: Vec2 -> Vec2 -> ViewSize
range_ a b =
withVec2 a \aw ah ->
withVec2 b \bw bh ->
ViewSize
{ minWidth = Just $ min aw bw
, maxWidth = Just $ max aw bw
, minHeight = Just $ min ah bh
, maxHeight = Just $ max ah bh
, clearance = noClearance
}
data Axis = Horizontal | Vertical
deriving (Eq, Show)
spacerSize :: Maybe Axis -> ViewSize
spacerSize = \case
Nothing -> infinite_
Just Horizontal -> infinite_{minHeight = Just 0, maxHeight = Just 0}
Just Vertical -> infinite_{minWidth = Just 0, maxWidth = Just 0}
-- | Creates a ViewSize that reports parent size
parent_ :: ViewSize
parent_ = ViewSize
{ minWidth = Nothing
, maxWidth = Nothing
, minHeight = Nothing
, maxHeight = Nothing
, clearance = noClearance
}
parentWidth :: ViewSize -> ViewSize
parentWidth a = a {minWidth = Nothing, maxWidth = Nothing}
parentHeight :: ViewSize -> ViewSize
parentHeight a = a {minHeight = Nothing, maxHeight = Nothing}
data FrameBounds = FrameBounds
{ frameMinWidth, frameMaxWidth
, frameMinHeight, frameMaxHeight :: Maybe Float
, frameClearance :: !Box.TRBL
} deriving (Eq, Show)
unbounded :: FrameBounds
unbounded = FrameBounds
{ frameMinWidth = Nothing
, frameMaxWidth = Nothing
, frameMinHeight = Nothing
, frameMaxHeight = Nothing
, frameClearance = noClearance
}
between :: Vec2 -> Vec2 -> FrameBounds
between a b =
withVec2 a \aw ah ->
withVec2 b \bw bh ->
heightWithin ah bh $ widthWithin aw bw unbounded
widthWithin :: Float -> Float -> FrameBounds -> FrameBounds
widthWithin lo hi bounds = bounds{frameMinWidth = Just (min lo hi), frameMaxWidth = Just (max lo hi)}
heightWithin :: Float -> Float -> FrameBounds -> FrameBounds
heightWithin lo hi bounds = bounds{frameMinHeight = Just (min lo hi), frameMaxHeight = Just (max lo hi)}
fillWidth :: FrameBounds -> FrameBounds
fillWidth bounds = bounds{frameMaxWidth = Just inf}
fillHeight :: FrameBounds -> FrameBounds
fillHeight bounds = bounds{frameMaxHeight = Just inf}
filling :: FrameBounds
filling = fillHeight $ fillWidth unbounded
-- * Layout steps
-- | Measurement pre-pass
measure :: LayoutView stuff => View () stuff -> View ViewSize stuff
measure = measureAlong Nothing
measureAlong :: LayoutView stuff => Maybe Axis -> View () stuff -> View ViewSize stuff
measureAlong stackAxis = \case
View {stuff} -> View{ann=viewFlexibility stuff, stuff}
Spacer{} -> Spacer{ann=spacerSize stackAxis}
Frame{..} -> Frame{ann=(fixed_ size){clearance = inner'.ann.clearance}, inner=inner', ..}
where
inner' = measureAlong stackAxis inner
FlexibleFrame{..} -> FlexibleFrame{ann=bounded, inner=inner', ..}
where
inner' = measureAlong stackAxis inner
innerFlex = inner'.ann
bounded = ViewSize
{ minWidth = frameLeast ordered.frameMinWidth ordered.frameMaxWidth innerFlex.minWidth
, maxWidth = frameMost ordered.frameMinWidth ordered.frameMaxWidth innerFlex.maxWidth
, minHeight = frameLeast ordered.frameMinHeight ordered.frameMaxHeight innerFlex.minHeight
, maxHeight = frameMost ordered.frameMinHeight ordered.frameMaxHeight innerFlex.maxHeight
, clearance = widerClearance bounds.frameClearance innerFlex.clearance
}
ordered = orderedBounds bounds
Padding{..} -> Padding{ann=expanded, inner=inner', ..}
where
inner' = measureAlong stackAxis inner
innerFlex = inner'.ann
expanded = withVec4 trbl4 \t r b l -> innerFlex
{ minWidth = (+ (l + r)) <$> innerFlex.minWidth
, maxWidth = (+ (l + r)) <$> innerFlex.maxWidth
, minHeight = (+ (t + b)) <$> innerFlex.minHeight
, maxHeight = (+ (t + b)) <$> innerFlex.maxHeight
, clearance = withClearance innerFlex \ct cr cb cl ->
Box.TRBL $ vec4 (unpadded t ct) (unpadded r cr) (unpadded b cb) (unpadded l cl)
}
unpadded pad clear
| clear > 0 = max 0 (clear - pad)
| otherwise = 0
Box.TRBL trbl4 = trbl
Offset{..} -> Offset{ann=inner'.ann, inner=inner', ..}
where
inner' = measureAlong stackAxis inner
Span{..} -> Span{ann=inner'.ann, inner=inner', ..}
where
inner' = measureAlong stackAxis inner
AspectRatio{..} -> AspectRatio{ann=ann', inner=inner', ..}
where
ann' = maybe inner'.ann (`aspectRange` inner'.ann) (usableAspect aspect)
inner' = measureAlong stackAxis inner
HStack{spacing, align, children} -> HStack{ann=gaps stackViewSize, children=measured, spacing, align}
where
measured = map (measureAlong $ Just Horizontal) children
sizes = map ann measured
stackViewSize = foldl' stackViewSize' (fixed_ 0) sizes
stackViewSize' a b = a
{ minWidth = (+) <$> a.minWidth <*> b.minWidth -- combined horizontal flex
, maxWidth = (+) <$> a.maxWidth <*> b.maxWidth
, minHeight = max <$> a.minHeight <*> b.minHeight -- union of vertical flex
, maxHeight = max <$> a.maxHeight <*> b.maxHeight
}
totalGaps = sum $ rowGaps spacing sizes
gaps vs = vs
{ minWidth = max 0 . (+ totalGaps) <$> vs.minWidth
, maxWidth = max 0 . (+ totalGaps) <$> vs.maxWidth
, clearance = rowClearance sizes
}
VStack{spacing, align, children} -> VStack{ann=gaps stackViewSize, children=measured, spacing, align}
where
measured = map (measureAlong $ Just Vertical) children
sizes = map ann measured
stackViewSize = foldl' stackViewSize' (fixed_ 0) sizes
stackViewSize' a b = a
{ minWidth = max <$> a.minWidth <*> b.minWidth -- union of horizontal flex
, maxWidth = max <$> a.maxWidth <*> b.maxWidth
, minHeight = (+) <$> a.minHeight <*> b.minHeight -- combined vertical flex
, maxHeight = (+) <$> a.maxHeight <*> b.maxHeight
}
totalGaps = sum $ columnGaps spacing sizes
gaps vs = vs
{ minHeight = max 0 . (+ totalGaps) <$> vs.minHeight
, maxHeight = max 0 . (+ totalGaps) <$> vs.maxHeight
, clearance = columnClearance sizes
}
ZStack{align, children} -> ZStack{ann=stackViewSize, align, children=measured}
where
measured = map (measureAlong Nothing) children
stackViewSize = foldl' (\vs -> stackViewSize' vs . ann) (fixed_ 0) measured
stackViewSize' a b = ViewSize
{ minWidth = max <$> a.minWidth <*> b.minWidth -- union of horizontal flex
, maxWidth = max <$> a.maxWidth <*> b.maxWidth
, minHeight = max <$> a.minHeight <*> b.minHeight -- union of vertical flex
, maxHeight = max <$> a.maxHeight <*> b.maxHeight
, clearance = widerClearance a.clearance b.clearance
}
Grid{columnSpacing, rowSpacing, align, rows} -> Grid{ann=gridSize, columnSpacing, rowSpacing, align, rows=measured}
where
measured = map (map (measureAlong Nothing)) rows
spotted = zip (concat $ gridSpots measured) (concatMap (map ann) measured)
columnCount = gridColumnCount (map fst spotted)
rowCount = length rows
columnGapsAt = spanGaps columnSpacing columnCount [(alongColumns spot, (leftEdge size.clearance, rightEdge size.clearance)) | (spot, size) <- spotted]
rowGapsAt = spanGaps rowSpacing rowCount [(alongRows spot, (topEdge size.clearance, bottomEdge size.clearance)) | (spot, size) <- spotted]
widths = axisRanges columnCount columnGapsAt [(alongColumns spot, widthRange size) | (spot, size) <- spotted]
heights = axisRanges rowCount rowGapsAt [(alongRows spot, heightRange size) | (spot, size) <- spotted]
gridSize = ViewSize
{ minWidth = Just $ max 0 (sum (map fst widths) + sum columnGapsAt)
, maxWidth = Just $ max 0 (sum (map snd widths) + sum columnGapsAt)
, minHeight = Just $ max 0 (sum (map fst heights) + sum rowGapsAt)
, maxHeight = Just $ max 0 (sum (map snd heights) + sum rowGapsAt)
, clearance = spanClearance rowCount columnCount [(spot, size.clearance) | (spot, size) <- spotted]
}
Overlay{align, primary, secondary} -> Overlay{ann=primary'.ann, align, primary=primary', secondary=secondary'}
where
primary' = measureAlong stackAxis primary -- pass-through wrt primary measurements
secondary' = measureAlong Nothing secondary -- ignore secondary flex
Background{align, primary, secondary} -> Background{ann=primary'.ann, align, primary=primary', secondary=secondary'}
where
primary' = measureAlong stackAxis primary
secondary' = measureAlong Nothing secondary
-- | Run the propose-report-place protocol on a flex-measured view tree
place :: LayoutView stuff => Box -> View ViewSize stuff -> View Box (Placed stuff)
place parent element = snd (suspend parent.size element) parent
-- | Propose-Report-Place protocol using continuations
--
-- Inner children can't be placed until the whole propose-report dance finishes.
suspend
:: forall stuff
. LayoutView stuff
=> Vec2
-> View ViewSize stuff
-> (Vec2, Box -> View Box (Placed stuff))
suspend proposed = \case
Spacer{ann} ->
( vsClamp proposed ann proposed
, \placed -> Spacer{ann=placed} -- keep the placed
)
View{stuff} ->
( reported -- report dynamic size
, \placed ->
View
{ ann = placed
, stuff = placeView @stuff placed cache -- instantiate the placed view
}
)
where
(reported, cache) = proposeView proposed stuff
Frame{..} ->
( size -- frame reports its size right away
, \placedFrame ->
Frame
{ ann = placedFrame -- keep the placed for itself
, inner =
let
-- now that the frame has its own box, it can properly place its contents
innerBox = Layout.placeSize align reported placedFrame
in
-- and resolve the continuation
suspended innerBox
, ..
}
)
where
(reported, suspended) = suspend size inner -- frame proposes its size
FlexibleFrame{..} ->
( framedSize bounds proposed reported
, \placed ->
let
innerBox = Layout.placeSize align reported placed
in
FlexibleFrame
{ ann = placed
, inner = suspended innerBox
, ..
}
)
where
(reported, suspended) = suspend (offeredSize bounds proposed) inner
Padding{..} ->
( reported + pads
, \placed ->
let
innerBox = Box.addPadding trbl placed
in
Padding
{ ann = placed
, inner = suspended innerBox
, ..
}
)
where
(reported, suspended) = suspend (proposed - pads) inner
pads = withVec4 trbl4 \t r b l -> vec2 (l + r) (t + b)
Box.TRBL trbl4 = trbl
Offset{..} ->
( reported
, \placed -> Offset
{ ann = placed
, inner = suspended $ Box.move xy placed
, ..
}
)
where
(reported, suspended) = suspend proposed inner
Span{..} ->
( reported
, \placed -> Span{ann = placed, inner = suspended placed, ..}
)
where
(reported, suspended) = suspend proposed inner
AspectRatio{..} ->
( maybe reported (`coverAspect` reported) ratio
, \placed ->
let
innerBox = Layout.placeSize align reported placed
in
AspectRatio
{ ann = placed
, inner = suspended innerBox
, ..
}
)
where
ratio = usableAspect aspect
(reported, suspended) = suspend (maybe proposed (\r -> fitAspect r $ growableRoom inner.ann proposed) ratio) inner
HStack{spacing, align, children} ->
-- Like the Frame, but operating on multiple elements
( vec2 runWidth crossHeight -- stack reports the combined size of its children reports
, \placedStack ->
let
placedChildren :: [View Box (Placed stuff)]
placedChildren =
Box.withTRBL (justify placedStack) \t _r b l ->
[ suspended $ Layout.placeSize align reportedSize (Box.fromTRBL t (l + start + w) b (l + start))
| ((reportedSize, suspended), start) <- zip children' starts
, let w = withVec2 reportedSize \w' _h -> w'
]
justify box =
withVec2 alignOrigins \origin _ ->
shiftRun Layout.cutLeft origin (Box.width box - runWidth) box
in
HStack
{ ann = maybe placedStack (foldMap1' ann) $ nonEmpty placedChildren
, children = placedChildren
, spacing
, align
}
)
where
Alignment alignOrigins = align
slotGaps = rowGaps spacing $ map ann children
gaps = sum slotGaps
(starts, runWidth) = runOffsets slotGaps [withVec2 reportedSize \w _h -> w | (reportedSize, _) <- children']
crossHeight = foldl' max 0 [withVec2 reportedSize \_w h -> h | (reportedSize, _) <- children']
-- | Record index, sort by flexibility, process, restore order
children' =
toList . array (0, numChildren - 1) $
snd $ mapAccumL f (fromIntegral numChildren, budget) $ zip (reservedAfter minWidthOf sorted) sorted
sorted = sortOn (widthFlexibility . ann . snd) $ zip [0 :: Int ..] children
minWidthOf = fromMaybe 0 . (.minWidth) . ann
numChildren = length children
budget = withVec2 proposed \w h -> vec2 (max 0 $ w - gaps) h
f (childrenRemaining, WithVec2 remW remH) (reserved, (ix, child)) =
( (childrenRemaining - 1.0, vec2 (max 0 $ remW - reportedWidth) remH)
, ( ix
, child'
) -- XXX: can use combineH here
)
where
WithVec2 reportedWidth _ = fst child'
child' = suspend (vec2 proposeWidth remH) child
proposeWidth = fairShare (minWidthOf child) reserved remW childrenRemaining
VStack{spacing, align, children} ->
-- Like the HStack, but advancing vertically
( vec2 crossWidth runHeight
, \placedStack ->
let
placedChildren :: [View Box (Placed stuff)]
placedChildren =
Box.withTRBL (justify placedStack) \t r _b l ->
[ suspended $ Layout.placeSize align reportedSize (Box.fromTRBL (t + start) r (t + start + h) l)
| ((reportedSize, suspended), start) <- zip children' starts
, let h = withVec2 reportedSize \_w h' -> h'
]
justify box =
withVec2 alignOrigins \_ origin ->
shiftRun Layout.cutTop origin (Box.height box - runHeight) box
in
VStack
{ ann = maybe placedStack (foldMap1' ann) $ nonEmpty placedChildren
, children = placedChildren
, spacing
, align
}
)
where
Alignment alignOrigins = align
slotGaps = columnGaps spacing $ map ann children
gaps = sum slotGaps
(starts, runHeight) = runOffsets slotGaps [withVec2 reportedSize \_w h -> h | (reportedSize, _) <- children']
crossWidth = foldl' max 0 [withVec2 reportedSize \w _h -> w | (reportedSize, _) <- children']
-- | Record index, sort by flexibility, process, restore order
children' =
toList . array (0, numChildren - 1) $
snd $ mapAccumL f (fromIntegral numChildren, budget) $ zip (reservedAfter minHeightOf sorted) sorted
sorted = sortOn (heightFlexibility . ann . snd) $ zip [0 :: Int ..] children
minHeightOf = fromMaybe 0 . (.minHeight) . ann
numChildren = length children
budget = withVec2 proposed \w h -> vec2 w (max 0 $ h - gaps)
f (childrenRemaining, WithVec2 remW remH) (reserved, (ix, child)) =
( (childrenRemaining - 1.0, vec2 remW (max 0 $ remH - reportedHeight))
, ( ix
, child'
) -- XXX: can use combineH here
)
where
WithVec2 _ reportedHeight = fst child'
child' = suspend (vec2 remW proposeHeight) child
proposeHeight = fairShare (minHeightOf child) reserved remH childrenRemaining
ZStack{align, children} ->
( foldl' max2 0 reporteds
, \placedStack ->
let
placedChildren =
[ suspended $ Layout.placeSize align reported placedStack
| (reported, suspended) <- zip reporteds suspendeds
]
in
ZStack
{ ann = maybe placedStack (foldMap1' ann) $ nonEmpty placedChildren
, align
, children = placedChildren
}
)
where
(reporteds, suspendeds) = unzip $ map (suspend proposed) children
Grid{columnSpacing, rowSpacing, align, rows} ->
( vec2 runWidth runHeight
, \placedGrid ->
let
justified =
withVec2 alignOrigins \originX originY ->
shiftRun Layout.cutTop originY (Box.height placedGrid - runHeight) $
shiftRun Layout.cutLeft originX (Box.width placedGrid - runWidth) placedGrid
placedRows =
Box.withTRBL justified \t _r _b l ->
[ [ placeCell $ Layout.placeSize align reported (slot t l spot)
| (spot, (reported, placeCell)) <- zip spotsInRow offeredInRow
]
| (spotsInRow, offeredInRow) <- zip spots offered
]
slot t l spot =
Box.fromTRBL top (left + spanWidth spot) (top + spanHeight spot) left
where
top = t + rowStarts !! spot.spotRow
left = l + columnStarts !! spot.spotColumn
in
Grid
{ ann = maybe placedGrid (foldMap1' ann) $ nonEmpty (concat placedRows)
, columnSpacing
, rowSpacing
, align
, rows = placedRows
}
)
where
Alignment alignOrigins = align
WithVec2 offeredWidth offeredHeight = proposed
spots = gridSpots rows
spotted = zip (concat spots) (concat rows)
columnCount = gridColumnCount (map fst spotted)
rowCount = length rows
columnGapsAt = spanGaps columnSpacing columnCount [(alongColumns spot, (leftEdge cell.ann.clearance, rightEdge cell.ann.clearance)) | (spot, cell) <- spotted]
rowGapsAt = spanGaps rowSpacing rowCount [(alongRows spot, (topEdge cell.ann.clearance, bottomEdge cell.ann.clearance)) | (spot, cell) <- spotted]
columnWidths =
settleAxis offeredWidth columnGapsAt
(axisRanges columnCount columnGapsAt [(alongColumns spot, widthRange cell.ann) | (spot, cell) <- spotted])
[ (alongColumns spot, widthRange cell.ann, \offer -> withVec2 (fst $ suspend (vec2 offer offeredHeight) cell) \w _h -> w)
| (spot, cell) <- spotted
]
spanWidth spot = spanLength columnWidths columnGapsAt (alongColumns spot)
rowHeights =
settleAxis offeredHeight rowGapsAt
(axisRanges rowCount rowGapsAt [(alongRows spot, heightRange cell.ann) | (spot, cell) <- spotted])
[ (alongRows spot, heightRange cell.ann, \offer -> withVec2 (fst $ suspend (vec2 (spanWidth spot) offer) cell) \_w h -> h)
| (spot, cell) <- spotted
]
spanHeight spot = spanLength rowHeights rowGapsAt (alongRows spot)
offered =
[ [suspend (vec2 (spanWidth spot) (spanHeight spot)) cell | (spot, cell) <- zip spotsInRow row]
| (spotsInRow, row) <- zip spots rows
]
(columnStarts, runWidth) = runOffsets columnGapsAt columnWidths
(rowStarts, runHeight) = runOffsets rowGapsAt rowHeights
Overlay{align, primary, secondary} ->
decorated proposed align primary secondary \placed primary' secondary' ->
Overlay{ann = placed, align, primary = primary', secondary = secondary'}
Background{align, primary, secondary} ->
decorated proposed align primary secondary \placed primary' secondary' ->
Background{ann = placed, align, primary = primary', secondary = secondary'}
decorated
:: LayoutView stuff
=> Vec2
-> Alignment
-> View ViewSize stuff
-> View ViewSize stuff
-> (Box -> View Box (Placed stuff) -> View Box (Placed stuff) -> View Box (Placed stuff))
-> (Vec2, Box -> View Box (Placed stuff))
decorated proposed align primary secondary rebuild =
( reportedPrimary
, \placed ->
let
placedPrimary = placePrimary placed
in
rebuild placed placedPrimary $ placeSecondary (Layout.placeSize align reportedSecondary placedPrimary.ann)
)
where
(reportedPrimary, placePrimary) = suspend proposed primary
(reportedSecondary, placeSecondary) = suspend reportedPrimary secondary
-- * Internals
inf :: Float
inf = 1 / 0
rowGaps :: Float -> [ViewSize] -> [Float]
rowGaps spacing sizes =
zipWith gap sizes (drop 1 sizes)
where
gap before after =
withClearance before \_t right _b _l ->
withClearance after \_t' _r' _b' left ->
widestGap spacing [right, left]
columnGaps :: Float -> [ViewSize] -> [Float]
columnGaps spacing sizes =
zipWith gap sizes (drop 1 sizes)
where
gap before after =
withClearance before \_t _r bottom _l ->
withClearance after \top _r' _b' _l' ->
widestGap spacing [bottom, top]
usableAspect :: Vec2 -> Maybe Vec2
usableAspect aspect =
withVec2 aspect \aw ah ->
let
quotient = aw / ah
in
if quotient > 0 && not (isInfinite quotient) then
Just $ vec2 (abs aw) (abs ah)
else
Nothing
fitAspect :: Vec2 -> Vec2 -> Vec2
fitAspect aspect room =
withVec2 aspect \aw ah ->
withVec2 room \rw rh ->
aspect ^* min (rw / aw) (rh / ah)
coverAspect :: Vec2 -> Vec2 -> Vec2
coverAspect aspect content =
withVec2 aspect \aw ah ->
withVec2 content \cw ch ->
aspect ^* max (cw / aw) (ch / ah)
growableRoom :: ViewSize -> Vec2 -> Vec2
growableRoom ViewSize{..} proposed =
withVec2 proposed \pw ph ->
vec2 (capGrowth minWidth maxWidth pw) (capGrowth minHeight maxHeight ph)
where
capGrowth (Just lo) (Just hi) p | lo < hi = min p hi
capGrowth _ _ p = p
aspectRange :: Vec2 -> ViewSize -> ViewSize
aspectRange aspect content@ViewSize{..} =
withVec2 (coverAspect aspect $ vec2 (fromMaybe 0 minWidth) (fromMaybe 0 minHeight)) \loW loH ->
withVec2 (coverAspect aspect largest) \hiW hiH ->
content
{ minWidth = Just loW
, maxWidth = Just hiW
, minHeight = Just loH
, maxHeight = Just hiH
}
where
room = fitAspect aspect $ growableRoom content (vec2 inf inf)
largest =
withVec2 room \rw rh ->
vec2 (answer minWidth maxWidth rw) (answer minHeight maxHeight rh)
answer lo hi r =
case (lo, hi) of
(Just l, Just h) | l < h -> min r h
(Just l, Just _) -> l
_ -> r
widestGap :: Float -> [Float] -> Float
widestGap spacing clearances = foldl' max spacing (filter (> 0) clearances)
rowClearance :: [ViewSize] -> Box.TRBL
rowClearance sizes =
case nonEmpty sizes of
Nothing ->
noClearance
Just ends ->
withClearance (NonEmpty.head ends) \_t _r _b left ->
withClearance (NonEmpty.last ends) \_t' right _b' _l' ->
withEdges (crossClearance sizes) \top _r'' bottom _l'' ->
Box.TRBL $ vec4 top right bottom left
columnClearance :: [ViewSize] -> Box.TRBL
columnClearance sizes =
case nonEmpty sizes of
Nothing ->
noClearance
Just ends ->
withClearance (NonEmpty.head ends) \top _r _b _l ->
withClearance (NonEmpty.last ends) \_t' _r' bottom _l' ->
withEdges (crossClearance sizes) \_t'' right _b'' left ->
Box.TRBL $ vec4 top right bottom left
crossClearance :: [ViewSize] -> Box.TRBL
crossClearance = foldl' widerClearance noClearance . map (.clearance)
widthRange :: ViewSize -> (Maybe Float, Maybe Float)
widthRange size = (size.minWidth, size.maxWidth)
heightRange :: ViewSize -> (Maybe Float, Maybe Float)
heightRange size = (size.minHeight, size.maxHeight)
sizedRange :: (Maybe Float, Maybe Float) -> Bool
sizedRange = \case
(_, Just most) -> not (isInfinite most)
_ -> False
trackRange :: [(Maybe Float, Maybe Float)] -> (Float, Float)
trackRange cells =
( least
, case [most | (_, Just most) <- cells, not (isInfinite most)] of
[] -> inf
sized -> max least (maximum sized)
)
where
least = foldl' max 0 [fromMaybe 0 lo | (lo, _) <- cells]
trackAnswer :: [((Maybe Float, Maybe Float), Float)] -> Float
trackAnswer cells =
foldl' max 0 $ map known counted
where
counted =
case filter (sizedRange . fst) cells of
[] -> cells
sized -> sized
known (range, probed) =
case range of
(Just lo, Just hi) | lo == hi -> lo
_ -> probed
settleTracks :: Float -> (track -> (Float, Float)) -> (track -> Float -> Float) -> [track] -> [Float]
settleTracks budget rangeOf answer tracks =
toList . array (0, length tracks - 1) . snd $
mapAccumL settle (fromIntegral $ length tracks, budget) (zip (reservedAfter (fst . rangeOf) sorted) sorted)
where
sorted = sortOn (flexibility . rangeOf . snd) $ zip [0 :: Int ..] tracks
flexibility (lo, hi) = hi - lo
settle (remaining, room) (reserved, (ix, track)) =
((remaining - 1, max 0 $ room - size), (ix, size))
where
least = fst (rangeOf track)
size = max least $ answer track (fairShare least reserved room remaining)
data Spot = Spot
{ spotRow, spotColumn, spotRows, spotColumns :: Int
}
deriving (Eq, Show)
alongColumns :: Spot -> (Int, Int)
alongColumns spot = (spot.spotColumn, spot.spotColumns)
alongRows :: Spot -> (Int, Int)
alongRows spot = (spot.spotRow, spot.spotRows)
cellSpan :: View ann stuff -> (Int, Int)
cellSpan = \case
Span{columnSpan, rowSpan} -> (max 1 columnSpan, max 1 rowSpan)
Frame{inner} -> cellSpan inner
FlexibleFrame{inner} -> cellSpan inner
AspectRatio{inner} -> cellSpan inner
Padding{inner} -> cellSpan inner
Offset{inner} -> cellSpan inner
Overlay{primary} -> cellSpan primary
Background{primary} -> cellSpan primary
_ -> (1, 1)
gridSpots :: [[View ann stuff]] -> [[Spot]]
gridSpots rows =
snd . mapAccumL placeRow [] $ zip [0 ..] (map (map cellSpan) rows)
where
rowCount = length rows
placeRow taken (row, spans) =
let
((taken', _), spots) = mapAccumL (placeCell row) (taken, 0) spans
in
(taken', spots)
placeCell row (taken, cursor) (columnsWanted, rowsWanted) =
((taken <> covered, column + columns), Spot{spotRow = row, spotColumn = column, spotRows = rows', spotColumns = columns})
where
free r c = (r, c) `notElem` taken
column = until (free row) (+ 1) cursor
columns = length $ takeWhile (free row) [column .. column + columnsWanted - 1]
rows' = length $ takeWhile (\r -> all (free r) [column .. column + columns - 1]) [row .. min (rowCount - 1) (row + rowsWanted - 1)]
covered = [(r, c) | r <- [row .. row + rows' - 1], c <- [column .. column + columns - 1]]
gridColumnCount :: [Spot] -> Int
gridColumnCount spots = foldl' max 0 [spot.spotColumn + spot.spotColumns | spot <- spots]
innerGaps :: [Float] -> Int -> Int -> Float
innerGaps gaps lead count = sum . take (count - 1) $ drop lead gaps
spanLength :: [Float] -> [Float] -> (Int, Int) -> Float
spanLength lengths gaps (lead, count) = sum (take count $ drop lead lengths) + innerGaps gaps lead count
spanGaps :: Float -> Int -> [((Int, Int), (Float, Float))] -> [Float]
spanGaps spacing count cells =
[ widestGap spacing $
[trailing | ((lead, n), (_leading, trailing)) <- cells, lead + n - 1 == boundary]
<> [leading | ((lead, _n), (leading, _trailing)) <- cells, lead == boundary + 1]
| boundary <- [0 .. count - 2]
]
spanClearance :: Int -> Int -> [(Spot, Box.TRBL)] -> Box.TRBL
spanClearance rowCount columnCount cells =
Box.TRBL $
vec4
(outer topEdge [edges | (spot, edges) <- cells, spot.spotRow == 0])
(outer rightEdge [edges | (spot, edges) <- cells, spot.spotColumn + spot.spotColumns == columnCount])
(outer bottomEdge [edges | (spot, edges) <- cells, spot.spotRow + spot.spotRows == rowCount])
(outer leftEdge [edges | (spot, edges) <- cells, spot.spotColumn == 0])
where
outer edge = foldl' max 0 . map edge
fillUp :: Float -> [(Int, Float)] -> [(Int, Float)]
fillUp excess capacities
| excess <= 0 || null open = []
| null saturated = [(track, share) | (track, _) <- open]
| otherwise = saturated <> fillUp (excess - sum (map snd saturated)) [(track, capacity) | (track, capacity) <- open, capacity >= share]
where
open = filter ((> 0) . snd) capacities
share = excess / fromIntegral (length open)
saturated = [(track, capacity) | (track, capacity) <- open, capacity < share]
amountFor :: Int -> [(Int, Float)] -> Float
amountFor track given = sum [amount | (track', amount) <- given, track' == track]
axisRanges :: Int -> [Float] -> [((Int, Int), (Maybe Float, Maybe Float))] -> [(Float, Float)]
axisRanges count gaps cells =
foldl' fitSpan singles spanning
where
singles =
[ case [range | ((lead, 1), range) <- cells, lead == track] of
[] -> (0, 0)
ranges -> trackRange ranges
| track <- [0 .. count - 1]
]
spanning = sortOn (snd . fst) [cell | cell@((_first, n), _range) <- cells, n > 1]
fitSpan ranges ((lead, n), range@(lo, hi)) =
raiseMost $ raiseLeast ranges
where
spanned = [lead .. lead + n - 1]
inner = innerGaps gaps lead n
raiseLeast current =
[ if track `elem` spanned then let least' = least + amountFor track given + evenly in (least', max most least') else (least, most)
| (track, (least, most)) <- zip [0 ..] current
]
where
excess = fromMaybe 0 lo - (sum [fst (current !! track) | track <- spanned] + inner)
given = fillUp excess [(track, snd (current !! track) - fst (current !! track)) | track <- spanned]
remaining = max 0 excess - sum (map snd given)
evenly = if remaining > 0 then remaining / fromIntegral n else 0
raiseMost current
| sizedRange range && all (\track -> not . isInfinite . snd $ current !! track) spanned =
let
excess = fromMaybe 0 hi - (sum [snd (current !! track) | track <- spanned] + inner)
in
if excess > 0 then
[ if track `elem` spanned then (least, most + excess / fromIntegral n) else (least, most)
| (track, (least, most)) <- zip [0 ..] current
]
else
current
| otherwise = current
settleAxis :: Float -> [Float] -> [(Float, Float)] -> [((Int, Int), (Maybe Float, Maybe Float), Float -> Float)] -> [Float]
settleAxis offered gaps ranges cells =
[ maybe (grown !! track) id (lookup track $ zip openTracks openLengths)
| track <- [0 .. length ranges - 1]
]
where
budget = max 0 (offered - sum gaps)
indexed = zip [0 :: Int ..] ranges
cappedTracks = [track | (track, (_least, most)) <- indexed, not (isInfinite most)]
openTracks = [track | (track, (_least, most)) <- indexed, isInfinite most]
singlesIn track = [(range, probe) | ((lead, 1), range, probe) <- cells, lead == track]
answer track share = trackAnswer [(range, probe share) | (range, probe) <- singlesIn track]
cappedLengths =
settleTracks (max 0 $ budget - sum [fst (ranges !! track) | track <- openTracks]) (ranges !!) answer cappedTracks
start =
[ maybe least id (lookup track $ zip cappedTracks cappedLengths)
| (track, (least, _most)) <- indexed
]
spanning = sortOn (\((_first, n), _range, _probe) -> n) [cell | cell@((_first, n), _range, _probe) <- cells, n > 1]
grown = foldl' fitSpan start spanning
fitSpan lengths ((lead, n), range, probe)
| not (sizedRange range) = lengths
| otherwise = [length' + amountFor track given | (track, length') <- zip [0 ..] lengths]
where
spanned = [lead .. lead + n - 1]
current = sum [lengths !! track | track <- spanned] + innerGaps gaps lead n
room = max 0 (budget - sum lengths)
wanted =
case range of
(Just lo, Just hi) | lo == hi -> lo
_ -> probe (current + room)
given = fillUp (wanted - current) [(track, snd (ranges !! track) - lengths !! track) | track <- spanned]
openLengths =
settleTracks (max 0 $ budget - sum [grown !! track | track <- cappedTracks]) (\track -> (grown !! track, inf)) answer openTracks
topEdge, rightEdge, bottomEdge, leftEdge :: Box.TRBL -> Float
topEdge edges = withEdges edges \t _r _b _l -> t
rightEdge edges = withEdges edges \_t r _b _l -> r
bottomEdge edges = withEdges edges \_t _r b _l -> b
leftEdge edges = withEdges edges \_t _r _b l -> l
reservedAfter :: (child -> Float) -> [(ix, child)] -> [Float]
reservedAfter minimumOf = drop 1 . scanr ((+) . minimumOf . snd) 0
fairShare :: Float -> Float -> Float -> Float -> Float
fairShare ownMinimum reserved remaining childrenRemaining =
max ownMinimum $ min (remaining / childrenRemaining) (max 0 $ remaining - reserved)
runOffsets :: [Float] -> [Float] -> ([Float], Float)
runOffsets gaps lengths =
case nonEmpty lengths of
Nothing ->
([], 0)
Just _ ->
(starts, max 0 $ last starts + last lengths)
where
starts = scanl (+) 0 $ zipWith (+) lengths gaps
shiftRun :: (Float -> Box -> (Box, Box)) -> Alignment.Origin -> Float -> Box -> Box
shiftRun cut origin slack box =
if origin == 0 || slack == 0 then
box
else
snd $ cut (slack * origin) box
widthFlexibility :: ViewSize -> Float
widthFlexibility ViewSize{..} = maybeBoth inf (-) maxWidth minWidth
heightFlexibility :: ViewSize -> Float
heightFlexibility ViewSize{..} = maybeBoth inf (-) maxHeight minHeight
frameLeast :: Maybe Float -> Maybe Float -> Maybe Float -> Maybe Float
frameLeast lower upper innerLeast =
case (lower, upper) of
(Nothing, Nothing) -> innerLeast
(Just lo, _) -> Just lo
(Nothing, Just hi) -> Just $ min hi (fromMaybe 0 innerLeast)
frameMost :: Maybe Float -> Maybe Float -> Maybe Float -> Maybe Float
frameMost lower upper innerMost =
case (lower, upper) of
(Nothing, Nothing) -> innerMost
(_, Just hi) -> Just hi
(Just lo, Nothing) -> Just $ max lo (fromMaybe inf innerMost)
orderedBounds :: FrameBounds -> FrameBounds
orderedBounds bounds =
bounds
{ frameMinWidth = lowest bounds.frameMinWidth bounds.frameMaxWidth
, frameMaxWidth = highest bounds.frameMinWidth bounds.frameMaxWidth
, frameMinHeight = lowest bounds.frameMinHeight bounds.frameMaxHeight
, frameMaxHeight = highest bounds.frameMinHeight bounds.frameMaxHeight
}
where
lowest (Just lo) (Just hi) = Just (min lo hi)
lowest lo _ = lo
highest (Just lo) (Just hi) = Just (max lo hi)
highest _ hi = hi
offeredSize :: FrameBounds -> Vec2 -> Vec2
offeredSize bounds proposed =
withVec2 proposed \w h ->
vec2 (offered frameMinWidth frameMaxWidth w) (offered frameMinHeight frameMaxHeight h)
where
FrameBounds{..} = orderedBounds bounds
offered lower upper = maybe id min upper . maybe id max lower
framedSize :: FrameBounds -> Vec2 -> Vec2 -> Vec2
framedSize bounds proposed reported =
withVec2 proposed \pw ph ->
withVec2 reported \rw rh ->
vec2 (framed frameMinWidth frameMaxWidth pw rw) (framed frameMinHeight frameMaxHeight ph rh)
where
FrameBounds{..} = orderedBounds bounds
framed lower upper offer content =
maybe id (\hi size -> min hi (max size offer)) upper $
maybe content (\lo -> max lo (min content offer)) lower
vsClamp :: Vec2 -> ViewSize -> Vec2 -> Vec2
vsClamp parent ViewSize{..} v =
withVec2 parent \pw ph ->
withVec2 v \w h ->
vec2
(maybeBoth pw (glClamp w) minWidth maxWidth)
(maybeBoth ph (glClamp h) minHeight maxHeight)
{-# INLINE maybeBoth #-}
maybeBoth :: t1 -> (t2 -> t3 -> t1) -> Maybe t2 -> Maybe t3 -> t1
maybeBoth _ j (Just a) (Just b) = j a b
maybeBoth n _ _ _ = n
combineH :: Vec2 -> Vec2 -> Vec2
combineH a b =
withVec2 a \aw ah ->
withVec2 b \bw bh ->
vec2 (aw + bw) (max ah bh)
combineV :: Vec2 -> Vec2 -> Vec2
combineV a b =
withVec2 a \aw ah ->
withVec2 b \bw bh ->
vec2 (max aw bw) (ah + bh)
max2 :: Vec2 -> Vec2 -> Vec2
max2 a b =
withVec2 a \aw ah ->
withVec2 b \bw bh ->
vec2 (max aw bw) (max ah bh)