1{-# LANGUAGE RecordWildCards #-}
3{-# LANGUAGE FlexibleInstances #-}
4{-# OPTIONS_GHC -D_XOPEN_SOURCE=500 #-}
6-- | Terminfo based terminal handling.
8-- The color handling assumes tektronix like. No HP support provided. If the terminal is not one I
9-- have easy access to then color support is entirely based of the docs. Probably with some
10-- assumptions mixed in.
12-- Copyright Corey O'Connor (coreyoconnor@gmail.com)
13module Graphics.Vty.Output.TerminfoBased ( reserveTerminal )
16import Graphics.Vty.Prelude
18import qualified Data.ByteString as BS
19import Data.Terminfo.Parse
20import Data.Terminfo.Eval
22import Graphics.Vty.Attributes
23import Graphics.Vty.DisplayAttributes
24import Graphics.Vty.Output.Interface
26import Blaze.ByteString.Builder (Write, writeToByteString)
28import Control.Monad.Trans
30import Data.Bits ((.&.))
31import Data.Foldable (foldMap)
33import Data.Maybe (isJust, isNothing, fromJust)
36import Foreign.C.Types ( CInt(..), CLong(..) )
39#ifdef __GLASGOW_HASKELL__
40#if __GLASGOW_HASKELL__ >= 611
41import GHC.IO.Handle.Internals (withHandle_)
42import GHC.IO.Handle.Types (Handle__(..))
43import qualified GHC.IO.FD as FD
44-- import qualified GHC.IO.Handle.FD as FD
45import GHC.IO.Exception
46import Data.Typeable (cast)
49import GHC.Handle hiding (fdToHandle)
50import qualified GHC.Handle
54import qualified System.Console.Terminfo as Terminfo
55#ifdef __GLASGOW_HASKELL__
56#if __GLASGOW_HASKELL__ >= 611
60import System.Posix.Types (Fd(..))
62data TerminfoCaps = TerminfoCaps
63 { smcup :: Maybe CapExpression
64 , rmcup :: Maybe CapExpression
65 , cup :: CapExpression
66 , cnorm :: Maybe CapExpression
67 , civis :: Maybe CapExpression
68 , supportsNoColors :: Bool
69 , useAltColorMap :: Bool
70 , setForeColor :: CapExpression
71 , setBackColor :: CapExpression
72 , setDefaultAttr :: CapExpression
73 , clearScreen :: CapExpression
74 , clearEol :: CapExpression
75 , displayAttrCaps :: DisplayAttrCaps
78data DisplayAttrCaps = DisplayAttrCaps
79 { setAttrStates :: Maybe CapExpression
80 , enterStandout :: Maybe CapExpression
81 , exitStandout :: Maybe CapExpression
82 , enterUnderline :: Maybe CapExpression
83 , exitUnderline :: Maybe CapExpression
84 , enterReverseVideo :: Maybe CapExpression
85 , enterDimMode :: Maybe CapExpression
86 , enterBoldMode :: Maybe CapExpression
89sendCapToTerminal :: Output -> CapExpression -> [CapParam] -> IO ()
90sendCapToTerminal t cap capParams = do
91 outputByteBuffer t $ writeToByteString $ writeCapExpr cap capParams
93{- | Uses terminfo for all control codes. While this should provide the most compatible terminal
94 - terminfo does not support some features that would increase efficiency and improve compatibility:
96 - * determine the character encoding supported by the terminal. Should this be taken from the LANG
97 - environment variable?
99 - * Provide independent string capabilities for all display attributes.
101 - todo: Some display attributes like underline and bold have independent string capabilities that
102 - should be used instead of the generic "sgr" string capability.
104reserveTerminal :: ( Applicative m, MonadIO m ) => String -> Handle -> m Output
105reserveTerminal inID outHandle = liftIO $ do
106 ti <- Terminfo.setupTerm inID
107 -- assumes set foreground always implies set background exists.
108 -- if set foreground is not set then all color changing style attributes are filtered.
109 msetaf <- probeCap ti "setaf"
110 msetf <- probeCap ti "setf"
111 let (noColors, useAlt, setForeCap)
113 Just setaf -> (False, False, setaf)
114 Nothing -> case msetf of
115 Just setf -> (False, True, setf)
116 Nothing -> (True, True, error $ "no fore color support for terminal " ++ inID)
117 msetab <- probeCap ti "setab"
118 msetb <- probeCap ti "setb"
121 Nothing -> case msetb of
123 Nothing -> error $ "no back color support for terminal " ++ inID
125 terminfoCaps <- pure TerminfoCaps
126 <*> probeCap ti "smcup"
127 <*> probeCap ti "rmcup"
128 <*> requireCap ti "cup"
129 <*> probeCap ti "cnorm"
130 <*> probeCap ti "civis"
134 <*> pure set_back_cap
135 <*> requireCap ti "sgr0"
136 <*> requireCap ti "clear"
137 <*> requireCap ti "el"
138 <*> currentDisplayAttrCaps ti
139 newAssumedStateRef <- newIORef initialAssumedState
142 , releaseTerminal = liftIO $ do
143 sendCap setDefaultAttr []
144 maybeSendCap cnorm []
146 , reserveDisplay = liftIO $ do
147 -- If there is no support for smcup: Clear the screen and then move the mouse to the
148 -- home position to approximate the behavior.
149 maybeSendCap smcup []
151 sendCap clearScreen []
152 , releaseDisplay = liftIO $ do
153 maybeSendCap rmcup []
154 maybeSendCap cnorm []
156 rawSize <- liftIO $ withFd outHandle getWindowSize
158 (w, h) | w < 0 || h < 0 -> fail $ "getwinsize returned < 0 : " ++ show rawSize
159 | otherwise -> return (w,h)
160 , outputByteBuffer = \outBytes -> do
161 BS.hPut outHandle outBytes
164 = case supportsNoColors terminfoCaps of
165 False -> case Terminfo.getCapability ti (Terminfo.tiGetNum "colors" ) of
169 , supportsCursorVisibility = isJust $ civis terminfoCaps
170 , assumedStateRef = newAssumedStateRef
171 -- I think fix would help assure tActual is the only reference. I was having issues
173 , mkDisplayContext = \tActual -> liftIO . terminfoDisplayContext tActual terminfoCaps
175 sendCap s = sendCapToTerminal t (s terminfoCaps)
176 maybeSendCap s = when (isJust $ s terminfoCaps) . sendCap (fromJust . s)
179requireCap :: (Applicative m, MonadIO m) => Terminfo.Terminal -> String -> m CapExpression
181 = case Terminfo.getCapability ti (Terminfo.tiGetStr capName) of
182 Nothing -> fail $ "Terminal does not define required capability \"" ++ capName ++ "\""
183 Just capStr -> parseCap capStr
185probeCap :: (Applicative m, MonadIO m) => Terminfo.Terminal -> String -> m (Maybe CapExpression)
187 = case Terminfo.getCapability ti (Terminfo.tiGetStr capName) of
188 Nothing -> return Nothing
189 Just capStr -> Just <$> parseCap capStr
191parseCap :: (Applicative m, MonadIO m) => String -> m CapExpression
193 case parseCapExpression capStr of
194 Left e -> fail $ show e
195 Right cap -> return cap
197currentDisplayAttrCaps :: ( Applicative m, MonadIO m )
200currentDisplayAttrCaps ti
201 = pure DisplayAttrCaps
202 <*> probeCap ti "sgr"
203 <*> probeCap ti "smso"
204 <*> probeCap ti "rmso"
205 <*> probeCap ti "smul"
206 <*> probeCap ti "rmul"
207 <*> probeCap ti "rev"
208 <*> probeCap ti "dim"
209 <*> probeCap ti "bold"
211foreign import ccall "gwinsz.h vty_c_get_window_size" c_getWindowSize :: Fd -> IO CLong
213getWindowSize :: Fd -> IO (Int,Int)
215 (a,b) <- (`divMod` 65536) `fmap` c_getWindowSize fd
216 return (fromIntegral b, fromIntegral a)
218terminfoDisplayContext :: Output -> TerminfoCaps -> DisplayRegion -> IO DisplayContext
219terminfoDisplayContext tActual terminfoCaps r = return dc
220 where dc = DisplayContext
221 { contextDevice = tActual
223 , writeMoveCursor = \x y -> writeCapExpr (cup terminfoCaps) [toEnum y, toEnum x]
224 , writeShowCursor = case cnorm terminfoCaps of
225 Nothing -> error "this terminal does not support show cursor"
226 Just c -> writeCapExpr c []
227 , writeHideCursor = case civis terminfoCaps of
228 Nothing -> error "this terminal does not support hide cursor"
229 Just c -> writeCapExpr c []
230 , writeSetAttr = terminfoWriteSetAttr dc terminfoCaps
231 , writeDefaultAttr = writeCapExpr (setDefaultAttr terminfoCaps) []
232 , writeRowEnd = writeCapExpr (clearEol terminfoCaps) []
233 , inlineHack = return ()
236-- | Portably setting the display attributes is a giant pain in the ass.
238-- If the terminal supports the sgr capability (which sets the on/off state of each style
239-- directly ; and, for no good reason, resets the colors to the default) this procedure is used:
241-- 0. set the style attributes. This resets the fore and back color.
243-- 1, If a foreground color is to be set then set the foreground color
245-- 2. likewise with the background color
247-- If the terminal does not support the sgr cap then:
248-- if there is a change from an applied color to the default (in either the fore or back color)
251-- 0. reset all display attributes (sgr0)
253-- 1. enter required style modes
255-- 2. set the fore color if required
257-- 3. set the back color if required
259-- Entering the required style modes could require a reset of the display attributes. If this is
260-- the case then the back and fore colors always need to be set if not default.
262-- This equation implements the above logic.
264-- \todo This assumes the removal of color changes in the display attributes is done as expected
265-- with noColors == True. See `limit_attr_for_display`
267-- \todo This assumes that fewer state changes, followed by fewer bytes, is what to optimize. I
268-- haven't measured this or even examined terminal implementations. *shrug*
269terminfoWriteSetAttr :: DisplayContext -> TerminfoCaps -> FixedAttr -> Attr -> DisplayAttrDiff -> Write
270terminfoWriteSetAttr dc terminfoCaps prevAttr reqAttr diffs = do
271 case (foreColorDiff diffs == ColorToDefault) || (backColorDiff diffs == ColorToDefault) of
272 -- The only way to reset either color, portably, to the default is to use either the set
273 -- state capability or the set default capability.
275 case reqDisplayCapSeqFor (displayAttrCaps terminfoCaps)
277 (styleToApplySeq $ fixedStyle attr) of
278 -- only way to reset a color to the defaults
279 EnterExitSeq caps -> writeDefaultAttr dc
281 foldMap (\cap -> writeCapExpr cap []) caps
284 -- implicitly resets the colors to the defaults
285 SetState state -> writeCapExpr (fromJust $ setAttrStates
289 (sgrArgsForState state)
292 -- Otherwise the display colors are not changing or changing between two non-default
295 -- Still, it could be the case that the change in display attributes requires the
296 -- colors to be reset because the required capability was not available.
297 case reqDisplayCapSeqFor (displayAttrCaps terminfoCaps)
299 (styleDiffs diffs) of
300 -- Really, if terminals were re-implemented with modern concepts instead of bowing
301 -- down to 40 yr old dumb terminal requirements this would be the only case ever
302 -- reached! Changes the style and color states according to the differences with
303 -- the currently applied states.
304 EnterExitSeq caps -> foldMap (\cap -> writeCapExpr cap []) caps
306 writeColorDiff setForeColor (foreColorDiff diffs)
308 writeColorDiff setBackColor (backColorDiff diffs)
309 -- implicitly resets the colors to the defaults
310 SetState state -> writeCapExpr (fromJust $ setAttrStates
311 $ displayAttrCaps terminfoCaps
313 (sgrArgsForState state)
316 colorMap = case useAltColorMap terminfoCaps of
317 False -> ansiColorIndex
318 True -> altColorIndex
319 attr = fixDisplayAttr prevAttr reqAttr
321 (case fixedForeColor attr of
322 Just c -> writeCapExpr (setForeColor terminfoCaps)
323 [toEnum $ colorMap c]
326 (case fixedBackColor attr of
327 Just c -> writeCapExpr (setBackColor terminfoCaps)
328 [toEnum $ colorMap c]
330 writeColorDiff _f NoColorChange
332 writeColorDiff _f ColorToDefault
333 = error "ColorToDefault is not a possible case for applyColorDiffs"
334 writeColorDiff f (SetColor c)
335 = writeCapExpr (f terminfoCaps) [toEnum $ colorMap c]
337-- | The color table used by a terminal is a 16 color set followed by a 240 color set that might not
338-- be supported by the terminal.
340-- This takes a Color which clearly identifies which pallete to use and computes the index
341-- into the full 256 color pallete.
342ansiColorIndex :: Color -> Int
343ansiColorIndex (ISOColor v) = fromEnum v
344ansiColorIndex (Color240 v) = 16 + fromEnum v
346-- | For terminals without setaf/setab
348-- See table in `man terminfo`
349-- Will error if not in table.
350altColorIndex :: Color -> Int
351altColorIndex (ISOColor 0) = 0
352altColorIndex (ISOColor 1) = 4
353altColorIndex (ISOColor 2) = 2
354altColorIndex (ISOColor 3) = 6
355altColorIndex (ISOColor 4) = 1
356altColorIndex (ISOColor 5) = 5
357altColorIndex (ISOColor 6) = 3
358altColorIndex (ISOColor 7) = 7
359altColorIndex (ISOColor v) = fromEnum v
360altColorIndex (Color240 v) = 16 + fromEnum v
362{- | The sequence of terminfo caps to apply a given style are determined according to these rules.
364 - 1. The assumption is that it's preferable to use the simpler enter/exit mode capabilities than
365 - the full set display attribute state capability.
367 - 2. If a mode is supposed to be removed but there is not an exit capability defined then the
368 - display attributes are reset to defaults then the display attribute state is set.
370 - 3. If a mode is supposed to be applied but there is not an enter capability defined then then
371 - display attribute state is set if possible. Otherwise the mode is not applied.
373 - 4. If the display attribute state is being set then just update the arguments to that for any
378 = EnterExitSeq [CapExpression]
379 | SetState DisplayAttrState
381data DisplayAttrState = DisplayAttrState
382 { applyStandout :: Bool
383 , applyUnderline :: Bool
384 , applyReverseVideo :: Bool
390sgrArgsForState :: DisplayAttrState -> [CapParam]
391sgrArgsForState attrState = map (\b -> if b then 1 else 0)
392 [ applyStandout attrState
393 , applyUnderline attrState
394 , applyReverseVideo attrState
395 , applyBlink attrState
397 , applyBold attrState
400 , False -- alt char set
403reqDisplayCapSeqFor :: DisplayAttrCaps -> Style -> [StyleStateChange] -> DisplayAttrSeq
404reqDisplayCapSeqFor caps s diffs
405 -- if the state transition implied by any diff cannot be supported with an enter/exit mode cap
406 -- then either the state needs to be set or the attribute change ignored.
407 = case (any noEnterExitCap diffs, isJust $ setAttrStates caps) of
408 -- If all the diffs have an enter-exit cap then just use those
409 ( False, _ ) -> EnterExitSeq $ map enterExitCap diffs
410 -- If not all the diffs have an enter-exit cap and there is no set state cap then filter out
411 -- all unsupported diffs and just apply the rest
412 ( True, False ) -> EnterExitSeq $ map enterExitCap
413 $ filter (not . noEnterExitCap) diffs
414 -- if not all the diffs have an enter-exit can and there is a set state cap then just use
415 -- the set state cap.
416 ( True, True ) -> SetState $ stateForStyle s
418 noEnterExitCap ApplyStandout = isNothing $ enterStandout caps
419 noEnterExitCap RemoveStandout = isNothing $ exitStandout caps
420 noEnterExitCap ApplyUnderline = isNothing $ enterUnderline caps
421 noEnterExitCap RemoveUnderline = isNothing $ exitUnderline caps
422 noEnterExitCap ApplyReverseVideo = isNothing $ enterReverseVideo caps
423 noEnterExitCap RemoveReverseVideo = True
424 noEnterExitCap ApplyBlink = True
425 noEnterExitCap RemoveBlink = True
426 noEnterExitCap ApplyDim = isNothing $ enterDimMode caps
427 noEnterExitCap RemoveDim = True
428 noEnterExitCap ApplyBold = isNothing $ enterBoldMode caps
429 noEnterExitCap RemoveBold = True
430 enterExitCap ApplyStandout = fromJust $ enterStandout caps
431 enterExitCap RemoveStandout = fromJust $ exitStandout caps
432 enterExitCap ApplyUnderline = fromJust $ enterUnderline caps
433 enterExitCap RemoveUnderline = fromJust $ exitUnderline caps
434 enterExitCap ApplyReverseVideo = fromJust $ enterReverseVideo caps
435 enterExitCap ApplyDim = fromJust $ enterDimMode caps
436 enterExitCap ApplyBold = fromJust $ enterBoldMode caps
437 enterExitCap _ = error "enterExitCap applied to diff that was known not to have one."
439stateForStyle :: Style -> DisplayAttrState
440stateForStyle s = DisplayAttrState
441 { applyStandout = isStyleSet standout
442 , applyUnderline = isStyleSet underline
443 , applyReverseVideo = isStyleSet reverseVideo
444 , applyBlink = isStyleSet blink
445 , applyDim = isStyleSet dim
446 , applyBold = isStyleSet bold
448 where isStyleSet = hasStyle s
450styleToApplySeq :: Style -> [StyleStateChange]
451styleToApplySeq s = concat
452 [ applyIfRequired ApplyStandout standout
453 , applyIfRequired ApplyUnderline underline
454 , applyIfRequired ApplyReverseVideo reverseVideo
455 , applyIfRequired ApplyBlink blink
456 , applyIfRequired ApplyDim dim
457 , applyIfRequired ApplyBlink bold
460 applyIfRequired op flag
461 = if 0 == (flag .&. s)
465-- from https://patch-tag.com/r/mae/sendfile/snapshot/current/content/pretty/src/Network/Socket/SendFile/Internal.hs
466-- The Fd should not be used after the action returns because the
467-- Handler may be garbage collected and than will cause the finalizer
469withFd :: Handle -> (Fd -> IO a) -> IO a
470#ifdef __GLASGOW_HASKELL__
471#if __GLASGOW_HASKELL__ >= 611
472withFd h f = withHandle_ "withFd" h $ \ Handle__{..} -> do
473 case cast haDevice of
474 Nothing -> ioError (ioeSetErrorString (mkIOError IllegalOperation
475 "withFd" (Just h) Nothing)
476 "handle is not a file descriptor")
477 Just fd -> f (Fd (fromIntegral (FD.fdFD fd)))
480 withHandle_ "withFd" h $ \ h_ ->
481 f (Fd (fromIntegral (haFD h_)))
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