1-- Copyright 2009-2010 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 )
26import Foreign.C.Types ( CLong )
30import qualified System.Console.Terminfo as Terminfo
34 { term_info_ID :: String
35 , term_info :: Terminfo.Terminal
36 , smcup :: Maybe CapExpression
37 , rmcup :: Maybe CapExpression
38 , cup :: CapExpression
39 , cnorm :: CapExpression
40 , civis :: CapExpression
41 , set_fore_color :: CapExpression
42 , set_back_color :: CapExpression
43 , set_default_attr :: CapExpression
44 , clear_screen :: CapExpression
45 , display_attr_caps :: DisplayAttrCaps
46 , term_handle :: Handle
49data DisplayAttrCaps = DisplayAttrCaps
50 { set_attr_states :: Maybe CapExpression
51 , enter_standout :: Maybe CapExpression
52 , exit_standout :: Maybe CapExpression
53 , enter_underline :: Maybe CapExpression
54 , exit_underline :: Maybe CapExpression
55 , enter_reverse_video :: Maybe CapExpression
56 , enter_dim_mode :: Maybe CapExpression
57 , enter_bold_mode :: Maybe CapExpression
60marshall_cap_to_terminal :: Term -> (Term -> CapExpression) -> [CapParam] -> IO ()
61marshall_cap_to_terminal t cap_selector cap_params = do
62 marshall_to_terminal t ( cap_expression_required_bytes (cap_selector t) cap_params )
63 ( serialize_cap_expression (cap_selector t) cap_params )
66{- | Uses terminfo for all control codes. While this should provide the most compatible terminal
67 - terminfo does not support some features that would increase efficiency and improve compatibility:
68 - * determine the character encoding supported by the terminal. Should this be taken from the LANG
69 - environment variable?
70 - * Provide independent string capabilities for all display attributes.
73 - todo: Some display attributes like underline and bold have independent string capabilities that
74 - should be used instead of the generic "sgr" string capability.
76terminal_instance :: ( Applicative m, MonadIO m ) => String -> m Term
77terminal_instance in_ID = do
78 ti <- liftIO $ Terminfo.setupTerm in_ID
80 = case Terminfo.getCapability ti (Terminfo.tiGetStr str) of
81 Nothing -> fail $ "Terminal does not define required capability \"" ++ str ++ "\""
83 parse_result <- parse_cap_expression cap_str
85 Left e -> fail $ show e
86 Right cap -> return cap
88 = case Terminfo.getCapability ti (Terminfo.tiGetStr cap_name) of
89 Nothing -> return Nothing
91 parse_result <- parse_cap_expression cap_str
93 Left e -> fail $ show e
94 Right cap -> return $ Just cap
95 the_handle <- liftIO $ hDuplicate stdout
100 <*> probe_cap "rmcup"
101 <*> require_cap "cup"
102 <*> require_cap "cnorm"
103 <*> require_cap "civis"
104 <*> require_cap "setaf"
105 <*> require_cap "setab"
106 <*> require_cap "sgr0"
107 <*> require_cap "clear"
108 <*> current_display_attr_caps ti
111current_display_attr_caps :: ( Applicative m, MonadIO m )
114current_display_attr_caps ti
115 = pure DisplayAttrCaps
124 where probe_cap cap_name
125 = case Terminfo.getCapability ti (Terminfo.tiGetStr cap_name) of
126 Nothing -> return Nothing
128 parse_result <- parse_cap_expression cap_str
130 Left e -> fail $ show e
131 Right cap -> return $ Just cap
133instance Terminal Term where
134 terminal_ID t = term_info_ID t ++ " :: TerminfoBased"
136 release_terminal t = do
137 liftIO $ marshall_cap_to_terminal t set_default_attr []
138 liftIO $ marshall_cap_to_terminal t cnorm []
139 liftIO $ hClose $ term_handle t
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 $ hFlush stdout
150 liftIO $ marshall_cap_to_terminal t clear_screen []
153 release_display t = do
154 if (isJust $ rmcup t)
155 then liftIO $ marshall_cap_to_terminal t (fromJust . rmcup) []
157 liftIO $ marshall_cap_to_terminal t cnorm []
160 display_terminal_instance t b c = do
162 = case Terminfo.getCapability (term_info t) (Terminfo.tiGetNum "colors" ) of
165 return $ c (DisplayContext b t color_count)
167 display_bounds _t = do
168 raw_size <- liftIO $ get_window_size
170 ( w, h ) | w < 0 || h < 0 -> fail $ "getwinsize returned < 0 : " ++ show raw_size
171 | otherwise -> return $ DisplayRegion (toEnum w) (toEnum h)
173 -- | Output the byte buffer of the specified size to the terminal device.
174 output_byte_buffer t out_ptr out_byte_count = do
175 -- if the out fd is actually the same as stdout's then a
176 -- flush is required *before* the c_output_byte_buffer call
177 -- otherwise there may still be data in GHC's internal stdout buffer.
178 -- _ <- handleToFd stdout
179 hPutBuf (term_handle t) out_ptr (fromEnum out_byte_count)
180 hFlush (term_handle t)
182 output_handle t = return (term_handle t)
184-- foreign import ccall unsafe "output_buffer.h stdout_output_buffer" c_output_byte_buffer
185-- :: CInt -> Ptr Word8 -> CSize -> IO ()
186foreign import ccall "gwinsz.h c_get_window_size" c_get_window_size
188-- foreign import ccall "fdatasync" c_fdatasync
191get_window_size :: IO (Int,Int)
193 (a,b) <- (`divMod` 65536) `fmap` c_get_window_size
194 return (fromIntegral b, fromIntegral a)
196data DisplayContext = DisplayContext
197 { bounds :: DisplayRegion
199 , supported_colors :: Word
202instance DisplayTerminal DisplayContext where
203 context_region d = bounds d
205 context_color_count d = supported_colors d
207 move_cursor_required_bytes d x y
208 = cap_expression_required_bytes (cup $ term d) [y, x]
209 serialize_move_cursor d x y out_ptr
210 = liftIO $ serialize_cap_expression (cup $ term d) [y, x] out_ptr
212 show_cursor_required_bytes d
213 = cap_expression_required_bytes (cnorm $ term d) []
214 serialize_show_cursor d out_ptr
215 = liftIO $ serialize_cap_expression (cnorm $ term d) [] out_ptr
217 hide_cursor_required_bytes d
218 = cap_expression_required_bytes (civis $ term d) []
219 serialize_hide_cursor d out_ptr
220 = liftIO $ serialize_cap_expression (civis $ term d) [] out_ptr
222 -- Instead of evaluating all the rules related to setting display attributes twice (once in
223 -- required bytes and again in serialize) or some memoization scheme just return a size
224 -- requirement as big the longest possible control string.
226 -- Which is assumed to the be less than 512 for now.
228 -- \todo Not verified as safe and wastes memory.
229 attr_required_bytes _d _prev_attr _req_attr _diffs = 512
231 -- Portably setting the display attributes is a giant pain in the ass.
232 -- If the terminal supports the sgr capability (which sets the on/off state of each style
233 -- directly ; and, for no good reason, resets the colors to the default) this always works:
234 -- 0. set the style attributes. This resets the fore and back color.
235 -- 1, If a foreground color is to be set then set the foreground color
236 -- 2. likewise with the background color
238 -- If the terminal does not support the sgr then
239 -- if there is a change from an applied color to the default (in either the fore or back color)
241 -- 0. reset all display attributes (sgr0)
242 -- 1. enter required style modes
243 -- 2. set the fore color if required
244 -- 3. set the back color if required
246 -- Entering the required style modes could require a reset of the display attributes. If this is
247 -- the case then the back and fore colors always need to be set if not default.
249 -- All this (I think) is satisfied by the following logic:
250 serialize_set_attr d prev_attr req_attr diffs out_ptr = do
251 case (fore_color_diff diffs == ColorToDefault) || (back_color_diff diffs == ColorToDefault) of
252 -- The only way to reset either color, portably, to the default is to use either the set
253 -- state capability or the set default capability.
255 case req_display_cap_seq_for ( display_attr_caps $ term d )
257 ( style_to_apply_seq $ fixed_style attr )
260 -- only way to reset a color to the defaults
261 -> serialize_default_attr d out_ptr
262 >>= (\out_ptr' -> liftIO $ foldM (\ptr cap -> serialize_cap_expression cap [] ptr) out_ptr' caps)
265 -- implicitly resets the colors to the defaults
266 -> liftIO $ serialize_cap_expression ( fromJust $ set_attr_states
270 ( sgr_args_for_state state )
273 -- Otherwise the display colors are not changing or changing between two non-default
276 -- Still, it could be the case that the change in display attributes requires the
277 -- colors to be reset because the required capability was not available.
278 case req_display_cap_seq_for ( display_attr_caps $ term d )
280 ( style_diffs diffs )
282 -- Really, if terminals were re-implemented with modern concepts instead of
283 -- bowing down to 40 yr old dumb terminal requirements this would be the
284 -- only case ever reached!
285 -- Changes the style and color states according to the differences with the
286 -- currently applied states.
288 -> liftIO ( foldM (\ptr cap -> serialize_cap_expression cap [] ptr) out_ptr caps )
289 >>= apply_color_diff set_fore_color ( fore_color_diff diffs )
290 >>= apply_color_diff set_back_color ( back_color_diff diffs )
292 -- implicitly resets the colors to the defaults
293 -> liftIO $ serialize_cap_expression ( fromJust $ set_attr_states
297 ( sgr_args_for_state state )
301 attr = fix_display_attr prev_attr req_attr
303 ptr' <- case fixed_fore_color attr of
304 Just c -> liftIO $ serialize_cap_expression ( set_fore_color $ term d )
305 [ ansi_color_index c ]
307 Nothing -> return ptr
308 ptr'' <- case fixed_back_color attr of
309 Just c -> liftIO $ serialize_cap_expression ( set_back_color $ term d )
310 [ ansi_color_index c ]
312 Nothing -> return ptr'
314 apply_color_diff _f NoColorChange ptr
316 apply_color_diff _f ColorToDefault _ptr
317 = fail "ColorToDefault is not a possible case for apply_color_diffs"
318 apply_color_diff f ( SetColor c ) ptr
319 = liftIO $ serialize_cap_expression ( f $ term d )
320 [ ansi_color_index c ]
323 default_attr_required_bytes d
324 = cap_expression_required_bytes (set_default_attr $ term d) []
325 serialize_default_attr d out_ptr = do
326 liftIO $ serialize_cap_expression ( set_default_attr $ term d ) [] out_ptr
328ansi_color_index :: Color -> Word
329ansi_color_index (ISOColor v) = toEnum $ fromEnum v
330ansi_color_index (Color240 v) = 16 + ( toEnum $ fromEnum v )
332{- The sequence of terminfo caps to apply a given style are determined according to these rules.
334 - 1. The assumption is that it's preferable to use the simpler enter/exit mode capabilities than
335 - the full set display attribute state capability.
337 - 2. If a mode is supposed to be removed but there is not an exit capability defined then the
338 - display attributes are reset to defaults then the display attribute state is set.
340 - 3. If a mode is supposed to be applied but there is not an enter capability defined then then
341 - display attribute state is set if possible. Otherwise the mode is not applied.
343 - 4. If the display attribute state is being set then just update the arguments to that for any
349 = EnterExitSeq [CapExpression]
350 | SetState DisplayAttrState
352data DisplayAttrState = DisplayAttrState
353 { apply_standout :: Bool
354 , apply_underline :: Bool
355 , apply_reverse_video :: Bool
356 , apply_blink :: Bool
361sgr_args_for_state :: DisplayAttrState -> [CapParam]
362sgr_args_for_state attr_state = map (\b -> if b then 1 else 0)
363 [ apply_standout attr_state
364 , apply_underline attr_state
365 , apply_reverse_video attr_state
366 , apply_blink attr_state
367 , apply_dim attr_state
368 , apply_bold attr_state
371 , False -- alt char set
374req_display_cap_seq_for :: DisplayAttrCaps -> Style -> [StyleStateChange] -> DisplayAttrSeq
375req_display_cap_seq_for caps s diffs
376 -- if the state transition implied by any diff cannot be supported with an enter/exit mode cap
377 -- then either the state needs to be set or the attribute change ignored.
378 = case (any no_enter_exit_cap diffs, isJust $ set_attr_states caps) of
379 -- If all the diffs have an enter-exit cap then just use those
380 ( False, _ ) -> EnterExitSeq $ map enter_exit_cap diffs
381 -- If not all the diffs have an enter-exit cap and there is no set state cap then filter out
382 -- all unsupported diffs and just apply the rest
383 ( True, False ) -> EnterExitSeq $ map enter_exit_cap
384 $ filter (not . no_enter_exit_cap) diffs
385 -- if not all the diffs have an enter-exit can and there is a set state cap then just use
386 -- the set state cap.
387 ( True, True ) -> SetState $ state_for_style s
389 no_enter_exit_cap ApplyStandout = isNothing $ enter_standout caps
390 no_enter_exit_cap RemoveStandout = isNothing $ exit_standout caps
391 no_enter_exit_cap ApplyUnderline = isNothing $ enter_underline caps
392 no_enter_exit_cap RemoveUnderline = isNothing $ exit_underline caps
393 no_enter_exit_cap ApplyReverseVideo = isNothing $ enter_reverse_video caps
394 no_enter_exit_cap RemoveReverseVideo = True
395 no_enter_exit_cap ApplyBlink = True
396 no_enter_exit_cap RemoveBlink = True
397 no_enter_exit_cap ApplyDim = isNothing $ enter_dim_mode caps
398 no_enter_exit_cap RemoveDim = True
399 no_enter_exit_cap ApplyBold = isNothing $ enter_bold_mode caps
400 no_enter_exit_cap RemoveBold = True
401 enter_exit_cap ApplyStandout = fromJust $ enter_standout caps
402 enter_exit_cap RemoveStandout = fromJust $ exit_standout caps
403 enter_exit_cap ApplyUnderline = fromJust $ enter_underline caps
404 enter_exit_cap RemoveUnderline = fromJust $ exit_underline caps
405 enter_exit_cap ApplyReverseVideo = fromJust $ enter_reverse_video caps
406 enter_exit_cap ApplyDim = fromJust $ enter_dim_mode caps
407 enter_exit_cap ApplyBold = fromJust $ enter_bold_mode caps
408 enter_exit_cap _ = error "enter_exit_cap applied to diff that was known not to have one."
410state_for_style :: Style -> DisplayAttrState
411state_for_style s = DisplayAttrState
412 { apply_standout = is_style_set standout
413 , apply_underline = is_style_set underline
414 , apply_reverse_video = is_style_set reverse_video
415 , apply_blink = is_style_set blink
416 , apply_dim = is_style_set dim
417 , apply_bold = is_style_set bold
419 where is_style_set = has_style s
421style_to_apply_seq :: Style -> [StyleStateChange]
422style_to_apply_seq s = concat
423 [ apply_if_required ApplyStandout standout
424 , apply_if_required ApplyUnderline underline
425 , apply_if_required ApplyReverseVideo reverse_video
426 , apply_if_required ApplyBlink blink
427 , apply_if_required ApplyDim dim
428 , apply_if_required ApplyBlink bold
431 apply_if_required ap flag
432 = 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