1-- Copyright 2009 Corey O'Connor
2{-# LANGUAGE ForeignFunctionInterface #-}
3{-# LANGUAGE ScopedTypeVariables #-}
4{-# LANGUAGE FlexibleInstances #-}
5{-# OPTIONS_GHC -D_XOPEN_SOURCE=500 #-}
6module Graphics.Vty.Terminal.TerminfoBased ( terminal_instance
10import Data.Terminfo.Parse
11import Data.Terminfo.Eval
13import Graphics.Vty.Attributes
14import Graphics.Vty.DisplayAttributes
15import Graphics.Vty.Terminal.Generic
16import Graphics.Vty.DisplayRegion
18import Control.Applicative
19import Control.Monad ( foldM )
20import Control.Monad.Trans
22import Data.Bits ( (.&.) )
23import Data.Maybe ( isJust, isNothing, fromJust )
27import Foreign.C.Types ( CLong, CSize, CInt )
29import qualified System.Console.Terminfo as Terminfo
32import System.Posix.Types ( Fd(..) )
35 { term_info_ID :: String
36 , term_info :: Terminfo.Terminal
37 , smcup :: Maybe CapExpression
38 , rmcup :: Maybe CapExpression
39 , cup :: CapExpression
40 , cnorm :: CapExpression
41 , civis :: CapExpression
42 , set_fore_color :: CapExpression
43 , set_back_color :: CapExpression
44 , set_default_attr :: CapExpression
45 , clear_screen :: CapExpression
46 , display_attr_caps :: DisplayAttrCaps
50data DisplayAttrCaps = DisplayAttrCaps
51 { set_attr_states :: Maybe CapExpression
52 , enter_standout :: Maybe CapExpression
53 , exit_standout :: Maybe CapExpression
54 , enter_underline :: Maybe CapExpression
55 , exit_underline :: Maybe CapExpression
56 , enter_reverse_video :: Maybe CapExpression
57 , enter_dim_mode :: Maybe CapExpression
58 , enter_bold_mode :: Maybe CapExpression
61marshall_cap_to_terminal :: Term -> (Term -> CapExpression) -> [CapParam] -> IO ()
62marshall_cap_to_terminal t cap_selector cap_params = do
63 marshall_to_terminal t ( cap_expression_required_bytes (cap_selector t) cap_params )
64 ( serialize_cap_expression (cap_selector t) 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.
77terminal_instance :: ( Applicative m, MonadIO m ) => String -> m Term
78terminal_instance in_ID = do
79 ti <- liftIO $ Terminfo.setupTerm in_ID
81 = case Terminfo.getCapability ti (Terminfo.tiGetStr str) of
82 Nothing -> fail $ "Terminal does not define required capability \"" ++ str ++ "\""
84 parse_result <- parse_cap_expression cap_str
86 Left e -> fail $ show e
87 Right cap -> return cap
89 = case Terminfo.getCapability ti (Terminfo.tiGetStr cap_name) of
90 Nothing -> return Nothing
92 parse_result <- parse_cap_expression cap_str
94 Left e -> fail $ show e
95 Right cap -> return $ Just cap
96 term_fd <- liftIO $ dup stdOutput
100 <*> probe_cap "smcup"
101 <*> probe_cap "rmcup"
102 <*> require_cap "cup"
103 <*> require_cap "cnorm"
104 <*> require_cap "civis"
105 <*> require_cap "setaf"
106 <*> require_cap "setab"
107 <*> require_cap "sgr0"
108 <*> require_cap "clear"
109 <*> current_display_attr_caps ti
112current_display_attr_caps :: ( Applicative m, MonadIO m )
115current_display_attr_caps ti
116 = pure DisplayAttrCaps
125 where probe_cap cap_name
126 = case Terminfo.getCapability ti (Terminfo.tiGetStr cap_name) of
127 Nothing -> return Nothing
129 parse_result <- parse_cap_expression cap_str
131 Left e -> fail $ show e
132 Right cap -> return $ Just cap
134instance Terminal Term where
135 terminal_ID t = term_info_ID t ++ " :: TerminfoBased"
137 release_terminal t = do
138 liftIO $ marshall_cap_to_terminal t set_default_attr []
139 liftIO $ marshall_cap_to_terminal t cnorm []
142 reserve_display t = do
143 if (isJust $ smcup t)
144 then liftIO $ marshall_cap_to_terminal t (fromJust . smcup) []
146 -- Screen on OS X does not appear to support smcup?
147 -- To approximate the expected behavior: clear the screen and then move the mouse to the
149 liftIO $ marshall_cap_to_terminal t clear_screen []
152 release_display t = do
153 if (isJust $ rmcup t)
154 then liftIO $ marshall_cap_to_terminal t (fromJust . rmcup) []
156 liftIO $ marshall_cap_to_terminal t cnorm []
159 display_terminal_instance t b c = do
161 = case Terminfo.getCapability (term_info t) (Terminfo.tiGetNum "colors" ) of
164 return $ c (DisplayContext b t color_count)
166 display_bounds _t = do
167 raw_size <- liftIO $ get_window_size
169 ( w, h ) | w < 0 || h < 0 -> fail $ "getwinsize returned < 0 : " ++ show raw_size
170 | otherwise -> return $ DisplayRegion (toEnum w) (toEnum h)
172 -- Output the byte buffer of the specified size to the terminal device.
173 output_byte_buffer t out_ptr out_byte_count = do
174 -- flush is required *before* the c_output_byte_buffer call
175 -- otherwise there may still be data in GHC's internal stdout buffer.
177 let Fd c_fd = term_fd t
178 if out_byte_count /= 0
179 then c_output_byte_buffer c_fd out_ptr ( toEnum $! fromEnum out_byte_count )
182foreign import ccall unsafe "output_buffer.h stdout_output_buffer" c_output_byte_buffer
183 :: CInt -> Ptr Word8 -> CSize -> IO ()
184foreign import ccall "gwinsz.h c_get_window_size" c_get_window_size
186foreign import ccall "fdatasync" c_fdatasync
189get_window_size :: IO (Int,Int)
191 (a,b) <- (`divMod` 65536) `fmap` c_get_window_size
192 return (fromIntegral b, fromIntegral a)
194data DisplayContext = DisplayContext
195 { bounds :: DisplayRegion
197 , supported_colors :: Word
200instance DisplayTerminal DisplayContext where
201 context_region d = bounds d
203 context_color_count d = supported_colors d
205 move_cursor_required_bytes d x y
206 = cap_expression_required_bytes (cup $ term d) [y, x]
207 serialize_move_cursor d x y out_ptr
208 = liftIO $ serialize_cap_expression (cup $ term d) [y, x] out_ptr
210 show_cursor_required_bytes d
211 = cap_expression_required_bytes (cnorm $ term d) []
212 serialize_show_cursor d out_ptr
213 = liftIO $ serialize_cap_expression (cnorm $ term d) [] out_ptr
215 hide_cursor_required_bytes d
216 = cap_expression_required_bytes (civis $ term d) []
217 serialize_hide_cursor d out_ptr
218 = liftIO $ serialize_cap_expression (civis $ term d) [] out_ptr
220 -- Instead of evaluating all the rules related to setting display attributes twice (once in
221 -- required bytes and again in serialize) or some memoization scheme just return a size
222 -- requirement as big the longest possible control string.
224 -- Which is assumed to the be less than 512 for now.
226 -- \todo Not verified as safe and wastes memory.
227 attr_required_bytes _d _prev_attr _req_attr _diffs = 512
229 -- Portably setting the display attributes is a giant pain in the ass.
230 -- If the terminal supports the sgr capability (which sets the on/off state of each style
231 -- directly ; and, for no good reason, resets the colors to the default) this always works:
232 -- 0. set the style attributes. This resets the fore and back color.
233 -- 1, If a foreground color is to be set then set the foreground color
234 -- 2. likewise with the background color
236 -- If the terminal does not support the sgr then
237 -- if there is a change from an applied color to the default (in either the fore or back color)
239 -- 0. reset all display attributes (sgr0)
240 -- 1. enter required style modes
241 -- 2. set the fore color if required
242 -- 3. set the back color if required
244 -- Entering the required style modes could require a reset of the display attributes. If this is
245 -- the case then the back and fore colors always need to be set if not default.
247 -- All this (I think) is satisfied by the following logic:
248 serialize_set_attr d prev_attr req_attr diffs out_ptr = do
249 case (fore_color_diff diffs == ColorToDefault) || (back_color_diff diffs == ColorToDefault) of
250 -- The only way to reset either color, portably, to the default is to use either the set
251 -- state capability or the set default capability.
253 case req_display_cap_seq_for ( display_attr_caps $ term d )
255 ( style_to_apply_seq $ fixed_style attr )
258 -- only way to reset a color to the defaults
259 -> serialize_default_attr d out_ptr
260 >>= (\out_ptr' -> liftIO $ foldM (\ptr cap -> serialize_cap_expression cap [] ptr) out_ptr' caps)
263 -- implicitly resets the colors to the defaults
264 -> liftIO $ serialize_cap_expression ( fromJust $ set_attr_states
268 ( sgr_args_for_state state )
271 -- Otherwise the display colors are not changing or changing between two non-default
274 -- Still, it could be the case that the change in display attributes requires the
275 -- colors to be reset because the required capability was not available.
276 case req_display_cap_seq_for ( display_attr_caps $ term d )
278 ( style_diffs diffs )
280 -- Really, if terminals were re-implemented with modern concepts instead of
281 -- bowing down to 40 yr old dumb terminal requirements this would be the
282 -- only case ever reached!
283 -- Changes the style and color states according to the differences with the
284 -- currently applied states.
286 -> liftIO ( foldM (\ptr cap -> serialize_cap_expression cap [] ptr) out_ptr caps )
287 >>= apply_color_diff set_fore_color ( fore_color_diff diffs )
288 >>= apply_color_diff set_back_color ( back_color_diff diffs )
290 -- implicitly resets the colors to the defaults
291 -> liftIO $ serialize_cap_expression ( fromJust $ set_attr_states
295 ( sgr_args_for_state state )
299 attr = fix_display_attr prev_attr req_attr
301 ptr' <- case fixed_fore_color attr of
302 Just c -> liftIO $ serialize_cap_expression ( set_fore_color $ term d )
303 [ ansi_color_index c ]
305 Nothing -> return ptr
306 ptr'' <- case fixed_back_color attr of
307 Just c -> liftIO $ serialize_cap_expression ( set_back_color $ term d )
308 [ ansi_color_index c ]
310 Nothing -> return ptr'
312 apply_color_diff _f NoColorChange ptr
314 apply_color_diff _f ColorToDefault _ptr
315 = fail "ColorToDefault is not a possible case for apply_color_diffs"
316 apply_color_diff f ( SetColor c ) ptr
317 = liftIO $ serialize_cap_expression ( f $ term d )
318 [ ansi_color_index c ]
321 default_attr_required_bytes d
322 = cap_expression_required_bytes (set_default_attr $ term d) []
323 serialize_default_attr d out_ptr = do
324 liftIO $ serialize_cap_expression ( set_default_attr $ term d ) [] out_ptr
326ansi_color_index :: Color -> Word
327ansi_color_index (ISOColor v) = toEnum $ fromEnum v
328ansi_color_index (Color240 v) = 16 + ( toEnum $ fromEnum v )
330{- The sequence of terminfo caps to apply a given style are determined according to these rules.
332 - 1. The assumption is that it's preferable to use the simpler enter/exit mode capabilities than
333 - the full set display attribute state capability.
335 - 2. If a mode is supposed to be removed but there is not an exit capability defined then the
336 - display attributes are reset to defaults then the display attribute state is set.
338 - 3. If a mode is supposed to be applied but there is not an enter capability defined then then
339 - display attribute state is set if possible. Otherwise the mode is not applied.
341 - 4. If the display attribute state is being set then just update the arguments to that for any
347 = EnterExitSeq [CapExpression]
348 | SetState DisplayAttrState
350data DisplayAttrState = DisplayAttrState
351 { apply_standout :: Bool
352 , apply_underline :: Bool
353 , apply_reverse_video :: Bool
354 , apply_blink :: Bool
359sgr_args_for_state :: DisplayAttrState -> [CapParam]
360sgr_args_for_state attr_state = map (\b -> if b then 1 else 0)
361 [ apply_standout attr_state
362 , apply_underline attr_state
363 , apply_reverse_video attr_state
364 , apply_blink attr_state
365 , apply_dim attr_state
366 , apply_bold attr_state
369 , False -- alt char set
372req_display_cap_seq_for :: DisplayAttrCaps -> Style -> [StyleStateChange] -> DisplayAttrSeq
373req_display_cap_seq_for caps s diffs
374 -- if the state transition implied by any diff cannot be supported with an enter/exit mode cap
375 -- then either the state needs to be set or the attribute change ignored.
376 = case (any no_enter_exit_cap diffs, isJust $ set_attr_states caps) of
377 -- If all the diffs have an enter-exit cap then just use those
378 ( False, _ ) -> EnterExitSeq $ map enter_exit_cap diffs
379 -- If not all the diffs have an enter-exit cap and there is no set state cap then filter out
380 -- all unsupported diffs and just apply the rest
381 ( True, False ) -> EnterExitSeq $ map enter_exit_cap
382 $ filter (not . no_enter_exit_cap) diffs
383 -- if not all the diffs have an enter-exit can and there is a set state cap then just use
384 -- the set state cap.
385 ( True, True ) -> SetState $ state_for_style s
387 no_enter_exit_cap ApplyStandout = isNothing $ enter_standout caps
388 no_enter_exit_cap RemoveStandout = isNothing $ exit_standout caps
389 no_enter_exit_cap ApplyUnderline = isNothing $ enter_underline caps
390 no_enter_exit_cap RemoveUnderline = isNothing $ exit_underline caps
391 no_enter_exit_cap ApplyReverseVideo = isNothing $ enter_reverse_video caps
392 no_enter_exit_cap RemoveReverseVideo = True
393 no_enter_exit_cap ApplyBlink = True
394 no_enter_exit_cap RemoveBlink = True
395 no_enter_exit_cap ApplyDim = isNothing $ enter_dim_mode caps
396 no_enter_exit_cap RemoveDim = True
397 no_enter_exit_cap ApplyBold = isNothing $ enter_bold_mode caps
398 no_enter_exit_cap RemoveBold = True
399 enter_exit_cap ApplyStandout = fromJust $ enter_standout caps
400 enter_exit_cap RemoveStandout = fromJust $ exit_standout caps
401 enter_exit_cap ApplyUnderline = fromJust $ enter_underline caps
402 enter_exit_cap RemoveUnderline = fromJust $ exit_underline caps
403 enter_exit_cap ApplyReverseVideo = fromJust $ enter_reverse_video caps
404 enter_exit_cap ApplyDim = fromJust $ enter_dim_mode caps
405 enter_exit_cap ApplyBold = fromJust $ enter_bold_mode caps
406 enter_exit_cap _ = error "enter_exit_cap applied to diff that was known not to have one."
408state_for_style :: Style -> DisplayAttrState
409state_for_style s = DisplayAttrState
410 { apply_standout = is_style_set standout
411 , apply_underline = is_style_set underline
412 , apply_reverse_video = is_style_set reverse_video
413 , apply_blink = is_style_set blink
414 , apply_dim = is_style_set dim
415 , apply_bold = is_style_set bold
417 where is_style_set = has_style s
419style_to_apply_seq :: Style -> [StyleStateChange]
420style_to_apply_seq s = concat
421 [ apply_if_required ApplyStandout standout
422 , apply_if_required ApplyUnderline underline
423 , apply_if_required ApplyReverseVideo reverse_video
424 , apply_if_required ApplyBlink blink
425 , apply_if_required ApplyDim dim
426 , apply_if_required ApplyBlink bold
429 apply_if_required ap flag
430 = 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