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