1-- | Terminfo based terminal handling.
3-- The color handling assumes tektronix like. No HP support provided. If the terminal is not one I
4-- have easy access to then color support is entirely based of the docs. Probably with some
5-- assumptions mixed in.
7-- Copyright Corey O'Connor (coreyoconnor@gmail.com)
8{-# LANGUAGE FlexibleInstances #-}
9{-# OPTIONS_GHC -D_XOPEN_SOURCE=500 #-}
10{-# CFILES gwinsz.c #-}
11module Graphics.Vty.Output.TerminfoBased ( reserve_terminal )
14import Graphics.Vty.Prelude
16import Data.Terminfo.Parse
17import Data.Terminfo.Eval
19import Graphics.Vty.Attributes
20import Graphics.Vty.DisplayAttributes
21import Graphics.Vty.Output.Interface
23import Control.Monad.Trans
25import Data.Bits ( (.&.) )
27import Data.Maybe ( isJust, isNothing, fromJust )
29import Foreign.C.Types ( CLong(..) )
33import qualified System.Console.Terminfo as Terminfo
35data TerminfoCaps = TerminfoCaps
36 { smcup :: Maybe CapExpression
37 , rmcup :: Maybe CapExpression
38 , cup :: CapExpression
39 , cnorm :: Maybe CapExpression
40 , civis :: Maybe CapExpression
41 , supports_no_colors :: Bool
42 , use_alt_color_map :: Bool
43 , set_fore_color :: CapExpression
44 , set_back_color :: CapExpression
45 , set_default_attr :: CapExpression
46 , clear_screen :: CapExpression
47 , clear_eol :: CapExpression
48 , display_attr_caps :: DisplayAttrCaps
51data DisplayAttrCaps = DisplayAttrCaps
52 { set_attr_states :: Maybe CapExpression
53 , enter_standout :: Maybe CapExpression
54 , exit_standout :: Maybe CapExpression
55 , enter_underline :: Maybe CapExpression
56 , exit_underline :: Maybe CapExpression
57 , enter_reverse_video :: Maybe CapExpression
58 , enter_dim_mode :: Maybe CapExpression
59 , enter_bold_mode :: Maybe CapExpression
62send_cap_to_terminal :: Output -> CapExpression -> [CapParam] -> IO ()
63send_cap_to_terminal t cap cap_params = do
64 send_to_terminal t (cap_expression_required_bytes cap cap_params)
65 (serialize_cap_expression cap cap_params)
67{- | Uses terminfo for all control codes. While this should provide the most compatible terminal
68 - terminfo does not support some features that would increase efficiency and improve compatibility:
69 - * determine the character encoding supported by the terminal. Should this be taken from the LANG
70 - environment variable?
71 - * Provide independent string capabilities for all display attributes.
74 - todo: Some display attributes like underline and bold have independent string capabilities that
75 - should be used instead of the generic "sgr" string capability.
77reserve_terminal :: ( Applicative m, MonadIO m ) => String -> Handle -> m Output
78reserve_terminal in_ID out_handle = liftIO $ do
79 ti <- Terminfo.setupTerm in_ID
80 -- assumes set foreground always implies set background exists.
81 -- if set foreground is not set then all color changing style attributes are filtered.
82 msetaf <- probe_cap ti "setaf"
83 msetf <- probe_cap ti "setf"
84 let (no_colors, use_alt, set_fore_cap)
86 Just setaf -> (False, False, setaf)
87 Nothing -> case msetf of
88 Just setf -> (False, True, setf)
89 Nothing -> (True, True, error $ "no fore color support for terminal " ++ in_ID)
90 msetab <- probe_cap ti "setab"
91 msetb <- probe_cap ti "setb"
94 Nothing -> case msetb of
96 Nothing -> error $ "no back color support for terminal " ++ in_ID
98 terminfo_caps <- pure TerminfoCaps
99 <*> probe_cap ti "smcup"
100 <*> probe_cap ti "rmcup"
101 <*> require_cap ti "cup"
102 <*> probe_cap ti "cnorm"
103 <*> probe_cap ti "civis"
106 <*> pure set_fore_cap
107 <*> pure set_back_cap
108 <*> require_cap ti "sgr0"
109 <*> require_cap ti "clear"
110 <*> require_cap ti "el"
111 <*> current_display_attr_caps ti
112 new_assumed_state_ref <- newIORef initial_assumed_state
114 { terminal_ID = in_ID
115 , release_terminal = liftIO $ do
116 send_cap set_default_attr []
117 maybe_send_cap cnorm []
119 , reserve_display = liftIO $ do
120 -- If there is no support for smcup: Clear the screen and then move the mouse to the
121 -- home position to approximate the behavior.
122 maybe_send_cap smcup []
124 send_cap clear_screen []
125 , release_display = liftIO $ do
126 maybe_send_cap rmcup []
127 maybe_send_cap cnorm []
128 , display_bounds = do
129 raw_size <- liftIO $ get_window_size
131 (w, h) | w < 0 || h < 0 -> fail $ "getwinsize returned < 0 : " ++ show raw_size
132 | otherwise -> return (w,h)
133 , output_byte_buffer = \out_ptr out_byte_count -> do
134 hPutBuf out_handle out_ptr (fromEnum out_byte_count)
136 , context_color_count
137 = case supports_no_colors terminfo_caps of
138 False -> case Terminfo.getCapability ti (Terminfo.tiGetNum "colors" ) of
142 , supports_cursor_visibility = isJust $ civis terminfo_caps
143 , assumed_state_ref = new_assumed_state_ref
144 -- I think fix would help assure t_actual is the only reference. I was having issues
146 , mk_display_context = \t_actual -> liftIO . terminfo_display_context t_actual terminfo_caps
148 send_cap s = send_cap_to_terminal t (s terminfo_caps)
149 maybe_send_cap s = when (isJust $ s terminfo_caps) . send_cap (fromJust . s)
152require_cap :: (Applicative m, MonadIO m) => Terminfo.Terminal -> String -> m CapExpression
153require_cap ti cap_name
154 = case Terminfo.getCapability ti (Terminfo.tiGetStr cap_name) of
155 Nothing -> fail $ "Terminal does not define required capability \"" ++ cap_name ++ "\""
156 Just cap_str -> parse_cap cap_str
158probe_cap :: (Applicative m, MonadIO m) => Terminfo.Terminal -> String -> m (Maybe CapExpression)
160 = case Terminfo.getCapability ti (Terminfo.tiGetStr cap_name) of
161 Nothing -> return Nothing
162 Just cap_str -> Just <$> parse_cap cap_str
164parse_cap :: (Applicative m, MonadIO m) => String -> m CapExpression
165parse_cap cap_str = do
166 parse_result <- parse_cap_expression cap_str
168 Left e -> fail $ show e
169 Right cap -> return cap
171current_display_attr_caps :: ( Applicative m, MonadIO m )
174current_display_attr_caps ti
175 = pure DisplayAttrCaps
176 <*> probe_cap ti "sgr"
177 <*> probe_cap ti "smso"
178 <*> probe_cap ti "rmso"
179 <*> probe_cap ti "smul"
180 <*> probe_cap ti "rmul"
181 <*> probe_cap ti "rev"
182 <*> probe_cap ti "dim"
183 <*> probe_cap ti "bold"
185foreign import ccall "gwinsz.h vty_c_get_window_size" c_get_window_size :: IO CLong
187get_window_size :: IO (Int,Int)
189 (a,b) <- (`divMod` 65536) `fmap` c_get_window_size
190 return (fromIntegral b, fromIntegral a)
192terminfo_display_context :: Output -> TerminfoCaps -> DisplayRegion -> IO DisplayContext
193terminfo_display_context t_actual terminfo_caps r =
194 let dc = DisplayContext
195 { context_device = t_actual
197 , move_cursor_required_bytes = \x y -> cap_expression_required_bytes (cup terminfo_caps)
199 , serialize_move_cursor = \x y out_ptr -> serialize_cap_expression (cup terminfo_caps)
202 , show_cursor_required_bytes = case cnorm terminfo_caps of
203 Nothing -> error "this terminal does not support show cursor"
204 Just c -> cap_expression_required_bytes c []
205 , serialize_show_cursor = \out_ptr -> do
206 case cnorm terminfo_caps of
207 Nothing -> fail "this terminal does not support show cursor"
208 Just c -> serialize_cap_expression c [] out_ptr
209 , hide_cursor_required_bytes = case civis terminfo_caps of
210 Nothing -> error "this terminal does not support hide cursor"
211 Just c -> cap_expression_required_bytes c []
212 , serialize_hide_cursor = \out_ptr -> do
213 case civis terminfo_caps of
214 Nothing -> fail "this terminal does not support hide cursor"
215 Just c -> serialize_cap_expression c [] out_ptr
216 , attr_required_bytes = \_prev_attr _req_attr _diffs -> assumed_attr_required_bytes
217 , serialize_set_attr = terminfo_serialize_set_attr dc terminfo_caps
218 , default_attr_required_bytes = cap_expression_required_bytes (set_default_attr terminfo_caps) []
219 , serialize_default_attr = serialize_cap_expression (set_default_attr terminfo_caps) []
220 , row_end_required_bytes = cap_expression_required_bytes (clear_eol terminfo_caps) []
221 , serialize_row_end = serialize_cap_expression (clear_eol terminfo_caps) []
222 , inline_hack = return ()
226-- | Instead of evaluating all the rules related to setting display attributes twice (once in
227-- required bytes and again in serialize) or some memoization scheme just return a size
228-- requirement as big the longest possible control string.
230-- Which is assumed to the be less than 512 for now.
232-- \todo Not verified as safe and wastes memory.
233assumed_attr_required_bytes :: Int
234assumed_attr_required_bytes = 512
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.
242-- 1, If a foreground color is to be set then set the foreground color
243-- 2. likewise with the background color
245-- If the terminal does not support the sgr cap then:
246-- if there is a change from an applied color to the default (in either the fore or back color)
248-- 0. reset all display attributes (sgr0)
249-- 1. enter required style modes
250-- 2. set the fore color if required
251-- 3. set the back color if required
253-- Entering the required style modes could require a reset of the display attributes. If this is
254-- the case then the back and fore colors always need to be set if not default.
256-- This equation implements the above logic.
258-- \todo This assumes the removal of color changes in the display attributes is done as expected
259-- with no_colors == True. See `limit_attr_for_display`
261-- \todo This assumes that fewer state changes, followed by fewer bytes, is what to optimize. I
262-- haven't measured this or even examined terminal implementations. *shrug*
263terminfo_serialize_set_attr :: DisplayContext
265 -> FixedAttr -> Attr -> DisplayAttrDiff -> OutputBuffer -> IO OutputBuffer
266terminfo_serialize_set_attr dc terminfo_caps prev_attr req_attr diffs out_ptr = do
267 case (fore_color_diff diffs == ColorToDefault) || (back_color_diff diffs == ColorToDefault) of
268 -- The only way to reset either color, portably, to the default is to use either the set
269 -- state capability or the set default capability.
271 case req_display_cap_seq_for ( display_attr_caps terminfo_caps )
273 ( style_to_apply_seq $ fixed_style attr )
276 -- only way to reset a color to the defaults
277 -> serialize_default_attr dc out_ptr
278 >>= (\out_ptr' -> liftIO $ foldM (\ptr cap -> serialize_cap_expression cap [] ptr) out_ptr' caps)
281 -- implicitly resets the colors to the defaults
282 -> liftIO $ serialize_cap_expression ( fromJust $ set_attr_states
286 ( sgr_args_for_state state )
289 -- Otherwise the display colors are not changing or changing between two non-default
292 -- Still, it could be the case that the change in display attributes requires the
293 -- colors to be reset because the required capability was not available.
294 case req_display_cap_seq_for (display_attr_caps terminfo_caps)
298 -- Really, if terminals were re-implemented with modern concepts instead of
299 -- bowing down to 40 yr old dumb terminal requirements this would be the
300 -- only case ever reached!
301 -- Changes the style and color states according to the differences with the
302 -- currently applied states.
304 -> foldM (\ptr cap -> serialize_cap_expression cap [] ptr) out_ptr caps
305 >>= apply_color_diff set_fore_color (fore_color_diff diffs)
306 >>= apply_color_diff set_back_color (back_color_diff diffs)
308 -- implicitly resets the colors to the defaults
309 -> serialize_cap_expression (fromJust $ set_attr_states
310 $ display_attr_caps terminfo_caps
312 (sgr_args_for_state state)
316 color_map = case use_alt_color_map terminfo_caps of
317 False -> ansi_color_index
318 True -> alt_color_index
319 attr = fix_display_attr prev_attr req_attr
321 ptr' <- case fixed_fore_color attr of
322 Just c -> serialize_cap_expression (set_fore_color terminfo_caps)
323 [ toEnum $ color_map c ]
325 Nothing -> return ptr
326 ptr'' <- case fixed_back_color attr of
327 Just c -> serialize_cap_expression (set_back_color terminfo_caps)
328 [ toEnum $ color_map c ]
330 Nothing -> return ptr'
332 apply_color_diff _f NoColorChange ptr
334 apply_color_diff _f ColorToDefault _ptr
335 = fail "ColorToDefault is not a possible case for apply_color_diffs"
336 apply_color_diff f ( SetColor c ) ptr
337 = serialize_cap_expression (f terminfo_caps)
338 [ toEnum $ color_map c ]
341-- | The color table used by a terminal is a 16 color set followed by a 240 color set that might not
342-- be supported by the terminal.
344-- This takes a Color which clearly identifies which pallete to use and computes the index
345-- into the full 256 color pallete.
346ansi_color_index :: Color -> Int
347ansi_color_index (ISOColor v) = fromEnum v
348ansi_color_index (Color240 v) = 16 + fromEnum v
350-- | For terminals without setaf/setab
352-- See table in `man terminfo`
353-- Will error if not in table.
354alt_color_index :: Color -> Int
355alt_color_index (ISOColor 0) = 0
356alt_color_index (ISOColor 1) = 4
357alt_color_index (ISOColor 2) = 2
358alt_color_index (ISOColor 3) = 6
359alt_color_index (ISOColor 4) = 1
360alt_color_index (ISOColor 5) = 5
361alt_color_index (ISOColor 6) = 3
362alt_color_index (ISOColor 7) = 7
363alt_color_index (ISOColor v) = fromEnum v
364alt_color_index (Color240 v) = 16 + fromEnum v
366{- | The sequence of terminfo caps to apply a given style are determined according to these rules.
368 - 1. The assumption is that it's preferable to use the simpler enter/exit mode capabilities than
369 - the full set display attribute state capability.
371 - 2. If a mode is supposed to be removed but there is not an exit capability defined then the
372 - display attributes are reset to defaults then the display attribute state is set.
374 - 3. If a mode is supposed to be applied but there is not an enter capability defined then then
375 - display attribute state is set if possible. Otherwise the mode is not applied.
377 - 4. If the display attribute state is being set then just update the arguments to that for any
382 = EnterExitSeq [CapExpression]
383 | SetState DisplayAttrState
385data DisplayAttrState = DisplayAttrState
386 { apply_standout :: Bool
387 , apply_underline :: Bool
388 , apply_reverse_video :: Bool
389 , apply_blink :: Bool
394sgr_args_for_state :: DisplayAttrState -> [CapParam]
395sgr_args_for_state attr_state = map (\b -> if b then 1 else 0)
396 [ apply_standout attr_state
397 , apply_underline attr_state
398 , apply_reverse_video attr_state
399 , apply_blink attr_state
400 , apply_dim attr_state
401 , apply_bold attr_state
404 , False -- alt char set
407req_display_cap_seq_for :: DisplayAttrCaps -> Style -> [StyleStateChange] -> DisplayAttrSeq
408req_display_cap_seq_for caps s diffs
409 -- if the state transition implied by any diff cannot be supported with an enter/exit mode cap
410 -- then either the state needs to be set or the attribute change ignored.
411 = case (any no_enter_exit_cap diffs, isJust $ set_attr_states caps) of
412 -- If all the diffs have an enter-exit cap then just use those
413 ( False, _ ) -> EnterExitSeq $ map enter_exit_cap diffs
414 -- If not all the diffs have an enter-exit cap and there is no set state cap then filter out
415 -- all unsupported diffs and just apply the rest
416 ( True, False ) -> EnterExitSeq $ map enter_exit_cap
417 $ filter (not . no_enter_exit_cap) diffs
418 -- if not all the diffs have an enter-exit can and there is a set state cap then just use
419 -- the set state cap.
420 ( True, True ) -> SetState $ state_for_style s
422 no_enter_exit_cap ApplyStandout = isNothing $ enter_standout caps
423 no_enter_exit_cap RemoveStandout = isNothing $ exit_standout caps
424 no_enter_exit_cap ApplyUnderline = isNothing $ enter_underline caps
425 no_enter_exit_cap RemoveUnderline = isNothing $ exit_underline caps
426 no_enter_exit_cap ApplyReverseVideo = isNothing $ enter_reverse_video caps
427 no_enter_exit_cap RemoveReverseVideo = True
428 no_enter_exit_cap ApplyBlink = True
429 no_enter_exit_cap RemoveBlink = True
430 no_enter_exit_cap ApplyDim = isNothing $ enter_dim_mode caps
431 no_enter_exit_cap RemoveDim = True
432 no_enter_exit_cap ApplyBold = isNothing $ enter_bold_mode caps
433 no_enter_exit_cap RemoveBold = True
434 enter_exit_cap ApplyStandout = fromJust $ enter_standout caps
435 enter_exit_cap RemoveStandout = fromJust $ exit_standout caps
436 enter_exit_cap ApplyUnderline = fromJust $ enter_underline caps
437 enter_exit_cap RemoveUnderline = fromJust $ exit_underline caps
438 enter_exit_cap ApplyReverseVideo = fromJust $ enter_reverse_video caps
439 enter_exit_cap ApplyDim = fromJust $ enter_dim_mode caps
440 enter_exit_cap ApplyBold = fromJust $ enter_bold_mode caps
441 enter_exit_cap _ = error "enter_exit_cap applied to diff that was known not to have one."
443state_for_style :: Style -> DisplayAttrState
444state_for_style s = DisplayAttrState
445 { apply_standout = is_style_set standout
446 , apply_underline = is_style_set underline
447 , apply_reverse_video = is_style_set reverse_video
448 , apply_blink = is_style_set blink
449 , apply_dim = is_style_set dim
450 , apply_bold = is_style_set bold
452 where is_style_set = has_style s
454style_to_apply_seq :: Style -> [StyleStateChange]
455style_to_apply_seq s = concat
456 [ apply_if_required ApplyStandout standout
457 , apply_if_required ApplyUnderline underline
458 , apply_if_required ApplyReverseVideo reverse_video
459 , apply_if_required ApplyBlink blink
460 , apply_if_required ApplyDim dim
461 , apply_if_required ApplyBlink bold
464 apply_if_required op flag
465 = if 0 == (flag .&. s)
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