2019-09-18 09:17:54 +03:00
|
|
|
{-
|
|
|
|
This allows multiple (zero or more) terminal clients to connect to
|
|
|
|
the *same* logical arvo terminal. Terminals that connect will be
|
|
|
|
given full event history since the creation of the demuxer.
|
|
|
|
-}
|
|
|
|
|
|
|
|
module Vere.Term.Demux (Demux, mkDemux, addDemux, useDemux) where
|
|
|
|
|
|
|
|
import UrbitPrelude
|
|
|
|
|
|
|
|
import Arvo (Belt)
|
|
|
|
import Vere.Term.API (Client(Client))
|
|
|
|
|
2019-09-19 02:11:00 +03:00
|
|
|
import qualified Vere.Term.API as Term
|
|
|
|
import qualified Vere.Term.Logic as Logic
|
2019-09-18 09:17:54 +03:00
|
|
|
|
|
|
|
|
2019-09-19 02:11:00 +03:00
|
|
|
-- External --------------------------------------------------------------------
|
2019-09-18 09:17:54 +03:00
|
|
|
|
|
|
|
data Demux = Demux
|
|
|
|
{ dConns :: TVar [Client]
|
2019-09-19 02:11:00 +03:00
|
|
|
, dStash :: TVar Logic.St
|
2019-09-18 09:17:54 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
mkDemux :: STM Demux
|
2019-09-19 02:11:00 +03:00
|
|
|
mkDemux = Demux <$> newTVar [] <*> newTVar Logic.init
|
2019-09-18 09:17:54 +03:00
|
|
|
|
|
|
|
addDemux :: Client -> Demux -> STM ()
|
|
|
|
addDemux conn Demux{..} = do
|
|
|
|
modifyTVar' dConns (conn:)
|
2019-09-19 02:11:00 +03:00
|
|
|
stash <- readTVar dStash
|
|
|
|
Term.give conn (Logic.toTermEv <$> Logic.drawState stash)
|
2019-09-18 09:17:54 +03:00
|
|
|
|
|
|
|
useDemux :: Demux -> Client
|
|
|
|
useDemux d = Client { give = dGive d, take = dTake d }
|
|
|
|
|
|
|
|
|
|
|
|
-- Internal --------------------------------------------------------------------
|
|
|
|
|
2019-09-19 02:11:00 +03:00
|
|
|
steps :: [Term.Ev] -> Logic.St -> Logic.St
|
|
|
|
steps termEvs st = foldl' Logic.step st $ concat $ Logic.fromTermEv <$> termEvs
|
|
|
|
|
2019-09-18 12:11:18 +03:00
|
|
|
dGive :: Demux -> [Term.Ev] -> STM ()
|
2019-09-19 02:11:00 +03:00
|
|
|
dGive Demux{..} evs = do
|
|
|
|
modifyTVar' dStash (force $ steps evs)
|
2019-09-18 09:17:54 +03:00
|
|
|
conns <- readTVar dConns
|
2019-09-19 02:11:00 +03:00
|
|
|
for_ conns $ \c -> Term.give c evs
|
2019-09-18 09:17:54 +03:00
|
|
|
|
|
|
|
dTake :: Demux -> STM Belt
|
|
|
|
dTake Demux{..} = do
|
|
|
|
conns <- readTVar dConns
|
|
|
|
asum (Term.take <$> conns)
|