@@ -1,225 +1,154 @@
1−{-|
2−Module: Reflex.Vty.Widget
3−Description: Basic set of widgets and building blocks for reflex-vty applications
4−-}
5−{-# Language UndecidableInstances #-}
6−
7−module Reflex.Vty.Widget where
1+{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE FunctionalDependencies #-}
4+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5+{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE RankNTypes #-}
8+{-# LANGUAGE RecursiveDo #-}
9+{-# LANGUAGE TypeFamilies #-}
10+module Reflex.Vty.Widget
11+ ( VtyWidgetCtx(..)
12+ , VtyWidget(..)
13+ , VtyWidgetOut(..)
14+ , runVtyWidget
15+ , mainWidget
16+ , mainWidgetWithHandle
17+ , HasDisplaySize(..)
18+ , displayWidth
19+ , displayHeight
20+ , HasFocus(..)
21+ , HasVtyInput(..)
22+ , Region(..)
23+ , regionSize
24+ , regionBlankImage
25+ , Drag (..)
26+ , drag
27+ , mouseDown
28+ , pane
29+ , modifyImages
30+ , tellImages
31+ , tellShutdown
32+ , wrapString
33+ , splitV
34+ , splitVDrag
35+ , fractionSz
36+ , box
37+ , string
38+ ) where
839
940import Control.Applicative (liftA2)
1041import Control.Monad.Fix (MonadFix)
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)
17−import Data.Set (Set)
18−import qualified Data.Set as Set
19−import Graphics.Vty (Image)
20−import qualified Graphics.Vty as V
42+import Control.Monad.Trans (lift)
43+import Control.Monad.Trans.Reader (ReaderT, runReaderT, asks, ask)
44+import Control.Monad.Trans.Writer (WriterT, runWriterT, censor, tell)
45+import Graphics.Vty (Image, Attr)
46+import qualified Graphics.Vty as V
2147import Reflex
22−import Reflex.Class ()
23−import Reflex.Host.Class (MonadReflexCreateTrigger)
48+
2449import Reflex.Vty.Host
2550
26−-- * Running a vty application
27−
28−-- | Sets up the top-level context for a vty widget and runs it with that context
29−mainWidgetWithHandle
30− :: V.Vty
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 ()))
40− -> IO ()
51+-- | The context within which a 'VtyWidget' runs
52+data VtyWidgetCtx t = VtyWidgetCtx
53+ { _vtyWidgetCtx_size :: Dynamic t (Int,Int)
54+ -- ^ The width and height of the region allocated to the widget.
55+ , _vtyWidgetCtx_focus :: Dynamic t Bool
56+ -- ^ Whether the widget should behave as if it has focus for keyboard input.
57+ , _vtyWidgetCtx_input :: Event t VtyEvent
58+ -- ^ User input events that the widget's parent chooses to share. These will generally
59+ -- be filtered for relevance:
60+ -- * Keyboard inputs are restricted to focused widgets
61+ -- * Mouse inputs are restricted to the region in which the widget resides and are
62+ -- translated into its internal coordinates.
63+ }
64+
65+-- | The output of a 'VtyWidget'
66+data VtyWidgetOut t = VtyWidgetOut
67+ { _vtyWidgetOut_images :: Behavior t [Image]
68+ -- ^ The visual output of the 'VtyWidget'
69+ , _vtyWidgetOut_shutdown :: Event t ()
70+ }
71+
72+instance Reflex t => Semigroup (VtyWidgetOut t) where
73+ wo <> wo' = VtyWidgetOut
74+ { _vtyWidgetOut_images = _vtyWidgetOut_images wo <> _vtyWidgetOut_images wo'
75+ , _vtyWidgetOut_shutdown = _vtyWidgetOut_shutdown wo <> _vtyWidgetOut_shutdown wo'
76+ }
77+
78+instance (Reflex t) => Monoid (VtyWidgetOut t) where
79+ mempty = VtyWidgetOut mempty mempty
80+ mappend wo wo' = wo <> wo'
81+
82+newtype VtyWidget t m a = VtyWidget { unVtyWidget :: WriterT (VtyWidgetOut t) (ReaderT (VtyWidgetCtx t) m) a }
83+ deriving (Functor, Applicative, Monad, MonadSample t, MonadHold t, MonadFix)
84+
85+-- | Runs a 'VtyWidget' with a given context
86+runVtyWidget :: (Reflex t)
87+ => VtyWidgetCtx t
88+ -> VtyWidget t m a
89+ -> m (a, VtyWidgetOut t)
90+runVtyWidget ctx w = runReaderT (runWriterT (unVtyWidget w)) ctx
91+
92+-- | Sets up the top-level context for a 'VtyWidget' and runs it with that context
93+mainWidgetWithHandle :: V.Vty -> (forall t m. MonadVtyApp t m => VtyWidget t m ()) -> IO ()
4194mainWidgetWithHandle vty child =
4295 runVtyAppWithHandle vty $ \dr0 inp -> do
4396 size <- holdDyn dr0 $ fforMaybe inp $ \case
4497 V.EvResize w h -> Just (w, h)
4598 _ -> Nothing
46− let inp' = fforMaybe inp $ \case
47− V.EvResize {} -> Nothing
48− x -> Just x
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
99+ let ctx = VtyWidgetCtx
100+ { _vtyWidgetCtx_size = size
101+ , _vtyWidgetCtx_input = inp
102+ , _vtyWidgetCtx_focus = constDyn True
103+ }
104+ ((), wo) <- runVtyWidget ctx child
57105 return $ VtyResult
58− { _vtyResult_picture = fmap (V.picForLayers . reverse) images
59− , _vtyResult_shutdown = shutdown
106+ { _vtyResult_picture = fmap (V.picForLayers . reverse) (_vtyWidgetOut_images wo)
107+ , _vtyResult_shutdown = _vtyWidgetOut_shutdown wo
60108 }
61109
62−-- | The output of a vty widget
63−data VtyWidgetOut t = VtyWidgetOut
64− { _vtyWidgetOut_shutdown :: Event t ()
65− }
66−
67110-- | Like 'mainWidgetWithHandle', but uses a default vty configuration
68−mainWidget
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 ()))
78− -> IO ()
111+mainWidget :: (forall t m. MonadVtyApp t m => VtyWidget t m ()) -> IO ()
79112mainWidget child = do
80113 vty <- getDefaultVty
81114 mainWidgetWithHandle vty child
82115
83−-- * Input Events
116+class (Reflex t, Monad m) => HasDisplaySize t m | m -> t where
117+ displaySize :: m (Dynamic t (Int, Int))
118+
119+instance (Reflex t, Monad m) => HasDisplaySize t (VtyWidget t m) where
120+ displaySize = VtyWidget . lift $ asks _vtyWidgetCtx_size
121+
122+displayWidth :: HasDisplaySize t m => m (Dynamic t Int)
123+displayWidth = fmap fst <$> displaySize
84124
85−-- | A class for things that can receive vty events as input
86−class HasInput t m | m -> t where
125+displayHeight :: HasDisplaySize t m => m (Dynamic t Int)
126+displayHeight = fmap snd <$> displaySize
127+
128+class HasVtyInput t m | m -> t where
87129 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− )
113−
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
149−
150−-- | Type synonym for a key and modifier combination
151−type KeyCombo = (V.Key, [V.Modifier])
152−
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 . (,[])
156−
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 (,[])
160−
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
180130
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
131+instance (Reflex t, Monad m) => HasVtyInput t (VtyWidget t m) where
132+ input = VtyWidget . lift $ asks _vtyWidgetCtx_input
133+
134+class HasFocus t m | m -> t where
135+ focus :: m (Dynamic t Bool)
136+
137+instance (Reflex t, Monad m) => HasFocus t (VtyWidget t m) where
138+ focus = VtyWidget . lift $ asks _vtyWidgetCtx_focus
219139
220−-- * Getting and setting the display region
140+class (Reflex t, Monad m) => ImageWriter t m | m -> t where
141+ tellImages :: Behavior t [Image] -> m ()
142+
143+instance (Reflex t, Monad m) => ImageWriter t (VtyWidget t m) where
144+ tellImages imgs = VtyWidget $ tell (mempty { _vtyWidgetOut_images = imgs })
145+
146+class (Reflex t, Monad m) => Shutdown t m where
147+ tellShutdown :: Event t () -> m ()
148+
149+instance (Reflex t, Monad m) => Shutdown t (VtyWidget t m) where
150+ tellShutdown sd = VtyWidget $ tell (mempty { _vtyWidgetOut_shutdown = sd })
221151
222−-- | A chunk of the display area
223152data Region = Region
224153 { _region_left :: Int
225154 , _region_top :: Int
@@ -228,334 +157,198 @@ data Region = Region
228157 }
229158 deriving (Show, Read, Eq, Ord)
230159
231−-- | A region that occupies no space.
232−nilRegion :: Region
233−nilRegion = Region 0 0 0 0
234−
235−-- | The width and height of a 'Region'
236160regionSize :: Region -> (Int, Int)
237161regionSize (Region _ _ w h) = (w, h)
238162
239−-- | Produces an 'Image' that fills a region with space characters
240−regionBlankImage :: V.Attr -> Region -> Image
241−regionBlankImage attr r@(Region _ _ width height) =
242− withinImage r $ V.charFill attr ' ' width height
243−
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− )
282−
283−instance (Monad m, Reflex t) => HasDisplayRegion t (DisplayRegion t m) where
284− askRegion = DisplayRegion ask
285− localRegion f = DisplayRegion . local f . unDisplayRegion
286−
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)
294−
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
300−
301−instance MonadTrans (DisplayRegion t) where
302− lift = DisplayRegion . lift
303−
304−instance MFunctor (DisplayRegion t) where
305− hoist f = DisplayRegion . hoist f . unDisplayRegion
306−
307−instance MonadNodeId m => MonadNodeId (DisplayRegion t m)
308−
309−-- | Run a 'DisplayRegion' action with a given 'Region'
310−runDisplayRegion
311− :: (Reflex t, Monad m)
312− => Dynamic t Region
313− -> DisplayRegion t m a
314− -> m a
315−runDisplayRegion r = flip runReaderT r . unDisplayRegion
316−
317−-- * Getting focus state
318−
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− )
347−
348−instance (Monad m, Reflex t) => HasFocusReader t (FocusReader t m) where
349− focus = FocusReader ask
350− localFocus f = FocusReader . local f . unFocusReader
351−
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)
358−
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
163+pane
375164 :: (Reflex t, Monad m)
376− => Dynamic t Bool
377− -> FocusReader t m a
378− -> m a
379−runFocusReader b = flip runReaderT b . unFocusReader
380−
381−-- * "Image" output
165+ => Dynamic t Region -- ^ Region into which we should draw the widget (in coordinates relative to our own)
166+ -> Dynamic t Bool -- ^ Whether the widget should be focused when the parent is.
167+ -> VtyWidget t m a
168+ -> VtyWidget t m a
169+pane reg foc child = VtyWidget $ do
170+ ctx <- lift ask
171+ let ctx' = VtyWidgetCtx
172+ { _vtyWidgetCtx_input = leftmost -- TODO: think about this leftmost more.
173+ [ ffor (updated reg) $ \(Region _ _ w h) -> V.EvResize w h
174+ , fmapMaybe id $
175+ attachWith (\(r,f) e -> filterInput r f e)
176+ (liftA2 (,) (current reg) (current foc))
177+ (_vtyWidgetCtx_input ctx)
178+ ]
179+ , _vtyWidgetCtx_focus = liftA2 (&&) (_vtyWidgetCtx_focus ctx) foc
180+ , _vtyWidgetCtx_size = fmap regionSize reg }
181+ (result, wo) <- lift . lift $ runVtyWidget ctx' child
182+ let images = _vtyWidgetOut_images wo
183+ images' = liftA2 (\r is -> map (withinImage r) is) (current reg) images
184+ wo' = wo { _vtyWidgetOut_images = images' }
185+ tell wo'
186+ return result
187+ where
188+ -- Filters input such that:
189+ -- * unfocused widgets receive no key events
190+ -- * mouse inputs outside the region are ignored
191+ -- * mouse inputs inside the region have their coordinates translated
192+ -- such that (0,0) is the top-left corner of the region
193+ filterInput :: Region -> Bool -> VtyEvent -> Maybe VtyEvent
194+ filterInput (Region l t w h) focused e = case e of
195+ V.EvKey _ _ | not focused -> Nothing
196+ V.EvMouseDown x y btn m -> mouse (\u v -> V.EvMouseDown u v btn m) x y
197+ V.EvMouseUp x y btn -> mouse (\u v -> V.EvMouseUp u v btn) x y
198+ _ -> Just e
199+ where
200+ mouse con x y
201+ | or [ x < l
202+ , y < t
203+ , x >= l + w
204+ , y >= t + h ] = Nothing
205+ | otherwise =
206+ Just (con (x - l) (y - t))
207+
208+data Drag = Drag
209+ { _drag_from :: (Int, Int) -- ^ Where the drag began
210+ , _drag_to :: (Int, Int) -- ^ Where the mouse currently is
211+ , _drag_button :: V.Button -- ^ Which mouse button is dragging
212+ , _drag_modifiers :: [V.Modifier] -- ^ What modifiers are held
213+ , _drag_end :: Bool -- ^ Whether the drag ended (the mouse button was released)
214+ }
215+ deriving (Eq, Ord, Show)
382216
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
424−
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)
430−
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
443− :: (Reflex t, Monad m)
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
502−
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
217+drag
218+ :: (Reflex t, MonadFix m, MonadHold t m)
219+ => V.Button
220+ -> VtyWidget t m (Event t Drag)
221+drag btn = do
222+ inp <- input
223+ let f :: Drag -> V.Event -> Maybe Drag
224+ f (Drag from _ _ mods end) = \case
225+ V.EvMouseDown x y btn' mods'
226+ | end -> Just $ Drag (x,y) (x,y) btn' mods' False
227+ | btn == btn' -> Just $ Drag from (x,y) btn mods' False
228+ | otherwise -> Nothing -- Ignore other buttons.
229+ V.EvMouseUp x y (Just btn')
230+ | end -> Nothing
231+ | btn == btn' -> Just $ Drag from (x,y) btn mods True
232+ | otherwise -> Nothing
233+ V.EvMouseUp x y Nothing -- Terminal doesn't specify mouse up button,
234+ -- assume it's the right one.
235+ | end -> Nothing
236+ | otherwise -> Just $ Drag from (x,y) btn mods True
237+ _ -> Nothing
238+ rec let newDrag = attachWithMaybe f (current dragD) inp
239+ dragD <- holdDyn (Drag (0,0) (0,0) V.BLeft [] True) -- gross, but ok.
240+ newDrag
241+ return (updated dragD)
242+
243+mouseDown
510244 :: (Reflex t, Monad m)
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
245+ => V.Button
246+ -> VtyWidget t m (Event t VtyEvent)
247+mouseDown btn = do
248+ i <- input
249+ return $ fforMaybe i $ \x -> case x of
250+ V.EvMouseDown _ _ btn' _ -> if btn == btn' then Just x else Nothing
251+ _ -> Nothing
518252
519−-- | Translates and crops an 'Image' so that it is contained by
520−-- the given 'Region'.
521−withinImage
522− :: Region
523− -> Image
524− -> Image
253+-- | A plain split of the available space into vertically stacked panes.
254+-- No visual separator is built in here.
255+splitV :: (Reflex t, Monad m)
256+ => Dynamic t (Int -> Int)
257+ -- ^ Function used to determine size of first pane based on available size
258+ -> Dynamic t (Bool, Bool)
259+ -- ^ How to focus the two sub-panes, given that we are focused.
260+ -> VtyWidget t m a
261+ -- ^ Widget for first pane
262+ -> VtyWidget t m b
263+ -- ^ Widget for second pane
264+ -> VtyWidget t m (a,b)
265+splitV sizeFunD focD wA wB = do
266+ sz <- displaySize
267+ let regA = (\f (w,h) -> Region 0 0 w (f h)) <$> sizeFunD <*> sz
268+ regB = (\(w,h) (Region _ _ _ hA) -> Region 0 hA w (h - hA)) <$> sz <*> regA
269+ ra <- pane regA (fst <$> focD) wA
270+ rb <- pane regB (snd <$> focD) wB
271+ return (ra,rb)
272+
273+-- | A split of the available space into two parts with a draggable separator.
274+-- Starts with half the space allocated to each, and the first pane has focus.
275+-- Clicking in a pane switches focus.
276+splitVDrag :: (Reflex t, MonadFix m, MonadHold t m)
277+ => VtyWidget t m a
278+ -> VtyWidget t m b
279+ -> VtyWidget t m (a,b)
280+splitVDrag wA wB = do
281+ sz <- displaySize
282+ (_, h0) <- sample $ current sz
283+ dragE <- drag V.BLeft
284+ let splitter0 = h0 `div` 2
285+ rec splitterCheckpoint <- holdDyn splitter0 $ fst <$> ffilter snd dragSplitter
286+ splitterPos <- holdDyn splitter0 $ fst <$> dragSplitter
287+ let dragSplitter = fforMaybe (attach (current splitterCheckpoint) dragE) $ \(splitterY, Drag (_, fromY) (_, toY) _ _ end) ->
288+ if splitterY == fromY then Just (toY, end) else Nothing
289+ regA = (\(w,_) sp -> Region 0 0 w sp) <$> sz <*> splitterPos
290+ regS = (\(w,_) sp -> Region 0 sp w 1) <$> sz <*> splitterPos
291+ regB = (\(w,h) sp -> Region 0 (sp + 1) w (h - sp - 1)) <$> sz <*> splitterPos
292+ focA <- holdDyn True $ leftmost
293+ [ True <$ mA
294+ , False <$ mB
295+ ]
296+ (mA, rA) <- pane regA focA $ withMouseDown wA
297+ tellImages $ ffor (current regS) $ \r -> [withinImage r (V.string mempty (replicate (_region_width r) '='))]
298+ (mB, rB) <- pane regB (not <$> focA) $ withMouseDown wB
299+ return (rA, rB)
300+ where
301+ withMouseDown x = do
302+ m <- mouseDown V.BLeft
303+ x' <- x
304+ return (m, x')
305+
306+fractionSz :: Double -> Int -> Int
307+fractionSz x h = round (fromIntegral h * x)
308+
309+modifyImages
310+ :: (Reflex t, MonadHold t m, MonadFix m)
311+ => Behavior t ([Image] -> [Image])
312+ -> VtyWidget t m a
313+ -> VtyWidget t m a
314+modifyImages f (VtyWidget w) = VtyWidget $ flip censor w $ \wo ->
315+ wo { _vtyWidgetOut_images = f <*> (_vtyWidgetOut_images wo) }
316+
317+box :: (Monad m, Reflex t)
318+ => VtyWidget t m a
319+ -> VtyWidget t m a
320+box child = do
321+ sz <- displaySize
322+ let boxReg = ffor (current sz) $ \(w,h) -> Region 0 0 w h
323+ innerReg = ffor sz $ \(w,h) -> Region 1 1 (w - 2) (h - 2)
324+ tellImages (fmap boxImages boxReg)
325+ tellImages (fmap (\r -> [regionBlankImage r]) (current innerReg))
326+ pane innerReg (pure True) child
327+ where
328+ boxImages :: Region -> [Image]
329+ boxImages r@(Region left top width height) =
330+ let hBorder = V.string mempty $ replicate width '-'
331+ vBorder = wrapString 1 mempty $ replicate (height - 2) '|'
332+ in [ withinImage (r { _region_height = 1 }) hBorder
333+ , withinImage (Region left (top + 1) 1 (height - 2)) vBorder
334+ , withinImage (Region (left + width - 1) (top + 1) 1 (height - 2)) vBorder
335+ , withinImage (r { _region_top = top + height - 1 }) hBorder
336+ ]
337+
338+string :: (Reflex t, Monad m) => Behavior t String -> VtyWidget t m ()
339+string msg = do
340+ dw <- displayWidth
341+ let img = (\w s -> [wrapString w mempty s]) <$> current dw <*> msg
342+ tellImages img
343+
344+regionBlankImage :: Region -> Image
345+regionBlankImage r@(Region _ _ width height) =
346+ withinImage r $ wrapString width V.defAttr $ replicate (width * height) ' '
347+
348+withinImage :: Region -> Image -> Image
525349withinImage (Region left top width height)
526350 | width < 0 || height < 0 = withinImage (Region left top 0 0)
527351 | otherwise = V.translate left top . V.crop width height
528352
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
556−
557−-- * Misc
558−
559−-- | A widget that draws nothing
560−blank :: Monad m => m ()
561−blank = return ()
353+wrapString :: Int -> Attr -> String -> Image
354+wrapString maxWidth attrs = V.vertCat . concatMap (fmap (V.string attrs) . fmap (take maxWidth) . takeWhile (not . null) . iterate (drop maxWidth)) . lines