{-# LANGUAGE AllowAmbiguousTypes #-}{-# LANGUAGE DefaultSignatures #-}{-| SwiftUI-like view treeThe 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 whereimport Data.Bifunctor (Bifunctor(..))import Data.Foldable (toList)import Data.Foldable1 (foldMap1')import Data.Traversable (foldMapDefault)import Data.Functor.Identity (Identity)import Data.List (mapAccumL, sortOn, zip4)import Data.List.NonEmpty (nonEmpty)import Data.List.NonEmpty qualified as NonEmptyimport Data.Maybe (catMaybes, fromMaybe, isJust, listToMaybe)import Geomancy ((^*))import Geomancy.Gl.Funs (glClamp)import Geomancy.Layout qualified as Layoutimport Geomancy.Layout.Alignment (Alignment(..))import Geomancy.Layout.Alignment qualified as Alignmentimport Geomancy.Layout.Box (Box(..))import Geomancy.Layout.Box qualified as Boximport 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 -> afoldWith 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 reportedMidline :: ReportedCache stuff -> Maybe Float reportedMidline _cache = Nothing -- | 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 instanceYou'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 protocolThe 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 viewsviewFun :: 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 placeddata GuidedFun stuff = GuidedFun ViewSize (Vec2 -> (Vec2, Maybe Float, Box -> stuff)) deriving (Functor)guidedFun :: ViewSize -> (Vec2 -> (Vec2, Maybe Float, Box -> stuff)) -> View () (GuidedFun stuff)guidedFun flex steps = View{ann=(), stuff=GuidedFun flex steps}instance LayoutView (GuidedFun stuff) where type ReportedCache (GuidedFun stuff) = (Maybe Float, Box -> stuff) type Placed (GuidedFun stuff) = stuff viewFlexibility (GuidedFun vs _) = vs proposeView size (GuidedFun _ f) = (reported, (midline, placeReported)) where (reported, midline, placeReported) = f size reportedMidline = fst placeView placed (_midline, placeReported) = placeReported placed-- * View tree{- | Layout skeletonIt 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 = foldMapDefaultinstance 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 innerinstance 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 shortcutsview_ :: stuff -> View () stuffview_ stuff = View{ann=(), ..}spacer_ :: View () stuffspacer_ = Spacer{ann=()}-- *** Containershstack_ :: [View () stuff] -> View () stuffhstack_ = hstack 0 Alignment.leftMiddlevstack_ :: [View () stuff] -> View () stuffvstack_ = vstack 0 Alignment.centerTophstack :: Float -> Alignment -> [View () stuff] -> View () stuffhstack spacing align children = HStack{ann=(), ..}vstack :: Float -> Alignment -> [View () stuff] -> View () stuffvstack spacing align children = VStack{ann=(), ..}zstack_ :: [View () stuff] -> View () stuffzstack_ = zstack Alignment.centerzstack :: Alignment -> [View () stuff] -> View () stuffzstack align children = ZStack{ann=(), ..}grid_ :: [[View () stuff]] -> View () stuffgrid_ = grid 0 0 Alignment.centergrid :: Float -> Float -> Alignment -> [[View () stuff]] -> View () stuffgrid columnSpacing rowSpacing align rows = Grid{ann=(), ..}overlay_ :: View () stuff -> View () stuff -> View () stuffoverlay_ = overlay Alignment.centeroverlay :: Alignment -> View () stuff -> View () stuff -> View () stuffoverlay align secondary primary = Overlay{ann=(), ..}background_ :: View () stuff -> View () stuff -> View () stuffbackground_ = background Alignment.centerbackground :: Alignment -> View () stuff -> View () stuff -> View () stuffbackground align secondary primary = Background{ann=(), ..}-- *** Modifiersframe_ :: Vec2 -> View () stuff -> View () stuffframe_ size inner = Frame{ann=(), align = Alignment.center, ..}flexible_ :: FrameBounds -> Alignment -> View () stuff -> View () stuffflexible_ bounds align inner = FlexibleFrame{ann=(), ..}aspect_ :: Vec2 -> View () stuff -> View () stuffaspect_ ratio inner = AspectRatio{ann=(), aspect=ratio, align=Alignment.center, ..}padding_ :: Vec4 -> View () stuff -> View () stuffpadding_ trbl inner = Padding{ann=(), trbl=Box.TRBL trbl, ..}offset_ :: Vec2 -> View () stuff -> View () stuffoffset_ xy inner = Offset{ann=(), ..}span_ :: Int -> Int -> View () stuff -> View () stuffspan_ 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.TRBLnoClearance = Box.TRBL 0withClearance :: ViewSize -> Box.WithTRBL r -> rwithClearance size = withEdges size.clearancewithEdges :: Box.TRBL -> Box.WithTRBL r -> rwithEdges (Box.TRBL trbl) = withVec4 trblwiderClearance :: Box.TRBL -> Box.TRBL -> Box.TRBLwiderClearance (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 -> ViewSizefixed_ 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_ :: ViewSizeinfinite_ = ViewSize { minWidth = Just 0 , maxWidth = Just inf , minHeight = Just 0 , maxHeight = Just inf , clearance = noClearance }range_ :: Vec2 -> Vec2 -> ViewSizerange_ 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 -> ViewSizespacerSize = \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 sizeparent_ :: ViewSizeparent_ = ViewSize { minWidth = Nothing , maxWidth = Nothing , minHeight = Nothing , maxHeight = Nothing , clearance = noClearance }parentWidth :: ViewSize -> ViewSizeparentWidth a = a {minWidth = Nothing, maxWidth = Nothing}parentHeight :: ViewSize -> ViewSizeparentHeight a = a {minHeight = Nothing, maxHeight = Nothing}data FrameBounds = FrameBounds { frameMinWidth, frameMaxWidth , frameMinHeight, frameMaxHeight :: Maybe Float , frameClearance :: !Box.TRBL } deriving (Eq, Show)unbounded :: FrameBoundsunbounded = FrameBounds { frameMinWidth = Nothing , frameMaxWidth = Nothing , frameMinHeight = Nothing , frameMaxHeight = Nothing , frameClearance = noClearance }between :: Vec2 -> Vec2 -> FrameBoundsbetween a b = withVec2 a \aw ah -> withVec2 b \bw bh -> heightWithin ah bh $ widthWithin aw bw unboundedwidthWithin :: Float -> Float -> FrameBounds -> FrameBoundswidthWithin lo hi bounds = bounds{frameMinWidth = Just (min lo hi), frameMaxWidth = Just (max lo hi)}heightWithin :: Float -> Float -> FrameBounds -> FrameBoundsheightWithin lo hi bounds = bounds{frameMinHeight = Just (min lo hi), frameMaxHeight = Just (max lo hi)}fillWidth :: FrameBounds -> FrameBoundsfillWidth bounds = bounds{frameMaxWidth = Just inf}fillHeight :: FrameBounds -> FrameBoundsfillHeight bounds = bounds{frameMaxHeight = Just inf}filling :: FrameBoundsfilling = fillHeight $ fillWidth unbounded-- * Layout steps-- | Measurement pre-passmeasure :: LayoutView stuff => View () stuff -> View ViewSize stuffmeasure = measureAlong NothingmeasureAlong :: LayoutView stuff => Maybe Axis -> View () stuff -> View ViewSize stuffmeasureAlong 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 treeplace :: 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 element = (reported, placeReported) where (reported, _midline, placeReported) = suspendGuided proposed elementsuspendGuided :: forall stuff . LayoutView stuff => Vec2 -> View ViewSize stuff -> (Vec2, Maybe Float, Box -> View Box (Placed stuff))suspendGuided proposed = \case Spacer{ann} -> ( vsClamp proposed ann proposed , Nothing , \placed -> Spacer{ann=placed} ) View{stuff} -> ( reported , reportedMidline @stuff cache , \placed -> View { ann = placed , stuff = placeView @stuff placed cache } ) where (reported, cache) = proposeView proposed stuff Frame{..} -> ( size , alignedMidline align size reported midline , \placedFrame -> Frame { ann = placedFrame , inner = suspended $ Layout.placeSize align reported placedFrame , .. } ) where (reported, midline, suspended) = suspendGuided size inner FlexibleFrame{..} -> ( framed , alignedMidline align framed reported midline , \placed -> FlexibleFrame { ann = placed , inner = suspended $ Layout.placeSize align reported placed , .. } ) where framed = framedSize bounds proposed reported (reported, midline, suspended) = suspendGuided (offeredSize bounds proposed) inner Padding{..} -> ( reported + pads , (+ top) <$> midline , \placed -> Padding { ann = placed , inner = suspended $ Box.addPadding trbl placed , .. } ) where (reported, midline, suspended) = suspendGuided (proposed - pads) inner pads = withVec4 trbl4 \t r b l -> vec2 (l + r) (t + b) top = withVec4 trbl4 \t _r _b _l -> t Box.TRBL trbl4 = trbl Offset{..} -> ( reported , midline , \placed -> Offset { ann = placed , inner = suspended $ Box.move xy placed , .. } ) where (reported, midline, suspended) = suspendGuided proposed inner Span{..} -> ( reported , midline , \placed -> Span{ann = placed, inner = suspended placed, ..} ) where (reported, midline, suspended) = suspendGuided proposed inner AspectRatio{..} -> ( covered , alignedMidline align covered reported midline , \placed -> AspectRatio { ann = placed , inner = suspended $ Layout.placeSize align reported placed , .. } ) where ratio = usableAspect aspect covered = maybe reported (`coverAspect` reported) ratio (reported, midline, suspended) = suspendGuided (maybe proposed (\r -> fitAspect r $ growableRoom inner.ann proposed) ratio) inner HStack{spacing, align, children} -> ( vec2 runWidth crossHeight , stackMidline , \placedStack -> let placedChildren :: [View Box (Placed stuff)] placedChildren = Box.withTRBL (justify placedStack) \t _r b l -> [ suspended $ Layout.placeSize align reportedSize (slot t b (l + start) reportedSize midline) | ((reportedSize, midline, suspended), start) <- zip children' starts ] slot t b left reportedSize midline = withVec2 reportedSize \w h -> if guided then let runTop = t + (b - t - crossHeight) * alignY childTop = runTop + above - fromMaybe (h * 0.5) midline in Box.fromTRBL childTop (left + w) (childTop + h) left else Box.fromTRBL t (left + w) b left justify box = shiftRun Layout.cutLeft alignX (Box.width box - runWidth) box in HStack { ann = maybe placedStack (foldMap1' ann) $ nonEmpty placedChildren , children = placedChildren , spacing , align } ) where Alignment alignOrigins = align WithVec2 alignX alignY = alignOrigins slotGaps = rowGaps spacing $ map ann children gaps = sum slotGaps (starts, runWidth) = runOffsets slotGaps [withVec2 reportedSize \w _h -> w | (reportedSize, _, _) <- children'] guided = alignY == Alignment.Middle && any (\(_, midline, _) -> isJust midline) children' extents = [withVec2 reportedSize \_w h -> let m = fromMaybe (h * 0.5) midline in (m, h - m) | (reportedSize, midline, _) <- children'] above = foldl' max (-inf) (map fst extents) below = foldl' max (-inf) (map snd extents) crossHeight | guided = above + below | otherwise = foldl' max 0 [withVec2 reportedSize \_w h -> h | (reportedSize, _, _) <- children'] stackMidline | guided = Just above | otherwise = firstJust [alignedMidline align (vec2 0 crossHeight) reportedSize midline | (reportedSize, midline, _) <- children'] 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') ) where (WithVec2 reportedWidth _, _, _) = child' child' = suspendGuided (vec2 proposeWidth remH) child proposeWidth = fairShare (minWidthOf child) reserved remW childrenRemaining VStack{spacing, align, children} -> ( vec2 crossWidth runHeight , firstJust [(+ start) <$> midline | ((_, midline, _), start) <- zip children' starts] , \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'] 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') ) where (WithVec2 _ reportedHeight, _, _) = child' child' = suspendGuided (vec2 remW proposeHeight) child proposeHeight = fairShare (minHeightOf child) reserved remH childrenRemaining ZStack{align, children} -> ( stackSize , firstJust [alignedMidline align stackSize reported midline | (reported, midline, _) <- suspendeds] , \placedStack -> let placedChildren = [ suspended $ Layout.placeSize align reported placedStack | (reported, _, suspended) <- suspendeds ] in ZStack { ann = maybe placedStack (foldMap1' ann) $ nonEmpty placedChildren , align , children = placedChildren } ) where suspendeds = map (suspendGuided proposed) children stackSize = foldl' max2 0 [reported | (reported, _, _) <- suspendeds] Grid{columnSpacing, rowSpacing, align, rows} -> ( vec2 runWidth runHeight , firstJust [ case guide of Just (above, below) -> Just $ rowStarts !! row + (rowHeights !! row - (above + below)) * alignY + above Nothing -> firstJust [ (+ rowStarts !! spot.spotRow) <$> alignedMidline align (vec2 0 $ spanHeight spot) reported midline | (spot, (reported, midline, _)) <- zip spotsInRow offeredInRow ] | (row, spotsInRow, offeredInRow, guide) <- zip4 [0 :: Int ..] spots offered guides ] , \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 $ cellBox guide spot reported midline (slot t l spot) | (spot, (reported, midline, placeCell)) <- zip spotsInRow offeredInRow ] | (spotsInRow, offeredInRow, guide) <- zip3 spots offered guides ] cellBox guide spot reported midline slotBox = case guide of Just (above, below) | spot.spotRows == 1 -> Box.withTRBL (Layout.placeSize align reported slotBox) \_top right _bottom left -> Box.withTRBL slotBox \slotTop _right slotBottom _left -> withVec2 reported \_w h -> let runTop = slotTop + (slotBottom - slotTop - (above + below)) * alignY childTop = runTop + above - fromMaybe (h * 0.5) midline in Box.fromTRBL childTop right (childTop + h) left _ -> Layout.placeSize align reported slotBox 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 _alignX alignY = alignOrigins 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) settledHeights = 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 ] settledRows = [ [suspendGuided (vec2 (spanWidth spot) (spanLength settledHeights rowGapsAt (alongRows spot))) cell | (spot, cell) <- zip spotsInRow row] | (spotsInRow, row) <- zip spots rows ] guides = [ rowGuide [(reported, midline) | (spot, (reported, midline, _)) <- zip spotsInRow settledInRow, spot.spotRows == 1] | (spotsInRow, settledInRow) <- zip spots settledRows ] rowGuide cells | alignY == Alignment.Middle && any (isJust . snd) cells = let extents = [withVec2 reported \_w h -> let m = fromMaybe (h * 0.5) midline in (m, h - m) | (reported, midline) <- cells] in Just (maximum (map fst extents), maximum (map snd extents)) | otherwise = Nothing rowHeights = zipWith (\settled guide -> maybe settled (\(above, below) -> max settled (above + below)) guide) settledHeights guides spanHeight spot = spanLength rowHeights rowGapsAt (alongRows spot) offered = [ [ if isJust guide && spot.spotRows == 1 then settledCell else suspendGuided (vec2 (spanWidth spot) (spanHeight spot)) cell | (spot, cell, settledCell) <- zip3 spotsInRow row settledInRow ] | (spotsInRow, row, settledInRow, guide) <- zip4 spots rows settledRows guides ] (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, Maybe Float, Box -> View Box (Placed stuff))decorated proposed align primary secondary rebuild = ( reportedPrimary , midlinePrimary , \placed -> let placedPrimary = placePrimary placed in rebuild placed placedPrimary $ placeSecondary (Layout.placeSize align reportedSecondary placedPrimary.ann) ) where (reportedPrimary, midlinePrimary, placePrimary) = suspendGuided proposed primary (reportedSecondary, placeSecondary) = suspend reportedPrimary secondaryalignedMidline :: Alignment -> Vec2 -> Vec2 -> Maybe Float -> Maybe FloatalignedMidline (Alignment origins) outer inner midline = withVec2 origins \_originX originY -> withVec2 outer \_outerWidth outerHeight -> withVec2 inner \_innerWidth innerHeight -> (+ (outerHeight - innerHeight) * originY) <$> midlinefirstJust :: [Maybe a] -> Maybe afirstJust = listToMaybe . catMaybes-- * Internalsinf :: Floatinf = 1 / 0rowGaps :: 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 Vec2usableAspect aspect = withVec2 aspect \aw ah -> let quotient = aw / ah in if quotient > 0 && not (isInfinite quotient) then Just $ vec2 (abs aw) (abs ah) else NothingfitAspect :: Vec2 -> Vec2 -> Vec2fitAspect aspect room = withVec2 aspect \aw ah -> withVec2 room \rw rh -> aspect ^* min (rw / aw) (rh / ah)coverAspect :: Vec2 -> Vec2 -> Vec2coverAspect aspect content = withVec2 aspect \aw ah -> withVec2 content \cw ch -> aspect ^* max (cw / aw) (ch / ah)growableRoom :: ViewSize -> Vec2 -> Vec2growableRoom 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 = paspectRange :: Vec2 -> ViewSize -> ViewSizeaspectRange 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 _ -> rwidestGap :: Float -> [Float] -> FloatwidestGap spacing clearances = foldl' max spacing (filter (> 0) clearances)rowClearance :: [ViewSize] -> Box.TRBLrowClearance 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 leftcolumnClearance :: [ViewSize] -> Box.TRBLcolumnClearance 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 leftcrossClearance :: [ViewSize] -> Box.TRBLcrossClearance = 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) -> BoolsizedRange = \case (_, Just most) -> not (isInfinite most) _ -> FalsetrackRange :: [(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)] -> FloattrackAnswer 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 -> max lo probed _ -> probedsettleTracks :: 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] -> IntgridColumnCount spots = foldl' max 0 [spot.spotColumn + spot.spotColumns | spot <- spots]innerGaps :: [Float] -> Int -> Int -> FloatinnerGaps gaps lead count = sum . take (count - 1) $ drop lead gapsspanLength :: [Float] -> [Float] -> (Int, Int) -> FloatspanLength lengths gaps (lead, count) = sum (take count $ drop lead lengths) + innerGaps gaps lead countspanGaps :: 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.TRBLspanClearance 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 edgefillUp :: 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)] -> FloatamountFor 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 = currentsettleAxis :: 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 -> max lo (probe current) _ -> 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 openTrackstopEdge, rightEdge, bottomEdge, leftEdge :: Box.TRBL -> FloattopEdge edges = withEdges edges \t _r _b _l -> trightEdge edges = withEdges edges \_t r _b _l -> rbottomEdge edges = withEdges edges \_t _r b _l -> bleftEdge edges = withEdges edges \_t _r _b l -> lreservedAfter :: (child -> Float) -> [(ix, child)] -> [Float]reservedAfter minimumOf = drop 1 . scanr ((+) . minimumOf . snd) 0fairShare :: Float -> Float -> Float -> Float -> FloatfairShare 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 gapsshiftRun :: (Float -> Box -> (Box, Box)) -> Alignment.Origin -> Float -> Box -> BoxshiftRun cut origin slack box = if origin == 0 || slack == 0 then box else snd $ cut (slack * origin) boxwidthFlexibility :: ViewSize -> FloatwidthFlexibility ViewSize{..} = maybeBoth inf (-) maxWidth minWidthheightFlexibility :: ViewSize -> FloatheightFlexibility ViewSize{..} = maybeBoth inf (-) maxHeight minHeightframeLeast :: Maybe Float -> Maybe Float -> Maybe Float -> Maybe FloatframeLeast 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 FloatframeMost 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 -> FrameBoundsorderedBounds 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 = hiofferedSize :: FrameBounds -> Vec2 -> Vec2offeredSize 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 lowerframedSize :: FrameBounds -> Vec2 -> Vec2 -> Vec2framedSize 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)) lowervsClamp :: Vec2 -> ViewSize -> Vec2 -> Vec2vsClamp 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 -> t1maybeBoth _ j (Just a) (Just b) = j a bmaybeBoth n _ _ _ = ncombineH :: Vec2 -> Vec2 -> Vec2combineH a b = withVec2 a \aw ah -> withVec2 b \bw bh -> vec2 (aw + bw) (max ah bh)combineV :: Vec2 -> Vec2 -> Vec2combineV a b = withVec2 a \aw ah -> withVec2 b \bw bh -> vec2 (max aw bw) (ah + bh)max2 :: Vec2 -> Vec2 -> Vec2max2 a b = withVec2 a \aw ah -> withVec2 b \bw bh -> vec2 (max aw bw) (max ah bh)