| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
 | module Terminal (
    TerminalOutput,
    TerminalLine,
    TerminalFootnote(..),
    initTerminalOutput,
    newLine,
    redrawLine,
    newFootnote,
    terminalHandle,
    terminalBlinkStatus,
) where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Data.Function
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.IO qualified as T
import System.IO
data TerminalOutput = TerminalOutput
    { outHandle :: Handle
    , outNumLines :: MVar Int
    , outNextFootnote :: MVar Int
    , outBlinkVar :: TVar Bool
    }
instance Eq TerminalOutput where
    (==) = (==) `on` outNumLines
data TerminalLine = TerminalLine
    { lineOutput :: TerminalOutput
    , lineNum :: Int
    }
    deriving (Eq)
data TerminalFootnote = TerminalFootnote
    { tfLine :: TerminalLine
    , tfNumber :: Int
    }
    deriving (Eq)
initTerminalOutput :: IO TerminalOutput
initTerminalOutput = do
    outHandle <- return stdout
    outNumLines <- newMVar 0
    outNextFootnote <- newMVar 1
    outBlinkVar <- newTVarIO False
    void $ forkIO $ forever $ do
        threadDelay 500000
        atomically $ writeTVar outBlinkVar . not =<< readTVar outBlinkVar
    return TerminalOutput {..}
newLine :: TerminalOutput -> Text -> IO TerminalLine
newLine lineOutput@TerminalOutput {..} text = do
    modifyMVar outNumLines $ \lineNum -> do
        T.putStrLn text
        hFlush outHandle
        return ( lineNum + 1, TerminalLine {..} )
redrawLine :: TerminalLine -> Text -> IO ()
redrawLine TerminalLine {..} text = do
    let TerminalOutput {..} = lineOutput
    withMVar outNumLines $ \total -> do
        let moveBy = total - lineNum
        T.putStr $ "\ESC[s\ESC[" <> T.pack (show moveBy) <> "F" <> text <> "\ESC[u"
        hFlush outHandle
newFootnote :: TerminalOutput -> Text -> IO TerminalFootnote
newFootnote tout@TerminalOutput {..} text = do
    modifyMVar outNextFootnote $ \tfNumber -> do
        tfLine <- newLine tout $ "[" <> T.pack (show tfNumber) <> "] " <> text
        hFlush outHandle
        return ( tfNumber + 1, TerminalFootnote {..} )
terminalHandle :: TerminalOutput -> Handle
terminalHandle = outHandle
terminalBlinkStatus :: TerminalOutput -> STM Bool
terminalBlinkStatus TerminalOutput {..} = readTVar outBlinkVar
 |