@@ -2,161 +2,41 @@
22Module: Reflex.Vty.Widget
33Description: Basic set of widgets and building blocks for reflex-vty applications
44-}
5−{-# LANGUAGE DefaultSignatures #-}
6−{-# LANGUAGE DeriveFunctor #-}
7−{-# LANGUAGE FlexibleContexts #-}
8−{-# LANGUAGE FlexibleInstances #-}
9−{-# LANGUAGE FunctionalDependencies #-}
10−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11−{-# LANGUAGE LambdaCase #-}
12−{-# LANGUAGE RankNTypes #-}
13−{-# LANGUAGE RecursiveDo #-}
14−{-# LANGUAGE ScopedTypeVariables #-}
15−{-# LANGUAGE StandaloneDeriving #-}
16−{-# LANGUAGE TupleSections #-}
17−{-# LANGUAGE TypeFamilies #-}
18−{-# LANGUAGE UndecidableInstances #-}
19−
20−module Reflex.Vty.Widget
21− ( VtyWidgetCtx(..)
22− , VtyWidget(..)
23− , VtyWidgetOut(..)
24− , ImageWriter(..)
25− , runVtyWidget
26− , mainWidget
27− , mainWidgetWithHandle
28− , HasDisplaySize(..)
29− , HasFocus(..)
30− , HasVtyInput(..)
31− , DynRegion(..)
32− , currentRegion
33− , Region(..)
34− , regionSize
35− , regionBlankImage
36− , Drag(..)
37− , drag
38− , MouseDown(..)
39− , MouseUp(..)
40− , mouseDown
41− , mouseUp
42− , ScrollDirection(..)
43− , mouseScroll
44− , pane
45− , splitV
46− , splitH
47− , splitVDrag
48− , boxTitle
49− , box
50− , boxStatic
51− , RichTextConfig(..)
52− , richText
53− , text
54− , scrollableText
55− , display
56− , BoxStyle(..)
57− , hyphenBoxStyle
58− , singleBoxStyle
59− , roundedBoxStyle
60− , thickBoxStyle
61− , doubleBoxStyle
62− , fill
63− , hRule
64− , KeyCombo
65− , key
66− , keys
67− , keyCombo
68− , keyCombos
69− , blank
70− ) where
5+{-# Language UndecidableInstances #-}
6+
7+module Reflex.Vty.Widget where
718
729import Control.Applicative (liftA2)
7310import Control.Monad.Fix (MonadFix)
74−import Control.Monad.Reader
75−import Control.Monad.Trans (lift)
76−import Data.Default (Default(..))
11+import Control.Monad.IO.Class (MonadIO)
12+import Control.Monad.Morph
13+import Control.Monad.NodeId
14+import Control.Monad.Reader (ReaderT, ask, local, runReaderT)
15+import Control.Monad.Ref
16+import Control.Monad.Trans (MonadTrans, lift)
7717import Data.Set (Set)
7818import qualified Data.Set as Set
79−import Data.Text (Text)
80−import qualified Data.Text as T
81−import qualified Data.Text.Zipper as TZ
8219import Graphics.Vty (Image)
8320import qualified Graphics.Vty as V
8421import Reflex
8522import Reflex.Class ()
8623import Reflex.Host.Class (MonadReflexCreateTrigger)
87−
8824import Reflex.Vty.Host
8925
90−import Control.Monad.NodeId
91−
92−-- | The context within which a 'VtyWidget' runs
93−data VtyWidgetCtx t = VtyWidgetCtx
94− { _vtyWidgetCtx_width :: Dynamic t Int
95− -- ^ The width of the region allocated to the widget.
96− , _vtyWidgetCtx_height :: Dynamic t Int
97− -- ^ The height of the region allocated to the widget.
98− , _vtyWidgetCtx_focus :: Dynamic t Bool
99− -- ^ Whether the widget should behave as if it has focus for keyboard input.
100− , _vtyWidgetCtx_input :: Event t VtyEvent
101− -- ^ User input events that the widget's parent chooses to share. These will generally
102− -- be filtered for relevance:
103− -- * Keyboard inputs are restricted to focused widgets
104− -- * Mouse inputs are restricted to the region in which the widget resides and are
105− -- translated into its internal coordinates.
106− }
107−
108−-- | The output of a 'VtyWidget'
109−data VtyWidgetOut t = VtyWidgetOut
110− { _vtyWidgetOut_shutdown :: Event t ()
111− }
112−
113−instance (Adjustable t m, MonadHold t m, Reflex t) => Adjustable t (VtyWidget t m) where
114− runWithReplace a0 a' = VtyWidget $ runWithReplace (unVtyWidget a0) $ fmap unVtyWidget a'
115− traverseIntMapWithKeyWithAdjust f dm0 dm' = VtyWidget $
116− traverseIntMapWithKeyWithAdjust (\k v -> unVtyWidget (f k v)) dm0 dm'
117− traverseDMapWithKeyWithAdjust f dm0 dm' = VtyWidget $ do
118− traverseDMapWithKeyWithAdjust (\k v -> unVtyWidget (f k v)) dm0 dm'
119− traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = VtyWidget $ do
120− traverseDMapWithKeyWithAdjustWithMove (\k v -> unVtyWidget (f k v)) dm0 dm'
121−
122−-- | A widget that can read its context and produce image output
123−newtype VtyWidget t m a = VtyWidget
124− { unVtyWidget :: BehaviorWriterT t [Image] (ReaderT (VtyWidgetCtx t) m) a
125− } deriving
126− ( Functor
127− , Applicative
128− , Monad
129− , MonadSample t
130− , MonadHold t
131− , MonadFix
132− , NotReady t
133− , ImageWriter t
134− , PostBuild t
135− , TriggerEvent t
136− , MonadReflexCreateTrigger t
137− , MonadIO
138− )
139−
140−deriving instance PerformEvent t m => PerformEvent t (VtyWidget t m)
141−instance MonadTrans (VtyWidget t) where
142− lift f = VtyWidget $ lift $ lift f
143−
144−instance MonadNodeId m => MonadNodeId (VtyWidget t m) where
145− getNextNodeId = VtyWidget $ do
146− lift $ lift $ getNextNodeId
147−
148−-- | Runs a 'VtyWidget' with a given context
149−runVtyWidget
150− :: (Reflex t, MonadNodeId m)
151− => VtyWidgetCtx t
152− -> VtyWidget t m a
153− -> m (a, Behavior t [Image])
154−runVtyWidget ctx w = runReaderT (runBehaviorWriterT (unVtyWidget w)) ctx
26+-- * Running a vty application
15527
156−-- | Sets up the top-level context for a 'VtyWidget' and runs it with that context
28+-- | Sets up the top-level context for a vty widget and runs it with that context
15729mainWidgetWithHandle
15830 :: V.Vty
159− -> (forall t m. (MonadVtyApp t m, MonadNodeId m) => VtyWidget t m (Event t ()))
31+ -> (forall t m.
32+ ( MonadVtyApp t m
33+ , HasImageWriter t m
34+ , MonadNodeId m
35+ , HasDisplayRegion t m
36+ , HasFocusReader t m
37+ , HasInput t m
38+ , HasTheme t m
39+ ) => m (Event t ()))
16040 -> IO ()
16141mainWidgetWithHandle vty child =
16242 runVtyAppWithHandle vty $ \dr0 inp -> do
@@ -166,71 +46,178 @@ mainWidgetWithHandle vty child =
16646 let inp' = fforMaybe inp $ \case
16747 V.EvResize {} -> Nothing
16848 x -> Just x
169− let ctx = VtyWidgetCtx
170− { _vtyWidgetCtx_width = fmap fst size
171− , _vtyWidgetCtx_height = fmap snd size
172− , _vtyWidgetCtx_input = inp'
173− , _vtyWidgetCtx_focus = constDyn True
174− }
175− (shutdown, images) <- runNodeIdT $ runVtyWidget ctx $ do
176− tellImages . ffor (current size) $ \(w, h) -> [V.charFill V.defAttr ' ' w h]
177− child
49+ (shutdown, images) <- runThemeReader (constant V.defAttr) $
50+ runFocusReader (pure True) $
51+ runDisplayRegion (fmap (\(w, h) -> Region 0 0 w h) size) $
52+ runImageWriter $
53+ runNodeIdT $
54+ runInput inp' $ do
55+ tellImages . ffor (current size) $ \(w, h) -> [V.charFill V.defAttr ' ' w h]
56+ child
17857 return $ VtyResult
17958 { _vtyResult_picture = fmap (V.picForLayers . reverse) images
18059 , _vtyResult_shutdown = shutdown
18160 }
18261
62+-- | The output of a vty widget
63+data VtyWidgetOut t = VtyWidgetOut
64+ { _vtyWidgetOut_shutdown :: Event t ()
65+ }
66+
18367-- | Like 'mainWidgetWithHandle', but uses a default vty configuration
18468mainWidget
185− :: (forall t m. (MonadVtyApp t m, MonadNodeId m) => VtyWidget t m (Event t ()))
69+ :: (forall t m.
70+ ( MonadVtyApp t m
71+ , HasImageWriter t m
72+ , MonadNodeId m
73+ , HasDisplayRegion t m
74+ , HasFocusReader t m
75+ , HasTheme t m
76+ , HasInput t m
77+ ) => m (Event t ()))
18678 -> IO ()
18779mainWidget child = do
18880 vty <- getDefaultVty
18981 mainWidgetWithHandle vty child
19082
191−-- | A class for things that know their own display size dimensions
192−class (Reflex t, Monad m) => HasDisplaySize t m | m -> t where
193− -- | Retrieve the display width (columns)
194− displayWidth :: m (Dynamic t Int)
195− default displayWidth :: (f m' ~ m, MonadTrans f, HasDisplaySize t m') => m (Dynamic t Int)
196− displayWidth = lift displayWidth
197− -- | Retrieve the display height (rows)
198− displayHeight :: m (Dynamic t Int)
199− default displayHeight :: (f m' ~ m, MonadTrans f, HasDisplaySize t m') => m (Dynamic t Int)
200− displayHeight = lift displayHeight
201−
202−instance (Reflex t, Monad m) => HasDisplaySize t (VtyWidget t m) where
203− displayWidth = VtyWidget . lift $ asks _vtyWidgetCtx_width
204− displayHeight = VtyWidget . lift $ asks _vtyWidgetCtx_height
205−
206−instance HasDisplaySize t m => HasDisplaySize t (ReaderT x m)
207−instance HasDisplaySize t m => HasDisplaySize t (BehaviorWriterT t x m)
208−instance HasDisplaySize t m => HasDisplaySize t (DynamicWriterT t x m)
209−instance HasDisplaySize t m => HasDisplaySize t (EventWriterT t x m)
210−
211−instance HasDisplaySize t m => HasDisplaySize t (NodeIdT m)
83+-- * Input Events
21284
21385-- | A class for things that can receive vty events as input
214−class HasVtyInput t m | m -> t where
86+class HasInput t m | m -> t where
21587 input :: m (Event t VtyEvent)
88+ default input :: (f m' ~ m, Monad m', MonadTrans f, HasInput t m') => m (Event t VtyEvent)
89+ input = lift input
90+ -- | User input events that the widget's parent chooses to share. These will generally
91+ -- be filtered for relevance.
92+ localInput :: (Event t VtyEvent -> Event t VtyEvent) -> m a -> m a
93+ default localInput :: (f m' ~ m, Monad m', MFunctor f, HasInput t m') => (Event t VtyEvent -> Event t VtyEvent) -> m a -> m a
94+ localInput f = hoist (localInput f)
95+
96+instance (Reflex t, Monad m) => HasInput t (Input t m) where
97+ input = Input ask
98+ localInput f (Input m) = Input $ local f m
99+
100+-- | A widget that can receive input events. See 'Graphics.Vty.Event'
101+newtype Input t m a = Input
102+ { unInput :: ReaderT (Event t VtyEvent) m a
103+ } deriving
104+ ( Functor
105+ , Applicative
106+ , Monad
107+ , MonadSample t
108+ , MonadHold t
109+ , MonadFix
110+ , MonadIO
111+ , MonadRef
112+ )
216113
217−instance (Reflex t, Monad m) => HasVtyInput t (VtyWidget t m) where
218− input = VtyWidget . lift $ asks _vtyWidgetCtx_input
114+instance (Adjustable t m, MonadHold t m, Reflex t) => Adjustable t (Input t m) where
115+ runWithReplace a0 a' = Input $ runWithReplace (unInput a0) $ fmap unInput a'
116+ traverseIntMapWithKeyWithAdjust f dm0 dm' = Input $
117+ traverseIntMapWithKeyWithAdjust (\k v -> unInput (f k v)) dm0 dm'
118+ traverseDMapWithKeyWithAdjust f dm0 dm' = Input $ do
119+ traverseDMapWithKeyWithAdjust (\k v -> unInput (f k v)) dm0 dm'
120+ traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = Input $ do
121+ traverseDMapWithKeyWithAdjustWithMove (\k v -> unInput (f k v)) dm0 dm'
122+
123+deriving instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (Input t m)
124+deriving instance NotReady t m => NotReady t (Input t m)
125+deriving instance PerformEvent t m => PerformEvent t (Input t m)
126+deriving instance PostBuild t m => PostBuild t (Input t m)
127+deriving instance TriggerEvent t m => TriggerEvent t (Input t m)
128+instance HasImageWriter t m => HasImageWriter t (Input t m)
129+instance HasDisplayRegion t m => HasDisplayRegion t (Input t m)
130+instance HasFocusReader t m => HasFocusReader t (Input t m)
131+
132+instance MonadTrans (Input t) where
133+ lift f = Input $ lift f
134+
135+instance MFunctor (Input t) where
136+ hoist f = Input . hoist f . unInput
137+
138+instance MonadNodeId m => MonadNodeId (Input t m)
139+
140+-- | Runs an 'Input' with a given context
141+runInput
142+ :: Reflex t
143+ => Event t VtyEvent
144+ -> Input t m a
145+ -> m a
146+runInput e w = runReaderT (unInput w) e
147+
148+-- ** Filtering input
219149
220−-- | A class for things that can dynamically gain and lose focus
221−class HasFocus t m | m -> t where
222− focus :: m (Dynamic t Bool)
150+-- | Type synonym for a key and modifier combination
151+type KeyCombo = (V.Key, [V.Modifier])
223152
224−instance (Reflex t, Monad m) => HasFocus t (VtyWidget t m) where
225− focus = VtyWidget . lift $ asks _vtyWidgetCtx_focus
153+-- | Emits an event that fires on a particular key press (without modifiers)
154+key :: (Monad m, Reflex t, HasInput t m) => V.Key -> m (Event t KeyCombo)
155+key = keyCombos . Set.singleton . (,[])
226156
227−-- | A class for widgets that can produce images to draw to the display
228−class (Reflex t, Monad m) => ImageWriter t m | m -> t where
229− -- | Send images upstream for rendering
230− tellImages :: Behavior t [Image] -> m ()
157+-- | Emits an event that fires on particular key presses (without modifiers)
158+keys :: (Monad m, Reflex t, HasInput t m) => [V.Key] -> m (Event t KeyCombo)
159+keys = keyCombos . Set.fromList . fmap (,[])
231160
232−instance (Monad m, Reflex t) => ImageWriter t (BehaviorWriterT t [Image] m) where
233− tellImages = tellBehavior
161+-- | Emit an event that fires whenever the provided key combination occurs
162+keyCombo
163+ :: (Reflex t, Monad m, HasInput t m)
164+ => KeyCombo
165+ -> m (Event t KeyCombo)
166+keyCombo = keyCombos . Set.singleton
167+
168+-- | Emit an event that fires whenever any of the provided key combinations occur
169+keyCombos
170+ :: (Reflex t, Monad m, HasInput t m)
171+ => Set KeyCombo
172+ -> m (Event t KeyCombo)
173+keyCombos ks = do
174+ i <- input
175+ return $ fforMaybe i $ \case
176+ V.EvKey k m -> if Set.member (k, m) ks
177+ then Just (k, m)
178+ else Nothing
179+ _ -> Nothing
180+
181+-- | Filter the keyboard input that a child widget may receive
182+filterKeys :: (Reflex t, HasInput t m) => (KeyCombo -> Bool) -> m a -> m a
183+filterKeys f x = localInput (ffilter (\case
184+ V.EvKey k mods -> f (k, mods)
185+ _ -> True)) x
186+
187+-- | Filter mouse input events based on whether they target a particular region
188+-- and translate them to the internal coordinate system of that region.
189+--
190+-- NB: Non-mouse events are passed through unfiltered and unchanged
191+mouseInRegion :: Region -> VtyEvent -> Maybe VtyEvent
192+mouseInRegion (Region l t w h) e = case e of
193+ V.EvMouseDown x y btn m -> mouse (\u v -> V.EvMouseDown u v btn m) x y
194+ V.EvMouseUp x y btn -> mouse (\u v -> V.EvMouseUp u v btn) x y
195+ _ -> Just e
196+ where
197+ mouse con x y
198+ | or [ x < l
199+ , y < t
200+ , x >= l + w
201+ , y >= t + h ] = Nothing
202+ | otherwise =
203+ Just (con (x - l) (y - t))
204+
205+-- | Filter mouse input outside the current display region and
206+-- all input if the region is not focused
207+inputInFocusedRegion
208+ :: (HasDisplayRegion t m, HasFocusReader t m, HasInput t m)
209+ => m (Event t VtyEvent)
210+inputInFocusedRegion = do
211+ inp <- input
212+ reg <- current <$> askRegion
213+ foc <- current <$> focus
214+ pure $ fmapMaybe id $ attachWith filterInput ((,) <$> reg <*> foc) inp
215+ where
216+ filterInput (r, f) = \case
217+ V.EvKey {} | not f -> Nothing
218+ x -> mouseInRegion r x
219+
220+-- * Getting and setting the display region
234221
235222-- | A chunk of the display area
236223data Region = Region
@@ -241,499 +228,334 @@ data Region = Region
241228 }
242229 deriving (Show, Read, Eq, Ord)
243230
244−-- | A dynamic chunk of the display area
245−data DynRegion t = DynRegion
246− { _dynRegion_left :: Dynamic t Int
247− , _dynRegion_top :: Dynamic t Int
248− , _dynRegion_width :: Dynamic t Int
249− , _dynRegion_height :: Dynamic t Int
250− }
231+-- | A region that occupies no space.
232+nilRegion :: Region
233+nilRegion = Region 0 0 0 0
251234
252235-- | The width and height of a 'Region'
253236regionSize :: Region -> (Int, Int)
254237regionSize (Region _ _ w h) = (w, h)
255238
256239-- | Produces an 'Image' that fills a region with space characters
257−regionBlankImage :: Region -> Image
258−regionBlankImage r@(Region _ _ width height) =
259− withinImage r $ V.charFill V.defAttr ' ' width height
240+regionBlankImage :: V.Attr -> Region -> Image
241+regionBlankImage attr r@(Region _ _ width height) =
242+ withinImage r $ V.charFill attr ' ' width height
260243
261−-- | A behavior of the current display area represented by a 'DynRegion'
262−currentRegion :: Reflex t => DynRegion t -> Behavior t Region
263−currentRegion (DynRegion l t w h) = Region <$> current l <*> current t <*> current w <*> current h
244+-- | A class for things that know their own display size dimensions
245+class (Reflex t, Monad m) => HasDisplayRegion t m | m -> t where
246+ -- | Retrieve the display region
247+ askRegion :: m (Dynamic t Region)
248+ default askRegion :: (f m' ~ m, MonadTrans f, HasDisplayRegion t m') => m (Dynamic t Region)
249+ askRegion = lift askRegion
250+ -- | Run an action in a local region, by applying a transformation to the region
251+ localRegion :: (Dynamic t Region -> Dynamic t Region) -> m a -> m a
252+ default localRegion :: (f m' ~ m, Monad m', MFunctor f, HasDisplayRegion t m') => (Dynamic t Region -> Dynamic t Region) -> m a -> m a
253+ localRegion f = hoist (localRegion f)
254+
255+-- | Retrieve the display width
256+displayWidth :: HasDisplayRegion t m => m (Dynamic t Int)
257+displayWidth = fmap _region_width <$> askRegion
258+
259+-- | Retrieve the display height
260+displayHeight :: HasDisplayRegion t m => m (Dynamic t Int)
261+displayHeight = fmap _region_height <$> askRegion
262+
263+instance HasDisplayRegion t m => HasDisplayRegion t (ReaderT x m)
264+instance HasDisplayRegion t m => HasDisplayRegion t (BehaviorWriterT t x m)
265+instance HasDisplayRegion t m => HasDisplayRegion t (DynamicWriterT t x m)
266+instance HasDisplayRegion t m => HasDisplayRegion t (EventWriterT t x m)
267+instance HasDisplayRegion t m => HasDisplayRegion t (NodeIdT m)
268+
269+-- | A widget that has access to a particular region of the vty display
270+newtype DisplayRegion t m a = DisplayRegion
271+ { unDisplayRegion :: ReaderT (Dynamic t Region) m a }
272+ deriving
273+ ( Functor
274+ , Applicative
275+ , Monad
276+ , MonadFix
277+ , MonadHold t
278+ , MonadIO
279+ , MonadRef
280+ , MonadSample t
281+ )
264282
265−-- | Translates and crops an 'Image' so that it is contained by
266−-- the given 'Region'.
267−withinImage
268− :: Region
269− -> Image
270− -> Image
271−withinImage (Region left top width height)
272− | width < 0 || height < 0 = withinImage (Region left top 0 0)
273− | otherwise = V.translate left top . V.crop width height
283+instance (Monad m, Reflex t) => HasDisplayRegion t (DisplayRegion t m) where
284+ askRegion = DisplayRegion ask
285+ localRegion f = DisplayRegion . local f . unDisplayRegion
274286
275−-- | Low-level widget combinator that runs a child 'VtyWidget' within
276−-- a given region and context. This widget filters and modifies the input
277−-- that the child widget receives such that:
278−-- * unfocused widgets receive no key events
279−-- * mouse inputs outside the region are ignored
280−-- * mouse inputs inside the region have their coordinates translated such
281−-- that (0,0) is the top-left corner of the region
282−pane
283− :: (Reflex t, Monad m, MonadNodeId m)
284− => DynRegion t
285− -> Dynamic t Bool -- ^ Whether the widget should be focused when the parent is.
286− -> VtyWidget t m a
287− -> VtyWidget t m a
288−pane dr foc child = VtyWidget $ do
289− ctx <- lift ask
290− let reg = currentRegion dr
291− let ctx' = VtyWidgetCtx
292− { _vtyWidgetCtx_input = leftmost -- TODO: think about this leftmost more.
293− [ fmapMaybe id $
294− attachWith (\(r,f) e -> filterInput r f e)
295− (liftA2 (,) reg (current foc))
296− (_vtyWidgetCtx_input ctx)
297− ]
298− , _vtyWidgetCtx_focus = liftA2 (&&) (_vtyWidgetCtx_focus ctx) foc
299− , _vtyWidgetCtx_width = _dynRegion_width dr
300− , _vtyWidgetCtx_height = _dynRegion_height dr
301− }
302− (result, images) <- lift . lift $ runVtyWidget ctx' child
303− let images' = liftA2 (\r is -> map (withinImage r) is) reg images
304− tellImages images'
305− return result
306− where
307− filterInput :: Region -> Bool -> VtyEvent -> Maybe VtyEvent
308− filterInput (Region l t w h) focused e = case e of
309− V.EvKey _ _ | not focused -> Nothing
310− V.EvMouseDown x y btn m -> mouse (\u v -> V.EvMouseDown u v btn m) x y
311− V.EvMouseUp x y btn -> mouse (\u v -> V.EvMouseUp u v btn) x y
312− _ -> Just e
313− where
314− mouse con x y
315− | or [ x < l
316− , y < t
317− , x >= l + w
318− , y >= t + h ] = Nothing
319− | otherwise =
320− Just (con (x - l) (y - t))
321−
322−-- | Information about a drag operation
323−data Drag = Drag
324− { _drag_from :: (Int, Int) -- ^ Where the drag began
325− , _drag_to :: (Int, Int) -- ^ Where the mouse currently is
326− , _drag_button :: V.Button -- ^ Which mouse button is dragging
327− , _drag_modifiers :: [V.Modifier] -- ^ What modifiers are held
328− , _drag_end :: Bool -- ^ Whether the drag ended (the mouse button was released)
329− }
330− deriving (Eq, Ord, Show)
331−
332−-- | Converts raw vty mouse drag events into an event stream of 'Drag's
333−drag
334− :: (Reflex t, MonadFix m, MonadHold t m)
335− => V.Button
336− -> VtyWidget t m (Event t Drag)
337−drag btn = do
338− inp <- input
339− let f :: Maybe Drag -> V.Event -> Maybe Drag
340− f Nothing = \case
341− V.EvMouseDown x y btn' mods
342− | btn == btn' -> Just $ Drag (x,y) (x,y) btn' mods False
343− | otherwise -> Nothing
344− _ -> Nothing
345− f (Just (Drag from _ _ mods end)) = \case
346− V.EvMouseDown x y btn' mods'
347− | end && btn == btn' -> Just $ Drag (x,y) (x,y) btn' mods' False
348− | btn == btn' -> Just $ Drag from (x,y) btn mods' False
349− | otherwise -> Nothing -- Ignore other buttons.
350− V.EvMouseUp x y (Just btn')
351− | end -> Nothing
352− | btn == btn' -> Just $ Drag from (x,y) btn mods True
353− | otherwise -> Nothing
354− V.EvMouseUp x y Nothing -- Terminal doesn't specify mouse up button,
355− -- assume it's the right one.
356− | end -> Nothing
357− | otherwise -> Just $ Drag from (x,y) btn mods True
358− _ -> Nothing
359− rec let newDrag = attachWithMaybe f (current dragD) inp
360− dragD <- holdDyn Nothing $ Just <$> newDrag
361− return (fmapMaybe id $ updated dragD)
362−
363−-- | Mouse down events for a particular mouse button
364−mouseDown
365− :: (Reflex t, Monad m)
366− => V.Button
367− -> VtyWidget t m (Event t MouseDown)
368−mouseDown btn = do
369− i <- input
370− return $ fforMaybe i $ \case
371− V.EvMouseDown x y btn' mods -> if btn == btn'
372− then Just $ MouseDown btn' (x, y) mods
373− else Nothing
374− _ -> Nothing
287+deriving instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (DisplayRegion t m)
288+deriving instance NotReady t m => NotReady t (DisplayRegion t m)
289+deriving instance PerformEvent t m => PerformEvent t (DisplayRegion t m)
290+deriving instance PostBuild t m => PostBuild t (DisplayRegion t m)
291+deriving instance TriggerEvent t m => TriggerEvent t (DisplayRegion t m)
292+instance HasImageWriter t m => HasImageWriter t (DisplayRegion t m)
293+instance HasFocusReader t m => HasFocusReader t (DisplayRegion t m)
375294
376−-- | Mouse up events for a particular mouse button
377−mouseUp
378− :: (Reflex t, Monad m)
379− => VtyWidget t m (Event t MouseUp)
380−mouseUp = do
381− i <- input
382− return $ fforMaybe i $ \case
383− V.EvMouseUp x y btn' -> Just $ MouseUp btn' (x, y)
384− _ -> Nothing
295+instance (Adjustable t m, MonadFix m, MonadHold t m) => Adjustable t (DisplayRegion t m) where
296+ runWithReplace (DisplayRegion a) e = DisplayRegion $ runWithReplace a $ fmap unDisplayRegion e
297+ traverseIntMapWithKeyWithAdjust f m e = DisplayRegion $ traverseIntMapWithKeyWithAdjust (\k v -> unDisplayRegion $ f k v) m e
298+ traverseDMapWithKeyWithAdjust f m e = DisplayRegion $ traverseDMapWithKeyWithAdjust (\k v -> unDisplayRegion $ f k v) m e
299+ traverseDMapWithKeyWithAdjustWithMove f m e = DisplayRegion $ traverseDMapWithKeyWithAdjustWithMove (\k v -> unDisplayRegion $ f k v) m e
385300
386−-- | Information about a mouse down event
387−data MouseDown = MouseDown
388− { _mouseDown_button :: V.Button
389− , _mouseDown_coordinates :: (Int, Int)
390− , _mouseDown_modifiers :: [V.Modifier]
391− }
392− deriving (Eq, Ord, Show)
301+instance MonadTrans (DisplayRegion t) where
302+ lift = DisplayRegion . lift
393303
394−-- | Information about a mouse up event
395−data MouseUp = MouseUp
396− { _mouseUp_button :: Maybe V.Button
397− , _mouseUp_coordinates :: (Int, Int)
398− }
399− deriving (Eq, Ord, Show)
304+instance MFunctor (DisplayRegion t) where
305+ hoist f = DisplayRegion . hoist f . unDisplayRegion
400306
401−-- | Mouse scroll direction
402−data ScrollDirection = ScrollDirection_Up | ScrollDirection_Down
403− deriving (Eq, Ord, Show)
307+instance MonadNodeId m => MonadNodeId (DisplayRegion t m)
404308
405−-- | Produce an event that fires when the mouse wheel is scrolled
406−mouseScroll
309+-- | Run a 'DisplayRegion' action with a given 'Region'
310+runDisplayRegion
407311 :: (Reflex t, Monad m)
408− => VtyWidget t m (Event t ScrollDirection)
409−mouseScroll = do
410− up <- mouseDown V.BScrollUp
411− down <- mouseDown V.BScrollDown
412− return $ leftmost
413− [ ScrollDirection_Up <$ up
414− , ScrollDirection_Down <$ down
415− ]
312+ => Dynamic t Region
313+ -> DisplayRegion t m a
314+ -> m a
315+runDisplayRegion r = flip runReaderT r . unDisplayRegion
416316
417−-- | Type synonym for a key and modifier combination
418−type KeyCombo = (V.Key, [V.Modifier])
317+-- * Getting focus state
419318
420−-- | Emits an event that fires on a particular key press (without modifiers)
421−key :: (Monad m, Reflex t) => V.Key -> VtyWidget t m (Event t KeyCombo)
422−key = keyCombos . Set.singleton . (,[])
319+-- | A class for things that can dynamically gain and lose focus
320+class (Reflex t, Monad m) => HasFocusReader t m | m -> t where
321+ focus :: m (Dynamic t Bool)
322+ default focus :: (f m' ~ m, Monad m', MonadTrans f, HasFocusReader t m') => m (Dynamic t Bool)
323+ focus = lift focus
324+ localFocus :: (Dynamic t Bool -> Dynamic t Bool) -> m a -> m a
325+ default localFocus :: (f m' ~ m, Monad m', MFunctor f, HasFocusReader t m') => (Dynamic t Bool -> Dynamic t Bool) -> m a -> m a
326+ localFocus f = hoist (localFocus f)
327+
328+instance HasFocusReader t m => HasFocusReader t (ReaderT x m)
329+instance HasFocusReader t m => HasFocusReader t (BehaviorWriterT t x m)
330+instance HasFocusReader t m => HasFocusReader t (DynamicWriterT t x m)
331+instance HasFocusReader t m => HasFocusReader t (EventWriterT t x m)
332+instance HasFocusReader t m => HasFocusReader t (NodeIdT m)
333+
334+-- | A widget that has access to information about whether it is focused
335+newtype FocusReader t m a = FocusReader
336+ { unFocusReader :: ReaderT (Dynamic t Bool) m a }
337+ deriving
338+ ( Functor
339+ , Applicative
340+ , Monad
341+ , MonadFix
342+ , MonadHold t
343+ , MonadIO
344+ , MonadRef
345+ , MonadSample t
346+ )
423347
424−-- | Emits an event that fires on particular key presses (without modifiers)
425−keys :: (Monad m, Reflex t) => [V.Key] -> VtyWidget t m (Event t KeyCombo)
426−keys = keyCombos . Set.fromList . fmap (,[])
348+instance (Monad m, Reflex t) => HasFocusReader t (FocusReader t m) where
349+ focus = FocusReader ask
350+ localFocus f = FocusReader . local f . unFocusReader
427351
428−-- | Emit an event that fires whenever the provided key combination occurs
429−keyCombo
430− :: (Reflex t, Monad m)
431− => KeyCombo
432− -> VtyWidget t m (Event t KeyCombo)
433−keyCombo = keyCombos . Set.singleton
352+deriving instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (FocusReader t m)
353+deriving instance NotReady t m => NotReady t (FocusReader t m)
354+deriving instance PerformEvent t m => PerformEvent t (FocusReader t m)
355+deriving instance PostBuild t m => PostBuild t (FocusReader t m)
356+deriving instance TriggerEvent t m => TriggerEvent t (FocusReader t m)
357+instance HasImageWriter t m => HasImageWriter t (FocusReader t m)
434358
435−-- | Emit an event that fires whenever any of the provided key combinations occur
436−keyCombos
359+instance (Adjustable t m, MonadFix m, MonadHold t m) => Adjustable t (FocusReader t m) where
360+ runWithReplace (FocusReader a) e = FocusReader $ runWithReplace a $ fmap unFocusReader e
361+ traverseIntMapWithKeyWithAdjust f m e = FocusReader $ traverseIntMapWithKeyWithAdjust (\k v -> unFocusReader $ f k v) m e
362+ traverseDMapWithKeyWithAdjust f m e = FocusReader $ traverseDMapWithKeyWithAdjust (\k v -> unFocusReader $ f k v) m e
363+ traverseDMapWithKeyWithAdjustWithMove f m e = FocusReader $ traverseDMapWithKeyWithAdjustWithMove (\k v -> unFocusReader $ f k v) m e
364+
365+instance MonadTrans (FocusReader t) where
366+ lift = FocusReader . lift
367+
368+instance MFunctor (FocusReader t) where
369+ hoist f = FocusReader . hoist f . unFocusReader
370+
371+instance MonadNodeId m => MonadNodeId (FocusReader t m)
372+
373+-- | Run a 'FocusReader' action with the given focus value
374+runFocusReader
437375 :: (Reflex t, Monad m)
438− => Set KeyCombo
439− -> VtyWidget t m (Event t KeyCombo)
440−keyCombos ks = do
441− i <- input
442− return $ fforMaybe i $ \case
443− V.EvKey k m -> if Set.member (k, m) ks
444− then Just (k, m)
445− else Nothing
446− _ -> Nothing
376+ => Dynamic t Bool
377+ -> FocusReader t m a
378+ -> m a
379+runFocusReader b = flip runReaderT b . unFocusReader
447380
448−-- | A plain split of the available space into vertically stacked panes.
449−-- No visual separator is built in here.
450−splitV :: (Reflex t, Monad m, MonadNodeId m)
451− => Dynamic t (Int -> Int)
452− -- ^ Function used to determine size of first pane based on available size
453− -> Dynamic t (Bool, Bool)
454− -- ^ How to focus the two sub-panes, given that we are focused.
455− -> VtyWidget t m a
456− -- ^ Widget for first pane
457− -> VtyWidget t m b
458− -- ^ Widget for second pane
459− -> VtyWidget t m (a,b)
460−splitV sizeFunD focD wA wB = do
461− dw <- displayWidth
462− dh <- displayHeight
463− let regA = DynRegion
464− { _dynRegion_left = pure 0
465− , _dynRegion_top = pure 0
466− , _dynRegion_width = dw
467− , _dynRegion_height = sizeFunD <*> dh
468− }
469− regB = DynRegion
470− { _dynRegion_left = pure 0
471− , _dynRegion_top = _dynRegion_height regA
472− , _dynRegion_width = dw
473− , _dynRegion_height = liftA2 (-) dh (_dynRegion_height regA)
474− }
475− ra <- pane regA (fst <$> focD) wA
476− rb <- pane regB (snd <$> focD) wB
477− return (ra,rb)
478−
479−-- | A plain split of the available space into horizontally stacked panes.
480−-- No visual separator is built in here.
481−splitH :: (Reflex t, Monad m, MonadNodeId m)
482− => Dynamic t (Int -> Int)
483− -- ^ Function used to determine size of first pane based on available size
484− -> Dynamic t (Bool, Bool)
485− -- ^ How to focus the two sub-panes, given that we are focused.
486− -> VtyWidget t m a
487− -- ^ Widget for first pane
488− -> VtyWidget t m b
489− -- ^ Widget for second pane
490− -> VtyWidget t m (a,b)
491−splitH sizeFunD focD wA wB = do
492− dw <- displayWidth
493− dh <- displayHeight
494− let regA = DynRegion
495− { _dynRegion_left = pure 0
496− , _dynRegion_top = pure 0
497− , _dynRegion_width = sizeFunD <*> dw
498− , _dynRegion_height = dh
499− }
500− regB = DynRegion
501− { _dynRegion_left = _dynRegion_width regA
502− , _dynRegion_top = pure 0
503− , _dynRegion_width = liftA2 (-) dw (_dynRegion_width regA)
504− , _dynRegion_height = dh
505− }
506− liftA2 (,) (pane regA (fmap fst focD) wA) (pane regB (fmap snd focD) wB)
507−
508−-- | A split of the available space into two parts with a draggable separator.
509−-- Starts with half the space allocated to each, and the first pane has focus.
510−-- Clicking in a pane switches focus.
511−splitVDrag :: (Reflex t, MonadFix m, MonadHold t m, MonadNodeId m)
512− => VtyWidget t m ()
513− -> VtyWidget t m a
514− -> VtyWidget t m b
515− -> VtyWidget t m (a,b)
516−splitVDrag wS wA wB = do
517− dh <- displayHeight
518− dw <- displayWidth
519− h0 <- sample $ current dh -- TODO
520− dragE <- drag V.BLeft
521− let splitter0 = h0 `div` 2
522− rec splitterCheckpoint <- holdDyn splitter0 $ leftmost [fst <$> ffilter snd dragSplitter, resizeSplitter]
523− splitterPos <- holdDyn splitter0 $ leftmost [fst <$> dragSplitter, resizeSplitter]
524− splitterFrac <- holdDyn ((1::Double) / 2) $ ffor (attach (current dh) (fst <$> dragSplitter)) $ \(h, x) ->
525− fromIntegral x / (max 1 (fromIntegral h))
526− let dragSplitter = fforMaybe (attach (current splitterCheckpoint) dragE) $
527− \(splitterY, Drag (_, fromY) (_, toY) _ _ end) ->
528− if splitterY == fromY then Just (toY, end) else Nothing
529− regA = DynRegion 0 0 dw splitterPos
530− regS = DynRegion 0 splitterPos dw 1
531− regB = DynRegion 0 (splitterPos + 1) dw (dh - splitterPos - 1)
532− resizeSplitter = ffor (attach (current splitterFrac) (updated dh)) $
533− \(frac, h) -> round (frac * fromIntegral h)
534− focA <- holdDyn True $ leftmost
535− [ True <$ mA
536− , False <$ mB
537− ]
538− (mA, rA) <- pane regA focA $ withMouseDown wA
539− pane regS (pure False) wS
540− (mB, rB) <- pane regB (not <$> focA) $ withMouseDown wB
541− return (rA, rB)
542− where
543− withMouseDown x = do
544− m <- mouseDown V.BLeft
545− x' <- x
546− return (m, x')
547−
548−-- | Fill the background with a particular character.
549−fill :: (Reflex t, Monad m) => Char -> VtyWidget t m ()
550−fill c = do
551− dw <- displayWidth
552− dh <- displayHeight
553− let fillImg = current $ liftA2 (\w h -> [V.charFill V.defAttr c w h]) dw dh
554− tellImages fillImg
555−
556−-- | Fill the background with the bottom
557−hRule :: (Reflex t, Monad m) => BoxStyle -> VtyWidget t m ()
558−hRule boxStyle = fill (_boxStyle_s boxStyle)
559−
560−-- | Defines a set of symbols to use to draw the outlines of boxes
561−-- C.f. https://en.wikipedia.org/wiki/Box-drawing_character
562−data BoxStyle = BoxStyle
563− { _boxStyle_nw :: Char
564− , _boxStyle_n :: Char
565− , _boxStyle_ne :: Char
566− , _boxStyle_e :: Char
567− , _boxStyle_se :: Char
568− , _boxStyle_s :: Char
569− , _boxStyle_sw :: Char
570− , _boxStyle_w :: Char
571− }
381+-- * "Image" output
572382
573−instance Default BoxStyle where
574− def = singleBoxStyle
575−
576−-- | A box style that uses hyphens and pipe characters. Doesn't handle
577−-- corners very well.
578−hyphenBoxStyle :: BoxStyle
579−hyphenBoxStyle = BoxStyle '-' '-' '-' '|' '-' '-' '-' '|'
580−
581−-- | A single line box style
582−singleBoxStyle :: BoxStyle
583−singleBoxStyle = BoxStyle '┌' '─' '┐' '│' '┘' '─' '└' '│'
584−
585−-- | A thick single line box style
586−thickBoxStyle :: BoxStyle
587−thickBoxStyle = BoxStyle '┏' '━' '┓' '┃' '┛' '━' '┗' '┃'
588−
589−-- | A double line box style
590−doubleBoxStyle :: BoxStyle
591−doubleBoxStyle = BoxStyle '╔' '═' '╗' '║' '╝' '═' '╚' '║'
592−
593−-- | A single line box style with rounded corners
594−roundedBoxStyle :: BoxStyle
595−roundedBoxStyle = BoxStyle '╭' '─' '╮' '│' '╯' '─' '╰' '│'
596−
597−-- | Draws a titled box in the provided style and a child widget inside of that box
598−boxTitle :: (Monad m, Reflex t, MonadNodeId m)
599− => Behavior t BoxStyle
600− -> Text
601− -> VtyWidget t m a
602− -> VtyWidget t m a
603−boxTitle boxStyle title child = do
604− dh <- displayHeight
605− dw <- displayWidth
606− let boxReg = DynRegion (pure 0) (pure 0) dw dh
607− innerReg = DynRegion (pure 1) (pure 1) (subtract 2 <$> dw) (subtract 2 <$> dh)
608− tellImages (boxImages <$> boxStyle <*> currentRegion boxReg)
609− tellImages (fmap (\r -> [regionBlankImage r]) (currentRegion innerReg))
610− pane innerReg (pure True) child
611− where
612− boxImages :: BoxStyle -> Region -> [Image]
613− boxImages style (Region left top width height) =
614− let right = left + width - 1
615− bottom = top + height - 1
616− sides =
617− [ withinImage (Region (left + 1) top (width - 2) 1) $
618− V.text' V.defAttr $
619− hPadText title (_boxStyle_n style) (width - 2)
620− , withinImage (Region right (top + 1) 1 (height - 2)) $
621− V.charFill V.defAttr (_boxStyle_e style) 1 (height - 2)
622− , withinImage (Region (left + 1) bottom (width - 2) 1) $
623− V.charFill V.defAttr (_boxStyle_s style) (width - 2) 1
624− , withinImage (Region left (top + 1) 1 (height - 2)) $
625− V.charFill V.defAttr (_boxStyle_w style) 1 (height - 2)
626− ]
627− corners =
628− [ withinImage (Region left top 1 1) $
629− V.char V.defAttr (_boxStyle_nw style)
630− , withinImage (Region right top 1 1) $
631− V.char V.defAttr (_boxStyle_ne style)
632− , withinImage (Region right bottom 1 1) $
633− V.char V.defAttr (_boxStyle_se style)
634− , withinImage (Region left bottom 1 1) $
635− V.char V.defAttr (_boxStyle_sw style)
636− ]
637− in sides ++ if width > 1 && height > 1 then corners else []
638− hPadText :: T.Text -> Char -> Int -> T.Text
639− hPadText t c l = if lt >= l
640− then t
641− else left <> t <> right
642− where
643− lt = T.length t
644− delta = l - lt
645− mkHalf n = T.replicate (n `div` 2) (T.singleton c)
646− left = mkHalf $ delta + 1
647− right = mkHalf delta
648−
649−-- | A box without a title
650−box :: (Monad m, Reflex t, MonadNodeId m)
651− => Behavior t BoxStyle
652− -> VtyWidget t m a
653− -> VtyWidget t m a
654−box boxStyle = boxTitle boxStyle mempty
655−
656−-- | A box whose style is static
657−boxStatic
658− :: (Reflex t, Monad m, MonadNodeId m)
659− => BoxStyle
660− -> VtyWidget t m a
661− -> VtyWidget t m a
662−boxStatic = box . pure
663−
664−-- | Configuration options for displaying "rich" text
665−data RichTextConfig t = RichTextConfig
666− { _richTextConfig_attributes :: Behavior t V.Attr
667− }
383+-- | A class for widgets that can produce images to draw to the display
384+class (Reflex t, Monad m) => HasImageWriter t m | m -> t where
385+ -- | Send images upstream for rendering
386+ tellImages :: Behavior t [Image] -> m ()
387+ default tellImages :: (f m' ~ m, Monad m', MonadTrans f, HasImageWriter t m') => Behavior t [Image] -> m ()
388+ tellImages = lift . tellImages
389+ -- | Apply a transformation to the images produced by the child actions
390+ mapImages :: (Behavior t [Image] -> Behavior t [Image]) -> m a -> m a
391+ default mapImages :: (f m' ~ m, Monad m', MFunctor f, HasImageWriter t m') => (Behavior t [Image] -> Behavior t [Image]) -> m a -> m a
392+ mapImages f = hoist (mapImages f)
393+
394+-- | A widget that can produce images to draw onto the display
395+newtype ImageWriter t m a = ImageWriter
396+ { unImageWriter :: BehaviorWriterT t [Image] m a }
397+ deriving
398+ ( Functor
399+ , Applicative
400+ , Monad
401+ , MonadFix
402+ , MonadHold t
403+ , MonadIO
404+ , MonadRef
405+ , MonadReflexCreateTrigger t
406+ , MonadSample t
407+ , NotReady t
408+ , PerformEvent t
409+ , PostBuild t
410+ , TriggerEvent t
411+ )
412+
413+instance MonadTrans (ImageWriter t) where
414+ lift = ImageWriter . lift
415+
416+instance MFunctor (ImageWriter t) where
417+ hoist f = ImageWriter . (hoist f) . unImageWriter
418+
419+instance (Adjustable t m, MonadFix m, MonadHold t m) => Adjustable t (ImageWriter t m) where
420+ runWithReplace (ImageWriter a) e = ImageWriter $ runWithReplace a $ fmap unImageWriter e
421+ traverseIntMapWithKeyWithAdjust f m e = ImageWriter $ traverseIntMapWithKeyWithAdjust (\k v -> unImageWriter $ f k v) m e
422+ traverseDMapWithKeyWithAdjust f m e = ImageWriter $ traverseDMapWithKeyWithAdjust (\k v -> unImageWriter $ f k v) m e
423+ traverseDMapWithKeyWithAdjustWithMove f m e = ImageWriter $ traverseDMapWithKeyWithAdjustWithMove (\k v -> unImageWriter $ f k v) m e
668424
669−instance Reflex t => Default (RichTextConfig t) where
670− def = RichTextConfig $ pure V.defAttr
425+instance HasImageWriter t m => HasImageWriter t (ReaderT x m)
426+instance HasImageWriter t m => HasImageWriter t (BehaviorWriterT t x m)
427+instance HasImageWriter t m => HasImageWriter t (DynamicWriterT t x m)
428+instance HasImageWriter t m => HasImageWriter t (EventWriterT t x m)
429+instance HasImageWriter t m => HasImageWriter t (NodeIdT m)
671430
672−-- | A widget that displays text with custom time-varying attributes
673−richText
431+instance (Monad m, Reflex t) => HasImageWriter t (ImageWriter t m) where
432+ tellImages = ImageWriter . tellBehavior
433+ mapImages f (ImageWriter x) = ImageWriter $ do
434+ (a, images) <- lift $ runBehaviorWriterT x
435+ tellBehavior $ f images
436+ pure a
437+
438+instance HasDisplayRegion t m => HasDisplayRegion t (ImageWriter t m)
439+instance HasFocusReader t m => HasFocusReader t (ImageWriter t m)
440+
441+-- | Run a widget that can produce images
442+runImageWriter
674443 :: (Reflex t, Monad m)
675− => RichTextConfig t
676− -> Behavior t Text
677− -> VtyWidget t m ()
678−richText cfg t = do
679− dw <- displayWidth
680− let img = (\w a s -> [wrapText w a s])
681− <$> current dw
682− <*> _richTextConfig_attributes cfg
683− <*> t
684− tellImages img
685− where
686− wrapText maxWidth attrs = V.vertCat
687− . concatMap (fmap (V.string attrs . T.unpack) . TZ.wrapWithOffset maxWidth 0)
688− . T.split (=='\n')
444+ => ImageWriter t m a
445+ -> m (a, Behavior t [Image])
446+runImageWriter = runBehaviorWriterT . unImageWriter
447+
448+-- * Theming
449+
450+-- | A class for things that can be visually styled
451+class (Reflex t, Monad m) => HasTheme t m | m -> t where
452+ theme :: m (Behavior t V.Attr)
453+ default theme :: (f m' ~ m, Monad m', MonadTrans f, HasTheme t m') => m (Behavior t V.Attr)
454+ theme = lift theme
455+ localTheme :: (Behavior t V.Attr -> Behavior t V.Attr) -> m a -> m a
456+ default localTheme :: (f m' ~ m, Monad m', MFunctor f, HasTheme t m') => (Behavior t V.Attr -> Behavior t V.Attr) -> m a -> m a
457+ localTheme f = hoist (localTheme f)
458+
459+instance HasTheme t m => HasTheme t (ReaderT x m)
460+instance HasTheme t m => HasTheme t (BehaviorWriterT t x m)
461+instance HasTheme t m => HasTheme t (DynamicWriterT t x m)
462+instance HasTheme t m => HasTheme t (EventWriterT t x m)
463+instance HasTheme t m => HasTheme t (NodeIdT m)
464+instance HasTheme t m => HasTheme t (Input t m)
465+instance HasTheme t m => HasTheme t (ImageWriter t m)
466+instance HasTheme t m => HasTheme t (DisplayRegion t m)
467+instance HasTheme t m => HasTheme t (FocusReader t m)
468+
469+-- | A widget that has access to theme information
470+newtype ThemeReader t m a = ThemeReader
471+ { unThemeReader :: ReaderT (Behavior t V.Attr) m a }
472+ deriving
473+ ( Functor
474+ , Applicative
475+ , Monad
476+ , MonadFix
477+ , MonadHold t
478+ , MonadIO
479+ , MonadRef
480+ , MonadSample t
481+ )
482+
483+instance (Monad m, Reflex t) => HasTheme t (ThemeReader t m) where
484+ theme = ThemeReader ask
485+ localTheme f = ThemeReader . local f . unThemeReader
486+
487+deriving instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ThemeReader t m)
488+deriving instance NotReady t m => NotReady t (ThemeReader t m)
489+deriving instance PerformEvent t m => PerformEvent t (ThemeReader t m)
490+deriving instance PostBuild t m => PostBuild t (ThemeReader t m)
491+deriving instance TriggerEvent t m => TriggerEvent t (ThemeReader t m)
492+instance HasImageWriter t m => HasImageWriter t (ThemeReader t m)
493+
494+instance (Adjustable t m, MonadFix m, MonadHold t m) => Adjustable t (ThemeReader t m) where
495+ runWithReplace (ThemeReader a) e = ThemeReader $ runWithReplace a $ fmap unThemeReader e
496+ traverseIntMapWithKeyWithAdjust f m e = ThemeReader $ traverseIntMapWithKeyWithAdjust (\k v -> unThemeReader $ f k v) m e
497+ traverseDMapWithKeyWithAdjust f m e = ThemeReader $ traverseDMapWithKeyWithAdjust (\k v -> unThemeReader $ f k v) m e
498+ traverseDMapWithKeyWithAdjustWithMove f m e = ThemeReader $ traverseDMapWithKeyWithAdjustWithMove (\k v -> unThemeReader $ f k v) m e
499+
500+instance MonadTrans (ThemeReader t) where
501+ lift = ThemeReader . lift
689502
690−-- | Renders text, wrapped to the container width
691−text
503+instance MFunctor (ThemeReader t) where
504+ hoist f = ThemeReader . hoist f . unThemeReader
505+
506+instance MonadNodeId m => MonadNodeId (ThemeReader t m)
507+
508+-- | Run a 'ThemeReader' action with the given focus value
509+runThemeReader
692510 :: (Reflex t, Monad m)
693− => Behavior t Text
694− -> VtyWidget t m ()
695−text = richText def
696−
697−-- | Scrollable text widget. The output pair exposes the current scroll position and total number of lines (including those
698−-- that are hidden)
699−scrollableText
700− :: forall t m. (Reflex t, MonadHold t m, MonadFix m)
701− => Event t Int
702− -- ^ Number of lines to scroll by
703− -> Behavior t Text
704− -> VtyWidget t m (Behavior t (Int, Int))
705− -- ^ (Current scroll position, total number of lines)
706−scrollableText scrollBy t = do
707− dw <- displayWidth
708− let imgs = wrap <$> current dw <*> t
709− kup <- key V.KUp
710− kdown <- key V.KDown
711− m <- mouseScroll
712− let requestedScroll :: Event t Int
713− requestedScroll = leftmost
714− [ 1 <$ kdown
715− , (-1) <$ kup
716− , ffor m $ \case
717− ScrollDirection_Up -> (-1)
718− ScrollDirection_Down -> 1
719− , scrollBy
720− ]
721− updateLine maxN delta ix = min (max 0 (ix + delta)) maxN
722− lineIndex :: Dynamic t Int <- foldDyn (\(maxN, delta) ix -> updateLine (maxN - 1) delta ix) 0 $
723− attach (length <$> imgs) requestedScroll
724− tellImages $ fmap ((:[]) . V.vertCat) $ drop <$> current lineIndex <*> imgs
725− return $ (,) <$> ((+) <$> current lineIndex <*> pure 1) <*> (length <$> imgs)
726− where
727− wrap maxWidth = concatMap (fmap (V.string V.defAttr . T.unpack) . TZ.wrapWithOffset maxWidth 0) . T.split (=='\n')
511+ => Behavior t V.Attr
512+ -> ThemeReader t m a
513+ -> m a
514+runThemeReader b = flip runReaderT b . unThemeReader
515+
516+
517+-- ** Manipulating images
518+
519+-- | Translates and crops an 'Image' so that it is contained by
520+-- the given 'Region'.
521+withinImage
522+ :: Region
523+ -> Image
524+ -> Image
525+withinImage (Region left top width height)
526+ | width < 0 || height < 0 = withinImage (Region left top 0 0)
527+ | otherwise = V.translate left top . V.crop width height
528+
529+-- | Crop a behavior of images to a behavior of regions. See 'withinImage'.
530+imagesInRegion
531+ :: Reflex t
532+ => Behavior t Region
533+ -> Behavior t [Image]
534+ -> Behavior t [Image]
535+imagesInRegion reg = liftA2 (\r is -> map (withinImage r) is) reg
536+
537+-- * Running sub-widgets
538+
539+-- | Low-level widget combinator that runs a child widget within
540+-- a given region and context. This widget filters and modifies the input
541+-- that the child widget receives such that:
542+-- * unfocused widgets receive no key events
543+-- * mouse inputs outside the region are ignored
544+-- * mouse inputs inside the region have their coordinates translated such
545+-- that (0,0) is the top-left corner of the region
546+pane
547+ :: (Reflex t, Monad m, HasInput t m, HasImageWriter t m, HasDisplayRegion t m, HasFocusReader t m)
548+ => Dynamic t Region
549+ -> Dynamic t Bool -- ^ Whether the widget should be focused when the parent is.
550+ -> m a
551+ -> m a
552+pane dr foc child = localRegion (const dr) $
553+ mapImages (imagesInRegion $ current dr) $
554+ localFocus (const foc) $
555+ inputInFocusedRegion >>= \e -> localInput (const e) child
728556
729−-- | Renders any behavior whose value can be converted to
730−-- 'String' as text
731−display
732− :: (Reflex t, Monad m, Show a)
733− => Behavior t a
734− -> VtyWidget t m ()
735−display a = text $ T.pack . show <$> a
557+-- * Misc
736558
737559-- | A widget that draws nothing
738−blank :: Monad m => VtyWidget t m ()
560+blank :: Monad m => m ()
739561blank = return ()