on c0faeca help sign in
vty/src/Graphics/Vty/Terminal/TerminfoBased.hs
436 lines 20 kB history raw
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
7 )
8 where
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 )
24import Data.Word
26import Foreign.Ptr
27import Foreign.C.Types ( CLong, CSize, CInt )
29import qualified System.Console.Terminfo as Terminfo
30import System.IO
31import System.Posix.IO
32import System.Posix.Types ( Fd(..) )
34data Term = Term
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
47 , term_fd :: Fd
48 }
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
59 }
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 )
65 return ()
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.
72 -
73 -
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.
76 -}
77terminal_instance :: ( Applicative m, MonadIO m ) => String -> m Term
78terminal_instance in_ID = do
79 ti <- liftIO $ Terminfo.setupTerm in_ID
80 let require_cap str
81 = case Terminfo.getCapability ti (Terminfo.tiGetStr str) of
82 Nothing -> fail $ "Terminal does not define required capability \"" ++ str ++ "\""
83 Just cap_str -> do
84 parse_result <- parse_cap_expression cap_str
85 case parse_result of
86 Left e -> fail $ show e
87 Right cap -> return cap
88 probe_cap cap_name
89 = case Terminfo.getCapability ti (Terminfo.tiGetStr cap_name) of
90 Nothing -> return Nothing
91 Just cap_str -> do
92 parse_result <- parse_cap_expression cap_str
93 case parse_result of
94 Left e -> fail $ show e
95 Right cap -> return $ Just cap
96 the_fd <- liftIO $ dup stdOutput
97 pure Term
98 <*> pure in_ID
99 <*> pure ti
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
110 <*> pure the_fd
112current_display_attr_caps :: ( Applicative m, MonadIO m )
113 => Terminfo.Terminal
114 -> m DisplayAttrCaps
115current_display_attr_caps ti
116 = pure DisplayAttrCaps
117 <*> probe_cap "sgr"
118 <*> probe_cap "smso"
119 <*> probe_cap "rmso"
120 <*> probe_cap "smul"
121 <*> probe_cap "rmul"
122 <*> probe_cap "rev"
123 <*> probe_cap "dim"
124 <*> probe_cap "bold"
125 where probe_cap cap_name
126 = case Terminfo.getCapability ti (Terminfo.tiGetStr cap_name) of
127 Nothing -> return Nothing
128 Just cap_str -> do
129 parse_result <- parse_cap_expression cap_str
130 case parse_result of
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 []
140 liftIO $ closeFd $ term_fd t
141 return ()
143 reserve_display t = do
144 if (isJust $ smcup t)
145 then liftIO $ marshall_cap_to_terminal t (fromJust . smcup) []
146 else return ()
147 -- Screen on OS X does not appear to support smcup?
148 -- To approximate the expected behavior: clear the screen and then move the mouse to the
149 -- home position.
150 liftIO $ hFlush stdout
151 liftIO $ marshall_cap_to_terminal t clear_screen []
152 return ()
154 release_display t = do
155 if (isJust $ rmcup t)
156 then liftIO $ marshall_cap_to_terminal t (fromJust . rmcup) []
157 else return ()
158 liftIO $ marshall_cap_to_terminal t cnorm []
159 return ()
161 display_terminal_instance t b c = do
162 let color_count
163 = case Terminfo.getCapability (term_info t) (Terminfo.tiGetNum "colors" ) of
164 Nothing -> 8
165 Just v -> toEnum v
166 return $ c (DisplayContext b t color_count)
168 display_bounds _t = do
169 raw_size <- liftIO $ get_window_size
170 case raw_size of
171 ( w, h ) | w < 0 || h < 0 -> fail $ "getwinsize returned < 0 : " ++ show raw_size
172 | otherwise -> return $ DisplayRegion (toEnum w) (toEnum h)
174 -- | Output the byte buffer of the specified size to the terminal device.
175 output_byte_buffer t out_ptr out_byte_count = do
176 -- if the out fd is actually the same as stdout's then a
177 -- flush is required *before* the c_output_byte_buffer call
178 -- otherwise there may still be data in GHC's internal stdout buffer.
179 -- _ <- handleToFd stdout
180 let Fd c_fd = term_fd t
181 if out_byte_count /= 0
182 then c_output_byte_buffer c_fd out_ptr ( toEnum $! fromEnum out_byte_count )
183 else return ()
185foreign import ccall unsafe "output_buffer.h stdout_output_buffer" c_output_byte_buffer
186 :: CInt -> Ptr Word8 -> CSize -> IO ()
187foreign import ccall "gwinsz.h c_get_window_size" c_get_window_size
188 :: IO CLong
189-- foreign import ccall "fdatasync" c_fdatasync
190-- :: CInt -> IO CInt
192get_window_size :: IO (Int,Int)
193get_window_size = do
194 (a,b) <- (`divMod` 65536) `fmap` c_get_window_size
195 return (fromIntegral b, fromIntegral a)
197data DisplayContext = DisplayContext
198 { bounds :: DisplayRegion
199 , term :: Term
200 , supported_colors :: Word
201 }
203instance DisplayTerminal DisplayContext where
204 context_region d = bounds d
206 context_color_count d = supported_colors d
208 move_cursor_required_bytes d x y
209 = cap_expression_required_bytes (cup $ term d) [y, x]
210 serialize_move_cursor d x y out_ptr
211 = liftIO $ serialize_cap_expression (cup $ term d) [y, x] out_ptr
213 show_cursor_required_bytes d
214 = cap_expression_required_bytes (cnorm $ term d) []
215 serialize_show_cursor d out_ptr
216 = liftIO $ serialize_cap_expression (cnorm $ term d) [] out_ptr
218 hide_cursor_required_bytes d
219 = cap_expression_required_bytes (civis $ term d) []
220 serialize_hide_cursor d out_ptr
221 = liftIO $ serialize_cap_expression (civis $ term d) [] out_ptr
223 -- Instead of evaluating all the rules related to setting display attributes twice (once in
224 -- required bytes and again in serialize) or some memoization scheme just return a size
225 -- requirement as big the longest possible control string.
226 --
227 -- Which is assumed to the be less than 512 for now.
228 --
229 -- \todo Not verified as safe and wastes memory.
230 attr_required_bytes _d _prev_attr _req_attr _diffs = 512
232 -- Portably setting the display attributes is a giant pain in the ass.
233 -- If the terminal supports the sgr capability (which sets the on/off state of each style
234 -- directly ; and, for no good reason, resets the colors to the default) this always works:
235 -- 0. set the style attributes. This resets the fore and back color.
236 -- 1, If a foreground color is to be set then set the foreground color
237 -- 2. likewise with the background color
238 --
239 -- If the terminal does not support the sgr then
240 -- if there is a change from an applied color to the default (in either the fore or back color)
241 -- then:
242 -- 0. reset all display attributes (sgr0)
243 -- 1. enter required style modes
244 -- 2. set the fore color if required
245 -- 3. set the back color if required
246 --
247 -- Entering the required style modes could require a reset of the display attributes. If this is
248 -- the case then the back and fore colors always need to be set if not default.
249 --
250 -- All this (I think) is satisfied by the following logic:
251 serialize_set_attr d prev_attr req_attr diffs out_ptr = do
252 case (fore_color_diff diffs == ColorToDefault) || (back_color_diff diffs == ColorToDefault) of
253 -- The only way to reset either color, portably, to the default is to use either the set
254 -- state capability or the set default capability.
255 True -> do
256 case req_display_cap_seq_for ( display_attr_caps $ term d )
257 ( fixed_style attr )
258 ( style_to_apply_seq $ fixed_style attr )
259 of
260 EnterExitSeq caps
261 -- only way to reset a color to the defaults
262 -> serialize_default_attr d out_ptr
263 >>= (\out_ptr' -> liftIO $ foldM (\ptr cap -> serialize_cap_expression cap [] ptr) out_ptr' caps)
264 >>= set_colors
265 SetState state
266 -- implicitly resets the colors to the defaults
267 -> liftIO $ serialize_cap_expression ( fromJust $ set_attr_states
268 $ display_attr_caps
269 $ term d
270 )
271 ( sgr_args_for_state state )
272 out_ptr
273 >>= set_colors
274 -- Otherwise the display colors are not changing or changing between two non-default
275 -- points.
276 False -> do
277 -- Still, it could be the case that the change in display attributes requires the
278 -- colors to be reset because the required capability was not available.
279 case req_display_cap_seq_for ( display_attr_caps $ term d )
280 ( fixed_style attr )
281 ( style_diffs diffs )
282 of
283 -- Really, if terminals were re-implemented with modern concepts instead of
284 -- bowing down to 40 yr old dumb terminal requirements this would be the
285 -- only case ever reached!
286 -- Changes the style and color states according to the differences with the
287 -- currently applied states.
288 EnterExitSeq caps
289 -> liftIO ( foldM (\ptr cap -> serialize_cap_expression cap [] ptr) out_ptr caps )
290 >>= apply_color_diff set_fore_color ( fore_color_diff diffs )
291 >>= apply_color_diff set_back_color ( back_color_diff diffs )
292 SetState state
293 -- implicitly resets the colors to the defaults
294 -> liftIO $ serialize_cap_expression ( fromJust $ set_attr_states
295 $ display_attr_caps
296 $ term d
297 )
298 ( sgr_args_for_state state )
299 out_ptr
300 >>= set_colors
301 where
302 attr = fix_display_attr prev_attr req_attr
303 set_colors ptr = do
304 ptr' <- case fixed_fore_color attr of
305 Just c -> liftIO $ serialize_cap_expression ( set_fore_color $ term d )
306 [ ansi_color_index c ]
307 ptr
308 Nothing -> return ptr
309 ptr'' <- case fixed_back_color attr of
310 Just c -> liftIO $ serialize_cap_expression ( set_back_color $ term d )
311 [ ansi_color_index c ]
312 ptr'
313 Nothing -> return ptr'
314 return ptr''
315 apply_color_diff _f NoColorChange ptr
316 = return ptr
317 apply_color_diff _f ColorToDefault _ptr
318 = fail "ColorToDefault is not a possible case for apply_color_diffs"
319 apply_color_diff f ( SetColor c ) ptr
320 = liftIO $ serialize_cap_expression ( f $ term d )
321 [ ansi_color_index c ]
322 ptr
324 default_attr_required_bytes d
325 = cap_expression_required_bytes (set_default_attr $ term d) []
326 serialize_default_attr d out_ptr = do
327 liftIO $ serialize_cap_expression ( set_default_attr $ term d ) [] out_ptr
329ansi_color_index :: Color -> Word
330ansi_color_index (ISOColor v) = toEnum $ fromEnum v
331ansi_color_index (Color240 v) = 16 + ( toEnum $ fromEnum v )
333{- The sequence of terminfo caps to apply a given style are determined according to these rules.
334 -
335 - 1. The assumption is that it's preferable to use the simpler enter/exit mode capabilities than
336 - the full set display attribute state capability.
337 -
338 - 2. If a mode is supposed to be removed but there is not an exit capability defined then the
339 - display attributes are reset to defaults then the display attribute state is set.
340 -
341 - 3. If a mode is supposed to be applied but there is not an enter capability defined then then
342 - display attribute state is set if possible. Otherwise the mode is not applied.
343 -
344 - 4. If the display attribute state is being set then just update the arguments to that for any
345 - apply/remove.
346 -
347 -}
349data DisplayAttrSeq
350 = EnterExitSeq [CapExpression]
351 | SetState DisplayAttrState
353data DisplayAttrState = DisplayAttrState
354 { apply_standout :: Bool
355 , apply_underline :: Bool
356 , apply_reverse_video :: Bool
357 , apply_blink :: Bool
358 , apply_dim :: Bool
359 , apply_bold :: Bool
360 }
362sgr_args_for_state :: DisplayAttrState -> [CapParam]
363sgr_args_for_state attr_state = map (\b -> if b then 1 else 0)
364 [ apply_standout attr_state
365 , apply_underline attr_state
366 , apply_reverse_video attr_state
367 , apply_blink attr_state
368 , apply_dim attr_state
369 , apply_bold attr_state
370 , False -- invis
371 , False -- protect
372 , False -- alt char set
373 ]
375req_display_cap_seq_for :: DisplayAttrCaps -> Style -> [StyleStateChange] -> DisplayAttrSeq
376req_display_cap_seq_for caps s diffs
377 -- if the state transition implied by any diff cannot be supported with an enter/exit mode cap
378 -- then either the state needs to be set or the attribute change ignored.
379 = case (any no_enter_exit_cap diffs, isJust $ set_attr_states caps) of
380 -- If all the diffs have an enter-exit cap then just use those
381 ( False, _ ) -> EnterExitSeq $ map enter_exit_cap diffs
382 -- If not all the diffs have an enter-exit cap and there is no set state cap then filter out
383 -- all unsupported diffs and just apply the rest
384 ( True, False ) -> EnterExitSeq $ map enter_exit_cap
385 $ filter (not . no_enter_exit_cap) diffs
386 -- if not all the diffs have an enter-exit can and there is a set state cap then just use
387 -- the set state cap.
388 ( True, True ) -> SetState $ state_for_style s
389 where
390 no_enter_exit_cap ApplyStandout = isNothing $ enter_standout caps
391 no_enter_exit_cap RemoveStandout = isNothing $ exit_standout caps
392 no_enter_exit_cap ApplyUnderline = isNothing $ enter_underline caps
393 no_enter_exit_cap RemoveUnderline = isNothing $ exit_underline caps
394 no_enter_exit_cap ApplyReverseVideo = isNothing $ enter_reverse_video caps
395 no_enter_exit_cap RemoveReverseVideo = True
396 no_enter_exit_cap ApplyBlink = True
397 no_enter_exit_cap RemoveBlink = True
398 no_enter_exit_cap ApplyDim = isNothing $ enter_dim_mode caps
399 no_enter_exit_cap RemoveDim = True
400 no_enter_exit_cap ApplyBold = isNothing $ enter_bold_mode caps
401 no_enter_exit_cap RemoveBold = True
402 enter_exit_cap ApplyStandout = fromJust $ enter_standout caps
403 enter_exit_cap RemoveStandout = fromJust $ exit_standout caps
404 enter_exit_cap ApplyUnderline = fromJust $ enter_underline caps
405 enter_exit_cap RemoveUnderline = fromJust $ exit_underline caps
406 enter_exit_cap ApplyReverseVideo = fromJust $ enter_reverse_video caps
407 enter_exit_cap ApplyDim = fromJust $ enter_dim_mode caps
408 enter_exit_cap ApplyBold = fromJust $ enter_bold_mode caps
409 enter_exit_cap _ = error "enter_exit_cap applied to diff that was known not to have one."
411state_for_style :: Style -> DisplayAttrState
412state_for_style s = DisplayAttrState
413 { apply_standout = is_style_set standout
414 , apply_underline = is_style_set underline
415 , apply_reverse_video = is_style_set reverse_video
416 , apply_blink = is_style_set blink
417 , apply_dim = is_style_set dim
418 , apply_bold = is_style_set bold
419 }
420 where is_style_set = has_style s
422style_to_apply_seq :: Style -> [StyleStateChange]
423style_to_apply_seq s = concat
424 [ apply_if_required ApplyStandout standout
425 , apply_if_required ApplyUnderline underline
426 , apply_if_required ApplyReverseVideo reverse_video
427 , apply_if_required ApplyBlink blink
428 , apply_if_required ApplyDim dim
429 , apply_if_required ApplyBlink bold
430 ]
431 where
432 apply_if_required ap flag
433 = if 0 == ( flag .&. s )
434 then []
435 else [ ap ]