summaryrefslogtreecommitdiffstats
path: root/Main.hs
blob: 484f72f3155cc9b549244669e8c1ddabe9e1d173 (plain)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Main where

import Control.Applicative
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Monad
import Data.Char
import Data.IORef
import Data.List
import Data.Time.Clock (getCurrentTime)
import Data.Time.Format (formatTime)
import Numeric (showIntAtBase)
import System.IO
import System.Locale (defaultTimeLocale, rfc822DateFormat)
--import System.Posix.Signals

import Control.Monad.Error
import Control.Monad.Writer
import Control.Monad.State

import Buffer


data VTState = VTState
    { buffer :: Buffer
    , mode :: Mode
    }

emptyState = VTState emptyBuffer (NormalMode nmap)



main :: IO ()
main = do
  hSetEcho stdin False
  hSetBuffering stdin NoBuffering

  tid <- myThreadId

  -- WINCH
  -- TODO installHandler 28 (Catch $ ioctl 0 ...) Nothing

  lock <- newMVar emptyBuffer

  renderInputLine emptyBuffer
  hFlush stdout

  forkIO $ (dateThread 1000000) lock
  uiThread (NormalMode nmap) lock


dateThread delay lock = forever $ do
    t <- getCurrentTime
    withMVar lock $ \ buf -> do
      clearLine
      putStrLn $ formatTime defaultTimeLocale rfc822DateFormat t
      renderInputLine buf
      hFlush stdout
    threadDelay delay


uiThread mod lock = do
    c <- getCommand mod
    mod' <- modifyMVar lock $ \ buf -> do
        let st = VTState
                { mode = mod
                , buffer = buf
                }

        ((eSt, lines), st') <- runExecCommand st (execCommand c)

        clearLine
        forM_ lines putStrLn

        whenLeft eSt $ \err ->
          ringBell >>
          putStrLn (prettyError err)

        when (show (mode st) /= show (mode st')) $ do
            putStrLn $ "change mode: " ++ (show $ mode st')

        renderInputLine (buffer st')
        hFlush stdout
        return (buffer st', mode st')

    uiThread mod' lock


data Command
  = AlertBadInput String
  | InsertChar Char
  | InsertNextCharVerbatim
  | InsertCharThenChangeMode Char Mode
  | MoveCursorRight
  | MoveCursorLeft
  | KillLastWord
  | KillLastChar
  | KillNextChar
  | ExecuteInputBuffer
  | UnboundSequence String String
  | GotoBOL
  | GotoEOL

data ExecError
  = UnboundSequenceError String String
  | UnhandledInputError String
  | OtherError String

instance Error ExecError where
  noMsg = OtherError "something went wrong"

prettyError :: ExecError -> String
prettyError e = rec e
  where
    color cc s = "\x1b[" ++ cc ++ "m" ++ s ++ "\x1b[m"
    rec (UnboundSequenceError s n) =
      color "31" $ "unbound sequence: <" ++ (pp "31;1" s) ++ "\x1b[;31m> "
                  ++ (pp "31;1" n)

    rec (UnhandledInputError s) =
      color "31" $ "unhandled input: <" ++ (pp "31;1" s) ++ "\x1b[;31m>"

    rec (OtherError s) =
      color "31" $ "error: " ++ s

    -- TODO cc is ColorCode
    pp cc = concat . map (pp1 cc)
    pp1 cc c
      | isPrint c = [c]
      | otherwise = specialChar cc $
        case c of
          '\x1b' -> "^["
          _ -> charToCode c
    specialChar cc s = "\x1b[1;35m" ++ s ++ "\x1b[;" ++ cc ++ "m"




modifyBuffer :: (Buffer -> Buffer) -> ExecM ()
modifyBuffer f =
    modify $ \st -> st { buffer = f (buffer st) }


-- TODO instance Show Buffer (w/newtype Buffer)

showBuffer :: Buffer -> String
showBuffer (lhs, rhs) = lhs ++ rhs



newtype ExecM a = ExecM
    ( ErrorT ExecError (WriterT [String] (StateT VTState IO)) a
    )
  deriving
    ( Applicative
    , Functor
    , Monad
    , MonadError ExecError
    , MonadIO
    , MonadState VTState
    , MonadWriter [String]
    )

runExecCommand ::
    VTState -> ExecM a -> IO ((Either ExecError a, [String]), VTState)

runExecCommand st (ExecM ex) =
    runStateT (runWriterT (runErrorT ex)) st



insertChar c (ls, rs) = (ls ++ [c], rs)


execCommand :: Command -> ExecM ()

execCommand GotoBOL =
    modifyBuffer (move GotoFirstChar)

execCommand GotoEOL =
    modifyBuffer (move GotoEndOfLine)

execCommand MoveCursorLeft = do
    get >>= flip (when . null . fst . buffer)
                 (throwError $ OtherError "no char to move left")
    modifyBuffer (move $ GotoLeft 1)

execCommand MoveCursorRight = do
    get >>= flip (when . null . snd . buffer)
                 (throwError $ OtherError "no char to move right")
    modifyBuffer (move $ GotoRight 1)

execCommand (InsertChar c) =
    modifyBuffer (insertChar c)

execCommand (InsertCharThenChangeMode c m) =
    modify $ \ q -> q
      { mode = m
      , buffer = insertChar c (buffer q)
      }

execCommand InsertNextCharVerbatim =
    modify $ \ q -> q
      { mode = VerbatimMode
      }

execCommand ExecuteInputBuffer = do
    b <- gets buffer
    tell [ "input: <" ++ (concat $ map (reform 32) $ showBuffer b) ++ ">" ]
    modifyBuffer (const emptyBuffer)

execCommand KillNextChar = do
    get >>= flip (when . null . snd . buffer)
                 (throwError $ OtherError "nothing to kill right")
    modifyBuffer $ \(lhs, _:rhs') -> (lhs, rhs')

execCommand KillLastChar = do
    get >>= flip (when . null . fst . buffer)
                 (throwError $ OtherError "nothing to kill left")
    modifyBuffer $ \(lhs, rhs) -> (init lhs, rhs)

execCommand KillLastWord = do
    get >>= flip (when . null . fst . buffer)
                 (throwError $ OtherError "nothing to kill left")
    modifyBuffer $
      \(lhs, rhs) -> (foldr dropWhileEnd lhs [not . isSpace, isSpace], rhs)

execCommand (AlertBadInput s) =
    throwError (UnhandledInputError s)

execCommand (UnboundSequence s n) =
    throwError (UnboundSequenceError s n)






reform colorCode c =
    if isPrint c
      then normal colorCode [c]
      else
        special colorCode $
          case ord c of
            27 -> "^["
            _ -> charToCode c

normal colorCode s = "\x1b[" ++ show colorCode ++ "m" ++ s ++ "\x1b[m"
special colorCode s = "\x1b[1;" ++ show colorCode ++ "m" ++ s ++ "\x1b[m"



-- XXX assumes that the cursor is already at the (cleared) input line
renderInputLine :: Buffer -> IO ()
renderInputLine (lhs, rhs) = do
    putStr $ "> " ++ pp lhs ++ pp rhs
    moveCursorLeft (length $ ppVis rhs)
  where
    pp = concat . map reform
    reform c =
      if isPrint c
        then [c]
        else
          "\x1b[35m" ++ (
            case ord c of
              27 -> "^["
              _ -> charToCode c
          ) ++ "\x1b[m"

    ppVis = concat . map reformVis
    reformVis c =
      if isPrint c
        then [c]
        else
            case ord c of
              27 -> "^["
              _ -> charToCode c






clearLine =
    putStr "\x1b[2K" >>
    moveCursorLeft 80


ringBell = putStr "\x07" -- BEL '\a'


moveCursorLeft 0 = return ()
moveCursorLeft i = putStr $ "\x1b[" ++ show i ++ "D"


-- TODO? charToCode c = "\\x" ++ showHex (ord c)
charToCode c = "\\x" ++ showIntAtBase 16 intToDigit (ord c) ""





-- TODO pressing ESC, then F11 etc. is ugly
nmap =
  [ ("\x01", GotoBOL)
  , ("\x05", GotoEOL)
  , ("\x1b[3~", KillNextChar)
  , ("\x1b[C", MoveCursorRight)
  , ("\x1b[D", MoveCursorLeft)
  , ("\x16", InsertNextCharVerbatim) -- ^V
  , ("\x17", KillLastWord) -- ^W
  , ("\x0a", ExecuteInputBuffer)
  , ("\x7f", KillLastChar) -- Delete
  , ("\x08", KillLastChar) -- BackSpace
  ]
  ++ [unboundSequence "\x1b[2~" "<Insert>"]
  ++ [unboundSequence "\x1b[5~" "<Prior>"]    -- page up
  ++ [unboundSequence "\x1b[6~" "<Next>"]     -- page dn
  ++ [unboundSequence "\x1b[7~" "<Home>"]
  ++ [unboundSequence "\x1b[8~" "<End>"]
  ++ [unboundSequence "\x1b[2$" "<S-Insert>"]
  ++ [unboundSequence "\x1b[5$" "<S-Prior>"]    -- page up
  ++ [unboundSequence "\x1b[6$" "<S-Next>"]     -- page dn
  ++ [unboundSequence "\x1b[7$" "<S-Home>"]
  ++ [unboundSequence "\x1b[8$" "<S-End>"]
  ++ [unboundSequence "\x1b\x1b[2$" "<S-M-Insert>"]
  ++ [unboundSequence "\x1b\x1b[5$" "<S-M-Prior>"]    -- page up
  ++ [unboundSequence "\x1b\x1b[6$" "<S-M-Next>"]     -- page dn
  ++ [unboundSequence "\x1b\x1b[7$" "<S-M-Home>"]
  ++ [unboundSequence "\x1b\x1b[8$" "<S-M-End>"]
  ++ [unboundSequence "\x1b\x1b[A" "<M-Up>"]
  ++ [unboundSequence "\x1b\x1b[B" "<M-Down>"]
  ++ [unboundSequence "\x1b\x1b[C" "<M-Right>"]
  ++ [unboundSequence "\x1b\x1b[D" "<M-Left>"]
  ++ [unboundSequence "\x1b\x1b[a" "<S-M-Up>"]
  ++ [unboundSequence "\x1b\x1b[b" "<S-M-Down>"]
  ++ [unboundSequence "\x1b\x1b[c" "<S-M-Right>"]
  ++ [unboundSequence "\x1b\x1b[d" "<S-M-Left>"]
  ++ [unboundSequence "\x1b[a" "<S-Up>"]
  ++ [unboundSequence "\x1b[b" "<S-Down>"]
  ++ [unboundSequence "\x1b[c" "<S-Right>"]
  ++ [unboundSequence "\x1b[d" "<S-Left>"]
  ++ [unboundSequence "\x1bOa" "<C-Up>"]
  ++ [unboundSequence "\x1bOb" "<C-Down>"]
  ++ [unboundSequence "\x1bOc" "<C-Right>"]
  ++ [unboundSequence "\x1bOd" "<C-Left>"]
  ++ [unboundSequence "\x1b\x1bOa" "<C-M-Up>"]
  ++ [unboundSequence "\x1b\x1bOb" "<C-M-Down>"]
  ++ [unboundSequence "\x1b\x1bOc" "<C-M-Right>"]
  ++ [unboundSequence "\x1b\x1bOd" "<C-M-Left>"]
  ++ [unboundSequence "\x1b[11~" "<F1>"]
  ++ [unboundSequence "\x1b[12~" "<F2>"]
  ++ [unboundSequence "\x1b[13~" "<F3>"]
  ++ [unboundSequence "\x1b[14~" "<F4>"]
  ++ [unboundSequence "\x1b[15~" "<F5>"]
  ++ [unboundSequence "\x1b[17~" "<F6>"]
  ++ [unboundSequence "\x1b[18~" "<F7>"]
  ++ [unboundSequence "\x1b[19~" "<F8>"]
  ++ [unboundSequence "\x1b[20~" "<F9>"]
  ++ [unboundSequence "\x1b[21~" "<F10>"]
  ++ [unboundSequence "\x1b[23~" "<F11>"]
  ++ [unboundSequence "\x1b[24~" "<F12>"]

  ++ [unboundSequence "\x1b\x1b[2~" "<M-Insert>"]
  ++ [unboundSequence "\x1b\x1b[3~" "<M-Delete>"]
  ++ map (\ i -> unboundSequence ("\x1b\x1b[" ++ show i ++ "~")
                                 ("<M-F" ++ show i ++ ">"))
          [11..24]
  ++ [unboundSequence "\x1b\x7f" "<M-BackSpace>"]
  ++ [unboundSequence "\x1b\x0a" "<M-Return>"]


unboundSequence seq name =
  (seq, UnboundSequence seq name)


data Mode
  = NormalMode [(String, Command)]
  | VerbatimMode

instance  Show Mode  where
  show (NormalMode _) = "normal"
  show VerbatimMode = "verbatim"


getCommand :: Mode -> IO Command
getCommand (NormalMode map) = getMappedCommand map
getCommand VerbatimMode = verbatimKeymap


getMappedCommand :: [(String, Command)] -> IO Command
getMappedCommand xs = do
    c <- getChar
    if any (isPrefixOf [c] . fst) xs
      then rec [c]
      else
        if isPrint c
          then return $ InsertChar c
          else return $ AlertBadInput [c]
  where
    rec :: String -> IO Command
    rec s =
      case lookup s xs of
        Just c -> return c
        _ ->
          if any (isPrefixOf s . fst) xs
            then do
              c <- getChar
              rec $ s ++ [c]
            else
              return $ AlertBadInput s


verbatimKeymap :: IO Command
verbatimKeymap = do
  c <- getChar
  --return $ InsertCharThenChangeMode c defaultGetCommand
  return $ InsertCharThenChangeMode c (NormalMode nmap)


-- TODO Control.Monad.whenLeft
whenLeft :: Monad m => Either a b -> (a -> m ()) -> m ()
whenLeft (Left x) f = f x
whenLeft _ _ = return ()