1-- Copyright 2009-2010 Corey O'Connor
2{-# OPTIONS_GHC -Wall #-}
3{-# LANGUAGE ForeignFunctionInterface #-}
4module Graphics.Vty.LLInput ( Key(..)
13import Data.Maybe ( mapMaybe
15import Data.List( inits )
17import qualified Data.Map as M( fromList, lookup )
18import qualified Data.Set as S( fromList, member )
20import Codec.Binary.UTF8.Generic (decode)
22import Control.Monad (when)
23import Control.Concurrent
24import Control.Exception
26import System.Console.Terminfo
28import System.Posix.Signals.Exts
29import System.Posix.Terminal
30import System.Posix.IO ( stdInput
36-- |Representations of non-modifier keys.
37data Key = KEsc | KFun Int | KBackTab | KPrtScr | KPause | KASCII Char | KBS | KIns
38 | KHome | KPageUp | KDel | KEnd | KPageDown | KBegin | KNP5 | KUp | KMenu
39 | KLeft | KDown | KRight | KEnter
40 deriving (Eq,Show,Ord)
42-- |Modifier keys. Key codes are interpreted such that users are more likely to
43-- have Meta than Alt; for instance on the PC Linux console, 'MMeta' will
44-- generally correspond to the physical Alt key.
45data Modifier = MShift | MCtrl | MMeta | MAlt
46 deriving (Eq,Show,Ord)
48-- |Mouse buttons. Not yet used.
49data Button = BLeft | BMiddle | BRight
50 deriving (Eq,Show,Ord)
53data Event = EvKey Key [Modifier] | EvMouse Int Int Button [Modifier]
55 deriving (Eq,Show,Ord)
57data KClass = Valid Key [Modifier] | Invalid | Prefix | MisPfx Key [Modifier] [Char]
60-- | Set up the terminal for input. Returns a function which reads key
61-- events, and a function for shutting down the terminal access.
62initTermInput :: Int -> Terminal -> IO (IO Event, IO ())
63initTermInput escDelay terminal = do
64 eventChannel <- newChan
65 inputChannel <- newChan
66 hadInput <- newEmptyMVar
67 oattr <- getTerminalAttributes stdInput
68 let nattr = foldl withoutMode oattr [StartStopOutput, KeyboardInterrupts,
69 EnableEcho, ProcessInput, ExtendedFunctions]
70 setTerminalAttributes stdInput nattr Immediately
72 let inputToEventThread :: IO ()
73 inputToEventThread = loop []
74 where loop kb = case (classify kb) of
75 Prefix -> do c <- readChan inputChannel
78 MisPfx k m s -> writeChan eventChannel (EvKey k m) >> loop s
79 Valid k m -> writeChan eventChannel (EvKey k m) >> loop ""
81 finishAtomicInput = writeChan inputChannel '\xFFFE'
87 setFdOption stdInput NonBlockingRead False
88 threadWaitRead stdInput
89 setFdOption stdInput NonBlockingRead True
90 _ <- try readAll :: IO (Either IOException ())
91 when (escDelay == 0) finishAtomicInput
94 (bytes, bytes_read) <- fdRead stdInput 1
95 when (bytes_read > 0) $ do
96 _ <- tryPutMVar hadInput () -- signal input
97 writeChan inputChannel (head bytes)
99 -- | If there is no input for some time, this thread puts '\xFFFE' in the
101 noInputThread :: IO ()
102 noInputThread = when (escDelay > 0) loop
104 takeMVar hadInput -- wait for some input
105 threadDelay escDelay -- microseconds
106 hadNoInput <- isEmptyMVar hadInput -- no input yet?
112 compile :: [[([Char],(Key,[Modifier]))]] -> [Char] -> KClass
113 compile lst = cl' where
115 pfx = S.fromList $ concatMap (init . inits . fst) $ lst'
116 mlst = M.fromList lst'
117 cl' str = case S.member str pfx of
119 False -> case M.lookup str mlst of
120 Just (k,m) -> Valid k m
121 Nothing -> case head $ mapMaybe (\s -> (,) s `fmap` M.lookup s mlst) $ init $ inits str of
122 (s,(k,m)) -> MisPfx k m (drop (length s) str)
124 -- ANSI specific bits
127 classify, classifyTab :: [Char] -> KClass
130 classify "\xFFFE" = Invalid
131 classify s@(c:_) | ord c >= 0xC2 =
132 if utf8Length (ord c) > length s then Prefix else classifyUtf8 s -- beginning of an utf8 sequence
133 classify other = classifyTab other
135 classifyUtf8 s = case decode ((map (fromIntegral . ord) s) :: [Word8]) of
136 Just (unicodeChar, _) -> Valid (KASCII unicodeChar) []
137 _ -> Invalid -- something bad happened; just ignore and continue.
139 classifyTab = compile (caps_classify_table : ansi_classify_table)
141 caps_tabls = [("khome", (KHome, [])),
142 ("kend", (KEnd, [])),
143 ("cbt", (KBackTab, [])),
144 ("kcud1", (KDown, [])),
145 ("kcuu1", (KUp, [])),
146 ("kcuf1", (KRight, [])),
147 ("kcub1", (KLeft, [])),
149 ("kLFT", (KLeft, [MShift])),
150 ("kRIT", (KRight, [MShift]))
153 caps_classify_table = [(x,y) | (Just x,y) <- map (first (getCapability terminal . tiGetStr)) $ caps_tabls]
155 ansi_classify_table :: [[([Char], (Key, [Modifier]))]]
156 ansi_classify_table =
157 [ let k c s = ("\ESC["++c,(s,[])) in [ k "G" KNP5
168 -- Support for arrows
169 [("\ESC[" ++ charCnt ++ show mc++c,(s,m))
170 | charCnt <- ["1;", ""], -- we can have a count or not
171 (m,mc) <- [([MShift],2::Int), ([MCtrl],5), ([MMeta],3),
172 ([MShift, MCtrl],6), ([MShift, MMeta],4)], -- modifiers and their codes
173 (c,s) <- [("A", KUp), ("B", KDown), ("C", KRight), ("D", KLeft)] -- directions and their codes
176 let k n s = ("\ESC["++show n++"~",(s,[])) in zipWith k [2::Int,3,5,6,1,4]
177 [KIns,KDel,KPageUp,KPageDown,KHome,KEnd],
179 -- Support for simple characters.
180 [ (x:[],(KASCII x,[])) | x <- map toEnum [0..255] ],
182 -- Support for function keys (should use terminfo)
183 [ ("\ESC[["++[toEnum(64+i)],(KFun i,[])) | i <- [1..5] ],
184 let f ff nrs m = [ ("\ESC["++show n++"~",(KFun (n-(nrs!!0)+ff), m)) | n <- nrs ] in
185 concat [ f 6 [17..21] [], f 11 [23,24] [], f 1 [25,26] [MShift], f 3 [28,29] [MShift], f 5 [31..34] [MShift] ],
186 [ ('\ESC':[x],(KASCII x,[MMeta])) | x <- '\ESC':'\t':[' ' .. '\DEL'] ],
189 [ ([toEnum x],(KASCII y,[MCtrl]))
190 | (x,y) <- zip ([0..31]) ('@':['a'..'z']++['['..'_']),
191 y /= 'i' -- Resolve issue #3 where CTRL-i hides TAB.
195 [ ('\ESC':[toEnum x],(KASCII y,[MMeta,MCtrl])) | (x,y) <- zip [0..31] ('@':['a'..'z']++['['..'_']) ],
198 [ -- special support for ESC
199 ("\ESC",(KEsc,[])) , ("\ESC\ESC",(KEsc,[MMeta])),
201 -- Special support for backspace
202 ("\DEL",(KBS,[])), ("\ESC\DEL",(KBS,[MMeta])),
204 -- Special support for Enter
205 ("\ESC\^J",(KEnter,[MMeta])), ("\^J",(KEnter,[])) ]
208 eventThreadId <- forkIO $ inputToEventThread
209 inputThreadId <- forkIO $ inputThread
210 noInputThreadId <- forkIO $ noInputThread
211 let pokeIO = (Catch $ do let e = error "(getsize in input layer)"
212 setTerminalAttributes stdInput nattr Immediately
213 writeChan eventChannel (EvResize e e))
214 _ <- installHandler windowChange pokeIO Nothing
215 _ <- installHandler continueProcess pokeIO Nothing
216 let uninit = do killThread eventThreadId
217 killThread inputThreadId
218 killThread noInputThreadId
219 _ <- installHandler windowChange Ignore Nothing
220 _ <- installHandler continueProcess Ignore Nothing
221 setTerminalAttributes stdInput oattr Immediately
222 return (readChan eventChannel, uninit)
224first :: (a -> b) -> (a,c) -> (b,c)
225first f (x,y) = (f x, y)
227utf8Length :: (Num t, Ord a, Num a) => a -> t
234foreign import ccall "set_term_timing" set_term_timing :: IO ()
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list