on master help sign in
refactor vty to use standard naming convention.
commita4ef14d1d93e305ea1d77dc2bd285f5816883f0c authorCorey O'Connor <coreyoconnor@gmail.com> dateFri 11 Apr 2014, 17:51 (13 years ago) parent76b1a60
63 files changed+3209−3192
CHANGELOG+5−3 scripts/256colres.pl+3−3 src/Codec/Binary/UTF8/Debug.hs+4−4 src/Data/Terminfo/Eval.hs+46−48 src/Data/Terminfo/Parse.hs+172−172 src/Graphics/Text/Width.hs+6−6 src/Graphics/Vty.hs+43−43 src/Graphics/Vty/Attributes.hs+50−46 src/Graphics/Vty/Attributes/Color240.hs+3−3 src/Graphics/Vty/Debug.hs+14−14 src/Graphics/Vty/Debug/Image.hs+10−10 src/Graphics/Vty/DisplayAttributes.hs+42−42 src/Graphics/Vty/Image.hs+122−122 src/Graphics/Vty/Image/Internal.hs+136−136 src/Graphics/Vty/Inline.hs+43−44 src/Graphics/Vty/Inline/Unsafe.hs+21−7 src/Graphics/Vty/Input.hs+19−19 src/Graphics/Vty/Input/Internal.hs+72−72 src/Graphics/Vty/Input/Terminfo.hs+29−29 src/Graphics/Vty/Input/Terminfo/ANSI.hs+18−18 src/Graphics/Vty/Input/Terminfo/XTerm7Bit.hs+18−18 src/Graphics/Vty/Output.hs+37−37 src/Graphics/Vty/Output/Interface.hs+112−112 src/Graphics/Vty/Output/MacOSX.hs+25−25 src/Graphics/Vty/Output/Mock.hs+27−27 src/Graphics/Vty/Output/TerminfoBased.hs+229−229 src/Graphics/Vty/Output/XTermColor.hs+22−22 src/Graphics/Vty/Picture.hs+25−25 src/Graphics/Vty/PictureToSpans.hs+167−167 src/Graphics/Vty/Prelude.hs+4−4 src/Graphics/Vty/Span.hs+50−50 test/BenchImageFuzz.hs+6−6 test/BenchNoDiffOpt.hs+16−16 test/BenchRenderChar.hs+19−19 test/BenchVerticalScroll.hs+8−8 test/ControlTable.hs+3−3 test/EventEcho.hs+14−14 test/Rouge.hs+52−52 test/RougeStory.hs+73−73 test/Verify.hs+4−4 test/Verify/Data/Terminfo/Parse.hs+30−30 test/Verify/Graphics/Vty/Attributes.hs+30−30 test/Verify/Graphics/Vty/Image.hs+55−55 test/Verify/Graphics/Vty/Output.hs+10−10 test/Verify/Graphics/Vty/Picture.hs+10−10 test/Verify/Graphics/Vty/Span.hs+6−6 test/VerifyCropSpanGeneration.hs+55−55 test/VerifyEmptyImageProps.hs+2−2 test/VerifyEvalTerminfoCaps.hs+26−26 test/VerifyImageOps.hs+113−113 test/VerifyImageTrans.hs+17−17 test/VerifyInline.hs+2−2 test/VerifyLayersSpanGeneration.hs+87−87 test/VerifyOutput.hs+29−29 test/VerifyParseTerminfoCaps.hs+45−45 test/VerifySimpleSpanGeneration.hs+154−154 test/VerifyUsingMockInput.hs+119−119 test/VerifyUsingMockTerminal.hs+51−51 test/VerifyUtf8Width.hs+13−13 test/benchmark.hs+21−21 test/interactive_terminal_test.hs+557−557 test/vty-examples.cabal+6−6 test/vty_inline_example.hs+2−2
CHANGELOG+5−3
@@ -1,4 +1,6 @@
115.0.0
2+ * The naming convention now matches:
3+ * http://www.haskell.org/haskellwiki/Programming_guidelines#Naming_Conventions
24 * all projects using vty for input must be compiled with -threaded. This could be resolved but
35 would like to avoid the complexity for now.
46 * mkVtyEscDelay has been removed. Use "mkVty def". Which initialized vty with the default
@@ -27,14 +29,14 @@
2729 added to to pad images when images of different sizes are joined.
2830 * If the background is clear there is no background layer.
2931 * If there is a background character then the bottom layer is the background layer.
30− * empty_picture is a Picture with no layers and no cursor
31− * add_to_top and add_to_bottom add a layer to the top and bottom of the given Picture.
32+ * emptyPicture is a Picture with no layers and no cursor
33+ * addToTop and addToBottom add a layer to the top and bottom of the given Picture.
3234 * compatibility improvements:
3335 * terminfo based terminals with no cursor support are silently accepted. The cursor
3436 visibility changes in the Picture will have no effect.
3537 * alternate (setf/setb) color maps supported. Though colors beyond the first 8 are just a
3638 guess.
37− * added "rgb_color" for easy support of RGB specified colors.
39+ * added "rgbColor" for easy support of RGB specified colors.
3840 * examples moved to vty-examples package. See test directory for cabal file.
3941 * vty-interactive-terminal-test
4042 * interactive test. Useful for building a bug report for vty's author.
scripts/256colres.pl+3−3
@@ -59,9 +59,9 @@ import Text.Printf
5959--
6060-- generated from 256colres.pl which is forked from xterm 256colres.pl
6161-- todo: all values get clamped high.
62−rgb_color :: Integral i => i -> i -> i -> Color
63−rgb_color r g b
64− | r < 0 && g < 0 && b < 0 = error "rgb_color with negative color component intensity"
62+rgbColor :: Integral i => i -> i -> i -> Color
63+rgbColor r g b
64+ | r < 0 && g < 0 && b < 0 = error "rgbColor with negative color component intensity"
6565EOF
6666
6767my $grey_line=" | r == %d && g == %d && b == %d = Color240 %d\n";
src/Codec/Binary/UTF8/Debug.hs+4−4
@@ -10,9 +10,9 @@ import Numeric
1010
1111-- | Converts an array of ISO-10646 characters (Char type) to an array of Word8 bytes that is the
1212-- corresponding UTF8 byte sequence
13−utf8_from_iso :: [Int] -> [Word8]
14−utf8_from_iso = encode . map toEnum
13+utf8FromIso :: [Int] -> [Word8]
14+utf8FromIso = encode . map toEnum
1515
16−pp_utf8 :: [Int] -> IO ()
17−pp_utf8 = print . map (\f -> f "") . map showHex . utf8_from_iso
16+ppUtf8 :: [Int] -> IO ()
17+ppUtf8 = print . map (\f -> f "") . map showHex . utf8FromIso
1818
src/Data/Terminfo/Eval.hs+46−48
@@ -3,9 +3,8 @@
33{-# OPTIONS_GHC -funbox-strict-fields #-}
44{- Evaluates the paramaterized terminfo string capability with the given parameters.
55 -
6− - todo: This can be greatly simplified.
76 -}
8−module Data.Terminfo.Eval (write_cap_expr)
7+module Data.Terminfo.Eval (writeCapExpr)
98 where
109
1110import Blaze.ByteString.Builder.Word
@@ -24,9 +23,9 @@ import qualified Data.Vector.Unboxed as Vector
2423
2524-- | capability evaluator state
2625data EvalState = EvalState
27− { eval_stack :: ![CapParam]
28− , eval_expression :: !CapExpression
29− , eval_params :: ![CapParam]
26+ { evalStack :: ![CapParam]
27+ , evalExpression :: !CapExpression
28+ , evalParams :: ![CapParam]
3029 }
3130
3231type Eval a = StateT EvalState (Writer Write) a
@@ -34,98 +33,97 @@ type Eval a = StateT EvalState (Writer Write) a
3433pop :: Eval CapParam
3534pop = do
3635 s <- get
37− let v : stack' = eval_stack s
38− s' = s { eval_stack = stack' }
36+ let v : stack' = evalStack s
37+ s' = s { evalStack = stack' }
3938 put s'
4039 return v
4140
42−read_param :: Word -> Eval CapParam
43−read_param pn = do
44− !params <- get >>= return . eval_params
41+readParam :: Word -> Eval CapParam
42+readParam pn = do
43+ !params <- get >>= return . evalParams
4544 return $! genericIndex params pn
4645
4746push :: CapParam -> Eval ()
4847push !v = do
4948 s <- get
50− let s' = s { eval_stack = v : eval_stack s }
49+ let s' = s { evalStack = v : evalStack s }
5150 put s'
5251
53−apply_param_ops :: CapExpression -> [CapParam] -> [CapParam]
54−apply_param_ops cap params = foldl apply_param_op params (param_ops cap)
52+applyParamOps :: CapExpression -> [CapParam] -> [CapParam]
53+applyParamOps cap params = foldl applyParamOp params (paramOps cap)
5554
56−apply_param_op :: [CapParam] -> ParamOp -> [CapParam]
57−apply_param_op params IncFirstTwo = map (+ 1) params
55+applyParamOp :: [CapParam] -> ParamOp -> [CapParam]
56+applyParamOp params IncFirstTwo = map (+ 1) params
5857
59−write_cap_expr :: CapExpression -> [CapParam] -> Write
60−write_cap_expr cap params =
61− let params' = apply_param_ops cap params
58+writeCapExpr :: CapExpression -> [CapParam] -> Write
59+writeCapExpr cap params =
60+ let params' = applyParamOps cap params
6261 s_0 = EvalState [] cap params'
63− in snd $ runWriter (runStateT (write_cap_ops (cap_ops cap)) s_0)
62+ in snd $ runWriter (runStateT (writeCapOps (capOps cap)) s_0)
6463
65−write_cap_ops :: CapOps -> Eval ()
66−write_cap_ops ops = mapM_ write_cap_op ops
64+writeCapOps :: CapOps -> Eval ()
65+writeCapOps ops = mapM_ writeCapOp ops
6766
68−write_cap_op :: CapOp -> Eval ()
69−write_cap_op (Bytes !offset !count) = do
70− !cap <- get >>= return . eval_expression
71− let bytes = Vector.take count $ Vector.drop offset (cap_bytes cap)
67+writeCapOp :: CapOp -> Eval ()
68+writeCapOp (Bytes !offset !count) = do
69+ !cap <- get >>= return . evalExpression
70+ let bytes = Vector.take count $ Vector.drop offset (capBytes cap)
7271 Vector.forM_ bytes $ tell.writeWord8
73−write_cap_op DecOut = do
72+writeCapOp DecOut = do
7473 p <- pop
75− let out_str = show p
76− forM_ out_str $ tell.writeWord8.toEnum.fromEnum
77−write_cap_op CharOut = do
74+ forM_ (show p) $ tell.writeWord8.toEnum.fromEnum
75+writeCapOp CharOut = do
7876 pop >>= tell.writeWord8.toEnum.fromEnum
79−write_cap_op (PushParam pn) = do
80− read_param pn >>= push
81−write_cap_op (PushValue v) = do
77+writeCapOp (PushParam pn) = do
78+ readParam pn >>= push
79+writeCapOp (PushValue v) = do
8280 push v
83−write_cap_op (Conditional expr parts) = do
84− write_cap_ops expr
85− write_contitional_parts parts
81+writeCapOp (Conditional expr parts) = do
82+ writeCapOps expr
83+ writeContitionalParts parts
8684 where
87− write_contitional_parts [] = return ()
88− write_contitional_parts ((true_ops, false_ops) : false_parts) = do
85+ writeContitionalParts [] = return ()
86+ writeContitionalParts ((trueOps, false_ops) : falseParts) = do
8987 -- (man 5 terminfo)
9088 -- Usually the %? expr part pushes a value onto the stack, and %t pops it from the
9189 -- stack, testing if it is nonzero (true). If it is zero (false), control
9290 -- passes to the %e (else) part.
9391 v <- pop
9492 if v /= 0
95− then write_cap_ops true_ops
93+ then writeCapOps trueOps
9694 else do
97− write_cap_ops false_ops
98− write_contitional_parts false_parts
95+ writeCapOps false_ops
96+ writeContitionalParts falseParts
9997
100−write_cap_op BitwiseOr = do
98+writeCapOp BitwiseOr = do
10199 v_0 <- pop
102100 v_1 <- pop
103101 push $ v_0 .|. v_1
104−write_cap_op BitwiseAnd = do
102+writeCapOp BitwiseAnd = do
105103 v_0 <- pop
106104 v_1 <- pop
107105 push $ v_0 .&. v_1
108−write_cap_op BitwiseXOr = do
106+writeCapOp BitwiseXOr = do
109107 v_1 <- pop
110108 v_0 <- pop
111109 push $ v_0 `xor` v_1
112−write_cap_op ArithPlus = do
110+writeCapOp ArithPlus = do
113111 v_1 <- pop
114112 v_0 <- pop
115113 push $ v_0 + v_1
116−write_cap_op ArithMinus = do
114+writeCapOp ArithMinus = do
117115 v_1 <- pop
118116 v_0 <- pop
119117 push $ v_0 - v_1
120−write_cap_op CompareEq = do
118+writeCapOp CompareEq = do
121119 v_1 <- pop
122120 v_0 <- pop
123121 push $ if v_0 == v_1 then 1 else 0
124−write_cap_op CompareLt = do
122+writeCapOp CompareLt = do
125123 v_1 <- pop
126124 v_0 <- pop
127125 push $ if v_0 < v_1 then 1 else 0
128−write_cap_op CompareGt = do
126+writeCapOp CompareGt = do
129127 v_1 <- pop
130128 v_0 <- pop
131129 push $ if v_0 > v_1 then 1 else 0
src/Data/Terminfo/Parse.hs+172−172
@@ -19,25 +19,25 @@ import Numeric (showHex)
1919import Text.ParserCombinators.Parsec
2020
2121data CapExpression = CapExpression
22− { cap_ops :: !CapOps
23− , cap_bytes :: !(Vector.Vector Word8)
24− , source_string :: !String
25− , param_count :: !Int
26− , param_ops :: !ParamOps
22+ { capOps :: !CapOps
23+ , capBytes :: !(Vector.Vector Word8)
24+ , sourceString :: !String
25+ , paramCount :: !Int
26+ , paramOps :: !ParamOps
2727 } deriving (Eq)
2828
2929instance Show CapExpression where
3030 show c
31− = "CapExpression { " ++ show (cap_ops c) ++ " }"
32− ++ " <- [" ++ hex_dump ( map ( toEnum . fromEnum ) $! source_string c ) ++ "]"
33− ++ " <= " ++ show (source_string c)
31+ = "CapExpression { " ++ show (capOps c) ++ " }"
32+ ++ " <- [" ++ hex_dump ( map ( toEnum . fromEnum ) $! sourceString c ) ++ "]"
33+ ++ " <= " ++ show (sourceString c)
3434 where
3535 hex_dump :: [Word8] -> String
3636 hex_dump = foldr (\b s -> showHex b s) ""
3737
3838instance NFData CapExpression where
39− rnf (CapExpression ops !_bytes !str !c !p_ops)
40− = rnf ops `seq` rnf str `seq` rnf c `seq` rnf p_ops
39+ rnf (CapExpression ops !_bytes !str !c !pOps)
40+ = rnf ops `seq` rnf str `seq` rnf c `seq` rnf pOps
4141
4242type CapParam = Word
4343
@@ -60,10 +60,10 @@ data CapOp =
6060 deriving (Show, Eq)
6161
6262instance NFData CapOp where
63− rnf (Bytes offset byte_count ) = rnf offset `seq` rnf byte_count
63+ rnf (Bytes offset byteCount ) = rnf offset `seq` rnf byteCount
6464 rnf (PushParam pn) = rnf pn
6565 rnf (PushValue v) = rnf v
66− rnf (Conditional c_expr c_parts) = rnf c_expr `seq` rnf c_parts
66+ rnf (Conditional cExpr cParts) = rnf cExpr `seq` rnf cParts
6767 rnf BitwiseOr = ()
6868 rnf BitwiseXOr = ()
6969 rnf BitwiseAnd = ()
@@ -83,256 +83,256 @@ data ParamOp =
8383instance NFData ParamOp where
8484 rnf IncFirstTwo = ()
8585
86−parse_cap_expression :: String -> Either ParseError CapExpression
87−parse_cap_expression cap_string =
88− let v = runParser cap_expression_parser
89− initial_build_state
90− "terminfo cap"
91− cap_string
86+parseCapExpression :: String -> Either ParseError CapExpression
87+parseCapExpression capString =
88+ let v = runParser capExpressionParser
89+ initialBuildState
90+ "terminfo cap"
91+ capString
9292 in case v of
9393 Left e -> Left e
94− Right build_results -> Right $ construct_cap_expression cap_string build_results
94+ Right buildResults -> Right $ constructCapExpression capString buildResults
9595
96−construct_cap_expression :: [Char] -> BuildResults -> CapExpression
97−construct_cap_expression cap_string build_results =
96+constructCapExpression :: [Char] -> BuildResults -> CapExpression
97+constructCapExpression capString buildResults =
9898 let expr = CapExpression
99− { cap_ops = out_cap_ops build_results
99+ { capOps = outCapOps buildResults
100100 -- The cap bytes are the lower 8 bits of the input string's characters.
101101 -- \todo Verify the input string actually contains an 8bit byte per character.
102− , cap_bytes = Vector.fromList $ map (toEnum.fromEnum) cap_string
103− , source_string = cap_string
104− , param_count = out_param_count build_results
105− , param_ops = out_param_ops build_results
102+ , capBytes = Vector.fromList $ map (toEnum.fromEnum) capString
103+ , sourceString = capString
104+ , paramCount = outParamCount buildResults
105+ , paramOps = outParamOps buildResults
106106 }
107107 in rnf expr `seq` expr
108108
109109type CapParser a = GenParser Char BuildState a
110110
111−cap_expression_parser :: CapParser BuildResults
112−cap_expression_parser = do
113− rs <- many $ param_escape_parser <|> bytes_op_parser
111+capExpressionParser :: CapParser BuildResults
112+capExpressionParser = do
113+ rs <- many $ paramEscapeParser <|> bytesOpParser
114114 return $ mconcat rs
115115
116−param_escape_parser :: CapParser BuildResults
117−param_escape_parser = do
116+paramEscapeParser :: CapParser BuildResults
117+paramEscapeParser = do
118118 _ <- char '%'
119− inc_offset 1
120− literal_percent_parser <|> param_op_parser
119+ incOffset 1
120+ literalPercentParser <|> paramOpParser
121121
122−literal_percent_parser :: CapParser BuildResults
123−literal_percent_parser = do
122+literalPercentParser :: CapParser BuildResults
123+literalPercentParser = do
124124 _ <- char '%'
125− start_offset <- getState >>= return . next_offset
126− inc_offset 1
127− return $ BuildResults 0 [Bytes start_offset 1] []
128−
129−param_op_parser :: CapParser BuildResults
130−param_op_parser
131− = increment_op_parser
132− <|> push_op_parser
133− <|> dec_out_parser
134− <|> char_out_parser
135− <|> conditional_op_parser
136− <|> bitwise_op_parser
137− <|> arith_op_parser
138− <|> literal_int_op_parser
139− <|> compare_op_parser
140− <|> char_const_parser
141−
142−increment_op_parser :: CapParser BuildResults
143−increment_op_parser = do
125+ startOffset <- getState >>= return . nextOffset
126+ incOffset 1
127+ return $ BuildResults 0 [Bytes startOffset 1] []
128+
129+paramOpParser :: CapParser BuildResults
130+paramOpParser
131+ = incrementOpParser
132+ <|> pushOpParser
133+ <|> decOutParser
134+ <|> charOutParser
135+ <|> conditionalOpParser
136+ <|> bitwiseOpParser
137+ <|> arithOpParser
138+ <|> literalIntOpParser
139+ <|> compareOpParser
140+ <|> charConstParser
141+
142+incrementOpParser :: CapParser BuildResults
143+incrementOpParser = do
144144 _ <- char 'i'
145− inc_offset 1
145+ incOffset 1
146146 return $ BuildResults 0 [] [ IncFirstTwo ]
147147
148−push_op_parser :: CapParser BuildResults
149−push_op_parser = do
148+pushOpParser :: CapParser BuildResults
149+pushOpParser = do
150150 _ <- char 'p'
151− param_n <- digit >>= return . (\d -> read [d])
152− inc_offset 2
153− return $ BuildResults (fromEnum param_n) [PushParam $ param_n - 1] []
151+ paramN <- digit >>= return . (\d -> read [d])
152+ incOffset 2
153+ return $ BuildResults (fromEnum paramN) [PushParam $ paramN - 1] []
154154
155−dec_out_parser :: CapParser BuildResults
156−dec_out_parser = do
155+decOutParser :: CapParser BuildResults
156+decOutParser = do
157157 _ <- char 'd'
158− inc_offset 1
158+ incOffset 1
159159 return $ BuildResults 0 [ DecOut ] []
160160
161−char_out_parser :: CapParser BuildResults
162−char_out_parser = do
161+charOutParser :: CapParser BuildResults
162+charOutParser = do
163163 _ <- char 'c'
164− inc_offset 1
164+ incOffset 1
165165 return $ BuildResults 0 [ CharOut ] []
166166
167−conditional_op_parser :: CapParser BuildResults
168−conditional_op_parser = do
167+conditionalOpParser :: CapParser BuildResults
168+conditionalOpParser = do
169169 _ <- char '?'
170− inc_offset 1
171− cond_part <- many_expr conditional_true_parser
172− parts <- many_p
173− ( do
174− true_part <- many_expr $ choice [ try $ lookAhead conditional_end_parser
175− , conditional_false_parser
176− ]
177− false_part <- many_expr $ choice [ try $ lookAhead conditional_end_parser
178− , conditional_true_parser
179− ]
180− return ( true_part, false_part )
181− )
182− conditional_end_parser
183−
184− let true_parts = map fst parts
185− false_parts = map snd parts
186− BuildResults n cond cond_param_ops = cond_part
187−
188− let n' = maximum $ n : map out_param_count true_parts
189− n'' = maximum $ n' : map out_param_count false_parts
190−
191− let true_ops = map out_cap_ops true_parts
192− false_ops = map out_cap_ops false_parts
193− cond_parts = zip true_ops false_ops
194−
195− let true_param_ops = mconcat $ map out_param_ops true_parts
196− false_param_ops = mconcat $ map out_param_ops false_parts
197− p_ops = mconcat [cond_param_ops, true_param_ops, false_param_ops]
198−
199− return $ BuildResults n'' [ Conditional cond cond_parts ] p_ops
170+ incOffset 1
171+ cond_part <- manyExpr conditionalTrueParser
172+ parts <- manyP
173+ ( do
174+ truePart <- manyExpr $ choice [ try $ lookAhead conditionalEndParser
175+ , conditionalFalseParser
176+ ]
177+ falsePart <- manyExpr $ choice [ try $ lookAhead conditionalEndParser
178+ , conditionalTrueParser
179+ ]
180+ return ( truePart, falsePart )
181+ )
182+ conditionalEndParser
183+
184+ let trueParts = map fst parts
185+ falseParts = map snd parts
186+ BuildResults n cond condParamOps = cond_part
187+
188+ let n' = maximum $ n : map outParamCount trueParts
189+ n'' = maximum $ n' : map outParamCount falseParts
190+
191+ let trueOps = map outCapOps trueParts
192+ falseOps = map outCapOps falseParts
193+ condParts = zip trueOps falseOps
194+
195+ let trueParamOps = mconcat $ map outParamOps trueParts
196+ falseParamOps = mconcat $ map outParamOps falseParts
197+ pOps = mconcat [condParamOps, trueParamOps, falseParamOps]
198+
199+ return $ BuildResults n'' [ Conditional cond condParts ] pOps
200200
201201 where
202− many_p !p !end = choice
202+ manyP !p !end = choice
203203 [ try end >> return []
204204 , do !v <- p
205− !vs <- many_p p end
205+ !vs <- manyP p end
206206 return $! v : vs
207207 ]
208− many_expr end = liftM mconcat $ many_p ( param_escape_parser <|> bytes_op_parser ) end
208+ manyExpr end = liftM mconcat $ manyP ( paramEscapeParser <|> bytesOpParser ) end
209209
210−conditional_true_parser :: CapParser ()
211−conditional_true_parser = do
210+conditionalTrueParser :: CapParser ()
211+conditionalTrueParser = do
212212 _ <- string "%t"
213− inc_offset 2
213+ incOffset 2
214214
215−conditional_false_parser :: CapParser ()
216−conditional_false_parser = do
215+conditionalFalseParser :: CapParser ()
216+conditionalFalseParser = do
217217 _ <- string "%e"
218− inc_offset 2
218+ incOffset 2
219219
220−conditional_end_parser :: CapParser ()
221−conditional_end_parser = do
220+conditionalEndParser :: CapParser ()
221+conditionalEndParser = do
222222 _ <- string "%;"
223− inc_offset 2
223+ incOffset 2
224224
225−bitwise_op_parser :: CapParser BuildResults
226−bitwise_op_parser
227− = bitwise_or_parser
228− <|> bitwise_and_parser
229− <|> bitwise_xor_parser
225+bitwiseOpParser :: CapParser BuildResults
226+bitwiseOpParser
227+ = bitwiseOrParser
228+ <|> bitwiseAndParser
229+ <|> bitwiseXorParser
230230
231−bitwise_or_parser :: CapParser BuildResults
232−bitwise_or_parser = do
231+bitwiseOrParser :: CapParser BuildResults
232+bitwiseOrParser = do
233233 _ <- char '|'
234− inc_offset 1
234+ incOffset 1
235235 return $ BuildResults 0 [ BitwiseOr ] [ ]
236236
237−bitwise_and_parser :: CapParser BuildResults
238−bitwise_and_parser = do
237+bitwiseAndParser :: CapParser BuildResults
238+bitwiseAndParser = do
239239 _ <- char '&'
240− inc_offset 1
240+ incOffset 1
241241 return $ BuildResults 0 [ BitwiseAnd ] [ ]
242242
243−bitwise_xor_parser :: CapParser BuildResults
244−bitwise_xor_parser = do
243+bitwiseXorParser :: CapParser BuildResults
244+bitwiseXorParser = do
245245 _ <- char '^'
246− inc_offset 1
246+ incOffset 1
247247 return $ BuildResults 0 [ BitwiseXOr ] [ ]
248248
249−arith_op_parser :: CapParser BuildResults
250−arith_op_parser
251− = plus_op
252− <|> minus_op
249+arithOpParser :: CapParser BuildResults
250+arithOpParser
251+ = plusOp
252+ <|> minusOp
253253 where
254− plus_op = do
254+ plusOp = do
255255 _ <- char '+'
256− inc_offset 1
256+ incOffset 1
257257 return $ BuildResults 0 [ ArithPlus ] [ ]
258− minus_op = do
258+ minusOp = do
259259 _ <- char '-'
260− inc_offset 1
260+ incOffset 1
261261 return $ BuildResults 0 [ ArithMinus ] [ ]
262262
263−literal_int_op_parser :: CapParser BuildResults
264−literal_int_op_parser = do
263+literalIntOpParser :: CapParser BuildResults
264+literalIntOpParser = do
265265 _ <- char '{'
266− inc_offset 1
267− n_str <- many1 digit
268− inc_offset $ toEnum $ length n_str
269− let n :: Word = read n_str
266+ incOffset 1
267+ nStr <- many1 digit
268+ incOffset $ toEnum $ length nStr
269+ let n :: Word = read nStr
270270 _ <- char '}'
271− inc_offset 1
271+ incOffset 1
272272 return $ BuildResults 0 [ PushValue n ] [ ]
273273
274−compare_op_parser :: CapParser BuildResults
275−compare_op_parser
276− = compare_eq_op
277− <|> compare_lt_op
278− <|> compare_gt_op
274+compareOpParser :: CapParser BuildResults
275+compareOpParser
276+ = compareEqOp
277+ <|> compareLtOp
278+ <|> compareGtOp
279279 where
280− compare_eq_op = do
280+ compareEqOp = do
281281 _ <- char '='
282− inc_offset 1
282+ incOffset 1
283283 return $ BuildResults 0 [ CompareEq ] [ ]
284− compare_lt_op = do
284+ compareLtOp = do
285285 _ <- char '<'
286− inc_offset 1
286+ incOffset 1
287287 return $ BuildResults 0 [ CompareLt ] [ ]
288− compare_gt_op = do
288+ compareGtOp = do
289289 _ <- char '>'
290− inc_offset 1
290+ incOffset 1
291291 return $ BuildResults 0 [ CompareGt ] [ ]
292292
293−bytes_op_parser :: CapParser BuildResults
294−bytes_op_parser = do
293+bytesOpParser :: CapParser BuildResults
294+bytesOpParser = do
295295 bytes <- many1 $ satisfy (/= '%')
296− start_offset <- getState >>= return . next_offset
296+ startOffset <- getState >>= return . nextOffset
297297 let !c = length bytes
298298 !s <- getState
299− let s' = s { next_offset = start_offset + c }
299+ let s' = s { nextOffset = startOffset + c }
300300 setState s'
301− return $ BuildResults 0 [Bytes start_offset c] []
301+ return $ BuildResults 0 [Bytes startOffset c] []
302302
303−char_const_parser :: CapParser BuildResults
304−char_const_parser = do
303+charConstParser :: CapParser BuildResults
304+charConstParser = do
305305 _ <- char '\''
306− char_value <- liftM (toEnum . fromEnum) anyChar
306+ charValue <- liftM (toEnum . fromEnum) anyChar
307307 _ <- char '\''
308− inc_offset 3
309− return $ BuildResults 0 [ PushValue char_value ] [ ]
308+ incOffset 3
309+ return $ BuildResults 0 [ PushValue charValue ] [ ]
310310
311311data BuildState = BuildState
312− { next_offset :: Int
312+ { nextOffset :: Int
313313 }
314314
315−inc_offset :: Int -> CapParser ()
316−inc_offset n = do
315+incOffset :: Int -> CapParser ()
316+incOffset n = do
317317 s <- getState
318− let s' = s { next_offset = next_offset s + n }
318+ let s' = s { nextOffset = nextOffset s + n }
319319 setState s'
320320
321−initial_build_state :: BuildState
322−initial_build_state = BuildState 0
321+initialBuildState :: BuildState
322+initialBuildState = BuildState 0
323323
324324data BuildResults = BuildResults
325− { out_param_count :: !Int
326− , out_cap_ops :: !CapOps
327− , out_param_ops :: !ParamOps
325+ { outParamCount :: !Int
326+ , outCapOps :: !CapOps
327+ , outParamOps :: !ParamOps
328328 }
329329
330330instance Monoid BuildResults where
331331 mempty = BuildResults 0 [] []
332332 v0 `mappend` v1
333333 = BuildResults
334− { out_param_count = (out_param_count v0) `max` (out_param_count v1)
335− , out_cap_ops = (out_cap_ops v0) `mappend` (out_cap_ops v1)
336− , out_param_ops = (out_param_ops v0) `mappend` (out_param_ops v1)
334+ { outParamCount = (outParamCount v0) `max` (outParamCount v1)
335+ , outCapOps = (outCapOps v0) `mappend` (outCapOps v1)
336+ , outParamOps = (outParamOps v0) `mappend` (outParamOps v1)
337337 }
338338
src/Graphics/Text/Width.hs+6−6
@@ -3,8 +3,8 @@
33{-# LANGUAGE ForeignFunctionInterface #-}
44module Graphics.Text.Width ( wcwidth
55 , wcswidth
6− , safe_wcwidth
7− , safe_wcswidth
6+ , safeWcwidth
7+ , safeWcswidth
88 )
99 where
1010
@@ -21,14 +21,14 @@ wcswidth = sum . map wcwidth
2121-- implemented.
2222
2323-- | Returns the display width of a character. Assumes all characters with unknown widths are 0 width
24−safe_wcwidth :: Char -> Int
25−safe_wcwidth c = case wcwidth c of
24+safeWcwidth :: Char -> Int
25+safeWcwidth c = case wcwidth c of
2626 i | i < 0 -> 0
2727 | otherwise -> i
2828
2929-- | Returns the display width of a string. Assumes all characters with unknown widths are 0 width
30−safe_wcswidth :: String -> Int
31−safe_wcswidth str = case wcswidth str of
30+safeWcswidth :: String -> Int
31+safeWcswidth str = case wcswidth str of
3232 i | i < 0 -> 0
3333 | otherwise -> i
3434
src/Graphics/Vty.hs+43−43
@@ -60,16 +60,16 @@ import Data.IORef
6060--
6161-- \todo Remove explicit `shutdown` requirement.
6262data Vty = Vty
63− { -- | Outputs the given Picture. Equivalent to 'output_picture' applied to a display context
63+ { -- | Outputs the given Picture. Equivalent to 'outputPicture' applied to a display context
6464 -- implicitly managed by Vty. The managed display context is reset on resize.
6565 update :: Picture -> IO ()
6666 -- | Get one Event object, blocking if necessary. This will refresh the terminal if the event
6767 -- is a 'EvResize'.
68− , next_event :: IO Event
68+ , nextEvent :: IO Event
6969 -- | The input interface. See 'Input'
70− , input_iface :: Input
70+ , inputIface :: Input
7171 -- | The output interface. See 'Output'
72− , output_iface :: Output
72+ , outputIface :: Output
7373 -- | Refresh the display. Normally the library takes care of refreshing. Nonetheless, some
7474 -- other program might output to the terminal and mess up the display. In that case the
7575 -- application might want to force a refresh.
@@ -83,24 +83,24 @@ data Vty = Vty
8383-- created at a time.
8484mkVty :: Config -> IO Vty
8585mkVty config = do
86− input <- input_for_current_terminal config
87− out <- output_for_current_terminal
86+ input <- inputForCurrentTerminal config
87+ out <- outputForCurrentTerminal
8888 intMkVty input out
8989
9090intMkVty :: Input -> Output -> IO Vty
9191intMkVty input out = do
92− reserve_display out
93− let shutdown_io = do
94− shutdown_input input
95− release_display out
96− release_terminal out
97− last_pic_ref <- newIORef Nothing
98− last_update_ref <- newIORef Nothing
92+ reserveDisplay out
93+ let shutdownIo = do
94+ shutdownInput input
95+ releaseDisplay out
96+ releaseTerminal out
97+ lastPicRef <- newIORef Nothing
98+ lastUpdateRef <- newIORef Nothing
9999
100− let inner_update in_pic = do
101− b@(w,h) <- display_bounds out
102− let cursor = pic_cursor in_pic
103− in_pic' = case cursor of
100+ let innerUpdate inPic = do
101+ b@(w,h) <- displayBounds out
102+ let cursor = picCursor inPic
103+ inPic' = case cursor of
104104 Cursor x y ->
105105 let
106106 x' = case x of
@@ -111,43 +111,43 @@ intMkVty input out = do
111111 _ | y < 0 -> 0
112112 | y >= h -> h - 1
113113 | otherwise -> y
114− in in_pic { pic_cursor = Cursor x' y' }
115− _ -> in_pic
116− mlast_update <- readIORef last_update_ref
117− update_data <- case mlast_update of
114+ in inPic { picCursor = Cursor x' y' }
115+ _ -> inPic
116+ mlastUpdate <- readIORef lastUpdateRef
117+ updateData <- case mlastUpdate of
118118 Nothing -> do
119− dc <- display_context out b
120− output_picture dc in_pic'
119+ dc <- displayContext out b
120+ outputPicture dc inPic'
121121 return (b, dc)
122− Just (last_bounds, last_context) -> do
122+ Just (last_bounds, lastContext) -> do
123123 if b /= last_bounds
124124 then do
125− dc <- display_context out b
126− output_picture dc in_pic'
125+ dc <- displayContext out b
126+ outputPicture dc inPic'
127127 return (b, dc)
128128 else do
129− output_picture last_context in_pic'
130− return (b, last_context)
131− writeIORef last_update_ref $ Just update_data
132− writeIORef last_pic_ref $ Just in_pic'
129+ outputPicture lastContext inPic'
130+ return (b, lastContext)
131+ writeIORef lastUpdateRef $ Just updateData
132+ writeIORef lastPicRef $ Just inPic'
133133
134− let inner_refresh
135− = writeIORef last_update_ref Nothing
136− >> readIORef last_pic_ref
137− >>= maybe ( return () ) ( \pic -> inner_update pic )
134+ let innerRefresh
135+ = writeIORef lastUpdateRef Nothing
136+ >> readIORef lastPicRef
137+ >>= maybe ( return () ) ( \pic -> innerUpdate pic )
138138
139− let gkey = do k <- readChan $ _event_channel input
139+ let gkey = do k <- readChan $ _eventChannel input
140140 case k of
141− (EvResize _ _) -> inner_refresh
142− >> display_bounds out
141+ (EvResize _ _) -> innerRefresh
142+ >> displayBounds out
143143 >>= return . (\(w,h)-> EvResize w h)
144144 _ -> return k
145145
146− return $ Vty { update = inner_update
147− , next_event = gkey
148− , input_iface = input
149− , output_iface = out
150− , refresh = inner_refresh
151− , shutdown = shutdown_io
146+ return $ Vty { update = innerUpdate
147+ , nextEvent = gkey
148+ , inputIface = input
149+ , outputIface = out
150+ , refresh = innerRefresh
151+ , shutdown = shutdownIo
152152 }
153153
src/Graphics/Vty/Attributes.hs+50−46
@@ -3,10 +3,10 @@
33{-# LANGUAGE RankNTypes #-}
44-- | Display attributes
55--
6−-- Typically the values 'def_attr' or 'current_attr' are modified to form attributes:
6+-- Typically the values 'defAttr' or 'currentAttr' are modified to form attributes:
77--
88-- @
9−-- def_attr `with_fore_color` red
9+-- defAttr `withForeColor` red
1010-- @
1111--
1212-- Is the attribute that will set the foreground color to red and the background color to the
@@ -15,14 +15,14 @@
1515-- This can then be used to build an image wiht a red foreground like so:
1616--
1717-- @
18−-- string (def_attr `with_fore_color` red) "this text will be red"
18+-- string (defAttr `withForeColor` red) "this text will be red"
1919-- @
2020--
21−-- The default attributes set by 'def_attr' have a presentation determined by the terminal. This is
21+-- The default attributes set by 'defAttr' have a presentation determined by the terminal. This is
2222-- not something VTY can control. The user is free to define the color scheme of the terminal as
2323-- they see fit. Up to the limits of the terminal anyways.
2424--
25−-- The value 'current_attr' will keep the attributes of whatever was output previously.
25+-- The value 'currentAttr' will keep the attributes of whatever was output previously.
2626--
2727-- \todo This API is very verbose IMO. I'd like something more succinct.
2828module Graphics.Vty.Attributes ( module Graphics.Vty.Attributes
@@ -32,6 +32,7 @@ module Graphics.Vty.Attributes ( module Graphics.Vty.Attributes
3232 where
3333
3434import Data.Bits
35+import Data.Default
3536import Data.Monoid
3637import Data.Word
3738
@@ -45,9 +46,9 @@ import Graphics.Vty.Attributes.Color240
4546-- foreground. The 240 colors and 16 colors are points in different palettes. See Color for more
4647-- information.
4748data Attr = Attr
48− { attr_style :: !(MaybeDefault Style)
49− , attr_fore_color :: !(MaybeDefault Color)
50− , attr_back_color :: !(MaybeDefault Color)
49+ { attrStyle :: !(MaybeDefault Style)
50+ , attrForeColor :: !(MaybeDefault Color)
51+ , attrBackColor :: !(MaybeDefault Color)
5152 } deriving ( Eq, Show )
5253
5354-- This could be encoded into a single 32 bit word. The 32 bit word is first divided
@@ -84,17 +85,17 @@ data Attr = Attr
8485instance Monoid Attr where
8586 mempty = Attr mempty mempty mempty
8687 mappend attr_0 attr_1 =
87− Attr ( attr_style attr_0 `mappend` attr_style attr_1 )
88− ( attr_fore_color attr_0 `mappend` attr_fore_color attr_1 )
89− ( attr_back_color attr_0 `mappend` attr_back_color attr_1 )
88+ Attr ( attrStyle attr_0 `mappend` attrStyle attr_1 )
89+ ( attrForeColor attr_0 `mappend` attrForeColor attr_1 )
90+ ( attrBackColor attr_0 `mappend` attrBackColor attr_1 )
9091
9192-- | Specifies the display attributes such that the final style and color values do not depend on
9293-- the previously applied display attribute. The display attributes can still depend on the
9394-- terminal's default colors (unfortunately).
9495data FixedAttr = FixedAttr
95− { fixed_style :: !Style
96− , fixed_fore_color :: !(Maybe Color)
97− , fixed_back_color :: !(Maybe Color)
96+ { fixedStyle :: !Style
97+ , fixedForeColor :: !(Maybe Color)
98+ , fixedBackColor :: !(Maybe Color)
9899 } deriving ( Eq, Show )
99100
100101-- | The style and color attributes can either be the terminal defaults. Or be equivalent to the
@@ -131,16 +132,16 @@ cyan = ISOColor 6
131132white = ISOColor 7
132133
133134-- | Bright/Vivid variants of the standard 8-color ANSI
134−bright_black, bright_red, bright_green, bright_yellow :: Color
135−bright_blue, bright_magenta, bright_cyan, bright_white :: Color
136−bright_black = ISOColor 8
137−bright_red = ISOColor 9
138−bright_green = ISOColor 10
139−bright_yellow = ISOColor 11
140−bright_blue = ISOColor 12
141−bright_magenta= ISOColor 13
142−bright_cyan = ISOColor 14
143−bright_white = ISOColor 15
135+brightBlack, brightRed, brightGreen, brightYellow :: Color
136+brightBlue, brightMagenta, brightCyan, brightWhite :: Color
137+brightBlack = ISOColor 8
138+brightRed = ISOColor 9
139+brightGreen = ISOColor 10
140+brightYellow = ISOColor 11
141+brightBlue = ISOColor 12
142+brightMagenta= ISOColor 13
143+brightCyan = ISOColor 14
144+brightWhite = ISOColor 15
144145
145146-- | Styles are represented as an 8 bit word. Each bit in the word is 1 if the style attribute
146147-- assigned to that bit should be applied and 0 if the style attribute should not be applied.
@@ -152,7 +153,7 @@ type Style = Word8
152153--
153154-- * underline
154155--
155−-- * reverse_video
156+-- * reverseVideo
156157--
157158-- * blink
158159--
@@ -162,52 +163,55 @@ type Style = Word8
162163--
163164-- ( The invisible, protect, and altcharset display attributes some terminals support are not
164165-- supported via VTY.)
165−standout, underline, reverse_video, blink, dim, bold :: Style
166+standout, underline, reverseVideo, blink, dim, bold :: Style
166167standout = 0x01
167168underline = 0x02
168−reverse_video = 0x04
169+reverseVideo = 0x04
169170blink = 0x08
170171dim = 0x10
171172bold = 0x20
172173
173−default_style_mask :: Style
174−default_style_mask = 0x00
174+defaultStyleMask :: Style
175+defaultStyleMask = 0x00
175176
176−style_mask :: Attr -> Word8
177−style_mask attr
178− = case attr_style attr of
177+styleMask :: Attr -> Word8
178+styleMask attr
179+ = case attrStyle attr of
179180 Default -> 0
180181 KeepCurrent -> 0
181182 SetTo v -> v
182183
183184-- | true if the given Style value has the specified Style set.
184−has_style :: Style -> Style -> Bool
185−has_style s bit_mask = ( s .&. bit_mask ) /= 0
185+hasStyle :: Style -> Style -> Bool
186+hasStyle s bit_mask = ( s .&. bit_mask ) /= 0
186187
187188-- | Set the foreground color of an `Attr'.
188−with_fore_color :: Attr -> Color -> Attr
189−with_fore_color attr c = attr { attr_fore_color = SetTo c }
189+withForeColor :: Attr -> Color -> Attr
190+withForeColor attr c = attr { attrForeColor = SetTo c }
190191
191192-- | Set the background color of an `Attr'.
192−with_back_color :: Attr -> Color -> Attr
193−with_back_color attr c = attr { attr_back_color = SetTo c }
193+withBackColor :: Attr -> Color -> Attr
194+withBackColor attr c = attr { attrBackColor = SetTo c }
194195
195196-- | Add the given style attribute
196−with_style :: Attr -> Style -> Attr
197−with_style attr style_flag = attr { attr_style = SetTo $ style_mask attr .|. style_flag }
197+withStyle :: Attr -> Style -> Attr
198+withStyle attr style_flag = attr { attrStyle = SetTo $ styleMask attr .|. style_flag }
198199
199200-- | Sets the style, background color and foreground color to the default values for the terminal.
200201-- There is no easy way to determine what the default background and foreground colors are.
201−def_attr :: Attr
202−def_attr = Attr Default Default Default
202+defAttr :: Attr
203+defAttr = Attr Default Default Default
204+
205+instance Default Attr where
206+ def = defAttr
203207
204208-- | Keeps the style, background color and foreground color that was previously set. Used to
205209-- override some part of the previous style.
206210--
207−-- EG: current_style `with_fore_color` bright_magenta
211+-- EG: current_style `withForeColor` brightMagenta
208212--
209213-- Would be the currently applied style (be it underline, bold, etc) but with the foreground color
210−-- set to bright_magenta.
211−current_attr :: Attr
212−current_attr = Attr KeepCurrent KeepCurrent KeepCurrent
214+-- set to brightMagenta.
215+currentAttr :: Attr
216+currentAttr = Attr KeepCurrent KeepCurrent KeepCurrent
213217
src/Graphics/Vty/Attributes/Color240.hs+3−3
@@ -11,9 +11,9 @@ import Text.Printf
1111--
1212-- generated from 256colres.pl which is forked from xterm 256colres.pl
1313-- todo: all values get clamped high.
14−rgb_color :: Integral i => i -> i -> i -> Color
15−rgb_color r g b
16− | r < 0 && g < 0 && b < 0 = error "rgb_color with negative color component intensity"
14+rgbColor :: Integral i => i -> i -> i -> Color
15+rgbColor r g b
16+ | r < 0 && g < 0 && b < 0 = error "rgbColor with negative color component intensity"
1717 | r == 8 && g == 8 && b == 8 = Color240 216
1818 | r == 18 && g == 18 && b == 18 = Color240 217
1919 | r == 28 && g == 28 && b == 28 = Color240 218
src/Graphics/Vty/Debug.hs+14−14
@@ -12,29 +12,29 @@ import Graphics.Vty.Span
1212
1313import qualified Data.Vector as Vector
1414
15−row_ops_effected_columns :: DisplayOps -> [Int]
16−row_ops_effected_columns ops
17− = Vector.toList $ Vector.map span_ops_effected_columns ops
15+rowOpsEffectedColumns :: DisplayOps -> [Int]
16+rowOpsEffectedColumns ops
17+ = Vector.toList $ Vector.map spanOpsEffectedColumns ops
1818
19−all_spans_have_width :: DisplayOps -> Int -> Bool
20−all_spans_have_width ops expected
21− = all (== expected) $ Vector.toList $ Vector.map span_ops_effected_columns ops
19+allSpansHaveWidth :: DisplayOps -> Int -> Bool
20+allSpansHaveWidth ops expected
21+ = all (== expected) $ Vector.toList $ Vector.map spanOpsEffectedColumns ops
2222
23−span_ops_effected_rows :: DisplayOps -> Int
24−span_ops_effected_rows ops
23+spanOpsEffectedRows :: DisplayOps -> Int
24+spanOpsEffectedRows ops
2525 = toEnum $ length (filter (not . null . Vector.toList) (Vector.toList ops))
2626
2727type SpanConstructLog = [SpanConstructEvent]
2828data SpanConstructEvent = SpanSetAttr Attr
2929
30−is_set_attr :: Attr -> SpanConstructEvent -> Bool
31−is_set_attr expected_attr (SpanSetAttr in_attr)
32− | in_attr == expected_attr = True
33−is_set_attr _attr _event = False
30+isSetAttr :: Attr -> SpanConstructEvent -> Bool
31+isSetAttr expectedAttr (SpanSetAttr inAttr)
32+ | inAttr == expectedAttr = True
33+isSetAttr _attr _event = False
3434
3535data MockWindow = MockWindow Int Int
3636 deriving (Show, Eq)
3737
38−region_for_window :: MockWindow -> DisplayRegion
39−region_for_window (MockWindow w h) = (w,h)
38+regionForWindow :: MockWindow -> DisplayRegion
39+regionForWindow (MockWindow w h) = (w,h)
4040
src/Graphics/Vty/Debug/Image.hs+10−10
@@ -6,26 +6,26 @@ type ImageConstructLog = [ImageConstructEvent]
66data ImageConstructEvent = ImageConstructEvent
77 deriving ( Show, Eq )
88
9−forward_image_ops :: [Image -> Image]
10−forward_image_ops = map forward_transform debug_image_ops
9+forwardImageOps :: [Image -> Image]
10+forwardImageOps = map forwardTransform debugImageOps
1111
12−forward_transform, reverse_transform :: ImageOp -> (Image -> Image)
12+forwardTransform, reverseTransform :: ImageOp -> (Image -> Image)
1313
14−forward_transform (ImageOp f _) = f
15−reverse_transform (ImageOp _ r) = r
14+forwardTransform (ImageOp f _) = f
15+reverseTransform (ImageOp _ r) = r
1616
1717data ImageOp = ImageOp ImageEndo ImageEndo
1818type ImageEndo = Image -> Image
1919
20−debug_image_ops :: [ImageOp]
21−debug_image_ops =
22− [ id_image_op
20+debugImageOps :: [ImageOp]
21+debugImageOps =
22+ [ idImageOp
2323 -- , render_single_column_char_op
2424 -- , render_double_column_char_op
2525 ]
2626
27−id_image_op :: ImageOp
28−id_image_op = ImageOp id id
27+idImageOp :: ImageOp
28+idImageOp = ImageOp id id
2929
3030-- render_char_op :: ImageOp
3131-- render_char_op = ImageOp id id
src/Graphics/Vty/DisplayAttributes.hs+42−42
@@ -12,18 +12,18 @@ import Data.Monoid (Monoid(..), mconcat)
1212-- attributes as an Attr produces a FixedAttr that represents the current display attributes. This
1313-- is done by using the previously applied display attributes to remove the "KeepCurrent"
1414-- abstraction.
15−fix_display_attr :: FixedAttr -> Attr -> FixedAttr
16−fix_display_attr fattr attr
17− = FixedAttr (fix_style (fixed_style fattr) (attr_style attr))
18− (fix_color (fixed_fore_color fattr) (attr_fore_color attr))
19− (fix_color (fixed_back_color fattr) (attr_back_color attr))
15+fixDisplayAttr :: FixedAttr -> Attr -> FixedAttr
16+fixDisplayAttr fattr attr
17+ = FixedAttr (fixStyle (fixedStyle fattr) (attrStyle attr))
18+ (fixColor (fixedForeColor fattr) (attrForeColor attr))
19+ (fixColor (fixedBackColor fattr) (attrBackColor attr))
2020 where
21− fix_style _s Default = default_style_mask
22− fix_style s KeepCurrent = s
23− fix_style _s (SetTo new_style) = new_style
24− fix_color _c Default = Nothing
25− fix_color c KeepCurrent = c
26− fix_color _c (SetTo c) = Just c
21+ fixStyle _s Default = defaultStyleMask
22+ fixStyle s KeepCurrent = s
23+ fixStyle _s (SetTo newStyle) = newStyle
24+ fixColor _c Default = Nothing
25+ fixColor c KeepCurrent = c
26+ fixColor _c (SetTo c) = Just c
2727
2828-- | difference between two display attributes. Used in the calculation of the operations required
2929-- to go from one display attribute to the next.
@@ -32,34 +32,34 @@ fix_display_attr fattr attr
3232-- This turned out to be very expensive: A *lot* more data would be sent to the terminal than
3333-- required.
3434data DisplayAttrDiff = DisplayAttrDiff
35− { style_diffs :: [StyleStateChange]
36− , fore_color_diff :: DisplayColorDiff
37− , back_color_diff :: DisplayColorDiff
35+ { styleDiffs :: [StyleStateChange]
36+ , foreColorDiff :: DisplayColorDiff
37+ , backColorDiff :: DisplayColorDiff
3838 }
3939 deriving (Show)
4040
4141instance Monoid DisplayAttrDiff where
4242 mempty = DisplayAttrDiff [] NoColorChange NoColorChange
4343 mappend d_0 d_1 =
44− let ds = simplify_style_diffs (style_diffs d_0) (style_diffs d_1)
45− fcd = simplify_color_diffs (fore_color_diff d_0) (fore_color_diff d_1)
46− bcd = simplify_color_diffs (back_color_diff d_0) (back_color_diff d_1)
44+ let ds = simplifyStyleDiffs (styleDiffs d_0) (styleDiffs d_1)
45+ fcd = simplifyColorDiffs (foreColorDiff d_0) (foreColorDiff d_1)
46+ bcd = simplifyColorDiffs (backColorDiff d_0) (backColorDiff d_1)
4747 in DisplayAttrDiff ds fcd bcd
4848
4949-- | Used in the computation of a final style attribute change.
5050--
5151-- TODO(corey): not really a simplify but a monoid instance.
52−simplify_style_diffs :: [StyleStateChange] -> [StyleStateChange] -> [StyleStateChange]
53−simplify_style_diffs cs_0 cs_1 = cs_0 `mappend` cs_1
52+simplifyStyleDiffs :: [StyleStateChange] -> [StyleStateChange] -> [StyleStateChange]
53+simplifyStyleDiffs cs_0 cs_1 = cs_0 `mappend` cs_1
5454
5555-- | Consider two display color attributes diffs. What display color attribute diff are these
5656-- equivalent to?
5757--
5858-- TODO(corey): not really a simplify but a monoid instance.
59−simplify_color_diffs :: DisplayColorDiff -> DisplayColorDiff -> DisplayColorDiff
60−simplify_color_diffs _cd ColorToDefault = ColorToDefault
61−simplify_color_diffs cd NoColorChange = cd
62−simplify_color_diffs _cd (SetColor !c) = SetColor c
59+simplifyColorDiffs :: DisplayColorDiff -> DisplayColorDiff -> DisplayColorDiff
60+simplifyColorDiffs _cd ColorToDefault = ColorToDefault
61+simplifyColorDiffs cd NoColorChange = cd
62+simplifyColorDiffs _cd (SetColor !c) = SetColor c
6363
6464-- | Difference between two display color attribute changes.
6565data DisplayColorDiff
@@ -87,33 +87,33 @@ data StyleStateChange
8787
8888-- | Determines the diff between two display&color attributes. This diff determines the operations
8989-- that actually get output to the terminal.
90−display_attr_diffs :: FixedAttr -> FixedAttr -> DisplayAttrDiff
91−display_attr_diffs attr attr' = DisplayAttrDiff
92− { style_diffs = diff_styles (fixed_style attr) (fixed_style attr')
93− , fore_color_diff = diff_color (fixed_fore_color attr) (fixed_fore_color attr')
94− , back_color_diff = diff_color (fixed_back_color attr) (fixed_back_color attr')
90+displayAttrDiffs :: FixedAttr -> FixedAttr -> DisplayAttrDiff
91+displayAttrDiffs attr attr' = DisplayAttrDiff
92+ { styleDiffs = diffStyles (fixedStyle attr) (fixedStyle attr')
93+ , foreColorDiff = diffColor (fixedForeColor attr) (fixedForeColor attr')
94+ , backColorDiff = diffColor (fixedBackColor attr) (fixedBackColor attr')
9595 }
9696
97−diff_color :: Maybe Color -> Maybe Color -> DisplayColorDiff
98−diff_color Nothing (Just c') = SetColor c'
99−diff_color (Just c) (Just c')
97+diffColor :: Maybe Color -> Maybe Color -> DisplayColorDiff
98+diffColor Nothing (Just c') = SetColor c'
99+diffColor (Just c) (Just c')
100100 | c == c' = NoColorChange
101101 | otherwise = SetColor c'
102−diff_color Nothing Nothing = NoColorChange
103−diff_color (Just _) Nothing = ColorToDefault
102+diffColor Nothing Nothing = NoColorChange
103+diffColor (Just _) Nothing = ColorToDefault
104104
105−diff_styles :: Style -> Style -> [StyleStateChange]
106−diff_styles prev cur
105+diffStyles :: Style -> Style -> [StyleStateChange]
106+diffStyles prev cur
107107 = mconcat
108− [ style_diff standout ApplyStandout RemoveStandout
109− , style_diff underline ApplyUnderline RemoveUnderline
110− , style_diff reverse_video ApplyReverseVideo RemoveReverseVideo
111− , style_diff blink ApplyBlink RemoveBlink
112− , style_diff dim ApplyDim RemoveDim
113− , style_diff bold ApplyBold RemoveBold
108+ [ styleDiff standout ApplyStandout RemoveStandout
109+ , styleDiff underline ApplyUnderline RemoveUnderline
110+ , styleDiff reverseVideo ApplyReverseVideo RemoveReverseVideo
111+ , styleDiff blink ApplyBlink RemoveBlink
112+ , styleDiff dim ApplyDim RemoveDim
113+ , styleDiff bold ApplyBold RemoveBold
114114 ]
115115 where
116− style_diff s sm rm
116+ styleDiff s sm rm
117117 = case (0 == prev .&. s, 0 == cur .&. s) of
118118 -- not set in either
119119 (True, True) -> []
src/Graphics/Vty/Image.hs+122−122
@@ -4,41 +4,41 @@
44{-# LANGUAGE DisambiguateRecordFields #-}
55module Graphics.Vty.Image ( DisplayText
66 , Image
7− , image_width
8− , image_height
9− , horiz_join
7+ , imageWidth
8+ , imageHeight
9+ , horizJoin
1010 , (<|>)
11− , vert_join
11+ , vertJoin
1212 , (<->)
13− , horiz_cat
14− , vert_cat
15− , background_fill
13+ , horizCat
14+ , vertCat
15+ , backgroundFill
1616 , text
1717 , text'
1818 , char
1919 , string
20− , iso_10646_string
21− , utf8_string
22− , utf8_bytestring
23− , utf8_bytestring'
24− , char_fill
25− , empty_image
26− , safe_wcwidth
27− , safe_wcswidth
20+ , iso10646String
21+ , utf8String
22+ , utf8Bytestring
23+ , utf8Bytestring'
24+ , charFill
25+ , emptyImage
26+ , safeWcwidth
27+ , safeWcswidth
2828 , wcwidth
2929 , wcswidth
3030 , crop
31− , crop_right
32− , crop_left
33− , crop_bottom
34− , crop_top
31+ , cropRight
32+ , cropLeft
33+ , cropBottom
34+ , cropTop
3535 , pad
3636 , resize
37− , resize_width
38− , resize_height
37+ , resizeWidth
38+ , resizeHeight
3939 , translate
40− , translate_x
41− , translate_y
40+ , translateX
41+ , translateY
4242 -- | The possible display attributes used in constructing an `Image`.
4343 , module Graphics.Vty.Attributes
4444 )
@@ -60,52 +60,52 @@ infixr 5 <|>
6060infixr 4 <->
6161
6262-- | An area of the picture's bacground (See Background) of w columns and h rows.
63−background_fill :: Int -> Int -> Image
64−background_fill w h
63+backgroundFill :: Int -> Int -> Image
64+backgroundFill w h
6565 | w == 0 = EmptyImage
6666 | h == 0 = EmptyImage
6767 | otherwise = BGFill w h
6868
69−-- | Combines two images horizontally. Alias for horiz_join
69+-- | Combines two images horizontally. Alias for horizJoin
7070--
7171-- infixr 5
7272(<|>) :: Image -> Image -> Image
73−(<|>) = horiz_join
73+(<|>) = horizJoin
7474
75−-- | Combines two images vertically. Alias for vert_join
75+-- | Combines two images vertically. Alias for vertJoin
7676--
7777-- infixr 4
7878(<->) :: Image -> Image -> Image
79−(<->) = vert_join
79+(<->) = vertJoin
8080
8181-- | Compose any number of images horizontally.
82−horiz_cat :: [Image] -> Image
83−horiz_cat = foldr horiz_join EmptyImage
82+horizCat :: [Image] -> Image
83+horizCat = foldr horizJoin EmptyImage
8484
8585-- | Compose any number of images vertically.
86−vert_cat :: [Image] -> Image
87−vert_cat = foldr vert_join EmptyImage
86+vertCat :: [Image] -> Image
87+vertCat = foldr vertJoin EmptyImage
8888
8989-- | A Data.Text.Lazy value
9090text :: Attr -> TL.Text -> Image
9191text a txt
9292 | TL.length txt == 0 = EmptyImage
93− | otherwise = let display_width = safe_wcswidth (TL.unpack txt)
94− in HorizText a txt display_width (fromIntegral $! TL.length txt)
93+ | otherwise = let displayWidth = safeWcswidth (TL.unpack txt)
94+ in HorizText a txt displayWidth (fromIntegral $! TL.length txt)
9595
9696-- | A Data.Text value
9797text' :: Attr -> T.Text -> Image
9898text' a txt
9999 | T.length txt == 0 = EmptyImage
100− | otherwise = let display_width = safe_wcswidth (T.unpack txt)
101− in HorizText a (TL.fromStrict txt) display_width (T.length txt)
100+ | otherwise = let displayWidth = safeWcswidth (T.unpack txt)
101+ in HorizText a (TL.fromStrict txt) displayWidth (T.length txt)
102102
103103-- | an image of a single character. This is a standard Haskell 31-bit character assumed to be in
104104-- the ISO-10646 encoding.
105105char :: Attr -> Char -> Image
106106char a c =
107− let display_width = safe_wcwidth c
108− in HorizText a (TL.singleton c) display_width 1
107+ let displayWidth = safeWcwidth c
108+ in HorizText a (TL.singleton c) displayWidth 1
109109
110110-- | A string of characters layed out on a single row with the same display attribute. The string is
111111-- assumed to be a sequence of ISO-10646 characters.
@@ -114,51 +114,51 @@ char a c =
114114-- UTF-8 encoded source file, for example, may be represented as a ISO-10646 string.
115115-- That is, I think, the case with GHC 6.10. This means, for the most part, you don't need to worry
116116-- about the encoding format when outputting string literals. Just provide the string literal
117−-- directly to iso_10646_string or string.
117+-- directly to iso10646String or string.
118118--
119−iso_10646_string :: Attr -> String -> Image
120−iso_10646_string a str =
121− let display_width = safe_wcswidth str
122− in HorizText a (TL.pack str) display_width (length str)
119+iso10646String :: Attr -> String -> Image
120+iso10646String a str =
121+ let displayWidth = safeWcswidth str
122+ in HorizText a (TL.pack str) displayWidth (length str)
123123
124−-- | Alias for iso_10646_string. Since the usual case is that a literal string like "foo" is
124+-- | Alias for iso10646String. Since the usual case is that a literal string like "foo" is
125125-- represented internally as a list of ISO 10646 31 bit characters.
126126--
127127-- Note: Keep in mind that GHC will compile source encoded as UTF-8 but the literal strings, while
128128-- UTF-8 encoded in the source, will be transcoded to a ISO 10646 31 bit characters runtime
129129-- representation.
130130string :: Attr -> String -> Image
131−string = iso_10646_string
131+string = iso10646String
132132
133133-- | A string of characters layed out on a single row. The input is assumed to be the bytes for
134134-- UTF-8 encoded text.
135−utf8_string :: Attr -> [Word8] -> Image
136−utf8_string a bytes = utf8_bytestring a (BL.pack bytes)
135+utf8String :: Attr -> [Word8] -> Image
136+utf8String a bytes = utf8Bytestring a (BL.pack bytes)
137137
138138-- | Renders a UTF-8 encoded lazy bytestring.
139−utf8_bytestring :: Attr -> BL.ByteString -> Image
140−utf8_bytestring a bs = text a (TL.decodeUtf8 bs)
139+utf8Bytestring :: Attr -> BL.ByteString -> Image
140+utf8Bytestring a bs = text a (TL.decodeUtf8 bs)
141141
142142-- | Renders a UTF-8 encoded strict bytestring.
143−utf8_bytestring' :: Attr -> B.ByteString -> Image
144−utf8_bytestring' a bs = text' a (T.decodeUtf8 bs)
143+utf8Bytestring' :: Attr -> B.ByteString -> Image
144+utf8Bytestring' a bs = text' a (T.decodeUtf8 bs)
145145
146146-- | creates a fill of the specified character. The dimensions are in number of characters wide and
147147-- number of rows high.
148−char_fill :: Integral d => Attr -> Char -> d -> d -> Image
149−char_fill _a _c 0 _h = EmptyImage
150−char_fill _a _c _w 0 = EmptyImage
151−char_fill a c w h =
152− vert_cat $ replicate (fromIntegral h) $ HorizText a txt display_width char_width
148+charFill :: Integral d => Attr -> Char -> d -> d -> Image
149+charFill _a _c 0 _h = EmptyImage
150+charFill _a _c _w 0 = EmptyImage
151+charFill a c w h =
152+ vertCat $ replicate (fromIntegral h) $ HorizText a txt displayWidth char_width
153153 where
154154 txt = TL.replicate (fromIntegral w) (TL.singleton c)
155− display_width = safe_wcwidth c * (fromIntegral w)
155+ displayWidth = safeWcwidth c * (fromIntegral w)
156156 char_width = fromIntegral w
157157
158158-- | The empty image. Useful for fold combinators. These occupy no space nor define any display
159159-- attributes.
160−empty_image :: Image
161−empty_image = EmptyImage
160+emptyImage :: Image
161+emptyImage = EmptyImage
162162
163163-- | pad the given image. This adds background character fills to the left, top, right, bottom.
164164-- The pad values are how many display columns or rows to add.
@@ -171,38 +171,38 @@ pad in_l in_t in_r in_b in_image
171171 -- TODO: uh.
172172 go 0 0 0 0 i = i
173173 go 0 0 0 b i = VertJoin i (BGFill w b) w h
174− where w = image_width i
175− h = image_height i + b
174+ where w = imageWidth i
175+ h = imageHeight i + b
176176 go 0 0 r b i = go 0 0 0 b $ HorizJoin i (BGFill r h) w h
177− where w = image_width i + r
178− h = image_height i
177+ where w = imageWidth i + r
178+ h = imageHeight i
179179 go 0 t r b i = go 0 0 r b $ VertJoin (BGFill w t) i w h
180− where w = image_width i
181− h = image_height i + t
180+ where w = imageWidth i
181+ h = imageHeight i + t
182182 go l t r b i = go 0 t r b $ HorizJoin (BGFill l h) i w h
183− where w = image_width i + l
184− h = image_height i
183+ where w = imageWidth i + l
184+ h = imageHeight i
185185
186186-- | translates an image by padding or cropping the top and left.
187187--
188188-- This can have an unexpected effect: Translating an image to less than (0,0) then to greater than
189189-- (0,0) will crop the image.
190190translate :: Int -> Int -> Image -> Image
191−translate x y i = translate_x x (translate_y y i)
191+translate x y i = translateX x (translateY y i)
192192
193193-- | translates an image by padding or cropping the left
194−translate_x :: Int -> Image -> Image
195−translate_x x i
196− | x < 0 = let s = abs x in CropLeft i s (image_width i - s) (image_height i)
194+translateX :: Int -> Image -> Image
195+translateX x i
196+ | x < 0 = let s = abs x in CropLeft i s (imageWidth i - s) (imageHeight i)
197197 | x == 0 = i
198− | otherwise = let h = image_height i in HorizJoin (BGFill x h) i (image_width i + x) h
198+ | otherwise = let h = imageHeight i in HorizJoin (BGFill x h) i (imageWidth i + x) h
199199
200200-- | translates an image by padding or cropping the top
201−translate_y :: Int -> Image -> Image
202−translate_y y i
203− | y < 0 = let s = abs y in CropTop i s (image_width i) (image_height i - s)
201+translateY :: Int -> Image -> Image
202+translateY y i
203+ | y < 0 = let s = abs y in CropTop i s (imageWidth i) (imageHeight i - s)
204204 | y == 0 = i
205− | otherwise = let w = image_width i in VertJoin (BGFill w y) i w (image_height i + y)
205+ | otherwise = let w = imageWidth i in VertJoin (BGFill w y) i w (imageHeight i + y)
206206
207207-- | Ensure an image is no larger than the provided size. If the image is larger then crop the right
208208-- or bottom.
@@ -212,94 +212,94 @@ translate_y y i
212212crop :: Int -> Int -> Image -> Image
213213crop 0 _ _ = EmptyImage
214214crop _ 0 _ = EmptyImage
215−crop w h i = crop_bottom h (crop_right w i)
215+crop w h i = cropBottom h (cropRight w i)
216216
217217-- | crop the display height. If the image is less than or equal in height then this operation has
218218-- no effect. Otherwise the image is cropped from the bottom.
219−crop_bottom :: Int -> Image -> Image
220−crop_bottom 0 _ = EmptyImage
221−crop_bottom h in_i
219+cropBottom :: Int -> Image -> Image
220+cropBottom 0 _ = EmptyImage
221+cropBottom h in_i
222222 | h < 0 = error "cannot crop height to less than zero"
223223 | otherwise = go in_i
224224 where
225225 go EmptyImage = EmptyImage
226− go i@(CropBottom {cropped_image, output_width, output_height})
227− | output_height <= h = i
228− | otherwise = CropBottom cropped_image output_width h
226+ go i@(CropBottom {croppedImage, outputWidth, outputHeight})
227+ | outputHeight <= h = i
228+ | otherwise = CropBottom croppedImage outputWidth h
229229 go i
230− | h >= image_height i = i
231− | otherwise = CropBottom i (image_width i) h
230+ | h >= imageHeight i = i
231+ | otherwise = CropBottom i (imageWidth i) h
232232
233233-- | ensure the image is no wider than the given width. If the image is wider then crop the right
234234-- side.
235−crop_right :: Int -> Image -> Image
236−crop_right 0 _ = EmptyImage
237−crop_right w in_i
235+cropRight :: Int -> Image -> Image
236+cropRight 0 _ = EmptyImage
237+cropRight w in_i
238238 | w < 0 = error "cannot crop width to less than zero"
239239 | otherwise = go in_i
240240 where
241241 go EmptyImage = EmptyImage
242− go i@(CropRight {cropped_image, output_width, output_height})
243− | output_width <= w = i
244− | otherwise = CropRight cropped_image w output_height
242+ go i@(CropRight {croppedImage, outputWidth, outputHeight})
243+ | outputWidth <= w = i
244+ | otherwise = CropRight croppedImage w outputHeight
245245 go i
246− | w >= image_width i = i
247− | otherwise = CropRight i w (image_height i)
246+ | w >= imageWidth i = i
247+ | otherwise = CropRight i w (imageHeight i)
248248
249249-- | ensure the image is no wider than the given width. If the image is wider then crop the left
250250-- side.
251−crop_left :: Int -> Image -> Image
252−crop_left 0 _ = EmptyImage
253−crop_left w in_i
251+cropLeft :: Int -> Image -> Image
252+cropLeft 0 _ = EmptyImage
253+cropLeft w in_i
254254 | w < 0 = error "cannot crop the width to less than zero"
255255 | otherwise = go in_i
256256 where
257257 go EmptyImage = EmptyImage
258− go i@(CropLeft {cropped_image, left_skip, output_width, output_height})
259− | output_width <= w = i
258+ go i@(CropLeft {croppedImage, leftSkip, outputWidth, outputHeight})
259+ | outputWidth <= w = i
260260 | otherwise =
261− let left_skip' = left_skip + output_width - w
262− in CropLeft cropped_image left_skip' w output_height
261+ let leftSkip' = leftSkip + outputWidth - w
262+ in CropLeft croppedImage leftSkip' w outputHeight
263263 go i
264− | image_width i <= w = i
265− | otherwise = CropLeft i (image_width i - w) w (image_height i)
264+ | imageWidth i <= w = i
265+ | otherwise = CropLeft i (imageWidth i - w) w (imageHeight i)
266266
267267-- | crop the display height. If the image is less than or equal in height then this operation has
268268-- no effect. Otherwise the image is cropped from the top.
269−crop_top :: Int -> Image -> Image
270−crop_top 0 _ = EmptyImage
271−crop_top h in_i
269+cropTop :: Int -> Image -> Image
270+cropTop 0 _ = EmptyImage
271+cropTop h in_i
272272 | h < 0 = error "cannot crop the height to less than zero"
273273 | otherwise = go in_i
274274 where
275275 go EmptyImage = EmptyImage
276− go i@(CropTop {cropped_image, top_skip, output_width, output_height})
277− | output_height <= h = i
278− | otherwise =
279− let top_skip' = top_skip + output_height - h
280− in CropTop cropped_image top_skip' output_width h
276+ go i@(CropTop {croppedImage, topSkip, outputWidth, outputHeight})
277+ | outputHeight <= h = i
278+ | otherwise =
279+ let topSkip' = topSkip + outputHeight - h
280+ in CropTop croppedImage topSkip' outputWidth h
281281 go i
282− | image_height i <= h = i
283− | otherwise = CropTop i (image_height i - h) (image_width i) h
282+ | imageHeight i <= h = i
283+ | otherwise = CropTop i (imageHeight i - h) (imageWidth i) h
284284
285285-- | Generic resize. Pads and crops as required to assure the given display width and height.
286286-- This is biased to pad/crop the right and bottom.
287287resize :: Int -> Int -> Image -> Image
288−resize w h i = resize_height h (resize_width w i)
288+resize w h i = resizeHeight h (resizeWidth w i)
289289
290290-- | Resize the width. Pads and crops as required to assure the given display width.
291291-- This is biased to pad/crop the right.
292−resize_width :: Int -> Image -> Image
293−resize_width w i = case w `compare` image_width i of
294− LT -> crop_right w i
292+resizeWidth :: Int -> Image -> Image
293+resizeWidth w i = case w `compare` imageWidth i of
294+ LT -> cropRight w i
295295 EQ -> i
296− GT -> i <|> BGFill (w - image_width i) (image_height i)
296+ GT -> i <|> BGFill (w - imageWidth i) (imageHeight i)
297297
298298-- | Resize the height. Pads and crops as required to assure the given display height.
299299-- This is biased to pad/crop the bottom.
300−resize_height :: Int -> Image -> Image
301−resize_height h i = case h `compare` image_height i of
302− LT -> crop_bottom h i
300+resizeHeight :: Int -> Image -> Image
301+resizeHeight h i = case h `compare` imageHeight i of
302+ LT -> cropBottom h i
303303 EQ -> i
304− GT -> i <-> BGFill (image_width i) (h - image_height i)
304+ GT -> i <-> BGFill (imageWidth i) (h - imageHeight i)
305305
src/Graphics/Vty/Image/Internal.hs+136−136
@@ -22,21 +22,21 @@ type DisplayText = TL.Text
2222-- TODO: store a skip list in HorizText(?)
2323-- TODO: represent display strings containing chars that are not 1 column chars as a separate
2424-- display string value?
25−clip_text :: DisplayText -> Int -> Int -> DisplayText
26−clip_text txt left_skip right_clip =
25+clipText :: DisplayText -> Int -> Int -> DisplayText
26+clipText txt leftSkip rightClip =
2727 -- CPS would clarify this I think
28− let (to_drop,pad_prefix) = clip_for_char_width left_skip txt 0
29− txt' = if pad_prefix then TL.cons '…' (TL.drop (to_drop+1) txt) else TL.drop to_drop txt
30− (to_take,pad_suffix) = clip_for_char_width right_clip txt' 0
31− txt'' = TL.append (TL.take to_take txt') (if pad_suffix then TL.singleton '…' else TL.empty)
32− clip_for_char_width 0 _ n = (n, False)
33− clip_for_char_width w t n
28+ let (toDrop,padPrefix) = clipForCharWidth leftSkip txt 0
29+ txt' = if padPrefix then TL.cons '…' (TL.drop (toDrop+1) txt) else TL.drop toDrop txt
30+ (toTake,padSuffix) = clipForCharWidth rightClip txt' 0
31+ txt'' = TL.append (TL.take toTake txt') (if padSuffix then TL.singleton '…' else TL.empty)
32+ clipForCharWidth 0 _ n = (n, False)
33+ clipForCharWidth w t n
3434 | TL.null t = (n, False)
3535 | w < cw = (n, True)
3636 | w == cw = (n+1, False)
37− | w > cw = clip_for_char_width (w - cw) (TL.tail t) (n + 1)
38− where cw = safe_wcwidth (TL.head t)
39− clip_for_char_width _ _ _ = error "clip_for_char_width applied to undefined"
37+ | w > cw = clipForCharWidth (w - cw) (TL.tail t) (n + 1)
38+ where cw = safeWcwidth (TL.head t)
39+ clipForCharWidth _ _ _ = error "clipForCharWidth applied to undefined"
4040 in txt''
4141
4242-- | This is the internal representation of Images. Use the constructors in "Graphics.Vty.Image" to
@@ -57,70 +57,70 @@ data Image =
5757 -- | A horizontal text span is always >= 1 column and has a row height of 1.
5858 HorizText
5959 { attr :: Attr
60− -- | The text to display. The display width of the text is always output_width.
61− , display_text :: DisplayText
60+ -- | The text to display. The display width of the text is always outputWidth.
61+ , displayText :: DisplayText
6262 -- | The number of display columns for the text. Always > 0.
63− , output_width :: Int
63+ , outputWidth :: Int
6464 -- | the number of characters in the text. Always > 0.
65− , char_width :: Int
65+ , charWidth :: Int
6666 }
6767 -- | A horizontal join can be constructed between any two images. However a HorizJoin instance is
68− -- required to be between two images of equal height. The horiz_join constructor adds background
68+ -- required to be between two images of equal height. The horizJoin constructor adds background
6969 -- fills to the provided images that assure this is true for the HorizJoin value produced.
7070 | HorizJoin
71− { part_left :: Image
72− , part_right :: Image
73− , output_width :: Int -- ^ image_width part_left == image_width part_right. Always > 1
74− , output_height :: Int -- ^ image_height part_left == image_height part_right. Always > 0
71+ { partLeft :: Image
72+ , partRight :: Image
73+ , outputWidth :: Int -- ^ imageWidth partLeft == imageWidth partRight. Always > 1
74+ , outputHeight :: Int -- ^ imageHeight partLeft == imageHeight partRight. Always > 0
7575 }
7676 -- | A veritical join can be constructed between any two images. However a VertJoin instance is
77− -- required to be between two images of equal width. The vert_join constructor adds background
77+ -- required to be between two images of equal width. The vertJoin constructor adds background
7878 -- fills to the provides images that assure this is true for the VertJoin value produced.
7979 | VertJoin
80− { part_top :: Image
81− , part_bottom :: Image
82− , output_width :: Int -- ^ image_width part_top == image_width part_bottom. always > 0
83− , output_height :: Int -- ^ image_height part_top == image_height part_bottom. always > 1
80+ { partTop :: Image
81+ , partBottom :: Image
82+ , outputWidth :: Int -- ^ imageWidth partTop == imageWidth partBottom. always > 0
83+ , outputHeight :: Int -- ^ imageHeight partTop == imageHeight partBottom. always > 1
8484 }
8585 -- | A background fill will be filled with the background char. The background char is
8686 -- defined as a property of the Picture this Image is used to form.
8787 | BGFill
88− { output_width :: Int -- ^ always > 0
89− , output_height :: Int -- ^ always > 0
88+ { outputWidth :: Int -- ^ always > 0
89+ , outputHeight :: Int -- ^ always > 0
9090 }
9191 -- | Crop an image horizontally to a size by reducing the size from the right.
9292 | CropRight
93− { cropped_image :: Image
94− -- | Always < image_width cropped_image > 0
95− , output_width :: Int
96− , output_height :: Int -- ^ image_height cropped_image
93+ { croppedImage :: Image
94+ -- | Always < imageWidth croppedImage > 0
95+ , outputWidth :: Int
96+ , outputHeight :: Int -- ^ imageHeight croppedImage
9797 }
9898 -- | Crop an image horizontally to a size by reducing the size from the left.
9999 | CropLeft
100− { cropped_image :: Image
101− -- | Always < image_width cropped_image > 0
102− , left_skip :: Int
103− -- | Always < image_width cropped_image > 0
104− , output_width :: Int
105− , output_height :: Int
100+ { croppedImage :: Image
101+ -- | Always < imageWidth croppedImage > 0
102+ , leftSkip :: Int
103+ -- | Always < imageWidth croppedImage > 0
104+ , outputWidth :: Int
105+ , outputHeight :: Int
106106 }
107107 -- | Crop an image vertically to a size by reducing the size from the bottom
108108 | CropBottom
109− { cropped_image :: Image
110− -- | image_width cropped_image
111− , output_width :: Int
112− -- | height image is cropped to. Always < image_height cropped_image > 0
113− , output_height :: Int
109+ { croppedImage :: Image
110+ -- | imageWidth croppedImage
111+ , outputWidth :: Int
112+ -- | height image is cropped to. Always < imageHeight croppedImage > 0
113+ , outputHeight :: Int
114114 }
115115 -- | Crop an image vertically to a size by reducing the size from the top
116116 | CropTop
117− { cropped_image :: Image
118− -- | Always < image_height cropped_image > 0
119− , top_skip :: Int
120− -- | image_width cropped_image
121− , output_width :: Int
122− -- | Always < image_height cropped_image > 0
123− , output_height :: Int
117+ { croppedImage :: Image
118+ -- | Always < imageHeight croppedImage > 0
119+ , topSkip :: Int
120+ -- | imageWidth croppedImage
121+ , outputWidth :: Int
122+ -- | Always < imageHeight croppedImage > 0
123+ , outputHeight :: Int
124124 }
125125 -- | The empty image
126126 --
@@ -133,58 +133,58 @@ data Image =
133133 deriving Eq
134134
135135instance Show Image where
136− show ( HorizText { attr, display_text, output_width, char_width } )
137− = "HorizText " ++ show display_text
136+ show ( HorizText { attr, displayText, outputWidth, charWidth } )
137+ = "HorizText " ++ show displayText
138138 ++ "@(" ++ show attr ++ ","
139− ++ show output_width ++ ","
140− ++ show char_width ++ ")"
141− show ( BGFill { output_width, output_height } )
142− = "BGFill (" ++ show output_width ++ "," ++ show output_height ++ ")"
143− show ( HorizJoin { part_left = l, part_right = r, output_width = c } )
139+ ++ show outputWidth ++ ","
140+ ++ show charWidth ++ ")"
141+ show ( BGFill { outputWidth, outputHeight } )
142+ = "BGFill (" ++ show outputWidth ++ "," ++ show outputHeight ++ ")"
143+ show ( HorizJoin { partLeft = l, partRight = r, outputWidth = c } )
144144 = "HorizJoin " ++ show c ++ " (" ++ show l ++ " <|> " ++ show r ++ ")"
145− show ( VertJoin { part_top = t, part_bottom = b, output_width = c, output_height = r } )
145+ show ( VertJoin { partTop = t, partBottom = b, outputWidth = c, outputHeight = r } )
146146 = "VertJoin [" ++ show c ++ ", " ++ show r ++ "] (" ++ show t ++ ") <-> (" ++ show b ++ ")"
147− show ( CropRight { cropped_image, output_width, output_height } )
148− = "CropRight [" ++ show output_width ++ "," ++ show output_height ++ "]"
149− ++ " (" ++ show cropped_image ++ ")"
150− show ( CropLeft { cropped_image, left_skip, output_width, output_height } )
151− = "CropLeft [" ++ show left_skip ++ "," ++ show output_width ++ "," ++ show output_height ++ "]"
152− ++ " (" ++ show cropped_image ++ ")"
153− show ( CropBottom { cropped_image, output_width, output_height } )
154− = "CropBottom [" ++ show output_width ++ "," ++ show output_height ++ "]"
155− ++ " (" ++ show cropped_image ++ ")"
156− show ( CropTop { cropped_image, top_skip, output_width, output_height } )
157− = "CropTop [" ++ show top_skip ++ "," ++ show output_width ++ "," ++ show output_height ++ "]"
158− ++ " (" ++ show cropped_image ++ ")"
147+ show ( CropRight { croppedImage, outputWidth, outputHeight } )
148+ = "CropRight [" ++ show outputWidth ++ "," ++ show outputHeight ++ "]"
149+ ++ " (" ++ show croppedImage ++ ")"
150+ show ( CropLeft { croppedImage, leftSkip, outputWidth, outputHeight } )
151+ = "CropLeft [" ++ show leftSkip ++ "," ++ show outputWidth ++ "," ++ show outputHeight ++ "]"
152+ ++ " (" ++ show croppedImage ++ ")"
153+ show ( CropBottom { croppedImage, outputWidth, outputHeight } )
154+ = "CropBottom [" ++ show outputWidth ++ "," ++ show outputHeight ++ "]"
155+ ++ " (" ++ show croppedImage ++ ")"
156+ show ( CropTop { croppedImage, topSkip, outputWidth, outputHeight } )
157+ = "CropTop [" ++ show topSkip ++ "," ++ show outputWidth ++ "," ++ show outputHeight ++ "]"
158+ ++ " (" ++ show croppedImage ++ ")"
159159 show ( EmptyImage ) = "EmptyImage"
160160
161161-- | Attempts to pretty print just the structure of an image.
162162pp_image_structure :: Image -> String
163−pp_image_structure in_img = go 0 in_img
163+pp_image_structure inImg = go 0 inImg
164164 where
165165 go indent img = tab indent ++ pp indent img
166166 tab indent = concat $ replicate indent " "
167− pp _ (HorizText {output_width}) = "HorizText(" ++ show output_width ++ ")"
168− pp _ (BGFill {output_width, output_height})
169− = "BGFill(" ++ show output_width ++ "," ++ show output_height ++ ")"
170− pp i (HorizJoin {part_left = l, part_right = r, output_width = c})
167+ pp _ (HorizText {outputWidth}) = "HorizText(" ++ show outputWidth ++ ")"
168+ pp _ (BGFill {outputWidth, outputHeight})
169+ = "BGFill(" ++ show outputWidth ++ "," ++ show outputHeight ++ ")"
170+ pp i (HorizJoin {partLeft = l, partRight = r, outputWidth = c})
171171 = "HorizJoin(" ++ show c ++ ")\n" ++ go (i+1) l ++ "\n" ++ go (i+1) r
172− pp i (VertJoin {part_top = t, part_bottom = b, output_width = c, output_height = r})
172+ pp i (VertJoin {partTop = t, partBottom = b, outputWidth = c, outputHeight = r})
173173 = "VertJoin(" ++ show c ++ ", " ++ show r ++ ")\n"
174174 ++ go (i+1) t ++ "\n"
175175 ++ go (i+1) b
176− pp i (CropRight {cropped_image, output_width, output_height})
177− = "CropRight(" ++ show output_width ++ "," ++ show output_height ++ ")\n"
178− ++ go (i+1) cropped_image
179− pp i (CropLeft {cropped_image, left_skip, output_width, output_height})
180− = "CropLeft(" ++ show left_skip ++ "->" ++ show output_width ++ "," ++ show output_height ++ ")\n"
181− ++ go (i+1) cropped_image
182− pp i (CropBottom {cropped_image, output_width, output_height})
183− = "CropBottom(" ++ show output_width ++ "," ++ show output_height ++ ")\n"
184− ++ go (i+1) cropped_image
185− pp i (CropTop {cropped_image, top_skip, output_width, output_height})
186− = "CropTop("++ show output_width ++ "," ++ show top_skip ++ "->" ++ show output_height ++ ")\n"
187− ++ go (i+1) cropped_image
176+ pp i (CropRight {croppedImage, outputWidth, outputHeight})
177+ = "CropRight(" ++ show outputWidth ++ "," ++ show outputHeight ++ ")\n"
178+ ++ go (i+1) croppedImage
179+ pp i (CropLeft {croppedImage, leftSkip, outputWidth, outputHeight})
180+ = "CropLeft(" ++ show leftSkip ++ "->" ++ show outputWidth ++ "," ++ show outputHeight ++ ")\n"
181+ ++ go (i+1) croppedImage
182+ pp i (CropBottom {croppedImage, outputWidth, outputHeight})
183+ = "CropBottom(" ++ show outputWidth ++ "," ++ show outputHeight ++ ")\n"
184+ ++ go (i+1) croppedImage
185+ pp i (CropTop {croppedImage, topSkip, outputWidth, outputHeight})
186+ = "CropTop("++ show outputWidth ++ "," ++ show topSkip ++ "->" ++ show outputHeight ++ ")\n"
187+ ++ go (i+1) croppedImage
188188 pp _ EmptyImage = "EmptyImage"
189189
190190instance NFData Image where
@@ -199,37 +199,37 @@ instance NFData Image where
199199 rnf (HorizText a s w cw) = a `seq` s `deepseq` w `seq` cw `seq` ()
200200
201201-- | The width of an Image. This is the number display columns the image will occupy.
202−image_width :: Image -> Int
203−image_width HorizText { output_width = w } = w
204−image_width HorizJoin { output_width = w } = w
205−image_width VertJoin { output_width = w } = w
206−image_width BGFill { output_width = w } = w
207−image_width CropRight { output_width = w } = w
208−image_width CropLeft { output_width = w } = w
209−image_width CropBottom { output_width = w } = w
210−image_width CropTop { output_width = w } = w
211−image_width EmptyImage = 0
202+imageWidth :: Image -> Int
203+imageWidth HorizText { outputWidth = w } = w
204+imageWidth HorizJoin { outputWidth = w } = w
205+imageWidth VertJoin { outputWidth = w } = w
206+imageWidth BGFill { outputWidth = w } = w
207+imageWidth CropRight { outputWidth = w } = w
208+imageWidth CropLeft { outputWidth = w } = w
209+imageWidth CropBottom { outputWidth = w } = w
210+imageWidth CropTop { outputWidth = w } = w
211+imageWidth EmptyImage = 0
212212
213213-- | The height of an Image. This is the number of display rows the image will occupy.
214−image_height :: Image -> Int
215−image_height HorizText {} = 1
216−image_height HorizJoin { output_height = h } = h
217−image_height VertJoin { output_height = h } = h
218−image_height BGFill { output_height = h } = h
219−image_height CropRight { output_height = h } = h
220−image_height CropLeft { output_height = h } = h
221−image_height CropBottom { output_height = h } = h
222−image_height CropTop { output_height = h } = h
223−image_height EmptyImage = 0
214+imageHeight :: Image -> Int
215+imageHeight HorizText {} = 1
216+imageHeight HorizJoin { outputHeight = h } = h
217+imageHeight VertJoin { outputHeight = h } = h
218+imageHeight BGFill { outputHeight = h } = h
219+imageHeight CropRight { outputHeight = h } = h
220+imageHeight CropLeft { outputHeight = h } = h
221+imageHeight CropBottom { outputHeight = h } = h
222+imageHeight CropTop { outputHeight = h } = h
223+imageHeight EmptyImage = 0
224224
225225-- | Append in the Monoid instance is equivalent to <->.
226226instance Monoid Image where
227227 mempty = EmptyImage
228− mappend = vert_join
228+ mappend = vertJoin
229229
230230-- | combines two images side by side
231231--
232−-- Combines text chunks where possible. Assures output_width and output_height properties are not
232+-- Combines text chunks where possible. Assures outputWidth and outputHeight properties are not
233233-- violated.
234234--
235235-- The result image will have a width equal to the sum of the two images width. And the height will
@@ -237,30 +237,30 @@ instance Monoid Image where
237237-- missmatch will be filled with the background pattern.
238238--
239239-- TODO: the bg fill is biased towards top to bottom languages(?)
240−horiz_join :: Image -> Image -> Image
241−horiz_join EmptyImage i = i
242−horiz_join i EmptyImage = i
243−horiz_join i_0@(HorizText a_0 t_0 w_0 cw_0) i_1@(HorizText a_1 t_1 w_1 cw_1)
240+horizJoin :: Image -> Image -> Image
241+horizJoin EmptyImage i = i
242+horizJoin i EmptyImage = i
243+horizJoin i_0@(HorizText a_0 t_0 w_0 cw_0) i_1@(HorizText a_1 t_1 w_1 cw_1)
244244 | a_0 == a_1 = HorizText a_0 (TL.append t_0 t_1) (w_0 + w_1) (cw_0 + cw_1)
245245 -- TODO: assumes horiz text height is always 1
246246 | otherwise = HorizJoin i_0 i_1 (w_0 + w_1) 1
247−horiz_join i_0 i_1
247+horizJoin i_0 i_1
248248 -- If the images are of the same height then no padding is required
249249 | h_0 == h_1 = HorizJoin i_0 i_1 w h_0
250250 -- otherwise one of the images needs to be padded to the right size.
251251 | h_0 < h_1 -- Pad i_0
252− = let pad_amount = h_1 - h_0
253− in HorizJoin (VertJoin i_0 (BGFill w_0 pad_amount) w_0 h_1) i_1 w h_1
252+ = let padAmount = h_1 - h_0
253+ in HorizJoin (VertJoin i_0 (BGFill w_0 padAmount) w_0 h_1) i_1 w h_1
254254 | h_0 > h_1 -- Pad i_1
255− = let pad_amount = h_0 - h_1
256− in HorizJoin i_0 (VertJoin i_1 (BGFill w_1 pad_amount) w_1 h_0) w h_0
255+ = let padAmount = h_0 - h_1
256+ in HorizJoin i_0 (VertJoin i_1 (BGFill w_1 padAmount) w_1 h_0) w h_0
257257 where
258− w_0 = image_width i_0
259− w_1 = image_width i_1
258+ w_0 = imageWidth i_0
259+ w_1 = imageWidth i_1
260260 w = w_0 + w_1
261− h_0 = image_height i_0
262− h_1 = image_height i_1
263−horiz_join _ _ = error "horiz_join applied to undefined values."
261+ h_0 = imageHeight i_0
262+ h_1 = imageHeight i_1
263+horizJoin _ _ = error "horizJoin applied to undefined values."
264264
265265-- | combines two images vertically
266266--
@@ -270,24 +270,24 @@ horiz_join _ _ = error "horiz_join applied to undefined values."
270270-- pattern.
271271--
272272-- TODO: the bg fill is biased towards right to left languages(?)
273−vert_join :: Image -> Image -> Image
274−vert_join EmptyImage i = i
275−vert_join i EmptyImage = i
276−vert_join i_0 i_1
273+vertJoin :: Image -> Image -> Image
274+vertJoin EmptyImage i = i
275+vertJoin i EmptyImage = i
276+vertJoin i_0 i_1
277277 -- If the images are of the same width then no background padding is required
278278 | w_0 == w_1 = VertJoin i_0 i_1 w_0 h
279279 -- Otherwise one of the images needs to be padded to the size of the other image.
280280 | w_0 < w_1
281− = let pad_amount = w_1 - w_0
282− in VertJoin (HorizJoin i_0 (BGFill pad_amount h_0) w_1 h_0) i_1 w_1 h
281+ = let padAmount = w_1 - w_0
282+ in VertJoin (HorizJoin i_0 (BGFill padAmount h_0) w_1 h_0) i_1 w_1 h
283283 | w_0 > w_1
284− = let pad_amount = w_0 - w_1
285− in VertJoin i_0 (HorizJoin i_1 (BGFill pad_amount h_1) w_0 h_1) w_0 h
284+ = let padAmount = w_0 - w_1
285+ in VertJoin i_0 (HorizJoin i_1 (BGFill padAmount h_1) w_0 h_1) w_0 h
286286 where
287− w_0 = image_width i_0
288− w_1 = image_width i_1
289− h_0 = image_height i_0
290− h_1 = image_height i_1
287+ w_0 = imageWidth i_0
288+ w_1 = imageWidth i_1
289+ h_0 = imageHeight i_0
290+ h_1 = imageHeight i_1
291291 h = h_0 + h_1
292−vert_join _ _ = error "vert_join applied to undefined values."
292+vertJoin _ _ = error "vertJoin applied to undefined values."
293293
src/Graphics/Vty/Inline.hs+43−44
@@ -10,18 +10,18 @@
1010--
1111-- @
1212-- putStr \"Not styled. \"
13−-- put_attr_change_ $ do
14−-- back_color red
15−-- apply_style underline
13+-- putAttrChange_ $ do
14+-- backColor red
15+-- applyStyle underline
1616-- putStr \" Styled! \"
17−-- put_attr_change_ $ default_all
17+-- putAttrChange_ $ defaultAll
1818-- putStrLn \"Not styled.\"
1919-- @
2020--
21−-- 'put_attr_change' outputs the control codes to the terminal device 'Handle'. This is a duplicate
22−-- of the 'stdout' handle when the 'terminal_handle' was (first) acquired. If 'stdout' has since been
21+-- 'putAttrChange' outputs the control codes to the terminal device 'Handle'. This is a duplicate
22+-- of the 'stdout' handle when the 'terminalHandle' was (first) acquired. If 'stdout' has since been
2323-- changed then 'putStr', 'putStrLn', 'print' etc.. will output to a different 'Handle' than
24−-- 'put_attr_change'
24+-- 'putAttrChange'
2525--
2626-- Copyright 2009-2010 Corey O'Connor
2727{-# LANGUAGE BangPatterns #-}
@@ -49,63 +49,62 @@ import System.IO
4949type InlineM v = State Attr v
5050
5151-- | Set the background color to the provided 'Color'
52−back_color :: Color -> InlineM ()
53−back_color c = modify $ flip mappend ( current_attr `with_back_color` c )
52+backColor :: Color -> InlineM ()
53+backColor c = modify $ flip mappend ( currentAttr `withBackColor` c )
5454
5555-- | Set the foreground color to the provided 'Color'
56−fore_color :: Color -> InlineM ()
57−fore_color c = modify $ flip mappend ( current_attr `with_fore_color` c )
56+foreColor :: Color -> InlineM ()
57+foreColor c = modify $ flip mappend ( currentAttr `withForeColor` c )
5858
5959-- | Attempt to change the 'Style' of the following text.
6060--
6161-- If the terminal does not support the style change no error is produced. The style can still be
6262-- removed.
63−apply_style :: Style -> InlineM ()
64−apply_style s = modify $ flip mappend ( current_attr `with_style` s )
63+applyStyle :: Style -> InlineM ()
64+applyStyle s = modify $ flip mappend ( currentAttr `withStyle` s )
6565
6666-- | Attempt to remove the specified 'Style' from the display of the following text.
6767--
68−-- This will fail if apply_style for the given style has not been previously called.
69−remove_style :: Style -> InlineM ()
70−remove_style s_mask = modify $ \attr ->
71− let style' = case attr_style attr of
72− Default -> error $ "Graphics.Vty.Inline: Cannot remove_style if apply_style never used."
73− KeepCurrent -> error $ "Graphics.Vty.Inline: Cannot remove_style if apply_style never used."
74− SetTo s -> s .&. complement s_mask
75− in attr { attr_style = SetTo style' }
68+-- This will fail if applyStyle for the given style has not been previously called.
69+removeStyle :: Style -> InlineM ()
70+removeStyle sMask = modify $ \attr ->
71+ let style' = case attrStyle attr of
72+ Default -> error $ "Graphics.Vty.Inline: Cannot removeStyle if applyStyle never used."
73+ KeepCurrent -> error $ "Graphics.Vty.Inline: Cannot removeStyle if applyStyle never used."
74+ SetTo s -> s .&. complement sMask
75+ in attr { attrStyle = SetTo style' }
7676
7777-- | Reset the display attributes
78−default_all :: InlineM ()
79−default_all = put def_attr
78+defaultAll :: InlineM ()
79+defaultAll = put defAttr
8080
81−-- | Apply the provided display attribute changes to the given terminal.
81+-- | Apply the provided display attribute changes to the given terminal output device.
8282--
8383-- This does not flush the terminal.
84−put_attr_change :: ( Applicative m, MonadIO m ) => Output -> InlineM () -> m ()
85−put_attr_change out c = liftIO $ do
86− bounds <- display_bounds out
87− dc <- display_context out bounds
88− mfattr <- prev_fattr <$> readIORef (assumed_state_ref out)
84+putAttrChange :: ( Applicative m, MonadIO m ) => Output -> InlineM () -> m ()
85+putAttrChange out c = liftIO $ do
86+ bounds <- displayBounds out
87+ dc <- displayContext out bounds
88+ mfattr <- prevFattr <$> readIORef (assumedStateRef out)
8989 fattr <- case mfattr of
9090 Nothing -> do
91− liftIO $ output_byte_buffer out $ writeToByteString $ write_default_attr dc
92− return $ FixedAttr default_style_mask Nothing Nothing
91+ liftIO $ outputByteBuffer out $ writeToByteString $ writeDefaultAttr dc
92+ return $ FixedAttr defaultStyleMask Nothing Nothing
9393 Just v -> return v
94− let attr = execState c current_attr
95− attr' = limit_attr_for_display out attr
96− fattr' = fix_display_attr fattr attr'
97− diffs = display_attr_diffs fattr fattr'
98− output_byte_buffer out $ writeToByteString $ write_set_attr dc fattr attr' diffs
99− modifyIORef (assumed_state_ref out) $ \s -> s { prev_fattr = Just fattr' }
100− inline_hack dc
94+ let attr = execState c currentAttr
95+ attr' = limitAttrForDisplay out attr
96+ fattr' = fixDisplayAttr fattr attr'
97+ diffs = displayAttrDiffs fattr fattr'
98+ outputByteBuffer out $ writeToByteString $ writeSetAttr dc fattr attr' diffs
99+ modifyIORef (assumedStateRef out) $ \s -> s { prevFattr = Just fattr' }
100+ inlineHack dc
101101
102−-- | Apply the provided display attributes changes to the terminal that was current at the time this
103−-- was first used. Which, for most use cases, is the current terminal.
102+-- | Apply the provided display attributes changes to the terminal output device that was current at
103+-- the time this was first used. Which, for most use cases, is the current terminal.
104104--
105105-- This will flush the terminal output.
106−put_attr_change_ :: ( Applicative m, MonadIO m ) => InlineM () -> m ()
107−put_attr_change_ c = liftIO $ do
108− out <- withVty $ return . output_iface
106+putAttrChange_ :: ( Applicative m, MonadIO m ) => InlineM () -> m ()
107+putAttrChange_ c = liftIO $ withOutput $ \out -> do
109108 hFlush stdout
110− put_attr_change out c
109+ putAttrChange out c
111110 hFlush stdout
src/Graphics/Vty/Inline/Unsafe.hs+21−7
@@ -7,20 +7,34 @@ import Data.IORef
77
88import System.IO.Unsafe
99
10−global_vty :: IORef (Maybe Vty)
11−{-# NOINLINE global_vty #-}
12−global_vty = unsafePerformIO $ newIORef Nothing
10+globalVty :: IORef (Maybe Vty)
11+{-# NOINLINE globalVty #-}
12+globalVty = unsafePerformIO $ newIORef Nothing
13+
14+globalOutput :: IORef (Maybe Output)
15+{-# NOINLINE globalOutput #-}
16+globalOutput = unsafePerformIO $ newIORef Nothing
1317
1418-- | This will create a Vty instance using 'mkVty' and execute an IO action provided that instance.
15−-- The created Vty instance will be stored to the unsafe 'IORef' 'global_vty'.
19+-- The created Vty instance will be stored to the unsafe 'IORef' 'globalVty'.
1620withVty :: (Vty -> IO b) -> IO b
1721withVty f = do
18− mvty <- readIORef global_vty
22+ mvty <- readIORef globalVty
1923 vty <- case mvty of
2024 Nothing -> do
21− vty <- mkVty def
22− writeIORef global_vty (Just vty)
25+ vty <- mkVty $ def
26+ writeIORef globalVty (Just vty)
2327 return vty
2428 Just vty -> return vty
2529 f vty
2630
31+withOutput :: (Output -> IO b) -> IO b
32+withOutput f = do
33+ mout <- readIORef globalOutput
34+ out <- case mout of
35+ Nothing -> do
36+ out <- outputForCurrentTerminal
37+ writeIORef globalOutput (Just out)
38+ return out
39+ Just out -> return out
40+ f out
src/Graphics/Vty/Input.hs+19−19
@@ -39,8 +39,8 @@ module Graphics.Vty.Input ( Key(..)
3939 , Event(..)
4040 , Input(..)
4141 , Config(..)
42− , input_for_current_terminal
43− , input_for_name_and_io
42+ , inputForCurrentTerminal
43+ , inputForNameAndIO
4444 )
4545 where
4646
@@ -58,11 +58,11 @@ import System.Posix.IO (stdInput)
5858import System.Posix.Types (Fd)
5959
6060-- | Set up the current terminal for input.
61−-- This determines the current terminal then invokes 'input_for_name_and_io'
62−input_for_current_terminal :: Config -> IO Input
63−input_for_current_terminal config = do
64− term_name <- getEnv "TERM"
65− input_for_name_and_io config term_name stdInput
61+-- This determines the current terminal then invokes 'inputForNameAndIO'
62+inputForCurrentTerminal :: Config -> IO Input
63+inputForCurrentTerminal config = do
64+ termName <- getEnv "TERM"
65+ inputForNameAndIO config termName stdInput
6666
6767-- | Set up the terminal attached to the given Fd for input. Returns a 'Input'.
6868--
@@ -89,23 +89,23 @@ input_for_current_terminal config = do
8989-- * IEXTEN disabled
9090-- - extended functions are disabled. Uh. Whatever these are.
9191--
92−input_for_name_and_io :: Config -> String -> Fd -> IO Input
93−input_for_name_and_io config term_name term_fd = do
94− terminal <- Terminfo.setupTerm term_name
95− let classify_table = classify_table_for_term term_name terminal
96− (set_attrs,unset_attrs) <- attributeControl term_fd
97− set_attrs
98− input <- initInputForFd config classify_table term_fd
92+inputForNameAndIO :: Config -> String -> Fd -> IO Input
93+inputForNameAndIO config termName termFd = do
94+ terminal <- Terminfo.setupTerm termName
95+ let classifyTable = classifyTableForTerm termName terminal
96+ (setAttrs,unsetAttrs) <- attributeControl termFd
97+ setAttrs
98+ input <- initInputForFd config classifyTable termFd
9999 let pokeIO = Catch $ do
100100 let e = error "(getsize in input layer)"
101− set_attrs
102− writeChan (input^.event_channel) (EvResize e e)
101+ setAttrs
102+ writeChan (input^.eventChannel) (EvResize e e)
103103 _ <- installHandler windowChange pokeIO Nothing
104104 _ <- installHandler continueProcess pokeIO Nothing
105105 return $ input
106− { shutdown_input = do
107− shutdown_input input
106+ { shutdownInput = do
107+ shutdownInput input
108108 _ <- installHandler windowChange Ignore Nothing
109109 _ <- installHandler continueProcess Ignore Nothing
110− unset_attrs
110+ unsetAttrs
111111 }
src/Graphics/Vty/Input/Internal.hs+72−72
@@ -45,14 +45,14 @@ instance Default Config where
4545data Input = Input
4646 { -- | Channel of events direct from input processing. Unlike 'next_event' this will not refresh
4747 -- the display if the next event is an 'EvResize'.
48− _event_channel :: Chan Event
48+ _eventChannel :: Chan Event
4949 -- | Shuts down the input processing. This should return the terminal input state to before
5050 -- the input initialized.
51− , shutdown_input :: IO ()
51+ , shutdownInput :: IO ()
5252 -- | Changes to this value are reflected after the next event.
53− , _config_ref :: IORef Config
53+ , _configRef :: IORef Config
5454 -- | File descriptor used for input.
55− , _input_fd :: Fd
55+ , _inputFd :: Fd
5656 }
5757
5858makeLenses ''Input
@@ -71,10 +71,10 @@ data InputBuffer = InputBuffer
7171makeLenses ''InputBuffer
7272
7373data InputState = InputState
74− { _unprocessed_bytes :: String
75− , _applied_config :: Config
76− , _input_buffer :: InputBuffer
77− , _stop_request_ref :: IORef Bool
74+ { _unprocessedBytes :: String
75+ , _appliedConfig :: Config
76+ , _inputBuffer :: InputBuffer
77+ , _stopRequestRef :: IORef Bool
7878 , _classifier :: String -> KClass
7979 }
8080
@@ -84,63 +84,63 @@ type InputM a = StateT InputState (ReaderT Input IO) a
8484
8585-- this must be run on an OS thread dedicated to this input handling.
8686-- otherwise the terminal timing read behavior will block the execution of the lightweight threads.
87−loop_input_processor :: InputM ()
88−loop_input_processor = do
89− read_from_device >>= add_bytes_to_process
90− valid_events <- many parse_event
91− forM_ valid_events emit
92− drop_invalid
93− stop_if_requested <|> loop_input_processor
87+loopInputProcessor :: InputM ()
88+loopInputProcessor = do
89+ readFromDevice >>= addBytesToProcess
90+ validEvents <- many parseEvent
91+ forM_ validEvents emit
92+ dropInvalid
93+ stopIfRequested <|> loopInputProcessor
9494
95−add_bytes_to_process :: String -> InputM ()
96−add_bytes_to_process block = unprocessed_bytes <>= block
95+addBytesToProcess :: String -> InputM ()
96+addBytesToProcess block = unprocessedBytes <>= block
9797
9898emit :: Event -> InputM ()
99−emit event = view event_channel >>= liftIO . flip writeChan event
99+emit event = view eventChannel >>= liftIO . flip writeChan event
100100
101101-- There should be two versions of this method:
102102-- 1. using VMIN and VTIME when under the threaded runtime
103103-- 2. emulating VMIN and VTIME in userspace when under the non-threaded runtime.
104−read_from_device :: InputM String
105−read_from_device = do
106− new_config <- view config_ref >>= liftIO . readIORef
107− old_config <- use applied_config
108− fd <- view input_fd
109− when (new_config /= old_config) $ do
110− liftIO $ apply_timing_config fd new_config
111− applied_config .= new_config
112− buffer_ptr <- use $ input_buffer.ptr
113− max_bytes <- use $ input_buffer.size
104+readFromDevice :: InputM String
105+readFromDevice = do
106+ newConfig <- view configRef >>= liftIO . readIORef
107+ oldConfig <- use appliedConfig
108+ fd <- view inputFd
109+ when (newConfig /= oldConfig) $ do
110+ liftIO $ applyTimingConfig fd newConfig
111+ appliedConfig .= newConfig
112+ bufferPtr <- use $ inputBuffer.ptr
113+ maxBytes <- use $ inputBuffer.size
114114 liftIO $ do
115− bytes_read <- fdReadBuf fd buffer_ptr (fromIntegral max_bytes)
115+ bytes_read <- fdReadBuf fd bufferPtr (fromIntegral maxBytes)
116116 if bytes_read > 0
117− then fmap (map $ chr . fromIntegral) $ peekArray (fromIntegral bytes_read) buffer_ptr
117+ then fmap (map $ chr . fromIntegral) $ peekArray (fromIntegral bytes_read) bufferPtr
118118 else return []
119119
120−apply_timing_config :: Fd -> Config -> IO ()
121−apply_timing_config fd config =
120+applyTimingConfig :: Fd -> Config -> IO ()
121+applyTimingConfig fd config =
122122 let vtime = min 255 $ singleEscPeriod config `div` 100000
123− in set_term_timing fd 1 vtime
123+ in setTermTiming fd 1 vtime
124124
125−parse_event :: InputM Event
126−parse_event = do
125+parseEvent :: InputM Event
126+parseEvent = do
127127 c <- use classifier
128− b <- use unprocessed_bytes
128+ b <- use unprocessedBytes
129129 case c b of
130130 Valid e remaining -> do
131− unprocessed_bytes .= remaining
131+ unprocessedBytes .= remaining
132132 return e
133133 _ -> mzero
134134
135−drop_invalid :: InputM ()
136−drop_invalid = do
135+dropInvalid :: InputM ()
136+dropInvalid = do
137137 c <- use classifier
138− b <- use unprocessed_bytes
139− when (c b == Invalid) $ unprocessed_bytes .= []
138+ b <- use unprocessedBytes
139+ when (c b == Invalid) $ unprocessedBytes .= []
140140
141−stop_if_requested :: InputM ()
142−stop_if_requested = do
143− True <- (liftIO . readIORef) =<< use stop_request_ref
141+stopIfRequested :: InputM ()
142+stopIfRequested = do
143+ True <- (liftIO . readIORef) =<< use stopRequestRef
144144 return ()
145145
146146-- This makes a kind of tri. Has space efficiency issues with large input blocks.
@@ -151,25 +151,25 @@ stop_if_requested = do
151151compile :: ClassifyTable -> [Char] -> KClass
152152compile table = cl' where
153153 -- take all prefixes and create a set of these
154− prefix_set = S.fromList $ concatMap (init . inits . fst) $ table
155− event_for_input = M.fromList table
154+ prefixSet = S.fromList $ concatMap (init . inits . fst) $ table
155+ eventForInput = M.fromList table
156156 cl' [] = Prefix
157− cl' input_block = case M.lookup input_block event_for_input of
157+ cl' inputBlock = case M.lookup inputBlock eventForInput of
158158 Just e -> Valid e []
159− Nothing -> case S.member input_block prefix_set of
159+ Nothing -> case S.member inputBlock prefixSet of
160160 True -> Prefix
161− -- if the input_block is exactly what is expected for an event then consume the whole
161+ -- if the inputBlock is exactly what is expected for an event then consume the whole
162162 -- block and return the event
163163 -- look up progressively smaller tails of the input block until an event is found
164164 -- The assumption is that the event that consumes the most input bytes should be
165165 -- produced.
166166 -- The test verify_full_syn_input_to_event_2x verifies this.
167− -- H: There will always be one match. The prefix_set contains, by definition, all
167+ -- H: There will always be one match. The prefixSet contains, by definition, all
168168 -- prefixes of an event.
169169 False ->
170− let input_tails = init $ tail $ tails input_block
171− in case mapMaybe (\s -> (,) s `fmap` M.lookup s event_for_input) input_tails of
172− (s,e) : _ -> Valid e (drop (length s) input_block)
170+ let inputTails = init $ tail $ tails inputBlock
171+ in case mapMaybe (\s -> (,) s `fmap` M.lookup s eventForInput) inputTails of
172+ (s,e) : _ -> Valid e (drop (length s) inputBlock)
173173 -- neither a prefix or a full event. Might be interesting to log.
174174 [] -> Invalid
175175
@@ -198,15 +198,15 @@ utf8Length c
198198 | c < 0xF0 = 3
199199 | otherwise = 4
200200
201−run_input_processor_loop :: ClassifyTable -> Input -> IORef Bool -> IO ()
202−run_input_processor_loop classify_table input stop_flag = do
203− let buffer_size = 1024
204− allocaArray buffer_size $ \(buffer_ptr :: Ptr Word8) -> do
205− s0 <- InputState [] <$> readIORef (_config_ref input)
206− <*> pure (InputBuffer buffer_ptr buffer_size)
207− <*> pure stop_flag
208− <*> pure (classify classify_table)
209− runReaderT (evalStateT loop_input_processor s0) input
201+runInputProcessorLoop :: ClassifyTable -> Input -> IORef Bool -> IO ()
202+runInputProcessorLoop classifyTable input stopFlag = do
203+ let bufferSize = 1024
204+ allocaArray bufferSize $ \(bufferPtr :: Ptr Word8) -> do
205+ s0 <- InputState [] <$> readIORef (_configRef input)
206+ <*> pure (InputBuffer bufferPtr bufferSize)
207+ <*> pure stopFlag
208+ <*> pure (classify classifyTable)
209+ runReaderT (evalStateT loopInputProcessor s0) input
210210
211211attributeControl :: Fd -> IO (IO (), IO ())
212212attributeControl fd = do
@@ -214,21 +214,21 @@ attributeControl fd = do
214214 let vtyMode = foldl withoutMode original [ StartStopOutput, KeyboardInterrupts
215215 , EnableEcho, ProcessInput, ExtendedFunctions
216216 ]
217− let set_attrs = setTerminalAttributes fd vtyMode Immediately
218− unset_attrs = setTerminalAttributes fd original Immediately
219− return (set_attrs,unset_attrs)
217+ let setAttrs = setTerminalAttributes fd vtyMode Immediately
218+ unsetAttrs = setTerminalAttributes fd original Immediately
219+ return (setAttrs,unsetAttrs)
220220
221221-- This is an example of an algorithm where code coverage could be high, even 100%, but the
222222-- algorithm still under tested. I should collect more of these examples...
223223initInputForFd :: Config -> ClassifyTable -> Fd -> IO Input
224−initInputForFd config classify_table in_fd = do
225− apply_timing_config in_fd config
226− stop_flag <- newIORef False
224+initInputForFd config classifyTable inFd = do
225+ applyTimingConfig inFd config
226+ stopFlag <- newIORef False
227227 input <- Input <$> newChan
228− <*> pure (writeIORef stop_flag True)
228+ <*> pure (writeIORef stopFlag True)
229229 <*> newIORef config
230− <*> pure in_fd
231− _ <- forkOS $ run_input_processor_loop classify_table input stop_flag
230+ <*> pure inFd
231+ _ <- forkOS $ runInputProcessorLoop classifyTable input stopFlag
232232 return input
233233
234−foreign import ccall "vty_set_term_timing" set_term_timing :: Fd -> Int -> Int -> IO ()
234+foreign import ccall "vty_set_term_timing" setTermTiming :: Fd -> Int -> Int -> IO ()
src/Graphics/Vty/Input/Terminfo.hs+29−29
@@ -34,25 +34,25 @@ import System.Console.Terminfo
3434--
3535-- \todo terminfo meta is not supported.
3636-- \todo no 8bit
37−classify_table_for_term :: String -> Terminal -> ClassifyTable
38−classify_table_for_term term_name term =
39− concat $ caps_classify_table term keys_from_caps_table
40− : universal_table
41− : term_specific_tables term_name
37+classifyTableForTerm :: String -> Terminal -> ClassifyTable
38+classifyTableForTerm termName term =
39+ concat $ capsClassifyTable term keysFromCapsTable
40+ : universalTable
41+ : termSpecificTables termName
4242
4343-- | key table assumed to be applicable to all terminals.
44−universal_table :: ClassifyTable
45−universal_table = concat [visible_chars, ctrl_chars, ctrl_meta_chars, special_support_keys]
44+universalTable :: ClassifyTable
45+universalTable = concat [visibleChars, ctrlChars, ctrlMetaChars, specialSupportKeys]
4646
47−caps_classify_table :: Terminal -> [(String,Event)] -> ClassifyTable
48−caps_classify_table terminal table = [(x,y) | (Just x,y) <- map extract_cap table]
49− where extract_cap = first (getCapability terminal . tiGetStr)
47+capsClassifyTable :: Terminal -> [(String,Event)] -> ClassifyTable
48+capsClassifyTable terminal table = [(x,y) | (Just x,y) <- map extractCap table]
49+ where extractCap = first (getCapability terminal . tiGetStr)
5050
5151-- | tables specific to a given terminal that are not derivable from terminfo.
52−term_specific_tables :: String -> [ClassifyTable]
53−term_specific_tables term_name
54− | ANSI.supports term_name = ANSI.tables
55− | XTerm7Bit.supports term_name = XTerm7Bit.tables
52+termSpecificTables :: String -> [ClassifyTable]
53+termSpecificTables termName
54+ | ANSI.supports termName = ANSI.tables
55+ | XTerm7Bit.supports termName = XTerm7Bit.tables
5656 | otherwise = []
5757
5858-- | Visible characters in the ISO-8859-1 and UTF-8 common set.
@@ -62,16 +62,16 @@ term_specific_tables term_name
6262--
6363-- TODO: resolve
6464-- 1. start at ' '. The earlier characters are all ctrl_char_keys
65−visible_chars :: ClassifyTable
66−visible_chars = [ ([x], EvKey (KChar x) [])
67− | x <- [' ' .. toEnum 0xC1]
68− ]
65+visibleChars :: ClassifyTable
66+visibleChars = [ ([x], EvKey (KChar x) [])
67+ | x <- [' ' .. toEnum 0xC1]
68+ ]
6969
7070-- | Non visible characters in the ISO-8859-1 and UTF-8 common set translated to ctrl + char.
7171--
7272-- \todo resolve CTRL-i is the same as tab
73−ctrl_chars :: ClassifyTable
74−ctrl_chars =
73+ctrlChars :: ClassifyTable
74+ctrlChars =
7575 [ ([toEnum x],EvKey (KChar y) [MCtrl])
7676 | (x,y) <- zip ([0..31]) ('@':['a'..'z']++['['..'_']),
7777 y /= 'i', -- Resolve issue #3 where CTRL-i hides TAB.
@@ -79,12 +79,12 @@ ctrl_chars =
7979 ]
8080
8181-- | Ctrl+Meta+Char
82−ctrl_meta_chars :: ClassifyTable
83−ctrl_meta_chars = map (\(s,EvKey c m) -> ('\ESC':s, EvKey c (MMeta:m))) ctrl_chars
82+ctrlMetaChars :: ClassifyTable
83+ctrlMetaChars = map (\(s,EvKey c m) -> ('\ESC':s, EvKey c (MMeta:m))) ctrlChars
8484
8585-- | esc, meta esc, delete, meta delete, enter, meta enter
86−special_support_keys :: ClassifyTable
87−special_support_keys =
86+specialSupportKeys :: ClassifyTable
87+specialSupportKeys =
8888 [ -- special support for ESC
8989 ("\ESC",EvKey KEsc []), ("\ESC\ESC",EvKey KEsc [MMeta])
9090 -- Special support for backspace
@@ -150,8 +150,8 @@ special_support_keys =
150150-- * kRIT - shift right
151151--
152152-- * kcuu1 - up
153−keys_from_caps_table :: ClassifyTable
154−keys_from_caps_table =
153+keysFromCapsTable :: ClassifyTable
154+keysFromCapsTable =
155155 [ ("ka1", EvKey KUpLeft [])
156156 , ("ka3", EvKey KUpRight [])
157157 , ("kb2", EvKey KCenter [])
@@ -177,8 +177,8 @@ keys_from_caps_table =
177177 , ("kLFT", EvKey KLeft [MShift])
178178 , ("kRIT", EvKey KRight [MShift])
179179 , ("kcuu1", EvKey KUp [])
180− ] ++ function_key_caps_table
180+ ] ++ functionKeyCapsTable
181181
182182-- | cap names for function keys
183−function_key_caps_table :: ClassifyTable
184−function_key_caps_table = flip map [0..63] $ \n -> ("kf" ++ show n, EvKey (KFun n) [])
183+functionKeyCapsTable :: ClassifyTable
184+functionKeyCapsTable = flip map [0..63] $ \n -> ("kf" ++ show n, EvKey (KFun n) [])
src/Graphics/Vty/Input/Terminfo/ANSI.hs+18−18
@@ -8,8 +8,8 @@ supports "ansi" = True
88supports _ = False
99
1010-- | Encoding for navigation keys.
11−nav_keys_0 :: ClassifyTable
12−nav_keys_0 =
11+navKeys0 :: ClassifyTable
12+navKeys0 =
1313 [ k "G" KCenter
1414 , k "P" KPause
1515 , k "A" KUp
@@ -23,8 +23,8 @@ nav_keys_0 =
2323 where k c s = ("\ESC["++c, EvKey s [])
2424
2525-- | VT 100 (?) encoding for shift, meta and ctrl plus arrows/home/end
26−nav_keys_1 :: ClassifyTable
27−nav_keys_1 =
26+navKeys1 :: ClassifyTable
27+navKeys1 =
2828 [("\ESC[" ++ charCnt ++ show mc++c,EvKey s m)
2929 | charCnt <- ["1;", ""], -- we can have a count or not
3030 (m,mc) <- [([MShift],2::Int), ([MCtrl],5), ([MMeta],3),
@@ -34,15 +34,15 @@ nav_keys_1 =
3434 ]
3535
3636-- | VT 100 (?) encoding for ins, del, pageup, pagedown, home, end
37−nav_keys_2 :: ClassifyTable
38−nav_keys_2 =
37+navKeys2 :: ClassifyTable
38+navKeys2 =
3939 let k n s = ("\ESC["++show n++"~",EvKey s [])
4040 in zipWith k [2::Int,3,5,6,1,4]
4141 [KIns,KDel,KPageUp,KPageDown,KHome,KEnd]
4242
4343-- | VT 100 (?) encoding for ctrl + ins, del, pageup, pagedown, home, end
44−nav_keys_3 :: ClassifyTable
45−nav_keys_3 =
44+navKeys3 :: ClassifyTable
45+navKeys3 =
4646 let k n s = ("\ESC["++show n++";5~", EvKey s [MCtrl])
4747 in zipWith k [2::Int,3,5,6,1,4]
4848 [KIns,KDel,KPageUp,KPageDown,KHome,KEnd]
@@ -56,8 +56,8 @@ nav_keys_3 =
5656-- ``meta mode'' on and off, they can be given as smm and rmm."
5757--
5858-- That is more complex than below. I cannot fault the original author for just hard coding a table.
59−function_keys_1 :: ClassifyTable
60−function_keys_1 =
59+functionKeys1 :: ClassifyTable
60+functionKeys1 =
6161 let f ff nrs m = [ ("\ESC["++show n++"~",EvKey (KFun $ n-(nrs!!0)+ff) m) | n <- nrs ] in
6262 concat [f 1 [25,26] [MShift], f 3 [28,29] [MShift], f 5 [31..34] [MShift] ]
6363
@@ -70,19 +70,19 @@ function_keys_1 =
7070-- the same as ESC should examine km and current encoding.
7171-- 3. stopped enumeration at '~' instead of '\DEL'. The latter is mapped to KBS by
7272-- special_support_keys.
73−function_keys_2 :: ClassifyTable
74−function_keys_2 = [ ('\ESC':[x],EvKey (KChar x) [MMeta])
73+functionKeys2 :: ClassifyTable
74+functionKeys2 = [ ('\ESC':[x],EvKey (KChar x) [MMeta])
7575 | x <- '\t':[' ' .. '~']
7676 , x /= '['
7777 ]
7878
7979tables :: [ClassifyTable]
8080tables =
81− [ nav_keys_0
82− , nav_keys_1
83− , nav_keys_2
84− , nav_keys_3
85− , function_keys_1
86− , function_keys_2
81+ [ navKeys0
82+ , navKeys1
83+ , navKeys2
84+ , navKeys3
85+ , functionKeys1
86+ , functionKeys2
8787 ]
8888
src/Graphics/Vty/Input/Terminfo/XTerm7Bit.hs+18−18
@@ -12,8 +12,8 @@ supports term_name = "xterm" `isPrefixOf` term_name && not ("8bit" `isInfixOf` t
1212-- | Encoding for navigation keys.
1313--
1414-- TODO: This is not the same as the input bytes pulled from teh caps table.
15−nav_keys_0 :: ClassifyTable
16−nav_keys_0 =
15+navKeys0 :: ClassifyTable
16+navKeys0 =
1717 [ k "G" KCenter
1818 , k "P" KPause
1919 , k "A" KUp
@@ -27,8 +27,8 @@ nav_keys_0 =
2727 where k c s = ("\ESC["++c,EvKey s [])
2828
2929-- | VT 100 (?) encoding for shift, meta and ctrl plus arrows/home/end
30−nav_keys_1 :: ClassifyTable
31−nav_keys_1 =
30+navKeys1 :: ClassifyTable
31+navKeys1 =
3232 [("\ESC[" ++ charCnt ++ show mc++c,EvKey s m)
3333 | charCnt <- ["1;", ""], -- we can have a count or not
3434 (m,mc) <- [([MShift],2::Int), ([MCtrl],5), ([MMeta],3),
@@ -37,15 +37,15 @@ nav_keys_1 =
3737 ]
3838
3939-- | VT 100 (?) encoding for ins, del, pageup, pagedown, home, end
40−nav_keys_2 :: ClassifyTable
41−nav_keys_2 =
40+navKeys2 :: ClassifyTable
41+navKeys2 =
4242 let k n s = ("\ESC["++show n++"~",EvKey s [])
4343 in zipWith k [2::Int,3,5,6,1,4]
4444 [KIns,KDel,KPageUp,KPageDown,KHome,KEnd]
4545
4646-- | VT 100 (?) encoding for ctrl + ins, del, pageup, pagedown, home, end
47−nav_keys_3 :: ClassifyTable
48−nav_keys_3 =
47+navKeys3 :: ClassifyTable
48+navKeys3 =
4949 let k n s = ("\ESC["++show n++";5~",EvKey s [MCtrl])
5050 in zipWith k [2::Int,3,5,6,1,4]
5151 [KIns,KDel,KPageUp,KPageDown,KHome,KEnd]
@@ -59,8 +59,8 @@ nav_keys_3 =
5959-- ``meta mode'' on and off, they can be given as smm and rmm."
6060--
6161-- That is more complex than below. I cannot fault the original author for just hard coding a table.
62−function_keys_1 :: ClassifyTable
63−function_keys_1 =
62+functionKeys1 :: ClassifyTable
63+functionKeys1 =
6464 let f ff nrs m = [ ("\ESC["++show n++"~",EvKey (KFun $ n-(nrs!!0)+ff) m) | n <- nrs ] in
6565 concat [f 1 [25,26] [MShift], f 3 [28,29] [MShift], f 5 [31..34] [MShift] ]
6666
@@ -73,8 +73,8 @@ function_keys_1 =
7373-- the same as ESC should examine km and current encoding.
7474-- 3. stopped enumeration at '~' instead of '\DEL'. The latter is mapped to KBS by
7575-- special_support_keys.
76−function_keys_2 :: ClassifyTable
77−function_keys_2 = [ ('\ESC':[x],EvKey (KChar x) [MMeta])
76+functionKeys2 :: ClassifyTable
77+functionKeys2 = [ ('\ESC':[x],EvKey (KChar x) [MMeta])
7878 | x <- '\t':[' ' .. '~']
7979 , x /= '['
8080 ]
@@ -82,11 +82,11 @@ function_keys_2 = [ ('\ESC':[x],EvKey (KChar x) [MMeta])
8282-- | classify table for ANSI terminals
8383tables :: [ClassifyTable]
8484tables =
85− [ nav_keys_0
86− , nav_keys_1
87− , nav_keys_2
88− , nav_keys_3
89− , function_keys_1
90− , function_keys_2
85+ [ navKeys0
86+ , navKeys1
87+ , navKeys2
88+ , navKeys3
89+ , functionKeys1
90+ , functionKeys2
9191 ]
9292
src/Graphics/Vty/Output.hs+37−37
@@ -20,8 +20,8 @@ module Graphics.Vty.Output ( module Graphics.Vty.Output
2020 , Output(..) -- \todo hide constructors
2121 , AssumedState(..)
2222 , DisplayContext(..) -- \todo hide constructors
23− , output_picture
24− , display_context
23+ , outputPicture
24+ , displayContext
2525 )
2626 where
2727
@@ -74,35 +74,35 @@ import System.IO
7474--
7575-- \todo add an implementation for windows that does not depend on terminfo. Should be installable
7676-- with only what is provided in the haskell platform. Use ansi-terminal
77−output_for_current_terminal :: ( Applicative m, MonadIO m ) => m Output
78−output_for_current_terminal = do
79− term_type <- liftIO $ getEnv "TERM"
80− out_handle <- liftIO $ hDuplicate stdout
81− output_for_name_and_io term_type out_handle
77+outputForCurrentTerminal :: ( Applicative m, MonadIO m ) => m Output
78+outputForCurrentTerminal = do
79+ termType <- liftIO $ getEnv "TERM"
80+ outHandle <- liftIO $ hDuplicate stdout
81+ outputForNameAndIO termType outHandle
8282
8383-- | gives an output method structure for a terminal with the given name and the given 'Handle'.
84−output_for_name_and_io :: (Applicative m, MonadIO m) => String -> Handle -> m Output
85−output_for_name_and_io term_type out_handle = do
86− t <- if "xterm" `isPrefixOf` term_type
84+outputForNameAndIO :: (Applicative m, MonadIO m) => String -> Handle -> m Output
85+outputForNameAndIO termType outHandle = do
86+ t <- if "xterm" `isPrefixOf` termType
8787 then do
88− maybe_terminal_app <- get_env "TERM_PROGRAM"
89− case maybe_terminal_app of
88+ maybeTerminalApp <- mGetEnv "TERM_PROGRAM"
89+ case maybeTerminalApp of
9090 Nothing
91− -> XTermColor.reserve_terminal term_type out_handle
91+ -> XTermColor.reserveTerminal termType outHandle
9292 Just v | v == "Apple_Terminal" || v == "iTerm.app"
9393 -> do
94− maybe_xterm <- get_env "XTERM_VERSION"
95− case maybe_xterm of
96− Nothing -> MacOSX.reserve_terminal v out_handle
97− Just _ -> XTermColor.reserve_terminal term_type out_handle
94+ maybeXterm <- mGetEnv "XTERM_VERSION"
95+ case maybeXterm of
96+ Nothing -> MacOSX.reserveTerminal v outHandle
97+ Just _ -> XTermColor.reserveTerminal termType outHandle
9898 -- Assume any other terminal that sets TERM_PROGRAM to not be an OS X terminal.app
9999 -- like terminal?
100− _ -> XTermColor.reserve_terminal term_type out_handle
100+ _ -> XTermColor.reserveTerminal termType outHandle
101101 -- Not an xterm-like terminal. try for generic terminfo.
102− else TerminfoBased.reserve_terminal term_type out_handle
102+ else TerminfoBased.reserveTerminal termType outHandle
103103 return t
104104 where
105− get_env var = do
105+ mGetEnv var = do
106106 mv <- liftIO $ try $ getEnv var
107107 case mv of
108108 Left (_e :: SomeException) -> return $ Nothing
@@ -114,25 +114,25 @@ output_for_name_and_io term_type out_handle = do
114114-- Characters can be a variable number of columns in width.
115115--
116116-- Currently, the only way to set the cursor position to a given character coordinate is to specify
117−-- the coordinate in the Picture instance provided to output_picture or refresh.
118−set_cursor_pos :: MonadIO m => Output -> Int -> Int -> m ()
119−set_cursor_pos t x y = do
120− bounds <- display_bounds t
121− when (x >= 0 && x < region_width bounds && y >= 0 && y < region_height bounds) $ do
122− dc <- display_context t bounds
123− liftIO $ output_byte_buffer t $ writeToByteString $ write_move_cursor dc x y
117+-- the coordinate in the Picture instance provided to outputPicture or refresh.
118+setCursorPos :: MonadIO m => Output -> Int -> Int -> m ()
119+setCursorPos t x y = do
120+ bounds <- displayBounds t
121+ when (x >= 0 && x < regionWidth bounds && y >= 0 && y < regionHeight bounds) $ do
122+ dc <- displayContext t bounds
123+ liftIO $ outputByteBuffer t $ writeToByteString $ writeMoveCursor dc x y
124124
125125-- | Hides the cursor
126−hide_cursor :: MonadIO m => Output -> m ()
127−hide_cursor t = do
128− bounds <- display_bounds t
129− dc <- display_context t bounds
130− liftIO $ output_byte_buffer t $ writeToByteString $ write_hide_cursor dc
126+hideCursor :: MonadIO m => Output -> m ()
127+hideCursor t = do
128+ bounds <- displayBounds t
129+ dc <- displayContext t bounds
130+ liftIO $ outputByteBuffer t $ writeToByteString $ writeHideCursor dc
131131
132132-- | Shows the cursor
133−show_cursor :: MonadIO m => Output -> m ()
134−show_cursor t = do
135− bounds <- display_bounds t
136− dc <- display_context t bounds
137− liftIO $ output_byte_buffer t $ writeToByteString $ write_show_cursor dc
133+showCursor :: MonadIO m => Output -> m ()
134+showCursor t = do
135+ bounds <- displayBounds t
136+ dc <- displayContext t bounds
137+ liftIO $ outputByteBuffer t $ writeToByteString $ writeShowCursor dc
138138
src/Graphics/Vty/Output/Interface.hs+112−112
@@ -30,8 +30,8 @@ import qualified Data.Vector as Vector
3030
3131data Output = Output
3232 { -- | Text identifier for the output device. Used for debugging.
33− terminal_ID :: String
34− , release_terminal :: MonadIO m => m ()
33+ terminalID :: String
34+ , releaseTerminal :: MonadIO m => m ()
3535 -- | Clear the display and initialize the terminal to some initial display state.
3636 --
3737 -- The expectation of a program is that the display starts in some initial state.
@@ -46,45 +46,45 @@ data Output = Output
4646 --
4747 -- - The previous state cannot be determined
4848 -- - When exclusive access to a display is released the display returns to the previous state.
49− , reserve_display :: MonadIO m => m ()
50− -- | Return the display to the state before reserve_display
49+ , reserveDisplay :: MonadIO m => m ()
50+ -- | Return the display to the state before `reserveDisplay`
5151 -- If no previous state then set the display state to the initial state.
52− , release_display :: MonadIO m => m ()
52+ , releaseDisplay :: MonadIO m => m ()
5353 -- | Returns the current display bounds.
54− , display_bounds :: MonadIO m => m DisplayRegion
54+ , displayBounds :: MonadIO m => m DisplayRegion
5555 -- | Output the byte string to the terminal device.
56− , output_byte_buffer :: BS.ByteString -> IO ()
56+ , outputByteBuffer :: BS.ByteString -> IO ()
5757 -- | Maximum number of colors supported by the context.
58− , context_color_count :: Int
58+ , contextColorCount :: Int
5959 -- | if the cursor can be shown / hidden
60− , supports_cursor_visibility :: Bool
61− , assumed_state_ref :: IORef AssumedState
60+ , supportsCursorVisibility :: Bool
61+ , assumedStateRef :: IORef AssumedState
6262 -- | Acquire display access to the given region of the display.
6363 -- Currently all regions have the upper left corner of (0,0) and the lower right corner at
6464 -- (max display_width provided_width, max display_height provided_height)
65− , mk_display_context :: MonadIO m => Output -> DisplayRegion -> m DisplayContext
65+ , mkDisplayContext :: MonadIO m => Output -> DisplayRegion -> m DisplayContext
6666 }
6767
68−display_context :: MonadIO m => Output -> DisplayRegion -> m DisplayContext
69−display_context t = liftIO . mk_display_context t t
68+displayContext :: MonadIO m => Output -> DisplayRegion -> m DisplayContext
69+displayContext t = liftIO . mkDisplayContext t t
7070
7171data AssumedState = AssumedState
72− { prev_fattr :: Maybe FixedAttr
73− , prev_output_ops :: Maybe DisplayOps
72+ { prevFattr :: Maybe FixedAttr
73+ , prevOutputOps :: Maybe DisplayOps
7474 }
7575
76−initial_assumed_state :: AssumedState
77−initial_assumed_state = AssumedState Nothing Nothing
76+initialAssumedState :: AssumedState
77+initialAssumedState = AssumedState Nothing Nothing
7878
7979data DisplayContext = DisplayContext
80− { context_device :: Output
80+ { contextDevice :: Output
8181 -- | Provide the bounds of the display context.
82− , context_region :: DisplayRegion
82+ , contextRegion :: DisplayRegion
8383 -- | sets the output position to the specified row and column. Where the number of bytes
8484 -- required for the control codes can be specified seperate from the actual byte sequence.
85− , write_move_cursor :: Int -> Int -> Write
86− , write_show_cursor :: Write
87− , write_hide_cursor :: Write
85+ , writeMoveCursor :: Int -> Int -> Write
86+ , writeShowCursor :: Write
87+ , writeHideCursor :: Write
8888 -- | Assure the specified output attributes will be applied to all the following text until the
8989 -- next output attribute change. Where the number of bytes required for the control codes can
9090 -- be specified seperate from the actual byte sequence. The required number of bytes must be
@@ -96,17 +96,17 @@ data DisplayContext = DisplayContext
9696 -- attributes. In order to support this the currently applied display attributes are required.
9797 -- In addition it may be possible to optimize the state changes based off the currently applied
9898 -- display attributes.
99− , write_set_attr :: FixedAttr -> Attr -> DisplayAttrDiff -> Write
99+ , writeSetAttr :: FixedAttr -> Attr -> DisplayAttrDiff -> Write
100100 -- | Reset the display attributes to the default display attributes
101− , write_default_attr :: Write
102− , write_row_end :: Write
103− -- | See Graphics.Vty.Output.XTermColor.inline_hack
104− , inline_hack :: IO ()
101+ , writeDefaultAttr :: Write
102+ , writeRowEnd :: Write
103+ -- | See `Graphics.Vty.Output.XTermColor.inlineHack`
104+ , inlineHack :: IO ()
105105 }
106106
107107-- | All terminals serialize UTF8 text to the terminal device exactly as serialized in memory.
108−write_utf8_text :: BS.ByteString -> Write
109−write_utf8_text = writeByteString
108+writeUtf8Text :: BS.ByteString -> Write
109+writeUtf8Text = writeByteString
110110
111111-- | Displays the given `Picture`.
112112--
@@ -122,135 +122,135 @@ write_utf8_text = writeByteString
122122--
123123-- todo: specify possible IO exceptions.
124124-- abstract from IO monad to a MonadIO instance.
125−output_picture :: MonadIO m => DisplayContext -> Picture -> m ()
126−output_picture dc pic = liftIO $ do
127− as <- readIORef (assumed_state_ref $ context_device dc)
128− let manip_cursor = supports_cursor_visibility (context_device dc)
129− r = context_region dc
130− ops = display_ops_for_pic pic r
131− initial_attr = FixedAttr default_style_mask Nothing Nothing
125+outputPicture :: MonadIO m => DisplayContext -> Picture -> m ()
126+outputPicture dc pic = liftIO $ do
127+ as <- readIORef (assumedStateRef $ contextDevice dc)
128+ let manipCursor = supportsCursorVisibility (contextDevice dc)
129+ r = contextRegion dc
130+ ops = displayOpsForPic pic r
131+ initialAttr = FixedAttr defaultStyleMask Nothing Nothing
132132 -- Diff the previous output against the requested output. Differences are currently on a per-row
133133 -- basis.
134134 -- \todo handle resizes that crop the dominate directions better.
135− diffs :: [Bool] = case prev_output_ops as of
136− Nothing -> replicate (fromEnum $ region_height $ effected_region ops) True
137− Just previous_ops -> if effected_region previous_ops /= effected_region ops
138− then replicate (display_ops_rows ops) True
139− else zipWith (/=) (Vector.toList previous_ops)
135+ diffs :: [Bool] = case prevOutputOps as of
136+ Nothing -> replicate (fromEnum $ regionHeight $ effectedRegion ops) True
137+ Just previousOps -> if effectedRegion previousOps /= effectedRegion ops
138+ then replicate (displayOpsRows ops) True
139+ else zipWith (/=) (Vector.toList previousOps)
140140 (Vector.toList ops)
141141 -- build the Write corresponding to the output image
142− out = (if manip_cursor then write_hide_cursor dc else mempty)
143− `mappend` write_default_attr dc
144− `mappend` write_output_ops dc initial_attr diffs ops
142+ out = (if manipCursor then writeHideCursor dc else mempty)
143+ `mappend` writeDefaultAttr dc
144+ `mappend` writeOutputOps dc initialAttr diffs ops
145145 `mappend`
146− (case pic_cursor pic of
147− _ | not manip_cursor -> mempty
146+ (case picCursor pic of
147+ _ | not manipCursor -> mempty
148148 NoCursor -> mempty
149149 Cursor x y ->
150− let m = cursor_output_map ops $ pic_cursor pic
151− (ox, oy) = char_to_output_pos m (x,y)
152− in write_show_cursor dc `mappend` write_move_cursor dc ox oy
150+ let m = cursorOutputMap ops $ picCursor pic
151+ (ox, oy) = charToOutputPos m (x,y)
152+ in writeShowCursor dc `mappend` writeMoveCursor dc ox oy
153153 )
154154 -- ... then serialize
155− output_byte_buffer (context_device dc) (writeToByteString out)
155+ outputByteBuffer (contextDevice dc) (writeToByteString out)
156156 -- Cache the output spans.
157− let as' = as { prev_output_ops = Just ops }
158− writeIORef (assumed_state_ref $ context_device dc) as'
157+ let as' = as { prevOutputOps = Just ops }
158+ writeIORef (assumedStateRef $ contextDevice dc) as'
159159
160−write_output_ops :: DisplayContext -> FixedAttr -> [Bool] -> DisplayOps -> Write
161−write_output_ops dc in_fattr diffs ops =
162− let (_, out, _, _) = Vector.foldl' write_output_ops'
163− (0, mempty, in_fattr, diffs)
164− ops
160+writeOutputOps :: DisplayContext -> FixedAttr -> [Bool] -> DisplayOps -> Write
161+writeOutputOps dc inFattr diffs ops =
162+ let (_, out, _, _) = Vector.foldl' writeOutputOps'
163+ (0, mempty, inFattr, diffs)
164+ ops
165165 in out
166166 where
167− write_output_ops' (y, out, fattr, True : diffs') span_ops
168− = let (span_out, fattr') = write_span_ops dc y fattr span_ops
169− in (y+1, out `mappend` span_out, fattr', diffs')
170− write_output_ops' (y, out, fattr, False : diffs') _span_ops
167+ writeOutputOps' (y, out, fattr, True : diffs') spanOps
168+ = let (spanOut, fattr') = writeSpanOps dc y fattr spanOps
169+ in (y+1, out `mappend` spanOut, fattr', diffs')
170+ writeOutputOps' (y, out, fattr, False : diffs') _spanOps
171171 = (y + 1, out, fattr, diffs')
172− write_output_ops' (_y, _out, _fattr, []) _span_ops
172+ writeOutputOps' (_y, _out, _fattr, []) _spanOps
173173 = error "vty - output spans without a corresponding diff."
174174
175−write_span_ops :: DisplayContext -> Int -> FixedAttr -> SpanOps -> (Write, FixedAttr)
176−write_span_ops dc y in_fattr span_ops =
175+writeSpanOps :: DisplayContext -> Int -> FixedAttr -> SpanOps -> (Write, FixedAttr)
176+writeSpanOps dc y inFattr spanOps =
177177 -- The first operation is to set the cursor to the start of the row
178− let start = write_move_cursor dc 0 y
178+ let start = writeMoveCursor dc 0 y
179179 -- then the span ops are serialized in the order specified
180− in Vector.foldl' (\(out, fattr) op -> case write_span_op dc op fattr of
181− (op_out, fattr') -> (out `mappend` op_out, fattr')
180+ in Vector.foldl' (\(out, fattr) op -> case writeSpanOp dc op fattr of
181+ (op_out, fattr') -> (out `mappend` op_out, fattr')
182182 )
183− (start, in_fattr)
184− span_ops
183+ (start, inFattr)
184+ spanOps
185185
186−write_span_op :: DisplayContext -> SpanOp -> FixedAttr -> (Write, FixedAttr)
187−write_span_op dc (TextSpan attr _ _ str) fattr =
188− let attr' = limit_attr_for_display (context_device dc) attr
189− fattr' = fix_display_attr fattr attr'
190− diffs = display_attr_diffs fattr fattr'
191− out = write_set_attr dc fattr attr' diffs
192− `mappend` write_utf8_text (T.encodeUtf8 $ TL.toStrict str)
186+writeSpanOp :: DisplayContext -> SpanOp -> FixedAttr -> (Write, FixedAttr)
187+writeSpanOp dc (TextSpan attr _ _ str) fattr =
188+ let attr' = limitAttrForDisplay (contextDevice dc) attr
189+ fattr' = fixDisplayAttr fattr attr'
190+ diffs = displayAttrDiffs fattr fattr'
191+ out = writeSetAttr dc fattr attr' diffs
192+ `mappend` writeUtf8Text (T.encodeUtf8 $ TL.toStrict str)
193193 in (out, fattr')
194−write_span_op _dc (Skip _) _fattr = error "serialize_span_op for Skip"
195−write_span_op dc (RowEnd _) fattr = (write_row_end dc, fattr)
194+writeSpanOp _dc (Skip _) _fattr = error "serialize_span_op for Skip"
195+writeSpanOp dc (RowEnd _) fattr = (writeRowEnd dc, fattr)
196196
197197-- | The cursor position is given in X,Y character offsets. Due to multi-column characters this
198198-- needs to be translated to column, row positions.
199199data CursorOutputMap = CursorOutputMap
200− { char_to_output_pos :: (Int, Int) -> (Int, Int)
200+ { charToOutputPos :: (Int, Int) -> (Int, Int)
201201 }
202202
203−cursor_output_map :: DisplayOps -> Cursor -> CursorOutputMap
204−cursor_output_map span_ops _cursor = CursorOutputMap
205− { char_to_output_pos = \(cx, cy) -> (cursor_column_offset span_ops cx cy, cy)
203+cursorOutputMap :: DisplayOps -> Cursor -> CursorOutputMap
204+cursorOutputMap spanOps _cursor = CursorOutputMap
205+ { charToOutputPos = \(cx, cy) -> (cursorColumnOffset spanOps cx cy, cy)
206206 }
207207
208−cursor_column_offset :: DisplayOps -> Int -> Int -> Int
209−cursor_column_offset ops cx cy =
210− let cursor_row_ops = Vector.unsafeIndex ops (fromEnum cy)
211− (out_offset, _, _)
212− = Vector.foldl' ( \(d, current_cx, done) op ->
213− if done then (d, current_cx, done) else case span_op_has_width op of
214− Nothing -> (d, current_cx, False)
215− Just (cw, ow) -> case compare cx (current_cx + cw) of
208+cursorColumnOffset :: DisplayOps -> Int -> Int -> Int
209+cursorColumnOffset ops cx cy =
210+ let cursorRowOps = Vector.unsafeIndex ops (fromEnum cy)
211+ (outOffset, _, _)
212+ = Vector.foldl' ( \(d, currentCx, done) op ->
213+ if done then (d, currentCx, done) else case spanOpHasWidth op of
214+ Nothing -> (d, currentCx, False)
215+ Just (cw, ow) -> case compare cx (currentCx + cw) of
216216 GT -> ( d + ow
217− , current_cx + cw
217+ , currentCx + cw
218218 , False
219219 )
220220 EQ -> ( d + ow
221− , current_cx + cw
221+ , currentCx + cw
222222 , True
223223 )
224− LT -> ( d + columns_to_char_offset (cx - current_cx) op
225− , current_cx + cw
224+ LT -> ( d + columnsToCharOffset (cx - currentCx) op
225+ , currentCx + cw
226226 , True
227227 )
228228 )
229229 (0, 0, False)
230− cursor_row_ops
231− in out_offset
230+ cursorRowOps
231+ in outOffset
232232
233233-- | Not all terminals support all display attributes. This filters a display attribute to what the
234234-- given terminal can display.
235−limit_attr_for_display :: Output -> Attr -> Attr
236−limit_attr_for_display t attr
237− = attr { attr_fore_color = clamp_color $ attr_fore_color attr
238− , attr_back_color = clamp_color $ attr_back_color attr
235+limitAttrForDisplay :: Output -> Attr -> Attr
236+limitAttrForDisplay t attr
237+ = attr { attrForeColor = clampColor $ attrForeColor attr
238+ , attrBackColor = clampColor $ attrBackColor attr
239239 }
240240 where
241− clamp_color Default = Default
242− clamp_color KeepCurrent = KeepCurrent
243− clamp_color (SetTo c) = clamp_color' c
244− clamp_color' (ISOColor v)
245− | context_color_count t < 8 = Default
246− | context_color_count t < 16 && v >= 8 = SetTo $ ISOColor (v - 8)
247− | otherwise = SetTo $ ISOColor v
248− clamp_color' (Color240 v)
241+ clampColor Default = Default
242+ clampColor KeepCurrent = KeepCurrent
243+ clampColor (SetTo c) = clampColor' c
244+ clampColor' (ISOColor v)
245+ | contextColorCount t < 8 = Default
246+ | contextColorCount t < 16 && v >= 8 = SetTo $ ISOColor (v - 8)
247+ | otherwise = SetTo $ ISOColor v
248+ clampColor' (Color240 v)
249249 -- TODO: Choose closes ISO color?
250− | context_color_count t < 8 = Default
251− | context_color_count t < 16 = Default
252− | context_color_count t == 240 = SetTo $ Color240 v
250+ | contextColorCount t < 8 = Default
251+ | contextColorCount t < 16 = Default
252+ | contextColorCount t == 240 = SetTo $ Color240 v
253253 | otherwise
254254 = let p :: Double = fromIntegral v / 240.0
255− v' = floor $ p * (fromIntegral $ context_color_count t)
255+ v' = floor $ p * (fromIntegral $ contextColorCount t)
256256 in SetTo $ Color240 v'
src/Graphics/Vty/Output/MacOSX.hs+25−25
@@ -8,7 +8,7 @@
88{-# LANGUAGE MagicHash #-}
99{-# LANGUAGE FlexibleInstances #-}
1010{-# LANGUAGE TypeFamilies #-}
11−module Graphics.Vty.Output.MacOSX ( reserve_terminal )
11+module Graphics.Vty.Output.MacOSX ( reserveTerminal )
1212 where
1313
1414import Graphics.Vty.Output.Interface
@@ -23,41 +23,41 @@ import System.IO
2323-- "xterm-256color" is used.
2424--
2525-- This effects the terminfo lookup.
26−reserve_terminal :: ( Applicative m, MonadIO m ) => String -> Handle -> m Output
27−reserve_terminal v out_handle = do
28− let remap_term "iTerm.app" = "xterm-256color"
29− remap_term _ = "xterm"
30− flushed_put :: String -> IO ()
31− flushed_put str = do
32− hPutStr out_handle str
33− hFlush out_handle
34− t <- TerminfoBased.reserve_terminal (remap_term v) out_handle
35− return $ t { terminal_ID = terminal_ID t ++ " (Mac)"
36− , reserve_display = terminal_app_reserve_display flushed_put
37− , release_display = terminal_app_release_display flushed_put
26+reserveTerminal :: ( Applicative m, MonadIO m ) => String -> Handle -> m Output
27+reserveTerminal v outHandle = do
28+ let remapTerm "iTerm.app" = "xterm-256color"
29+ remapTerm _ = "xterm"
30+ flushedPut :: String -> IO ()
31+ flushedPut str = do
32+ hPutStr outHandle str
33+ hFlush outHandle
34+ t <- TerminfoBased.reserveTerminal (remapTerm v) outHandle
35+ return $ t { terminalID = terminalID t ++ " (Mac)"
36+ , reserveDisplay = terminalAppReserveDisplay flushedPut
37+ , releaseDisplay = terminalAppReleaseDisplay flushedPut
3838 }
3939
4040-- | Terminal.app requires the xterm-color smcup and rmcup caps. Not the generic xterm ones.
4141-- Otherwise, Terminal.app expects the xterm caps.
42−smcup_str, rmcup_str :: String
43−smcup_str = "\ESC7\ESC[?47h"
44−rmcup_str = "\ESC[2J\ESC[?47l\ESC8"
42+smcupStr, rmcupStr :: String
43+smcupStr = "\ESC7\ESC[?47h"
44+rmcupStr = "\ESC[2J\ESC[?47l\ESC8"
4545
4646-- | always smcup then clear the screen on terminal.app
4747--
4848-- \todo really?
49−terminal_app_reserve_display :: MonadIO m => (String -> IO ()) -> m ()
50−terminal_app_reserve_display flushed_put = liftIO $ do
51− flushed_put smcup_str
52− flushed_put clear_screen_str
49+terminalAppReserveDisplay :: MonadIO m => (String -> IO ()) -> m ()
50+terminalAppReserveDisplay flushedPut = liftIO $ do
51+ flushedPut smcupStr
52+ flushedPut clearScreenStr
5353
54−terminal_app_release_display :: MonadIO m => (String -> IO ()) -> m ()
55−terminal_app_release_display flushed_put = liftIO $ do
56− flushed_put rmcup_str
54+terminalAppReleaseDisplay :: MonadIO m => (String -> IO ()) -> m ()
55+terminalAppReleaseDisplay flushedPut = liftIO $ do
56+ flushedPut rmcupStr
5757
5858-- | iTerm needs a clear screen after smcup as well.
5959--
6060-- \todo but we apply to all mac terminals?
61−clear_screen_str :: String
62−clear_screen_str = "\ESC[H\ESC[2J"
61+clearScreenStr :: String
62+clearScreenStr = "\ESC[H\ESC[2J"
6363
src/Graphics/Vty/Output/Mock.hs+27−27
@@ -3,7 +3,7 @@
33{-# LANGUAGE TypeFamilies #-}
44-- | This provides a mock terminal implementation that is nice for testing. This transforms the
55-- output operations to visible characters. Which is nice for some tests.
6−module Graphics.Vty.Output.Mock ( MockData, mock_terminal )
6+module Graphics.Vty.Output.Mock ( MockData, mockTerminal )
77 where
88
99import Graphics.Vty.Prelude
@@ -32,39 +32,39 @@ type MockData = IORef (UTF8.UTF8 BS.ByteString)
3232--
3333-- The string representation is a sequence of identifiers where each identifier is the name of an
3434-- operation in the algebra.
35−mock_terminal :: (Applicative m, MonadIO m) => DisplayRegion -> m (MockData, Output)
36−mock_terminal r = liftIO $ do
37− out_ref <- newIORef undefined
38− new_assumed_state_ref <- newIORef initial_assumed_state
35+mockTerminal :: (Applicative m, MonadIO m) => DisplayRegion -> m (MockData, Output)
36+mockTerminal r = liftIO $ do
37+ outRef <- newIORef undefined
38+ newAssumedStateRef <- newIORef initialAssumedState
3939 let t = Output
40− { terminal_ID = "mock terminal"
41− , release_terminal = return ()
42− , reserve_display = return ()
43− , release_display = return ()
44− , display_bounds = return r
45− , output_byte_buffer = \bytes -> do
46− putStrLn $ "mock output_byte_buffer of " ++ show (BS.length bytes) ++ " bytes"
47− writeIORef out_ref $ UTF8.fromRep bytes
48− , context_color_count = 16
49− , supports_cursor_visibility = True
50− , assumed_state_ref = new_assumed_state_ref
51− , mk_display_context = \t_actual r_actual -> return $ DisplayContext
52− { context_region = r_actual
53− , context_device = t_actual
40+ { terminalID = "mock terminal"
41+ , releaseTerminal = return ()
42+ , reserveDisplay = return ()
43+ , releaseDisplay = return ()
44+ , displayBounds = return r
45+ , outputByteBuffer = \bytes -> do
46+ putStrLn $ "mock outputByteBuffer of " ++ show (BS.length bytes) ++ " bytes"
47+ writeIORef outRef $ UTF8.fromRep bytes
48+ , contextColorCount = 16
49+ , supportsCursorVisibility = True
50+ , assumedStateRef = newAssumedStateRef
51+ , mkDisplayContext = \tActual rActual -> return $ DisplayContext
52+ { contextRegion = rActual
53+ , contextDevice = tActual
5454 -- A cursor move is always visualized as the single character 'M'
55− , write_move_cursor = \_x _y -> writeWord8 $ toEnum $ fromEnum 'M'
55+ , writeMoveCursor = \_x _y -> writeWord8 $ toEnum $ fromEnum 'M'
5656 -- Show cursor is always visualized as the single character 'S'
57− , write_show_cursor = writeWord8 $ toEnum $ fromEnum 'S'
57+ , writeShowCursor = writeWord8 $ toEnum $ fromEnum 'S'
5858 -- Hide cursor is always visualized as the single character 'H'
59− , write_hide_cursor = writeWord8 $ toEnum $ fromEnum 'H'
59+ , writeHideCursor = writeWord8 $ toEnum $ fromEnum 'H'
6060 -- An attr change is always visualized as the single character 'A'
61− , write_set_attr = \_fattr _diffs _attr -> writeWord8 $ toEnum $ fromEnum 'A'
61+ , writeSetAttr = \_fattr _diffs _attr -> writeWord8 $ toEnum $ fromEnum 'A'
6262 -- default attr is always visualized as the single character 'D'
63− , write_default_attr = writeWord8 $ toEnum $ fromEnum 'D'
63+ , writeDefaultAttr = writeWord8 $ toEnum $ fromEnum 'D'
6464 -- row end is always visualized as the single character 'E'
65− , write_row_end = writeWord8 $ toEnum $ fromEnum 'E'
66− , inline_hack = return ()
65+ , writeRowEnd = writeWord8 $ toEnum $ fromEnum 'E'
66+ , inlineHack = return ()
6767 }
6868 }
69− return (out_ref, t)
69+ return (outRef, t)
7070
src/Graphics/Vty/Output/TerminfoBased.hs+229−229
@@ -10,7 +10,7 @@
1010-- assumptions mixed in.
1111--
1212-- Copyright Corey O'Connor (coreyoconnor@gmail.com)
13−module Graphics.Vty.Output.TerminfoBased ( reserve_terminal )
13+module Graphics.Vty.Output.TerminfoBased ( reserveTerminal )
1414 where
1515
1616import Graphics.Vty.Prelude
@@ -65,30 +65,30 @@ data TerminfoCaps = TerminfoCaps
6565 , cup :: CapExpression
6666 , cnorm :: Maybe CapExpression
6767 , civis :: Maybe CapExpression
68− , supports_no_colors :: Bool
69− , use_alt_color_map :: Bool
70− , set_fore_color :: CapExpression
71− , set_back_color :: CapExpression
72− , set_default_attr :: CapExpression
73− , clear_screen :: CapExpression
74− , clear_eol :: CapExpression
75− , display_attr_caps :: DisplayAttrCaps
68+ , supportsNoColors :: Bool
69+ , useAltColorMap :: Bool
70+ , setForeColor :: CapExpression
71+ , setBackColor :: CapExpression
72+ , setDefaultAttr :: CapExpression
73+ , clearScreen :: CapExpression
74+ , clearEol :: CapExpression
75+ , displayAttrCaps :: DisplayAttrCaps
7676 }
7777
7878data DisplayAttrCaps = DisplayAttrCaps
79− { set_attr_states :: Maybe CapExpression
80− , enter_standout :: Maybe CapExpression
81− , exit_standout :: Maybe CapExpression
82− , enter_underline :: Maybe CapExpression
83− , exit_underline :: Maybe CapExpression
84− , enter_reverse_video :: Maybe CapExpression
85− , enter_dim_mode :: Maybe CapExpression
86− , enter_bold_mode :: Maybe CapExpression
79+ { setAttrStates :: Maybe CapExpression
80+ , enterStandout :: Maybe CapExpression
81+ , exitStandout :: Maybe CapExpression
82+ , enterUnderline :: Maybe CapExpression
83+ , exitUnderline :: Maybe CapExpression
84+ , enterReverseVideo :: Maybe CapExpression
85+ , enterDimMode :: Maybe CapExpression
86+ , enterBoldMode :: Maybe CapExpression
8787 }
8888
89−send_cap_to_terminal :: Output -> CapExpression -> [CapParam] -> IO ()
90−send_cap_to_terminal t cap cap_params = do
91− output_byte_buffer t $ writeToByteString $ write_cap_expr cap cap_params
89+sendCapToTerminal :: Output -> CapExpression -> [CapParam] -> IO ()
90+sendCapToTerminal t cap capParams = do
91+ outputByteBuffer t $ writeToByteString $ writeCapExpr cap capParams
9292
9393{- | Uses terminfo for all control codes. While this should provide the most compatible terminal
9494 - terminfo does not support some features that would increase efficiency and improve compatibility:
@@ -100,136 +100,136 @@ send_cap_to_terminal t cap cap_params = do
100100 - todo: Some display attributes like underline and bold have independent string capabilities that
101101 - should be used instead of the generic "sgr" string capability.
102102 -}
103−reserve_terminal :: ( Applicative m, MonadIO m ) => String -> Handle -> m Output
104−reserve_terminal in_ID out_handle = liftIO $ do
105− ti <- Terminfo.setupTerm in_ID
103+reserveTerminal :: ( Applicative m, MonadIO m ) => String -> Handle -> m Output
104+reserveTerminal inID outHandle = liftIO $ do
105+ ti <- Terminfo.setupTerm inID
106106 -- assumes set foreground always implies set background exists.
107107 -- if set foreground is not set then all color changing style attributes are filtered.
108− msetaf <- probe_cap ti "setaf"
109− msetf <- probe_cap ti "setf"
110− let (no_colors, use_alt, set_fore_cap)
108+ msetaf <- probeCap ti "setaf"
109+ msetf <- probeCap ti "setf"
110+ let (noColors, useAlt, setForeCap)
111111 = case msetaf of
112112 Just setaf -> (False, False, setaf)
113113 Nothing -> case msetf of
114114 Just setf -> (False, True, setf)
115− Nothing -> (True, True, error $ "no fore color support for terminal " ++ in_ID)
116− msetab <- probe_cap ti "setab"
117− msetb <- probe_cap ti "setb"
115+ Nothing -> (True, True, error $ "no fore color support for terminal " ++ inID)
116+ msetab <- probeCap ti "setab"
117+ msetb <- probeCap ti "setb"
118118 let set_back_cap
119119 = case msetab of
120120 Nothing -> case msetb of
121121 Just setb -> setb
122− Nothing -> error $ "no back color support for terminal " ++ in_ID
122+ Nothing -> error $ "no back color support for terminal " ++ inID
123123 Just setab -> setab
124− terminfo_caps <- pure TerminfoCaps
125− <*> probe_cap ti "smcup"
126− <*> probe_cap ti "rmcup"
127− <*> require_cap ti "cup"
128− <*> probe_cap ti "cnorm"
129− <*> probe_cap ti "civis"
130− <*> pure no_colors
131− <*> pure use_alt
132− <*> pure set_fore_cap
124+ terminfoCaps <- pure TerminfoCaps
125+ <*> probeCap ti "smcup"
126+ <*> probeCap ti "rmcup"
127+ <*> requireCap ti "cup"
128+ <*> probeCap ti "cnorm"
129+ <*> probeCap ti "civis"
130+ <*> pure noColors
131+ <*> pure useAlt
132+ <*> pure setForeCap
133133 <*> pure set_back_cap
134− <*> require_cap ti "sgr0"
135− <*> require_cap ti "clear"
136− <*> require_cap ti "el"
137− <*> current_display_attr_caps ti
138− new_assumed_state_ref <- newIORef initial_assumed_state
134+ <*> requireCap ti "sgr0"
135+ <*> requireCap ti "clear"
136+ <*> requireCap ti "el"
137+ <*> currentDisplayAttrCaps ti
138+ newAssumedStateRef <- newIORef initialAssumedState
139139 let t = Output
140− { terminal_ID = in_ID
141− , release_terminal = liftIO $ do
142− send_cap set_default_attr []
143− maybe_send_cap cnorm []
144− hClose out_handle
145− , reserve_display = liftIO $ do
140+ { terminalID = inID
141+ , releaseTerminal = liftIO $ do
142+ sendCap setDefaultAttr []
143+ maybeSendCap cnorm []
144+ hClose outHandle
145+ , reserveDisplay = liftIO $ do
146146 -- If there is no support for smcup: Clear the screen and then move the mouse to the
147147 -- home position to approximate the behavior.
148− maybe_send_cap smcup []
149− hFlush out_handle
150− send_cap clear_screen []
151− , release_display = liftIO $ do
152− maybe_send_cap rmcup []
153− maybe_send_cap cnorm []
154− , display_bounds = do
155− raw_size <- liftIO $ withFd out_handle get_window_size
156− case raw_size of
157− (w, h) | w < 0 || h < 0 -> fail $ "getwinsize returned < 0 : " ++ show raw_size
148+ maybeSendCap smcup []
149+ hFlush outHandle
150+ sendCap clearScreen []
151+ , releaseDisplay = liftIO $ do
152+ maybeSendCap rmcup []
153+ maybeSendCap cnorm []
154+ , displayBounds = do
155+ rawSize <- liftIO $ withFd outHandle getWindowSize
156+ case rawSize of
157+ (w, h) | w < 0 || h < 0 -> fail $ "getwinsize returned < 0 : " ++ show rawSize
158158 | otherwise -> return (w,h)
159− , output_byte_buffer = \out_bytes -> do
160− BS.hPut out_handle out_bytes
161− hFlush out_handle
162− , context_color_count
163− = case supports_no_colors terminfo_caps of
159+ , outputByteBuffer = \outBytes -> do
160+ BS.hPut outHandle outBytes
161+ hFlush outHandle
162+ , contextColorCount
163+ = case supportsNoColors terminfoCaps of
164164 False -> case Terminfo.getCapability ti (Terminfo.tiGetNum "colors" ) of
165165 Nothing -> 8
166166 Just v -> toEnum v
167167 True -> 1
168− , supports_cursor_visibility = isJust $ civis terminfo_caps
169− , assumed_state_ref = new_assumed_state_ref
170− -- I think fix would help assure t_actual is the only reference. I was having issues
168+ , supportsCursorVisibility = isJust $ civis terminfoCaps
169+ , assumedStateRef = newAssumedStateRef
170+ -- I think fix would help assure tActual is the only reference. I was having issues
171171 -- tho.
172− , mk_display_context = \t_actual -> liftIO . terminfo_display_context t_actual terminfo_caps
172+ , mkDisplayContext = \tActual -> liftIO . terminfoDisplayContext tActual terminfoCaps
173173 }
174− send_cap s = send_cap_to_terminal t (s terminfo_caps)
175− maybe_send_cap s = when (isJust $ s terminfo_caps) . send_cap (fromJust . s)
174+ sendCap s = sendCapToTerminal t (s terminfoCaps)
175+ maybeSendCap s = when (isJust $ s terminfoCaps) . sendCap (fromJust . s)
176176 return t
177177
178−require_cap :: (Applicative m, MonadIO m) => Terminfo.Terminal -> String -> m CapExpression
179−require_cap ti cap_name
180− = case Terminfo.getCapability ti (Terminfo.tiGetStr cap_name) of
181− Nothing -> fail $ "Terminal does not define required capability \"" ++ cap_name ++ "\""
182− Just cap_str -> parse_cap cap_str
178+requireCap :: (Applicative m, MonadIO m) => Terminfo.Terminal -> String -> m CapExpression
179+requireCap ti capName
180+ = case Terminfo.getCapability ti (Terminfo.tiGetStr capName) of
181+ Nothing -> fail $ "Terminal does not define required capability \"" ++ capName ++ "\""
182+ Just capStr -> parseCap capStr
183183
184−probe_cap :: (Applicative m, MonadIO m) => Terminfo.Terminal -> String -> m (Maybe CapExpression)
185−probe_cap ti cap_name
186− = case Terminfo.getCapability ti (Terminfo.tiGetStr cap_name) of
187− Nothing -> return Nothing
188− Just cap_str -> Just <$> parse_cap cap_str
184+probeCap :: (Applicative m, MonadIO m) => Terminfo.Terminal -> String -> m (Maybe CapExpression)
185+probeCap ti capName
186+ = case Terminfo.getCapability ti (Terminfo.tiGetStr capName) of
187+ Nothing -> return Nothing
188+ Just capStr -> Just <$> parseCap capStr
189189
190−parse_cap :: (Applicative m, MonadIO m) => String -> m CapExpression
191−parse_cap cap_str = do
192− case parse_cap_expression cap_str of
190+parseCap :: (Applicative m, MonadIO m) => String -> m CapExpression
191+parseCap capStr = do
192+ case parseCapExpression capStr of
193193 Left e -> fail $ show e
194194 Right cap -> return cap
195195
196−current_display_attr_caps :: ( Applicative m, MonadIO m )
197− => Terminfo.Terminal
198− -> m DisplayAttrCaps
199−current_display_attr_caps ti
196+currentDisplayAttrCaps :: ( Applicative m, MonadIO m )
197+ => Terminfo.Terminal
198+ -> m DisplayAttrCaps
199+currentDisplayAttrCaps ti
200200 = pure DisplayAttrCaps
201− <*> probe_cap ti "sgr"
202− <*> probe_cap ti "smso"
203− <*> probe_cap ti "rmso"
204− <*> probe_cap ti "smul"
205− <*> probe_cap ti "rmul"
206− <*> probe_cap ti "rev"
207− <*> probe_cap ti "dim"
208− <*> probe_cap ti "bold"
201+ <*> probeCap ti "sgr"
202+ <*> probeCap ti "smso"
203+ <*> probeCap ti "rmso"
204+ <*> probeCap ti "smul"
205+ <*> probeCap ti "rmul"
206+ <*> probeCap ti "rev"
207+ <*> probeCap ti "dim"
208+ <*> probeCap ti "bold"
209209
210−foreign import ccall "gwinsz.h vty_c_get_window_size" c_get_window_size :: Fd -> IO CLong
210+foreign import ccall "gwinsz.h vty_c_get_window_size" c_getWindowSize :: Fd -> IO CLong
211211
212−get_window_size :: Fd -> IO (Int,Int)
213−get_window_size fd = do
214− (a,b) <- (`divMod` 65536) `fmap` c_get_window_size fd
212+getWindowSize :: Fd -> IO (Int,Int)
213+getWindowSize fd = do
214+ (a,b) <- (`divMod` 65536) `fmap` c_getWindowSize fd
215215 return (fromIntegral b, fromIntegral a)
216216
217−terminfo_display_context :: Output -> TerminfoCaps -> DisplayRegion -> IO DisplayContext
218−terminfo_display_context t_actual terminfo_caps r = return dc
217+terminfoDisplayContext :: Output -> TerminfoCaps -> DisplayRegion -> IO DisplayContext
218+terminfoDisplayContext tActual terminfoCaps r = return dc
219219 where dc = DisplayContext
220− { context_device = t_actual
221− , context_region = r
222− , write_move_cursor = \x y -> write_cap_expr (cup terminfo_caps) [toEnum y, toEnum x]
223− , write_show_cursor = case cnorm terminfo_caps of
220+ { contextDevice = tActual
221+ , contextRegion = r
222+ , writeMoveCursor = \x y -> writeCapExpr (cup terminfoCaps) [toEnum y, toEnum x]
223+ , writeShowCursor = case cnorm terminfoCaps of
224224 Nothing -> error "this terminal does not support show cursor"
225− Just c -> write_cap_expr c []
226− , write_hide_cursor = case civis terminfo_caps of
225+ Just c -> writeCapExpr c []
226+ , writeHideCursor = case civis terminfoCaps of
227227 Nothing -> error "this terminal does not support hide cursor"
228− Just c -> write_cap_expr c []
229− , write_set_attr = terminfo_write_set_attr dc terminfo_caps
230− , write_default_attr = write_cap_expr (set_default_attr terminfo_caps) []
231− , write_row_end = write_cap_expr (clear_eol terminfo_caps) []
232− , inline_hack = return ()
228+ Just c -> writeCapExpr c []
229+ , writeSetAttr = terminfoWriteSetAttr dc terminfoCaps
230+ , writeDefaultAttr = writeCapExpr (setDefaultAttr terminfoCaps) []
231+ , writeRowEnd = writeCapExpr (clearEol terminfoCaps) []
232+ , inlineHack = return ()
233233 }
234234
235235-- | Portably setting the display attributes is a giant pain in the ass.
@@ -255,102 +255,102 @@ terminfo_display_context t_actual terminfo_caps r = return dc
255255-- This equation implements the above logic.
256256--
257257-- \todo This assumes the removal of color changes in the display attributes is done as expected
258−-- with no_colors == True. See `limit_attr_for_display`
258+-- with noColors == True. See `limit_attr_for_display`
259259--
260260-- \todo This assumes that fewer state changes, followed by fewer bytes, is what to optimize. I
261261-- haven't measured this or even examined terminal implementations. *shrug*
262−terminfo_write_set_attr :: DisplayContext -> TerminfoCaps -> FixedAttr -> Attr -> DisplayAttrDiff -> Write
263−terminfo_write_set_attr dc terminfo_caps prev_attr req_attr diffs = do
264− case (fore_color_diff diffs == ColorToDefault) || (back_color_diff diffs == ColorToDefault) of
262+terminfoWriteSetAttr :: DisplayContext -> TerminfoCaps -> FixedAttr -> Attr -> DisplayAttrDiff -> Write
263+terminfoWriteSetAttr dc terminfoCaps prevAttr reqAttr diffs = do
264+ case (foreColorDiff diffs == ColorToDefault) || (backColorDiff diffs == ColorToDefault) of
265265 -- The only way to reset either color, portably, to the default is to use either the set
266266 -- state capability or the set default capability.
267267 True -> do
268− case req_display_cap_seq_for (display_attr_caps terminfo_caps)
269− (fixed_style attr )
270− (style_to_apply_seq $ fixed_style attr) of
268+ case reqDisplayCapSeqFor (displayAttrCaps terminfoCaps)
269+ (fixedStyle attr )
270+ (styleToApplySeq $ fixedStyle attr) of
271271 -- only way to reset a color to the defaults
272− EnterExitSeq caps -> write_default_attr dc
272+ EnterExitSeq caps -> writeDefaultAttr dc
273273 `mappend`
274− foldMap (\cap -> write_cap_expr cap []) caps
274+ foldMap (\cap -> writeCapExpr cap []) caps
275275 `mappend`
276− set_colors
276+ setColors
277277 -- implicitly resets the colors to the defaults
278− SetState state -> write_cap_expr (fromJust $ set_attr_states
279− $ display_attr_caps
280− $ terminfo_caps
281− )
282− (sgr_args_for_state state)
278+ SetState state -> writeCapExpr (fromJust $ setAttrStates
279+ $ displayAttrCaps
280+ $ terminfoCaps
281+ )
282+ (sgrArgsForState state)
283283 `mappend`
284− set_colors
284+ setColors
285285 -- Otherwise the display colors are not changing or changing between two non-default
286286 -- points.
287287 False -> do
288288 -- Still, it could be the case that the change in display attributes requires the
289289 -- colors to be reset because the required capability was not available.
290− case req_display_cap_seq_for (display_attr_caps terminfo_caps)
291− (fixed_style attr)
292− (style_diffs diffs) of
290+ case reqDisplayCapSeqFor (displayAttrCaps terminfoCaps)
291+ (fixedStyle attr)
292+ (styleDiffs diffs) of
293293 -- Really, if terminals were re-implemented with modern concepts instead of bowing
294294 -- down to 40 yr old dumb terminal requirements this would be the only case ever
295295 -- reached! Changes the style and color states according to the differences with
296296 -- the currently applied states.
297− EnterExitSeq caps -> foldMap (\cap -> write_cap_expr cap []) caps
297+ EnterExitSeq caps -> foldMap (\cap -> writeCapExpr cap []) caps
298298 `mappend`
299− write_color_diff set_fore_color (fore_color_diff diffs)
299+ writeColorDiff setForeColor (foreColorDiff diffs)
300300 `mappend`
301− write_color_diff set_back_color (back_color_diff diffs)
301+ writeColorDiff setBackColor (backColorDiff diffs)
302302 -- implicitly resets the colors to the defaults
303− SetState state -> write_cap_expr (fromJust $ set_attr_states
304− $ display_attr_caps terminfo_caps
305− )
306− (sgr_args_for_state state)
307− `mappend` set_colors
303+ SetState state -> writeCapExpr (fromJust $ setAttrStates
304+ $ displayAttrCaps terminfoCaps
305+ )
306+ (sgrArgsForState state)
307+ `mappend` setColors
308308 where
309− color_map = case use_alt_color_map terminfo_caps of
310− False -> ansi_color_index
311− True -> alt_color_index
312− attr = fix_display_attr prev_attr req_attr
313− set_colors =
314− (case fixed_fore_color attr of
315− Just c -> write_cap_expr (set_fore_color terminfo_caps)
316− [toEnum $ color_map c]
309+ colorMap = case useAltColorMap terminfoCaps of
310+ False -> ansiColorIndex
311+ True -> altColorIndex
312+ attr = fixDisplayAttr prevAttr reqAttr
313+ setColors =
314+ (case fixedForeColor attr of
315+ Just c -> writeCapExpr (setForeColor terminfoCaps)
316+ [toEnum $ colorMap c]
317317 Nothing -> mempty)
318318 `mappend`
319− (case fixed_back_color attr of
320− Just c -> write_cap_expr (set_back_color terminfo_caps)
321− [toEnum $ color_map c]
319+ (case fixedBackColor attr of
320+ Just c -> writeCapExpr (setBackColor terminfoCaps)
321+ [toEnum $ colorMap c]
322322 Nothing -> mempty)
323− write_color_diff _f NoColorChange
323+ writeColorDiff _f NoColorChange
324324 = mempty
325− write_color_diff _f ColorToDefault
326− = error "ColorToDefault is not a possible case for apply_color_diffs"
327− write_color_diff f (SetColor c)
328− = write_cap_expr (f terminfo_caps) [toEnum $ color_map c]
325+ writeColorDiff _f ColorToDefault
326+ = error "ColorToDefault is not a possible case for applyColorDiffs"
327+ writeColorDiff f (SetColor c)
328+ = writeCapExpr (f terminfoCaps) [toEnum $ colorMap c]
329329
330330-- | The color table used by a terminal is a 16 color set followed by a 240 color set that might not
331331-- be supported by the terminal.
332332--
333333-- This takes a Color which clearly identifies which pallete to use and computes the index
334334-- into the full 256 color pallete.
335−ansi_color_index :: Color -> Int
336−ansi_color_index (ISOColor v) = fromEnum v
337−ansi_color_index (Color240 v) = 16 + fromEnum v
335+ansiColorIndex :: Color -> Int
336+ansiColorIndex (ISOColor v) = fromEnum v
337+ansiColorIndex (Color240 v) = 16 + fromEnum v
338338
339339-- | For terminals without setaf/setab
340340--
341341-- See table in `man terminfo`
342342-- Will error if not in table.
343−alt_color_index :: Color -> Int
344−alt_color_index (ISOColor 0) = 0
345−alt_color_index (ISOColor 1) = 4
346−alt_color_index (ISOColor 2) = 2
347−alt_color_index (ISOColor 3) = 6
348−alt_color_index (ISOColor 4) = 1
349−alt_color_index (ISOColor 5) = 5
350−alt_color_index (ISOColor 6) = 3
351−alt_color_index (ISOColor 7) = 7
352−alt_color_index (ISOColor v) = fromEnum v
353−alt_color_index (Color240 v) = 16 + fromEnum v
343+altColorIndex :: Color -> Int
344+altColorIndex (ISOColor 0) = 0
345+altColorIndex (ISOColor 1) = 4
346+altColorIndex (ISOColor 2) = 2
347+altColorIndex (ISOColor 3) = 6
348+altColorIndex (ISOColor 4) = 1
349+altColorIndex (ISOColor 5) = 5
350+altColorIndex (ISOColor 6) = 3
351+altColorIndex (ISOColor 7) = 7
352+altColorIndex (ISOColor v) = fromEnum v
353+altColorIndex (Color240 v) = 16 + fromEnum v
354354
355355{- | The sequence of terminfo caps to apply a given style are determined according to these rules.
356356 -
@@ -372,85 +372,85 @@ data DisplayAttrSeq
372372 | SetState DisplayAttrState
373373
374374data DisplayAttrState = DisplayAttrState
375− { apply_standout :: Bool
376− , apply_underline :: Bool
377− , apply_reverse_video :: Bool
378− , apply_blink :: Bool
379− , apply_dim :: Bool
380− , apply_bold :: Bool
375+ { applyStandout :: Bool
376+ , applyUnderline :: Bool
377+ , applyReverseVideo :: Bool
378+ , applyBlink :: Bool
379+ , applyDim :: Bool
380+ , applyBold :: Bool
381381 }
382382
383−sgr_args_for_state :: DisplayAttrState -> [CapParam]
384−sgr_args_for_state attr_state = map (\b -> if b then 1 else 0)
385− [ apply_standout attr_state
386− , apply_underline attr_state
387− , apply_reverse_video attr_state
388− , apply_blink attr_state
389− , apply_dim attr_state
390− , apply_bold attr_state
383+sgrArgsForState :: DisplayAttrState -> [CapParam]
384+sgrArgsForState attrState = map (\b -> if b then 1 else 0)
385+ [ applyStandout attrState
386+ , applyUnderline attrState
387+ , applyReverseVideo attrState
388+ , applyBlink attrState
389+ , applyDim attrState
390+ , applyBold attrState
391391 , False -- invis
392392 , False -- protect
393393 , False -- alt char set
394394 ]
395395
396−req_display_cap_seq_for :: DisplayAttrCaps -> Style -> [StyleStateChange] -> DisplayAttrSeq
397−req_display_cap_seq_for caps s diffs
396+reqDisplayCapSeqFor :: DisplayAttrCaps -> Style -> [StyleStateChange] -> DisplayAttrSeq
397+reqDisplayCapSeqFor caps s diffs
398398 -- if the state transition implied by any diff cannot be supported with an enter/exit mode cap
399399 -- then either the state needs to be set or the attribute change ignored.
400− = case (any no_enter_exit_cap diffs, isJust $ set_attr_states caps) of
400+ = case (any noEnterExitCap diffs, isJust $ setAttrStates caps) of
401401 -- If all the diffs have an enter-exit cap then just use those
402− ( False, _ ) -> EnterExitSeq $ map enter_exit_cap diffs
402+ ( False, _ ) -> EnterExitSeq $ map enterExitCap diffs
403403 -- If not all the diffs have an enter-exit cap and there is no set state cap then filter out
404404 -- all unsupported diffs and just apply the rest
405− ( True, False ) -> EnterExitSeq $ map enter_exit_cap
406− $ filter (not . no_enter_exit_cap) diffs
405+ ( True, False ) -> EnterExitSeq $ map enterExitCap
406+ $ filter (not . noEnterExitCap) diffs
407407 -- if not all the diffs have an enter-exit can and there is a set state cap then just use
408408 -- the set state cap.
409− ( True, True ) -> SetState $ state_for_style s
409+ ( True, True ) -> SetState $ stateForStyle s
410410 where
411− no_enter_exit_cap ApplyStandout = isNothing $ enter_standout caps
412− no_enter_exit_cap RemoveStandout = isNothing $ exit_standout caps
413− no_enter_exit_cap ApplyUnderline = isNothing $ enter_underline caps
414− no_enter_exit_cap RemoveUnderline = isNothing $ exit_underline caps
415− no_enter_exit_cap ApplyReverseVideo = isNothing $ enter_reverse_video caps
416− no_enter_exit_cap RemoveReverseVideo = True
417− no_enter_exit_cap ApplyBlink = True
418− no_enter_exit_cap RemoveBlink = True
419− no_enter_exit_cap ApplyDim = isNothing $ enter_dim_mode caps
420− no_enter_exit_cap RemoveDim = True
421− no_enter_exit_cap ApplyBold = isNothing $ enter_bold_mode caps
422− no_enter_exit_cap RemoveBold = True
423− enter_exit_cap ApplyStandout = fromJust $ enter_standout caps
424− enter_exit_cap RemoveStandout = fromJust $ exit_standout caps
425− enter_exit_cap ApplyUnderline = fromJust $ enter_underline caps
426− enter_exit_cap RemoveUnderline = fromJust $ exit_underline caps
427− enter_exit_cap ApplyReverseVideo = fromJust $ enter_reverse_video caps
428− enter_exit_cap ApplyDim = fromJust $ enter_dim_mode caps
429− enter_exit_cap ApplyBold = fromJust $ enter_bold_mode caps
430− enter_exit_cap _ = error "enter_exit_cap applied to diff that was known not to have one."
411+ noEnterExitCap ApplyStandout = isNothing $ enterStandout caps
412+ noEnterExitCap RemoveStandout = isNothing $ exitStandout caps
413+ noEnterExitCap ApplyUnderline = isNothing $ enterUnderline caps
414+ noEnterExitCap RemoveUnderline = isNothing $ exitUnderline caps
415+ noEnterExitCap ApplyReverseVideo = isNothing $ enterReverseVideo caps
416+ noEnterExitCap RemoveReverseVideo = True
417+ noEnterExitCap ApplyBlink = True
418+ noEnterExitCap RemoveBlink = True
419+ noEnterExitCap ApplyDim = isNothing $ enterDimMode caps
420+ noEnterExitCap RemoveDim = True
421+ noEnterExitCap ApplyBold = isNothing $ enterBoldMode caps
422+ noEnterExitCap RemoveBold = True
423+ enterExitCap ApplyStandout = fromJust $ enterStandout caps
424+ enterExitCap RemoveStandout = fromJust $ exitStandout caps
425+ enterExitCap ApplyUnderline = fromJust $ enterUnderline caps
426+ enterExitCap RemoveUnderline = fromJust $ exitUnderline caps
427+ enterExitCap ApplyReverseVideo = fromJust $ enterReverseVideo caps
428+ enterExitCap ApplyDim = fromJust $ enterDimMode caps
429+ enterExitCap ApplyBold = fromJust $ enterBoldMode caps
430+ enterExitCap _ = error "enterExitCap applied to diff that was known not to have one."
431431
432−state_for_style :: Style -> DisplayAttrState
433−state_for_style s = DisplayAttrState
434− { apply_standout = is_style_set standout
435− , apply_underline = is_style_set underline
436− , apply_reverse_video = is_style_set reverse_video
437− , apply_blink = is_style_set blink
438− , apply_dim = is_style_set dim
439− , apply_bold = is_style_set bold
432+stateForStyle :: Style -> DisplayAttrState
433+stateForStyle s = DisplayAttrState
434+ { applyStandout = isStyleSet standout
435+ , applyUnderline = isStyleSet underline
436+ , applyReverseVideo = isStyleSet reverseVideo
437+ , applyBlink = isStyleSet blink
438+ , applyDim = isStyleSet dim
439+ , applyBold = isStyleSet bold
440440 }
441− where is_style_set = has_style s
441+ where isStyleSet = hasStyle s
442442
443−style_to_apply_seq :: Style -> [StyleStateChange]
444−style_to_apply_seq s = concat
445− [ apply_if_required ApplyStandout standout
446− , apply_if_required ApplyUnderline underline
447− , apply_if_required ApplyReverseVideo reverse_video
448− , apply_if_required ApplyBlink blink
449− , apply_if_required ApplyDim dim
450− , apply_if_required ApplyBlink bold
443+styleToApplySeq :: Style -> [StyleStateChange]
444+styleToApplySeq s = concat
445+ [ applyIfRequired ApplyStandout standout
446+ , applyIfRequired ApplyUnderline underline
447+ , applyIfRequired ApplyReverseVideo reverseVideo
448+ , applyIfRequired ApplyBlink blink
449+ , applyIfRequired ApplyDim dim
450+ , applyIfRequired ApplyBlink bold
451451 ]
452452 where
453− apply_if_required op flag
453+ applyIfRequired op flag
454454 = if 0 == (flag .&. s)
455455 then []
456456 else [op]
src/Graphics/Vty/Output/XTermColor.hs+22−22
@@ -1,5 +1,5 @@
11-- Copyright 2009-2010 Corey O'Connor
2−module Graphics.Vty.Output.XTermColor ( reserve_terminal )
2+module Graphics.Vty.Output.XTermColor ( reserveTerminal )
33 where
44
55import Graphics.Vty.Output.Interface
@@ -16,39 +16,39 @@ import Data.Foldable (foldMap)
1616import System.IO
1717
1818-- | Initialize the display to UTF-8.
19−reserve_terminal :: ( Applicative m, MonadIO m ) => String -> Handle -> m Output
20−reserve_terminal variant out_handle = liftIO $ do
21− let flushed_put str = do
22− hPutStr out_handle str
23− hFlush out_handle
19+reserveTerminal :: ( Applicative m, MonadIO m ) => String -> Handle -> m Output
20+reserveTerminal variant outHandle = liftIO $ do
21+ let flushedPut str = do
22+ hPutStr outHandle str
23+ hFlush outHandle
2424 -- If the terminal variant is xterm-color use xterm instead since, more often than not,
2525 -- xterm-color is broken.
2626 let variant' = if variant == "xterm-color" then "xterm" else variant
27− flushed_put set_utf8_char_set
28− t <- TerminfoBased.reserve_terminal variant' out_handle
27+ flushedPut setUtf8CharSet
28+ t <- TerminfoBased.reserveTerminal variant' outHandle
2929 let t' = t
30− { terminal_ID = terminal_ID t ++ " (xterm-color)"
31− , release_terminal = do
32− liftIO $ flushed_put set_default_char_set
33− release_terminal t
34− , mk_display_context = \t_actual r -> do
35− dc <- mk_display_context t t_actual r
36− return $ dc { inline_hack = xterm_inline_hack t' }
30+ { terminalID = terminalID t ++ " (xterm-color)"
31+ , releaseTerminal = do
32+ liftIO $ flushedPut setDefaultCharSet
33+ releaseTerminal t
34+ , mkDisplayContext = \tActual r -> do
35+ dc <- mkDisplayContext t tActual r
36+ return $ dc { inlineHack = xtermInlineHack t' }
3737 }
3838 return t'
3939
4040-- | These sequences set xterm based terminals to UTF-8 output.
4141--
4242-- \todo I don't know of a terminfo cap that is equivalent to this.
43−set_utf8_char_set, set_default_char_set :: String
44−set_utf8_char_set = "\ESC%G"
45−set_default_char_set = "\ESC%@"
43+setUtf8CharSet, setDefaultCharSet :: String
44+setUtf8CharSet = "\ESC%G"
45+setDefaultCharSet = "\ESC%@"
4646
4747-- | I think xterm is broken: Reseting the background color as the first bytes serialized on a
4848-- new line does not effect the background color xterm uses to clear the line. Which is used
4949-- *after* the next newline.
50−xterm_inline_hack :: Output -> IO ()
51−xterm_inline_hack t = do
52− let write_reset = foldMap (writeWord8.toEnum.fromEnum) "\ESC[K"
53− output_byte_buffer t $ writeToByteString write_reset
50+xtermInlineHack :: Output -> IO ()
51+xtermInlineHack t = do
52+ let writeReset = foldMap (writeWord8.toEnum.fromEnum) "\ESC[K"
53+ outputByteBuffer t $ writeToByteString writeReset
5454
src/Graphics/Vty/Picture.hs+25−25
@@ -13,12 +13,12 @@ import Control.DeepSeq
1313
1414-- | The type of images to be displayed using 'update'.
1515--
16−-- Can be constructed directly or using `pic_for_image`. Which provides an initial instance with
17−-- reasonable defaults for pic_cursor and pic_background.
16+-- Can be constructed directly or using `picForImage`. Which provides an initial instance with
17+-- reasonable defaults for picCursor and picBackground.
1818data Picture = Picture
19− { pic_cursor :: Cursor
20− , pic_layers :: [Image]
21− , pic_background :: Background
19+ { picCursor :: Cursor
20+ , picLayers :: [Image]
21+ , picBackground :: Background
2222 }
2323
2424instance Show Picture where
@@ -28,24 +28,24 @@ instance NFData Picture where
2828 rnf (Picture c l b) = c `deepseq` l `deepseq` b `deepseq` ()
2929
3030-- | a picture with no cursor, background or image layers
31−empty_picture :: Picture
32−empty_picture = Picture NoCursor [] ClearBackground
31+emptyPicture :: Picture
32+emptyPicture = Picture NoCursor [] ClearBackground
3333
3434-- | The given 'Image' is added as the top layer of the 'Picture'
35−add_to_top :: Picture -> Image -> Picture
36−add_to_top p i = p {pic_layers = i : pic_layers p}
35+addToTop :: Picture -> Image -> Picture
36+addToTop p i = p {picLayers = i : picLayers p}
3737
3838-- | The given 'Image' is added as the bottom layer of the 'Picture'
39−add_to_bottom :: Picture -> Image -> Picture
40−add_to_bottom p i = p {pic_layers = pic_layers p ++ [i]}
39+addToBottom :: Picture -> Image -> Picture
40+addToBottom p i = p {picLayers = picLayers p ++ [i]}
4141
4242-- | Create a picture for display for the given image. The picture will not have a displayed cursor
4343-- and no background pattern (ClearBackground) will be used.
44−pic_for_image :: Image -> Picture
45−pic_for_image i = Picture
46− { pic_cursor = NoCursor
47− , pic_layers = [i]
48− , pic_background = ClearBackground
44+picForImage :: Image -> Picture
45+picForImage i = Picture
46+ { picCursor = NoCursor
47+ , picLayers = [i]
48+ , picBackground = ClearBackground
4949 }
5050
5151-- | Create a picture for display with the given layers. Ordered top to bottom.
@@ -54,11 +54,11 @@ pic_for_image i = Picture
5454-- used.
5555--
5656-- The first 'Image' is the top layer.
57−pic_for_layers :: [Image] -> Picture
58−pic_for_layers is = Picture
59− { pic_cursor = NoCursor
60− , pic_layers = is
61− , pic_background = ClearBackground
57+picForLayers :: [Image] -> Picture
58+picForLayers is = Picture
59+ { picCursor = NoCursor
60+ , picLayers = is
61+ , picBackground = ClearBackground
6262 }
6363
6464-- | A picture can be configured either to not show the cursor or show the cursor at the specified
@@ -86,8 +86,8 @@ instance NFData Cursor where
8686-- screen to a picture.
8787data Background
8888 = Background
89− { background_char :: Char
90− , background_attr :: Attr
89+ { backgroundChar :: Char
90+ , backgroundAttr :: Attr
9191 }
9292 -- | A ClearBackground is:
9393 --
@@ -101,5 +101,5 @@ instance NFData Background where
101101 rnf ClearBackground = ()
102102
103103-- | Compatibility with applications that do not use more than a single layer.
104−pic_image :: Picture -> Image
105−pic_image = head . pic_layers
104+picImage :: Picture -> Image
105+picImage = head . picLayers
src/Graphics/Vty/PictureToSpans.hs+167−167
@@ -33,29 +33,29 @@ type MSpanOps s = MVector s SpanOp
3333
3434-- transform plus clip. More or less.
3535data BlitState = BlitState
36− -- we always snoc to the operation vectors. Thus the column_offset = length of row at row_offset
37− -- although, one possibility is to merge layers right in snoc_op (naming it something else, of
38− -- course). In which case columnn_offset would be applicable.
36+ -- we always snoc to the operation vectors. Thus the columnOffset = length of row at rowOffset
37+ -- although, one possibility is to merge layers right in snocOp (naming it something else, of
38+ -- course). In which case columnnOffset would be applicable.
3939 -- Right now we need it to exist.
40− { _column_offset :: Int
41− , _row_offset :: Int
42− -- clip coordinate space is in image space. Which means it's >= 0 and < image_width.
43− , _skip_columns :: Int
44− -- >= 0 and < image_height
45− , _skip_rows :: Int
46− -- includes consideration of skip_columns. In display space.
40+ { _columnOffset :: Int
41+ , _rowOffset :: Int
42+ -- clip coordinate space is in image space. Which means it's >= 0 and < imageWidth.
43+ , _skipColumns :: Int
44+ -- >= 0 and < imageHeight
45+ , _skipRows :: Int
46+ -- includes consideration of skipColumns. In display space.
4747 -- The number of columns from the next column to be defined to the end of the display for the
4848 -- row.
49− , _remaining_columns :: Int
50− -- includes consideration of skip_rows. In display space.
51− , _remaining_rows :: Int
49+ , _remainingColumns :: Int
50+ -- includes consideration of skipRows. In display space.
51+ , _remainingRows :: Int
5252 }
5353
5454makeLenses ''BlitState
5555
5656data BlitEnv s = BlitEnv
5757 { _region :: DisplayRegion
58− , _mrow_ops :: MRowOps s
58+ , _mrowOps :: MRowOps s
5959 }
6060
6161makeLenses ''BlitEnv
@@ -64,105 +64,105 @@ type BlitM s a = ReaderT (BlitEnv s) (StateT BlitState (ST s)) a
6464
6565-- | Produces the span ops that will render the given picture, possibly cropped or padded, into the
6666-- specified region.
67−display_ops_for_pic :: Picture -> DisplayRegion -> DisplayOps
68−display_ops_for_pic pic r = Vector.create (combined_ops_for_layers pic r)
67+displayOpsForPic :: Picture -> DisplayRegion -> DisplayOps
68+displayOpsForPic pic r = Vector.create (combinedOpsForLayers pic r)
6969
7070-- | Returns the DisplayOps for an image rendered to a window the size of the image.
7171--
7272-- largerly used only for debugging.
73−display_ops_for_image :: Image -> DisplayOps
74−display_ops_for_image i = display_ops_for_pic (pic_for_image i) (image_width i, image_height i)
73+displayOpsForImage :: Image -> DisplayOps
74+displayOpsForImage i = displayOpsForPic (picForImage i) (imageWidth i, imageHeight i)
7575
7676-- | Produces the span ops for each layer then combines them.
7777--
7878-- TODO: a fold over a builder function. start with span ops that are a bg fill of the entire
7979-- region.
80−combined_ops_for_layers :: Picture -> DisplayRegion -> ST s (MRowOps s)
81−combined_ops_for_layers pic r
82− | region_width r == 0 || region_height r == 0 = MVector.new 0
80+combinedOpsForLayers :: Picture -> DisplayRegion -> ST s (MRowOps s)
81+combinedOpsForLayers pic r
82+ | regionWidth r == 0 || regionHeight r == 0 = MVector.new 0
8383 | otherwise = do
84− layer_ops <- mapM (\layer -> build_spans layer r) (pic_layers pic)
85− case layer_ops of
84+ layerOps <- mapM (\layer -> buildSpans layer r) (picLayers pic)
85+ case layerOps of
8686 [] -> fail "empty picture"
87− [ops] -> substitute_skips (pic_background pic) ops
87+ [ops] -> substituteSkips (picBackground pic) ops
8888 -- instead of merging ops after generation the merging can be performed as part of
89− -- snoc_op.
90− top_ops : lower_ops -> do
91− ops <- foldM merge_under top_ops lower_ops
92− substitute_skips (pic_background pic) ops
89+ -- snocOp.
90+ topOps : lowerOps -> do
91+ ops <- foldM mergeUnder topOps lowerOps
92+ substituteSkips (picBackground pic) ops
9393
94−substitute_skips :: Background -> MRowOps s -> ST s (MRowOps s)
95−substitute_skips ClearBackground ops = do
94+substituteSkips :: Background -> MRowOps s -> ST s (MRowOps s)
95+substituteSkips ClearBackground ops = do
9696 forM_ [0 .. MVector.length ops - 1] $ \row -> do
97− row_ops <- MVector.read ops row
97+ rowOps <- MVector.read ops row
9898 -- the image operations assure that background fills are combined.
9999 -- clipping a background fill does not split the background fill.
100100 -- merging of image layers can split a skip, but only by the insertion of a non skip.
101101 -- all this combines to mean we can check the last operation and remove it if it's a skip
102102 -- todo: or does it?
103− let row_ops' = case Vector.last row_ops of
104− Skip w -> Vector.init row_ops `Vector.snoc` RowEnd w
105− _ -> row_ops
103+ let rowOps' = case Vector.last rowOps of
104+ Skip w -> Vector.init rowOps `Vector.snoc` RowEnd w
105+ _ -> rowOps
106106 -- now all the skips can be replaced by replications of ' ' of the required width.
107− let row_ops'' = swap_skips_for_single_column_char_span ' ' current_attr row_ops'
108− MVector.write ops row row_ops''
107+ let rowOps'' = swapSkipsForSingleColumnCharSpan ' ' currentAttr rowOps'
108+ MVector.write ops row rowOps''
109109 return ops
110−substitute_skips (Background {background_char, background_attr}) ops = do
110+substituteSkips (Background {backgroundChar, backgroundAttr}) ops = do
111111 -- At this point we decide if the background character is single column or not.
112112 -- obviously, single column is easier.
113− case safe_wcwidth background_char of
114− w | w == 0 -> fail $ "invalid background character " ++ show background_char
113+ case safeWcwidth backgroundChar of
114+ w | w == 0 -> fail $ "invalid background character " ++ show backgroundChar
115115 | w == 1 -> do
116116 forM_ [0 .. MVector.length ops - 1] $ \row -> do
117− row_ops <- MVector.read ops row
118− let row_ops' = swap_skips_for_single_column_char_span background_char background_attr row_ops
119− MVector.write ops row row_ops'
117+ rowOps <- MVector.read ops row
118+ let rowOps' = swapSkipsForSingleColumnCharSpan backgroundChar backgroundAttr rowOps
119+ MVector.write ops row rowOps'
120120 | otherwise -> do
121121 forM_ [0 .. MVector.length ops - 1] $ \row -> do
122− row_ops <- MVector.read ops row
123− let row_ops' = swap_skips_for_char_span w background_char background_attr row_ops
124− MVector.write ops row row_ops'
122+ rowOps <- MVector.read ops row
123+ let rowOps' = swapSkipsForCharSpan w backgroundChar backgroundAttr rowOps
124+ MVector.write ops row rowOps'
125125 return ops
126126
127−merge_under :: MRowOps s -> MRowOps s -> ST s (MRowOps s)
128−merge_under upper lower = do
127+mergeUnder :: MRowOps s -> MRowOps s -> ST s (MRowOps s)
128+mergeUnder upper lower = do
129129 forM_ [0 .. MVector.length upper - 1] $ \row -> do
130− upper_row_ops <- MVector.read upper row
131− lower_row_ops <- MVector.read lower row
132− let row_ops = merge_row_under upper_row_ops lower_row_ops
133− MVector.write upper row row_ops
130+ upperRowOps <- MVector.read upper row
131+ lowerRowOps <- MVector.read lower row
132+ let rowOps = mergeRowUnder upperRowOps lowerRowOps
133+ MVector.write upper row rowOps
134134 return upper
135135
136136-- fugly
137−merge_row_under :: SpanOps -> SpanOps -> SpanOps
138−merge_row_under upper_row_ops lower_row_ops =
139− on_upper_op Vector.empty (Vector.head upper_row_ops) (Vector.tail upper_row_ops) lower_row_ops
137+mergeRowUnder :: SpanOps -> SpanOps -> SpanOps
138+mergeRowUnder upperRowOps lowerRowOps =
139+ onUpperOp Vector.empty (Vector.head upperRowOps) (Vector.tail upperRowOps) lowerRowOps
140140 where
141141 -- H: it will never be the case that we are out of upper ops before lower ops.
142− on_upper_op :: SpanOps -> SpanOp -> SpanOps -> SpanOps -> SpanOps
143− on_upper_op out_ops op@(TextSpan _ w _ _) upper_ops lower_ops =
144− let lower_ops' = drop_ops w lower_ops
145− out_ops' = Vector.snoc out_ops op
146− in if Vector.null lower_ops'
147− then out_ops'
148− else on_upper_op out_ops' (Vector.head upper_ops) (Vector.tail upper_ops) lower_ops'
149− on_upper_op out_ops (Skip w) upper_ops lower_ops =
150− let (ops', lower_ops') = split_ops_at w lower_ops
151− out_ops' = out_ops `mappend` ops'
152− in if Vector.null lower_ops'
153− then out_ops'
154− else on_upper_op out_ops' (Vector.head upper_ops) (Vector.tail upper_ops) lower_ops'
155− on_upper_op _ (RowEnd _) _ _ = error "cannot merge rows containing RowEnd ops"
142+ onUpperOp :: SpanOps -> SpanOp -> SpanOps -> SpanOps -> SpanOps
143+ onUpperOp outOps op@(TextSpan _ w _ _) upperOps lowerOps =
144+ let lowerOps' = dropOps w lowerOps
145+ outOps' = Vector.snoc outOps op
146+ in if Vector.null lowerOps'
147+ then outOps'
148+ else onUpperOp outOps' (Vector.head upperOps) (Vector.tail upperOps) lowerOps'
149+ onUpperOp outOps (Skip w) upperOps lowerOps =
150+ let (ops', lowerOps') = splitOpsAt w lowerOps
151+ outOps' = outOps `mappend` ops'
152+ in if Vector.null lowerOps'
153+ then outOps'
154+ else onUpperOp outOps' (Vector.head upperOps) (Vector.tail upperOps) lowerOps'
155+ onUpperOp _ (RowEnd _) _ _ = error "cannot merge rows containing RowEnd ops"
156156
157157
158−swap_skips_for_single_column_char_span :: Char -> Attr -> SpanOps -> SpanOps
159−swap_skips_for_single_column_char_span c a = Vector.map f
158+swapSkipsForSingleColumnCharSpan :: Char -> Attr -> SpanOps -> SpanOps
159+swapSkipsForSingleColumnCharSpan c a = Vector.map f
160160 where f (Skip ow) = let txt = TL.pack $ replicate ow c
161161 in TextSpan a ow ow txt
162162 f v = v
163163
164−swap_skips_for_char_span :: Int -> Char -> Attr -> SpanOps -> SpanOps
165−swap_skips_for_char_span w c a = Vector.map f
164+swapSkipsForCharSpan :: Int -> Char -> Attr -> SpanOps -> SpanOps
165+swapSkipsForCharSpan w c a = Vector.map f
166166 where
167167 f (Skip ow) = let txt_0_cw = ow `div` w
168168 txt_0 = TL.pack $ replicate txt_0_cw c
@@ -178,10 +178,10 @@ swap_skips_for_char_span w c a = Vector.map f
178178-- Crops to the given display region.
179179--
180180-- \todo I'm pretty sure there is an algorithm that does not require a mutable buffer.
181−build_spans :: Image -> DisplayRegion -> ST s (MRowOps s)
182−build_spans image out_region = do
181+buildSpans :: Image -> DisplayRegion -> ST s (MRowOps s)
182+buildSpans image outRegion = do
183183 -- First we create a mutable vector for each rows output operations.
184− out_ops <- MVector.replicate (region_height out_region) Vector.empty
184+ outOps <- MVector.replicate (regionHeight outRegion) Vector.empty
185185 -- \todo I think building the span operations in display order would provide better performance.
186186 -- However, I got stuck trying to implement an algorithm that did this. This will be considered
187187 -- as a possible future optimization.
@@ -193,33 +193,33 @@ build_spans image out_region = do
193193 --
194194 -- The images are made into span operations from left to right. It's possible that this could
195195 -- easily be made to assure top to bottom output as well.
196− when (region_height out_region > 0 && region_width out_region > 0) $ do
196+ when (regionHeight outRegion > 0 && regionWidth outRegion > 0) $ do
197197 -- The ops builder recursively descends the image and outputs span ops that would
198198 -- display that image. The number of columns remaining in this row before exceeding the
199199 -- bounds is also provided. This is used to clip the span ops produced to the display.
200− let full_build = do
201− start_image_build image
200+ let fullBuild = do
201+ startImageBuild image
202202 -- Fill in any unspecified columns with a skip.
203− forM_ [0 .. (region_height out_region - 1)] (add_row_completion out_region)
204− init_env = BlitEnv out_region out_ops
205− init_state = BlitState 0 0 0 0 (region_width out_region) (region_height out_region)
206− _ <- runStateT (runReaderT full_build init_env) init_state
203+ forM_ [0 .. (regionHeight outRegion - 1)] (addRowCompletion outRegion)
204+ initEnv = BlitEnv outRegion outOps
205+ initState = BlitState 0 0 0 0 (regionWidth outRegion) (regionHeight outRegion)
206+ _ <- runStateT (runReaderT fullBuild initEnv) initState
207207 return ()
208− return out_ops
208+ return outOps
209209
210210-- | Add the operations required to build a given image to the current set of row operations
211211-- returns the number of columns and rows contributed to the output.
212−start_image_build :: Image -> BlitM s ()
213−start_image_build image = do
214− out_of_bounds <- is_out_of_bounds image <$> get
215− when (not out_of_bounds) $ add_maybe_clipped image
212+startImageBuild :: Image -> BlitM s ()
213+startImageBuild image = do
214+ outOfBounds <- isOutOfBounds image <$> get
215+ when (not outOfBounds) $ addMaybeClipped image
216216
217−is_out_of_bounds :: Image -> BlitState -> Bool
218−is_out_of_bounds i s
219− | s ^. remaining_columns <= 0 = True
220− | s ^. remaining_rows <= 0 = True
221− | s ^. skip_columns >= image_width i = True
222− | s ^. skip_rows >= image_height i = True
217+isOutOfBounds :: Image -> BlitState -> Bool
218+isOutOfBounds i s
219+ | s ^. remainingColumns <= 0 = True
220+ | s ^. remainingRows <= 0 = True
221+ | s ^. skipColumns >= imageWidth i = True
222+ | s ^. skipRows >= imageHeight i = True
223223 | otherwise = False
224224
225225-- | This adds an image that might be partially clipped to the output ops.
@@ -229,58 +229,58 @@ is_out_of_bounds i s
229229-- this.
230230--
231231-- \todo prove this cannot be called in an out of bounds case.
232−add_maybe_clipped :: forall s . Image -> BlitM s ()
233−add_maybe_clipped EmptyImage = return ()
234−add_maybe_clipped (HorizText a text_str ow _cw) = do
232+addMaybeClipped :: forall s . Image -> BlitM s ()
233+addMaybeClipped EmptyImage = return ()
234+addMaybeClipped (HorizText a textStr ow _cw) = do
235235 -- TODO: assumption that text spans are only 1 row high.
236− s <- use skip_rows
236+ s <- use skipRows
237237 when (s < 1) $ do
238− left_clip <- use skip_columns
239− right_clip <- use remaining_columns
240− let left_clipped = left_clip > 0
241− right_clipped = (ow - left_clip) > right_clip
242− if left_clipped || right_clipped
243− then let text_str' = clip_text text_str left_clip right_clip
244− in add_unclipped_text a text_str'
245− else add_unclipped_text a text_str
246−add_maybe_clipped (VertJoin top_image bottom_image _ow oh) = do
247− add_maybe_clipped_join "vert_join" skip_rows remaining_rows row_offset
248− (image_height top_image)
249− top_image
250− bottom_image
238+ leftClip <- use skipColumns
239+ rightClip <- use remainingColumns
240+ let leftClipped = leftClip > 0
241+ rightClipped = (ow - leftClip) > rightClip
242+ if leftClipped || rightClipped
243+ then let textStr' = clipText textStr leftClip rightClip
244+ in addUnclippedText a textStr'
245+ else addUnclippedText a textStr
246+addMaybeClipped (VertJoin topImage bottomImage _ow oh) = do
247+ addMaybeClippedJoin "vert_join" skipRows remainingRows rowOffset
248+ (imageHeight topImage)
249+ topImage
250+ bottomImage
251251 oh
252−add_maybe_clipped (HorizJoin left_image right_image ow _oh) = do
253− add_maybe_clipped_join "horiz_join" skip_columns remaining_columns column_offset
254− (image_width left_image)
255− left_image
256− right_image
252+addMaybeClipped (HorizJoin leftImage rightImage ow _oh) = do
253+ addMaybeClippedJoin "horiz_join" skipColumns remainingColumns columnOffset
254+ (imageWidth leftImage)
255+ leftImage
256+ rightImage
257257 ow
258−add_maybe_clipped BGFill {output_width, output_height} = do
258+addMaybeClipped BGFill {outputWidth, outputHeight} = do
259259 s <- get
260− let output_width' = min (output_width - s^.skip_columns) (s^.remaining_columns)
261− output_height' = min (output_height - s^.skip_rows ) (s^.remaining_rows)
262− y <- use row_offset
263− forM_ [y..y+output_height'-1] $ snoc_op (Skip output_width')
264−add_maybe_clipped CropRight {cropped_image, output_width} = do
265− s <- use skip_columns
266− r <- use remaining_columns
267− let x = output_width - s
268− when (x < r) $ remaining_columns .= x
269− add_maybe_clipped cropped_image
270−add_maybe_clipped CropLeft {cropped_image, left_skip} = do
271− skip_columns += left_skip
272− add_maybe_clipped cropped_image
273−add_maybe_clipped CropBottom {cropped_image, output_height} = do
274− s <- use skip_rows
275− r <- use remaining_rows
276− let x = output_height - s
277− when (x < r) $ remaining_rows .= x
278− add_maybe_clipped cropped_image
279−add_maybe_clipped CropTop {cropped_image, top_skip} = do
280− skip_rows += top_skip
281− add_maybe_clipped cropped_image
260+ let outputWidth' = min (outputWidth - s^.skipColumns) (s^.remainingColumns)
261+ outputHeight' = min (outputHeight - s^.skipRows ) (s^.remainingRows)
262+ y <- use rowOffset
263+ forM_ [y..y+outputHeight'-1] $ snocOp (Skip outputWidth')
264+addMaybeClipped CropRight {croppedImage, outputWidth} = do
265+ s <- use skipColumns
266+ r <- use remainingColumns
267+ let x = outputWidth - s
268+ when (x < r) $ remainingColumns .= x
269+ addMaybeClipped croppedImage
270+addMaybeClipped CropLeft {croppedImage, leftSkip} = do
271+ skipColumns += leftSkip
272+ addMaybeClipped croppedImage
273+addMaybeClipped CropBottom {croppedImage, outputHeight} = do
274+ s <- use skipRows
275+ r <- use remainingRows
276+ let x = outputHeight - s
277+ when (x < r) $ remainingRows .= x
278+ addMaybeClipped croppedImage
279+addMaybeClipped CropTop {croppedImage, topSkip} = do
280+ skipRows += topSkip
281+ addMaybeClipped croppedImage
282282
283−add_maybe_clipped_join :: forall s . String
283+addMaybeClippedJoin :: forall s . String
284284 -> Lens BlitState BlitState Int Int
285285 -> Lens BlitState BlitState Int Int
286286 -> Lens BlitState BlitState Int Int
@@ -289,7 +289,7 @@ add_maybe_clipped_join :: forall s . String
289289 -> Image
290290 -> Int
291291 -> BlitM s ()
292−add_maybe_clipped_join name skip remaining offset i0_dim i0 i1 size = do
292+addMaybeClippedJoin name skip remaining offset i0_dim i0 i1 size = do
293293 state <- get
294294 when (state^.remaining <= 0) $ fail $ name ++ " with remaining <= 0"
295295 case state^.skip of
@@ -297,48 +297,48 @@ add_maybe_clipped_join name skip remaining offset i0_dim i0 i1 size = do
297297 | s >= size -> fail $ name ++ " on fully clipped"
298298 | s == 0 -> if state^.remaining > i0_dim
299299 then do
300− add_maybe_clipped i0
300+ addMaybeClipped i0
301301 put $ state & offset +~ i0_dim & remaining -~ i0_dim
302− add_maybe_clipped i1
303− else add_maybe_clipped i0
302+ addMaybeClipped i1
303+ else addMaybeClipped i0
304304 | s < i0_dim ->
305305 let i0_dim' = i0_dim - s
306306 in if state^.remaining <= i0_dim'
307− then add_maybe_clipped i0
307+ then addMaybeClipped i0
308308 else do
309− add_maybe_clipped i0
309+ addMaybeClipped i0
310310 put $ state & offset +~ i0_dim' & remaining -~ i0_dim' & skip .~ 0
311− add_maybe_clipped i1
311+ addMaybeClipped i1
312312 | s >= i0_dim -> do
313313 put $ state & skip -~ i0_dim
314− add_maybe_clipped i1
314+ addMaybeClipped i1
315315 _ -> fail $ name ++ " has unhandled skip class"
316316
317−add_unclipped_text :: Attr -> DisplayText -> BlitM s ()
318−add_unclipped_text a txt = do
319− let op = TextSpan a used_display_columns
317+addUnclippedText :: Attr -> DisplayText -> BlitM s ()
318+addUnclippedText a txt = do
319+ let op = TextSpan a usedDisplayColumns
320320 (fromIntegral $ TL.length txt)
321321 txt
322− used_display_columns = wcswidth $ TL.unpack txt
323− use row_offset >>= snoc_op op
322+ usedDisplayColumns = wcswidth $ TL.unpack txt
323+ use rowOffset >>= snocOp op
324324
325−add_row_completion :: DisplayRegion -> Int -> BlitM s ()
326−add_row_completion display_region row = do
327− all_row_ops <- view mrow_ops
328− row_ops <- lift $ lift $ MVector.read all_row_ops row
329− let end_x = span_ops_effected_columns row_ops
330− when (end_x < region_width display_region) $ do
331− let ow = region_width display_region - end_x
332− snoc_op (Skip ow) row
325+addRowCompletion :: DisplayRegion -> Int -> BlitM s ()
326+addRowCompletion displayRegion row = do
327+ allRowOps <- view mrowOps
328+ rowOps <- lift $ lift $ MVector.read allRowOps row
329+ let end_x = spanOpsEffectedColumns rowOps
330+ when (end_x < regionWidth displayRegion) $ do
331+ let ow = regionWidth displayRegion - end_x
332+ snocOp (Skip ow) row
333333
334334-- | snocs the operation to the operations for the given row.
335−snoc_op :: SpanOp -> Int -> BlitM s ()
336−snoc_op !op !row = do
337− the_mrow_ops <- view mrow_ops
338− the_region <- view region
335+snocOp :: SpanOp -> Int -> BlitM s ()
336+snocOp !op !row = do
337+ theMrowOps <- view mrowOps
338+ theRegion <- view region
339339 lift $ lift $ do
340− ops <- MVector.read the_mrow_ops row
340+ ops <- MVector.read theMrowOps row
341341 let ops' = Vector.snoc ops op
342− when (span_ops_effected_columns ops' > region_width the_region)
342+ when (spanOpsEffectedColumns ops' > regionWidth theRegion)
343343 $ fail $ "row " ++ show row ++ " now exceeds region width"
344− MVector.write the_mrow_ops row ops'
344+ MVector.write theMrowOps row ops'
src/Graphics/Vty/Prelude.hs+4−4
@@ -11,8 +11,8 @@ import Control.Monad
1111-- | Named alias for a Int pair
1212type DisplayRegion = (Int,Int)
1313
14−region_width :: DisplayRegion -> Int
15−region_width = fst
14+regionWidth :: DisplayRegion -> Int
15+regionWidth = fst
1616
17−region_height :: DisplayRegion -> Int
18−region_height = snd
17+regionHeight :: DisplayRegion -> Int
18+regionHeight = snd
src/Graphics/Vty/Span.hs+50−50
@@ -8,7 +8,7 @@
88 - nth row (from top to bottom) of the picture to render.
99 -
1010 - A span op sequence will be defined for all rows and columns (and no more) of the region provided
11− - with the picture to spans_for_pic.
11+ - with the picture to `spansForPic`.
1212 -
1313 - todo: Partition attribute changes into multiple categories according to the serialized
1414 - representation of the various attributes.
@@ -19,7 +19,7 @@ module Graphics.Vty.Span
1919import Graphics.Vty.Prelude
2020
2121import Graphics.Vty.Image
22−import Graphics.Vty.Image.Internal ( clip_text )
22+import Graphics.Vty.Image.Internal ( clipText )
2323
2424import qualified Data.Text.Lazy as TL
2525import Data.Vector (Vector)
@@ -32,10 +32,10 @@ data SpanOp =
3232 -- character does not necessarially represent 1 colunm. See Codec.Binary.UTF8.Width
3333 -- TextSpan [Attr] [output width in columns] [number of characters] [data]
3434 TextSpan
35− { text_span_attr :: !Attr
36− , text_span_output_width :: !Int
37− , text_span_char_width :: !Int
38− , text_span_text :: DisplayText
35+ { textSpanAttr :: !Attr
36+ , textSpanOutputWidth :: !Int
37+ , textSpanCharWidth :: !Int
38+ , textSpanText :: DisplayText
3939 }
4040 -- | Skips the given number of columns
4141 -- A skip is transparent.... maybe? I am not sure how attribute changes interact.
@@ -54,39 +54,39 @@ data SpanOp =
5454-- color is changed.
5555type SpanOps = Vector SpanOp
5656
57−drop_ops :: Int -> SpanOps -> SpanOps
58−drop_ops w = snd . split_ops_at w
57+dropOps :: Int -> SpanOps -> SpanOps
58+dropOps w = snd . splitOpsAt w
5959
60−split_ops_at :: Int -> SpanOps -> (SpanOps, SpanOps)
61−split_ops_at in_w in_ops = split_ops_at' in_w in_ops
60+splitOpsAt :: Int -> SpanOps -> (SpanOps, SpanOps)
61+splitOpsAt in_w in_ops = splitOpsAt' in_w in_ops
6262 where
63− split_ops_at' 0 ops = (Vector.empty, ops)
64− split_ops_at' remaining_columns ops = case Vector.head ops of
65− t@(TextSpan {}) -> if remaining_columns >= text_span_output_width t
66− then let (pre,post) = split_ops_at' (remaining_columns - text_span_output_width t)
67− (Vector.tail ops)
63+ splitOpsAt' 0 ops = (Vector.empty, ops)
64+ splitOpsAt' remainingColumns ops = case Vector.head ops of
65+ t@(TextSpan {}) -> if remainingColumns >= textSpanOutputWidth t
66+ then let (pre,post) = splitOpsAt' (remainingColumns - textSpanOutputWidth t)
67+ (Vector.tail ops)
6868 in (Vector.cons t pre, post)
69− else let pre_txt = clip_text (text_span_text t) 0 remaining_columns
70− pre_op = TextSpan { text_span_attr = text_span_attr t
71− , text_span_output_width = remaining_columns
72− , text_span_char_width = fromIntegral $! TL.length pre_txt
73− , text_span_text = pre_txt
69+ else let pre_txt = clipText (textSpanText t) 0 remainingColumns
70+ pre_op = TextSpan { textSpanAttr = textSpanAttr t
71+ , textSpanOutputWidth = remainingColumns
72+ , textSpanCharWidth = fromIntegral $! TL.length pre_txt
73+ , textSpanText = pre_txt
7474 }
75− post_width = text_span_output_width t - remaining_columns
76− post_txt = clip_text (text_span_text t) remaining_columns post_width
77− post_op = TextSpan { text_span_attr = text_span_attr t
78− , text_span_output_width = post_width
79− , text_span_char_width = fromIntegral $! TL.length post_txt
80− , text_span_text = post_txt
75+ post_width = textSpanOutputWidth t - remainingColumns
76+ post_txt = clipText (textSpanText t) remainingColumns post_width
77+ post_op = TextSpan { textSpanAttr = textSpanAttr t
78+ , textSpanOutputWidth = post_width
79+ , textSpanCharWidth = fromIntegral $! TL.length post_txt
80+ , textSpanText = post_txt
8181 }
8282 in ( Vector.singleton pre_op
8383 , Vector.cons post_op (Vector.tail ops)
8484 )
85− Skip w -> if remaining_columns >= w
86− then let (pre,post) = split_ops_at' (remaining_columns - w) (Vector.tail ops)
85+ Skip w -> if remainingColumns >= w
86+ then let (pre,post) = splitOpsAt' (remainingColumns - w) (Vector.tail ops)
8787 in (Vector.cons (Skip w) pre, post)
88− else ( Vector.singleton $ Skip remaining_columns
89− , Vector.cons (Skip (w - remaining_columns)) (Vector.tail ops)
88+ else ( Vector.singleton $ Skip remainingColumns
89+ , Vector.cons (Skip (w - remainingColumns)) (Vector.tail ops)
9090 )
9191 RowEnd _ -> error "cannot split ops containing a row end"
9292
@@ -102,37 +102,37 @@ instance Show SpanOp where
102102-- | Number of columns the DisplayOps are defined for
103103--
104104-- All spans are verified to define same number of columns. See: VerifySpanOps
105−display_ops_columns :: DisplayOps -> Int
106−display_ops_columns ops
105+displayOpsColumns :: DisplayOps -> Int
106+displayOpsColumns ops
107107 | Vector.length ops == 0 = 0
108108 | otherwise = Vector.length $ Vector.head ops
109109
110110-- | Number of rows the DisplayOps are defined for
111−display_ops_rows :: DisplayOps -> Int
112−display_ops_rows ops = Vector.length ops
111+displayOpsRows :: DisplayOps -> Int
112+displayOpsRows ops = Vector.length ops
113113
114−effected_region :: DisplayOps -> DisplayRegion
115−effected_region ops = (display_ops_columns ops, display_ops_rows ops)
114+effectedRegion :: DisplayOps -> DisplayRegion
115+effectedRegion ops = (displayOpsColumns ops, displayOpsRows ops)
116116
117117-- | The number of columns a SpanOps effects.
118−span_ops_effected_columns :: SpanOps -> Int
119−span_ops_effected_columns in_ops = Vector.foldl' span_ops_effected_columns' 0 in_ops
118+spanOpsEffectedColumns :: SpanOps -> Int
119+spanOpsEffectedColumns in_ops = Vector.foldl' spanOpsEffectedColumns' 0 in_ops
120120 where
121− span_ops_effected_columns' t (TextSpan _ w _ _ ) = t + w
122− span_ops_effected_columns' t (Skip w) = t + w
123− span_ops_effected_columns' t (RowEnd w) = t + w
121+ spanOpsEffectedColumns' t (TextSpan _ w _ _ ) = t + w
122+ spanOpsEffectedColumns' t (Skip w) = t + w
123+ spanOpsEffectedColumns' t (RowEnd w) = t + w
124124
125125-- | The width of a single SpanOp in columns
126−span_op_has_width :: SpanOp -> Maybe (Int, Int)
127−span_op_has_width (TextSpan _ ow cw _) = Just (cw, ow)
128−span_op_has_width (Skip ow) = Just (ow,ow)
129−span_op_has_width (RowEnd ow) = Just (ow,ow)
126+spanOpHasWidth :: SpanOp -> Maybe (Int, Int)
127+spanOpHasWidth (TextSpan _ ow cw _) = Just (cw, ow)
128+spanOpHasWidth (Skip ow) = Just (ow,ow)
129+spanOpHasWidth (RowEnd ow) = Just (ow,ow)
130130
131131-- | returns the number of columns to the character at the given position in the span op
132−columns_to_char_offset :: Int -> SpanOp -> Int
133−columns_to_char_offset cx (TextSpan _ _ _ utf8_str) =
134− let str = TL.unpack utf8_str
132+columnsToCharOffset :: Int -> SpanOp -> Int
133+columnsToCharOffset cx (TextSpan _ _ _ utf8Str) =
134+ let str = TL.unpack utf8Str
135135 in wcswidth (take cx str)
136−columns_to_char_offset cx (Skip _) = cx
137−columns_to_char_offset cx (RowEnd _) = cx
136+columnsToCharOffset cx (Skip _) = cx
137+columnsToCharOffset cx (RowEnd _) = cx
138138
test/BenchImageFuzz.hs+6−6
@@ -15,15 +15,15 @@ import System.Random
1515rand :: Arbitrary a => IO a
1616rand = head <$> sample' arbitrary
1717
18−random_image :: IO Image
19−random_image = rand
18+randomImage :: IO Image
19+randomImage = rand
2020
21−random_picture = pic_for_image <$> random_image
21+randomPicture = picForImage <$> randomImage
2222
23−bench_0 = do
23+bench0 = do
2424 vty <- mkVty def
25− (w,h) <- display_bounds $ output_iface vty
26− let pictures = replicateM 3000 random_picture
25+ (w,h) <- displayBounds $ outputIface vty
26+ let pictures = replicateM 3000 randomPicture
2727 bench ps = do
2828 forM ps (update vty)
2929 shutdown vty
test/BenchNoDiffOpt.hs+16−16
@@ -16,24 +16,24 @@ import System.Environment( getArgs )
1616import System.IO
1717import System.Random
1818
19−bench_0 = do
20− let fixed_gen = mkStdGen 0
21− setStdGen fixed_gen
19+bench0 = do
20+ let fixedGen = mkStdGen 0
21+ setStdGen fixedGen
2222 vty <- mkVty def
23− (w,h) <- display_bounds $ output_iface vty
24− let images = return $ (image_0, image_1)
25− image_0 = char_fill def_attr 'X' w h
26− image_1 = char_fill def_attr '0' w h
23+ (w,h) <- displayBounds $ outputIface vty
24+ let images = return $ (image0, image1)
25+ image0 = charFill defAttr 'X' w h
26+ image1 = charFill defAttr '0' w h
2727 bench d = do
28− flip_out vty 300 image_0 image_1
28+ flipOut vty 300 image0 image1
2929 shutdown vty
3030 return $ Bench images bench
3131
32−flip_out vty n image_0 image_1 =
33− let !p_left = pic_for_image image_0
34− !p_right = pic_for_image image_1
35− w_left 0 = return ()
36− w_left n = update vty p_left >> w_right (n-1)
37− w_right 0 = return ()
38− w_right n = update vty p_right >> w_left (n-1)
39− in w_left n
32+flipOut vty n image0 image1 =
33+ let !pLeft = picForImage image0
34+ !pRight = picForImage image1
35+ wLeft 0 = return ()
36+ wLeft n = update vty pLeft >> wRight (n-1)
37+ wRight 0 = return ()
38+ wRight n = update vty pRight >> wLeft (n-1)
39+ in wLeft n
test/BenchRenderChar.hs+19−19
@@ -11,30 +11,30 @@ import Control.Monad ( forM_ )
1111
1212import Data.Default (def)
1313
14−bench_0 = do
14+bench0 = do
1515 vty <- mkVty def
16− (w,h) <- display_bounds $ output_iface vty
17− let test_chars = return $ take 500 $ cycle $ [ c | c <- ['a'..'z']]
16+ (w,h) <- displayBounds $ outputIface vty
17+ let testChars = return $ take 500 $ cycle $ [ c | c <- ['a'..'z']]
1818 bench d = do
19− forM_ d $ \test_char -> do
20− let test_image = test_image_using_char test_char w h
21− out_pic = pic_for_image test_image
22− update vty out_pic
19+ forM_ d $ \testChar -> do
20+ let testImage = testImageUsingChar testChar w h
21+ outPic = picForImage testImage
22+ update vty outPic
2323 shutdown vty
24− return $ Bench test_chars bench
24+ return $ Bench testChars bench
2525
26−test_image_using_char c w h
27− = vert_cat $ replicate (fromIntegral h)
28− $ horiz_cat $ map (char def_attr) (replicate (fromIntegral w) c)
26+testImageUsingChar c w h
27+ = vertCat $ replicate (fromIntegral h)
28+ $ horizCat $ map (char defAttr) (replicate (fromIntegral w) c)
2929
30−bench_1 = do
30+bench1 = do
3131 vty <- mkVty def
32− (w,h) <- display_bounds $ output_iface vty
33− let test_chars = return $ take 500 $ cycle $ [ c | c <- ['a'..'z']]
32+ (w,h) <- displayBounds $ outputIface vty
33+ let testChars = return $ take 500 $ cycle $ [ c | c <- ['a'..'z']]
3434 bench d = do
35− forM_ d $ \test_char -> do
36− let test_image = char_fill def_attr test_char w h
37− out_pic = pic_for_image test_image
38− update vty out_pic
35+ forM_ d $ \testChar -> do
36+ let testImage = charFill defAttr testChar w h
37+ outPic = picForImage testImage
38+ update vty outPic
3939 shutdown vty
40− return $ Bench test_chars bench
40+ return $ Bench testChars bench
test/BenchVerticalScroll.hs+8−8
@@ -14,12 +14,12 @@ import System.Environment( getArgs )
1414import System.IO
1515import System.Random
1616
17−bench_0 = do
18− let fixed_gen = mkStdGen 0
19− setStdGen fixed_gen
17+bench0 = do
18+ let fixedGen = mkStdGen 0
19+ setStdGen fixedGen
2020 return $ Bench (return ()) (\() -> mkVty def >>= liftM2 (>>) run shutdown)
2121
22−run vt = mapM_ (\p -> update vt p) . benchgen =<< display_bounds (output_iface vt)
22+run vt = mapM_ (\p -> update vt p) . benchgen =<< displayBounds (outputIface vt)
2323
2424-- Currently, we just do scrolling.
2525takem :: (a -> Int) -> Int -> [a] -> ([a],[a])
@@ -41,21 +41,21 @@ lengths ml g =
4141nums :: StdGen -> [(Attr, String)]
4242nums g = let (x,g2) = (random g :: (Int, StdGen))
4343 (c,g3) = random g2
44− in ( if c then def_attr `with_fore_color` red else def_attr
44+ in ( if c then defAttr `withForeColor` red else defAttr
4545 , shows x " "
4646 ) : nums g3
4747
4848pad :: Int -> Image -> Image
49−pad ml img = img <|> char_fill def_attr ' ' (ml - image_width img) 1
49+pad ml img = img <|> charFill defAttr ' ' (ml - imageWidth img) 1
5050
5151clines :: StdGen -> Int -> [Image]
52−clines g maxll = map (pad maxll . horiz_cat . map (uncurry string))
52+clines g maxll = map (pad maxll . horizCat . map (uncurry string))
5353 $ fold (length . snd) (lengths maxll g1) (nums g2)
5454 where (g1,g2) = split g
5555
5656benchgen :: DisplayRegion -> [Picture]
5757benchgen (w,h)
58− = take 2000 $ map ((\i -> pic_for_image i) . vert_cat . take (fromEnum h))
58+ = take 2000 $ map ((\i -> picForImage i) . vertCat . take (fromEnum h))
5959 $ tails
6060 $ clines (mkStdGen 80) w
6161
test/ControlTable.hs+3−3
@@ -6,9 +6,9 @@ import System.Console.Terminfo
66
77main = do
88 terminal <- setupTermFromEnv
9− control_table <- init_control_table terminal
9+ controlTable <- init_controlTable terminal
1010 putStrLn $ "ANSI terminal show cursor string: " ++ show cvis
11− putStrLn $ "Current terminal show cursor string: " ++ show (show_cursor_str control_table)
11+ putStrLn $ "Current terminal show cursor string: " ++ show (showCursorStr controlTable)
1212 putStrLn $ "ANSI terminal hide cursor string: " ++ show civis
13− putStrLn $ "Current terminal hide cursor string: " ++ show (hide_cursor_str control_table)
13+ putStrLn $ "Current terminal hide cursor string: " ++ show (hideCursorStr controlTable)
1414
test/EventEcho.hs+14−14
@@ -11,31 +11,31 @@ import Data.Sequence (Seq, (<|) )
1111import qualified Data.Sequence as Seq
1212import Data.Foldable
1313
14−event_buffer_size = 1000
14+eventBufferSize = 1000
1515
1616type App = RWST Vty () (Seq String) IO
1717
1818main = do
1919 vty <- mkVty def
20− _ <- execRWST (vty_interact False) vty Seq.empty
20+ _ <- execRWST (vtyInteract False) vty Seq.empty
2121 shutdown vty
2222
23−vty_interact :: Bool -> App ()
24−vty_interact should_exit = do
25− update_display
26− unless should_exit $ handle_next_event >>= vty_interact
23+vtyInteract :: Bool -> App ()
24+vtyInteract shouldExit = do
25+ updateDisplay
26+ unless shouldExit $ handleNextEvent >>= vtyInteract
2727
28−update_display :: App ()
29−update_display = do
30− let info = string def_attr "Press ESC to exit."
31− event_log <- foldMap (string def_attr) <$> get
32− let pic = pic_for_image $ info <-> event_log
28+updateDisplay :: App ()
29+updateDisplay = do
30+ let info = string defAttr "Press ESC to exit."
31+ eventLog <- foldMap (string defAttr) <$> get
32+ let pic = picForImage $ info <-> eventLog
3333 vty <- ask
3434 liftIO $ update vty pic
3535
36−handle_next_event = ask >>= liftIO . next_event >>= handle_event
36+handleNextEvent = ask >>= liftIO . nextEvent >>= handleEvent
3737 where
38− handle_event e = do
39− modify $ (<|) (show e) >>> Seq.take event_buffer_size
38+ handleEvent e = do
39+ modify $ (<|) (show e) >>> Seq.take eventBufferSize
4040 return $ e == EvKey KEsc []
4141
test/Rouge.hs+52−52
@@ -18,8 +18,8 @@ import System.IO
1818import System.Random
1919
2020data Dude = Dude
21− { dude_x :: Int
22− , dude_y :: Int
21+ { dudeX :: Int
22+ , dudeY :: Int
2323 } deriving (Show,Eq)
2424
2525data World = World
@@ -34,7 +34,7 @@ data Level = Level
3434 , geo :: Array (Int, Int) LevelPiece
3535 -- building the geo image is expensive. Cache it. Though VTY should go through greater lengths
3636 -- to avoid the need to cache images.
37− , geo_image :: Image
37+ , geoImage :: Image
3838 }
3939 deriving (Show,Eq)
4040
@@ -47,62 +47,62 @@ type Game = RWST Vty () World IO
4747
4848main = do
4949 vty <- mkVty def
50− level_0 <- mkLevel 1
51− let world_0 = World (Dude (fst $ start level_0) (snd $ start level_0)) level_0
52− (_final_world, ()) <- execRWST (play >> update_display) vty world_0
50+ level0 <- mkLevel 1
51+ let world0 = World (Dude (fst $ start level0) (snd $ start level0)) level0
52+ (_finalWorld, ()) <- execRWST (play >> updateDisplay) vty world0
5353 shutdown vty
5454
5555mkLevel difficulty = do
5656 let size = 80 * difficulty
57− [level_width, level_height] <- replicateM 2 $ randomRIO (size,size)
58− let randomP = (,) <$> randomRIO (2, level_width-3) <*> randomRIO (2, level_height-3)
57+ [levelWidth, levelHeight] <- replicateM 2 $ randomRIO (size,size)
58+ let randomP = (,) <$> randomRIO (2, levelWidth-3) <*> randomRIO (2, levelHeight-3)
5959 start <- randomP
6060 end <- randomP
6161 -- first the base geography: all rocks
62− let base_geo = array ((0,0), (level_width, level_height))
63− [((x,y),Rock) | x <- [0..level_width-1], y <- [0..level_height-1]]
62+ let baseGeo = array ((0,0), (levelWidth, levelHeight))
63+ [((x,y),Rock) | x <- [0..levelWidth-1], y <- [0..levelHeight-1]]
6464 -- next the empty spaces that make the rooms
6565 -- for this we generate a number of center points
6666 centers <- replicateM (2 ^ difficulty + difficulty) randomP
6767 -- generate rooms for all those points, plus the start and end
68− geo <- foldM (add_room level_width level_height) base_geo (start : end : centers)
69− return $ Level start end geo (build_geo_image geo)
68+ geo <- foldM (addRoom levelWidth levelHeight) baseGeo (start : end : centers)
69+ return $ Level start end geo (buildGeoImage geo)
7070
71−add_room level_width level_height geo (center_x, center_y) = do
71+addRoom levelWidth levelHeight geo (centerX, centerY) = do
7272 size <- randomRIO (5,15)
73− let x_min = max 1 (center_x - size)
74− x_max = min (level_width - 1) (center_x + size)
75− y_min = max 1 (center_y - size)
76− y_max = min (level_height - 1) (center_y + size)
77− let room = [((x,y), EmptySpace) | x <- [x_min..x_max - 1], y <- [y_min..y_max - 1]]
73+ let xMin = max 1 (centerX - size)
74+ xMax = min (levelWidth - 1) (centerX + size)
75+ yMin = max 1 (centerY - size)
76+ yMax = min (levelHeight - 1) (centerY + size)
77+ let room = [((x,y), EmptySpace) | x <- [xMin..xMax - 1], y <- [yMin..yMax - 1]]
7878 return (geo // room)
7979
80−image_for_geo EmptySpace = char (def_attr `with_back_color` green) ' '
81−image_for_geo Rock = char def_attr 'X'
80+imageForGeo EmptySpace = char (defAttr `withBackColor` green) ' '
81+imageForGeo Rock = char defAttr 'X'
8282
83−pieceA = def_attr `with_fore_color` blue `with_back_color` green
84−dumpA = def_attr `with_style` reverse_video
83+pieceA = defAttr `withForeColor` blue `withBackColor` green
84+dumpA = defAttr `withStyle` reverseVideo
8585
8686play = do
87− update_display
88− done <- process_event
87+ updateDisplay
88+ done <- processEvent
8989 unless done play
9090
91−process_event = do
92− k <- ask >>= liftIO . next_event
91+processEvent = do
92+ k <- ask >>= liftIO . nextEvent
9393 if k == EvKey KEsc []
9494 then return True
9595 else do
9696 case k of
9797 EvKey (KChar 'r') [MCtrl] -> ask >>= liftIO . refresh
98− EvKey KLeft [] -> move_dude (-1) 0
99− EvKey KRight [] -> move_dude 1 0
100− EvKey KUp [] -> move_dude 0 (-1)
101− EvKey KDown [] -> move_dude 0 1
98+ EvKey KLeft [] -> moveDude (-1) 0
99+ EvKey KRight [] -> moveDude 1 0
100+ EvKey KUp [] -> moveDude 0 (-1)
101+ EvKey KDown [] -> moveDude 0 1
102102 _ -> return ()
103103 return False
104104
105−move_dude dx dy = do
105+moveDude dx dy = do
106106 vty <- ask
107107 world <- get
108108 let Dude x y = dude world
@@ -113,35 +113,35 @@ move_dude dx dy = do
113113 EmptySpace -> put $ world { dude = Dude x' y' }
114114 _ -> return ()
115115
116−update_display :: Game ()
117−update_display = do
118− let info = string def_attr "Move with the arrows keys. Press ESC to exit."
116+updateDisplay :: Game ()
117+updateDisplay = do
118+ let info = string defAttr "Move with the arrows keys. Press ESC to exit."
119119 -- determine offsets to place the dude in the center of the level.
120− (w,h) <- asks output_iface >>= liftIO . display_bounds
121− the_dude <- gets dude
122− let ox = (w `div` 2) - dude_x the_dude
123− oy = (h `div` 2) - dude_y the_dude
120+ (w,h) <- asks outputIface >>= liftIO . displayBounds
121+ theDude <- gets dude
122+ let ox = (w `div` 2) - dudeX theDude
123+ oy = (h `div` 2) - dudeY theDude
124124 -- translate the world images to place the dude in the center of the level.
125125 world' <- map (translate ox oy) <$> world
126− let pic = pic_for_layers $ info : world'
126+ let pic = picForLayers $ info : world'
127127 vty <- ask
128128 liftIO $ update vty pic
129129
130130world :: Game [Image]
131131world = do
132− the_dude <- gets dude
133− the_level <- gets level
134− let dude_image = translate (dude_x the_dude) (dude_y the_dude) (char pieceA '@')
135− return [dude_image, geo_image the_level]
132+ theDude <- gets dude
133+ theLevel <- gets level
134+ let dudeImage = translate (dudeX theDude) (dudeY theDude) (char pieceA '@')
135+ return [dudeImage, geoImage theLevel]
136136
137−build_geo_image geo =
138− let (geo_width, geo_height) = snd $ bounds geo
137+buildGeoImage geo =
138+ let (geoWidth, geoHeight) = snd $ bounds geo
139139 -- seems like a the repeated index operation should be removable. This is not performing random
140140 -- access but (presumably) access in order of index.
141− in vert_cat [ geo_row
142− | y <- [0..geo_height-1]
143− , let geo_row = horiz_cat [ i
144− | x <- [0..geo_width-1]
145− , let i = image_for_geo (geo ! (x,y))
146− ]
147− ]
141+ in vertCat [ geoRow
142+ | y <- [0..geoHeight-1]
143+ , let geoRow = horizCat [ i
144+ | x <- [0..geoWidth-1]
145+ , let i = imageForGeo (geo ! (x,y))
146+ ]
147+ ]
test/RougeStory.hs+73−73
@@ -33,20 +33,20 @@ class Story repr where
3333
3434 -- A quest is for a goal where some aspects are known and others unknown.
3535 -- TODO: abstract to any Foldable?
36− empty_aspects :: repr Aspects
37− add_known_history :: repr History -> repr Aspects -> repr Aspects
38− add_known_obj :: repr Object -> repr Aspects -> repr Aspects
39− add_unknown_history :: repr History -> repr Aspects -> repr Aspects
40− add_unknown_obj :: repr Object -> repr Aspects -> repr Aspects
36+ emptyAspects :: repr Aspects
37+ addKnownHistory :: repr History -> repr Aspects -> repr Aspects
38+ addKnownObj :: repr Object -> repr Aspects -> repr Aspects
39+ addUnknownHistory :: repr History -> repr Aspects -> repr Aspects
40+ addUnknownObj :: repr Object -> repr Aspects -> repr Aspects
4141
4242 -- Aspects are animate objects, inanimate objects or histories.
43− animate_obj :: Type -> repr Object
44− inanimate_obj :: Type -> repr Object
43+ animateObj :: Type -> repr Object
44+ inanimateObj :: Type -> repr Object
4545 history :: repr History
4646
4747 -- The goal is to acquire, or dispose of an object.
48− dispose_obj :: repr Object -> repr Goal
49− acquire_obj :: repr Object -> repr Goal
48+ disposeObj :: repr Object -> repr Goal
49+ acquireObj :: repr Object -> repr Goal
5050
5151 -- What is an object? Well, that's anything that fits in the story language.
5252 -- Which at least means it's something that can be named
@@ -58,26 +58,26 @@ data Goal
5858data Aspects
5959data Object
6060
61−story_0 =
62− let bob = animate_obj "Human" `named` "Bob"
63− the_quest = quest (dispose_obj (inanimate_obj "YoYo" `named` "The Kitten Slayer"))
64− (add_known_obj bob empty_aspects)
65− in story "Bob" the_quest
61+story0 =
62+ let bob = animateObj "Human" `named` "Bob"
63+ theQuest = quest (disposeObj (inanimateObj "YoYo" `named` "The Kitten Slayer"))
64+ (addKnownObj bob emptyAspects)
65+ in story "Bob" theQuest
6666
6767{- TEMPLATE
6868instance Story X where
6969 story c q =
7070 quest g as =
71− empty_aspects =
72− add_known_history h as =
73− add_known_obj obj as =
74− add_unknown_history h as =
75− add_unknown_obj obj as =
76− animate_obj t =
77− inanimate_obj t =
71+ emptyAspects =
72+ addKnownHistory h as =
73+ addKnownObj obj as =
74+ addUnknownHistory h as =
75+ addUnknownObj obj as =
76+ animateObj t =
77+ inanimateObj t =
7878 history =
79− dispose_obj obj =
80− acquire_obj obj =
79+ disposeObj obj =
80+ acquireObj obj =
8181 named obj n =
8282-}
8383
@@ -85,16 +85,16 @@ newtype ShowStory t = ShowStory { unShowStory :: String }
8585instance Story ShowStory where
8686 story c q = ShowStory $ printf "History(%s,%s)" c (unShowStory q)
8787 quest g as = ShowStory $ printf "Quest(%s,%s)" (unShowStory g) (unShowStory as)
88− empty_aspects = ShowStory $ printf "EmptyAspects"
89− add_known_history h as = ShowStory $ printf "Known(%s):%s" (unShowStory h) (unShowStory as)
90− add_known_obj obj as = ShowStory $ printf "Known(%s):%s" (unShowStory obj) (unShowStory as)
91− add_unknown_history h as = ShowStory $ printf "Unknown(%s):%s" (unShowStory h) (unShowStory as)
92− add_unknown_obj obj as = ShowStory $ printf "Unknown(%s):%s" (unShowStory obj) (unShowStory as)
93− animate_obj t = ShowStory $ printf "%s :: AnimateObj" t
94− inanimate_obj t = ShowStory $ printf "%s :: InanimateObj" t
88+ emptyAspects = ShowStory $ printf "EmptyAspects"
89+ addKnownHistory h as = ShowStory $ printf "Known(%s):%s" (unShowStory h) (unShowStory as)
90+ addKnownObj obj as = ShowStory $ printf "Known(%s):%s" (unShowStory obj) (unShowStory as)
91+ addUnknownHistory h as = ShowStory $ printf "Unknown(%s):%s" (unShowStory h) (unShowStory as)
92+ addUnknownObj obj as = ShowStory $ printf "Unknown(%s):%s" (unShowStory obj) (unShowStory as)
93+ animateObj t = ShowStory $ printf "%s :: AnimateObj" t
94+ inanimateObj t = ShowStory $ printf "%s :: InanimateObj" t
9595 history = ShowStory $ printf "History"
96− dispose_obj obj = ShowStory $ printf "Goal(%s)" (unShowStory obj)
97− acquire_obj obj = ShowStory $ printf "Acquire(%s)" (unShowStory obj)
96+ disposeObj obj = ShowStory $ printf "Goal(%s)" (unShowStory obj)
97+ acquireObj obj = ShowStory $ printf "Acquire(%s)" (unShowStory obj)
9898 named obj n = ShowStory $ printf "%s+Name(%s)" (unShowStory obj) (show n)
9999
100100newtype TellStory t = TellStory { unTellStory :: String }
@@ -104,80 +104,80 @@ instance Story TellStory where
104104 quest (TellStory g) (TellStory as)
105105 | as == "" = TellStory $ g ++ "."
106106 | otherwise = TellStory $ g ++ ". In a world where... " ++ as
107− empty_aspects = TellStory ""
108− add_known_history (TellStory h) (TellStory as)
107+ emptyAspects = TellStory ""
108+ addKnownHistory (TellStory h) (TellStory as)
109109 = TellStory $ "Our hero knows the tale of\n\t" ++ h ++ ".\n" ++ as
110− add_known_obj (TellStory obj) (TellStory as)
110+ addKnownObj (TellStory obj) (TellStory as)
111111 = TellStory $ "Our hero knows of " ++ obj ++ ". " ++ as
112− add_unknown_history _ as = as
113− add_unknown_obj _ as = as
114− animate_obj t = TellStory t
115− inanimate_obj t = TellStory t
112+ addUnknownHistory _ as = as
113+ addUnknownObj _ as = as
114+ animateObj t = TellStory t
115+ inanimateObj t = TellStory t
116116 history = TellStory "History"
117− dispose_obj (TellStory obj)
117+ disposeObj (TellStory obj)
118118 = TellStory $ "to dispose of the accursed " ++ obj
119− acquire_obj (TellStory obj)
119+ acquireObj (TellStory obj)
120120 = TellStory $ "to acquire the great " ++ obj
121121 named (TellStory obj) name
122122 = TellStory $ obj ++ " with the name " ++ name
123123
124−newtype BuildSprites m t = BuildSprites {build_sprites :: StateT SpriteDB m ()}
124+newtype BuildSprites m t = BuildSprites {buildSprites :: StateT SpriteDB m ()}
125125
126126type Sprite = (Int, Int, Image)
127127type Collider = (Int,Int,Int,Int)
128128data SpriteDB = SpriteDB
129− { next_sprite_ID :: Int -- globally monotonic. H: Can fst . findMax + 1 be used?
130− , this_sprite_ID :: Int
131− , sprites :: Map Int Sprite
129+ { nextSpriteID :: Int -- globally monotonic. H: Can fst . findMax + 1 be used?
130+ , thisSpriteID :: Int
131+ , sprites :: Map Int Sprite
132132 }
133133 deriving (Show)
134134
135−get_sprite_ID :: MonadIO m => StateT SpriteDB m Int
136−get_sprite_ID = gets this_sprite_ID
135+getSpriteID :: MonadIO m => StateT SpriteDB m Int
136+getSpriteID = gets thisSpriteID
137137
138−new_sprite_ID :: MonadIO m => StateT SpriteDB m Int
139−new_sprite_ID = do
138+newSpriteID :: MonadIO m => StateT SpriteDB m Int
139+newSpriteID = do
140140 ctx <- get
141− let the_ID = next_sprite_ID ctx
142− put $ ctx {next_sprite_ID = the_ID + 1, this_sprite_ID = the_ID}
141+ let the_ID = nextSpriteID ctx
142+ put $ ctx {nextSpriteID = the_ID + 1, thisSpriteID = the_ID}
143143 return the_ID
144144
145−empty_sprite_db = SpriteDB 0 1 Map.empty
145+emptySpriteDb = SpriteDB 0 1 Map.empty
146146
147−add_sprite x y img i
147+addSprite x y img i
148148 = modify (\ctx -> ctx {sprites = Map.insert i (x,y,img) (sprites ctx)})
149149
150−add_random_sprite c i = do
150+addRandomSprite c i = do
151151 let img = char def_attr c
152152 [x,y] <- liftIO $ replicateM 2 $ randomRIO (-100,100)
153− add_sprite x y img i
153+ addSprite x y img i
154154
155155instance MonadIO m => Story (BuildSprites m) where
156156 story _c (BuildSprites q) = BuildSprites q
157157 quest (BuildSprites g) (BuildSprites as) = BuildSprites (g >> as)
158− empty_aspects = BuildSprites $ return ()
159− add_known_history h (BuildSprites as) = BuildSprites as
160− add_known_obj obj (BuildSprites as) = BuildSprites as
161− add_unknown_history h (BuildSprites as) = BuildSprites as
162− add_unknown_obj obj (BuildSprites as) = BuildSprites as
163− animate_obj _t = BuildSprites $ do
164− add_random_sprite '@' =<< new_sprite_ID
165− inanimate_obj _t = BuildSprites $ do
166− add_random_sprite 'X' =<< new_sprite_ID
158+ emptyAspects = BuildSprites $ return ()
159+ addKnownHistory h (BuildSprites as) = BuildSprites as
160+ addKnownObj obj (BuildSprites as) = BuildSprites as
161+ addUnknownHistory h (BuildSprites as) = BuildSprites as
162+ addUnknownObj obj (BuildSprites as) = BuildSprites as
163+ animateObj _t = BuildSprites $ do
164+ addRandomSprite '@' =<< newSpriteID
165+ inanimateObj _t = BuildSprites $ do
166+ addRandomSprite 'X' =<< newSpriteID
167167 history = BuildSprites $ return ()
168− dispose_obj (BuildSprites obj) = BuildSprites obj
169− acquire_obj (BuildSprites obj) = BuildSprites obj
168+ disposeObj (BuildSprites obj) = BuildSprites obj
169+ acquireObj (BuildSprites obj) = BuildSprites obj
170170 named (BuildSprites obj) n = BuildSprites obj
171171
172−render_sprites = foldMap render_sprite . sprites
173−render_sprite (x,y,img) = return $ translate x y img
172+renderSprites = foldMap renderSprite . sprites
173+renderSprite (x,y,img) = return $ translate x y img
174174
175175main = do
176− putStrLn $ unTellStory story_0
177− putStrLn $ unShowStory story_0
178− sprite_db <- execStateT (build_sprites story_0) empty_sprite_db
179− print sprite_db
180− let imgs = render_sprites sprite_db
176+ putStrLn $ unTellStory story0
177+ putStrLn $ unShowStory story0
178+ spriteDb <- execStateT (buildSprites story0) emptySpriteDb
179+ print spriteDb
180+ let imgs = renderSprites spriteDb
181181 p = pic_for_layers imgs
182182 withVty $ flip update p
183183 threadDelay 5000000
test/Verify.hs+4−4
@@ -50,11 +50,11 @@ import Control.Monad.State.Strict
5050import Numeric ( showHex )
5151
5252verify :: Testable t => String -> t -> Test
53−verify test_name p = Test $ TestInstance
54− { name = test_name
53+verify testName p = Test $ TestInstance
54+ { name = testName
5555 , run = do
56− qc_result <- quickCheckResult p
57− case qc_result of
56+ qcResult <- quickCheckResult p
57+ case qcResult of
5858 QC.Success {..} -> return $ Finished TS.Pass
5959 QC.Failure {numShrinks,reason} -> return $ Finished
6060 $ TS.Fail $ "After "
test/Verify/Data/Terminfo/Parse.hs+30−30
@@ -12,8 +12,8 @@ import qualified Data.Vector.Unboxed as Vector
1212
1313import Numeric
1414
15−hex_dump :: [Word8] -> String
16−hex_dump bytes = foldr (\b s -> showHex b s) "" bytes
15+hexDump :: [Word8] -> String
16+hexDump bytes = foldr (\b s -> showHex b s) "" bytes
1717
1818data NonParamCapString = NonParamCapString String
1919 deriving Show
@@ -32,7 +32,7 @@ instance Arbitrary LiteralPercentCap where
3232 arbitrary
3333 = ( do
3434 NonParamCapString s <- arbitrary
35− (s', bytes) <- insert_escape_op "%" [toEnum $ fromEnum '%'] s
35+ (s', bytes) <- insertEscapeOp "%" [toEnum $ fromEnum '%'] s
3636 return $ LiteralPercentCap s' bytes
3737 ) `suchThat` ( \(LiteralPercentCap str _) -> length str < 255 )
3838
@@ -43,7 +43,7 @@ instance Arbitrary IncFirstTwoCap where
4343 arbitrary
4444 = ( do
4545 NonParamCapString s <- arbitrary
46− (s', bytes) <- insert_escape_op "i" [] s
46+ (s', bytes) <- insertEscapeOp "i" [] s
4747 return $ IncFirstTwoCap s' bytes
4848 ) `suchThat` ( \(IncFirstTwoCap str _) -> length str < 255 )
4949
@@ -55,7 +55,7 @@ instance Arbitrary PushParamCap where
5555 = ( do
5656 NonParamCapString s <- arbitrary
5757 n <- choose (1,9)
58− (s', bytes) <- insert_escape_op ("p" ++ show n) [] s
58+ (s', bytes) <- insertEscapeOp ("p" ++ show n) [] s
5959 return $ PushParamCap s' n bytes
6060 ) `suchThat` ( \(PushParamCap str _ _) -> length str < 255 )
6161
@@ -67,46 +67,46 @@ instance Arbitrary DecPrintCap where
6767 = ( do
6868 NonParamCapString s <- arbitrary
6969 n <- choose (1,9)
70− (s', bytes) <- insert_escape_op ("p" ++ show n ++ "%d") [] s
70+ (s', bytes) <- insertEscapeOp ("p" ++ show n ++ "%d") [] s
7171 return $ DecPrintCap s' n bytes
7272 ) `suchThat` ( \(DecPrintCap str _ _) -> length str < 255 )
7373
74−insert_escape_op op_str repl_bytes s = do
75− insert_points <- listOf1 $ elements [0 .. length s - 1]
76− let s' = f s ('%' : op_str)
77− remaining_bytes = f (map (toEnum . fromEnum) s) repl_bytes
74+insertEscapeOp opStr replBytes s = do
75+ insertPoints <- listOf1 $ elements [0 .. length s - 1]
76+ let s' = f s ('%' : opStr)
77+ remainingBytes = f (map (toEnum . fromEnum) s) replBytes
7878 f in_vs out_v = concat [ vs
7979 | vi <- zip in_vs [0 .. length s - 1]
80− , let vs = fst vi : ( if snd vi `elem` insert_points
80+ , let vs = fst vi : ( if snd vi `elem` insertPoints
8181 then out_v
8282 else []
8383 )
8484 ]
85− return (s', remaining_bytes)
85+ return (s', remainingBytes)
8686
87−is_bytes_op :: CapOp -> Bool
88−is_bytes_op (Bytes {}) = True
89−-- is_bytes_op _ = False
87+isBytesOp :: CapOp -> Bool
88+isBytesOp (Bytes {}) = True
89+-- isBytesOp _ = False
9090
91−bytes_for_range cap offset count
92− = Vector.toList $ Vector.take count $ Vector.drop offset $ cap_bytes cap
91+bytesForRange cap offset count
92+ = Vector.toList $ Vector.take count $ Vector.drop offset $ capBytes cap
9393
94−collect_bytes :: CapExpression -> [Word8]
95−collect_bytes e = concat [ bytes
96− | Bytes offset count <- cap_ops e
97− , let bytes = bytes_for_range e offset count
98− ]
94+collectBytes :: CapExpression -> [Word8]
95+collectBytes e = concat [ bytes
96+ | Bytes offset count <- capOps e
97+ , let bytes = bytesForRange e offset count
98+ ]
9999
100100
101−verify_bytes_equal :: [Word8] -> [Word8] -> Result
102−verify_bytes_equal out_bytes expected_bytes
103− = if out_bytes == expected_bytes
101+verifyBytesEqual :: [Word8] -> [Word8] -> Result
102+verifyBytesEqual outBytes expectedBytes
103+ = if outBytes == expectedBytes
104104 then succeeded
105105 else failed
106− { reason = "out_bytes ["
107− ++ hex_dump out_bytes
108− ++ "] /= expected_bytes ["
109− ++ hex_dump expected_bytes
110− ++ "]"
106+ { reason = "outBytes ["
107+ ++ hexDump outBytes
108+ ++ "] /= expectedBytes ["
109+ ++ hexDump expectedBytes
110+ ++ "]"
111111 }
112112
test/Verify/Graphics/Vty/Attributes.hs+30−30
@@ -8,8 +8,8 @@ import Verify
88
99import Data.List ( delete )
1010
11−all_colors :: [Color]
12−all_colors =
11+allColors :: [Color]
12+allColors =
1313 [ black
1414 , red
1515 , green
@@ -18,56 +18,56 @@ all_colors =
1818 , magenta
1919 , cyan
2020 , white
21− , bright_black
22− , bright_red
23− , bright_green
24− , bright_yellow
25− , bright_blue
26− , bright_magenta
27− , bright_cyan
28− , bright_white
21+ , brightBlack
22+ , brightRed
23+ , brightGreen
24+ , brightYellow
25+ , brightBlue
26+ , brightMagenta
27+ , brightCyan
28+ , brightWhite
2929 ] ++ map Color240 [0..239]
3030
31−all_styles :: [Style]
32−all_styles =
31+allStyles :: [Style]
32+allStyles =
3333 [ standout
3434 , underline
35− , reverse_video
35+ , reverseVideo
3636 , blink
3737 , dim
3838 , bold
3939 ]
4040
4141-- Limit the possible attributes to just a few for now.
42−possible_attr_mods :: [ AttrOp ]
43−possible_attr_mods =
44− [ id_op
45− ] ++ map set_fore_color_op all_colors
46− ++ map set_back_color_op all_colors
47− ++ map set_style_op all_styles
42+possibleAttrMods :: [ AttrOp ]
43+possibleAttrMods =
44+ [ idOp
45+ ] ++ map setForeColorOp allColors
46+ ++ map setBackColorOp allColors
47+ ++ map setStyleOp allStyles
4848
4949instance Arbitrary Attr where
50− arbitrary = elements possible_attr_mods >>= return . flip apply_op def_attr
50+ arbitrary = elements possibleAttrMods >>= return . flip applyOp defAttr
5151
5252data DiffAttr = DiffAttr Attr Attr
5353
5454instance Arbitrary DiffAttr where
5555 arbitrary = do
56− op0 <- elements possible_attr_mods
57− let possible_attr_mods' = delete op0 possible_attr_mods
58− op1 <- elements possible_attr_mods'
59− return $ DiffAttr (apply_op op0 def_attr) (apply_op op1 def_attr)
56+ op0 <- elements possibleAttrMods
57+ let possibleAttrMods' = delete op0 possibleAttrMods
58+ op1 <- elements possibleAttrMods'
59+ return $ DiffAttr (applyOp op0 defAttr) (applyOp op1 defAttr)
6060
6161data AttrOp = AttrOp String (Attr -> Attr)
6262
6363instance Eq AttrOp where
6464 AttrOp n0 _ == AttrOp n1 _ = n0 == n1
6565
66−set_style_op s = AttrOp "set_style" (flip with_style s)
67−set_fore_color_op c = AttrOp "set_fore_color" (flip with_fore_color c)
68−set_back_color_op c = AttrOp "set_back_color" (flip with_back_color c)
69−id_op = AttrOp "id" id
66+setStyleOp s = AttrOp "set_style" (flip withStyle s)
67+setForeColorOp c = AttrOp "set_fore_color" (flip withForeColor c)
68+setBackColorOp c = AttrOp "set_back_color" (flip withBackColor c)
69+idOp = AttrOp "id" id
7070
71−apply_op :: AttrOp -> Attr -> Attr
72−apply_op (AttrOp _ f) a = f a
71+applyOp :: AttrOp -> Attr -> Attr
72+applyOp (AttrOp _ f) a = f a
7373
test/Verify/Graphics/Vty/Image.hs+55−55
@@ -27,18 +27,18 @@ data DefaultImage = DefaultImage Image
2727
2828instance Show DefaultImage where
2929 show (DefaultImage i)
30− = "DefaultImage (" ++ show i ++ ") " ++ show (image_width i, image_height i)
30+ = "DefaultImage (" ++ show i ++ ") " ++ show (imageWidth i, imageHeight i)
3131
3232instance Arbitrary DefaultImage where
3333 arbitrary = do
34− i <- return $ char def_attr 'X'
34+ i <- return $ char defAttr 'X'
3535 return $ DefaultImage i
3636
3737data SingleRowSingleAttrImage
3838 = SingleRowSingleAttrImage
39− { expected_attr :: Attr
40− , expected_columns :: Int
41− , row_image :: Image
39+ { expectedAttr :: Attr
40+ , expectedColumns :: Int
41+ , rowImage :: Image
4242 }
4343
4444instance Show SingleRowSingleAttrImage where
@@ -52,10 +52,10 @@ instance Arbitrary WidthResize where
5252 WidthResize f <- arbitrary
5353 w <- choose (1,64)
5454 oneof $ map (return . WidthResize)
55− [ \i -> (i, image_width i)
56− , \i -> (resize_width w $ fst $ f i, w)
57− , \i -> let i' = fst $ f i in (crop_left w i', min (image_width i') w)
58− , \i -> let i' = fst $ f i in (crop_right w i', min (image_width i') w)
55+ [ \i -> (i, imageWidth i)
56+ , \i -> (resizeWidth w $ fst $ f i, w)
57+ , \i -> let i' = fst $ f i in (cropLeft w i', min (imageWidth i') w)
58+ , \i -> let i' = fst $ f i in (cropRight w i', min (imageWidth i') w)
5959 ]
6060
6161newtype HeightResize = HeightResize (Image -> (Image, Int))
@@ -65,36 +65,36 @@ instance Arbitrary HeightResize where
6565 HeightResize f <- arbitrary
6666 h <- choose (1,64)
6767 oneof $ map (return . HeightResize)
68− [ \i -> (i, image_height i)
69− , \i -> (resize_height h $ fst $ f i, h)
70− , \i -> let i' = fst $ f i in (crop_top h i', min (image_height i') h)
71− , \i -> let i' = fst $ f i in (crop_bottom h i', min (image_height i') h)
68+ [ \i -> (i, imageHeight i)
69+ , \i -> (resizeHeight h $ fst $ f i, h)
70+ , \i -> let i' = fst $ f i in (cropTop h i', min (imageHeight i') h)
71+ , \i -> let i' = fst $ f i in (cropBottom h i', min (imageHeight i') h)
7272 ]
7373
7474newtype ImageResize = ImageResize (Image -> (Image, (Int, Int)))
7575
7676instance Arbitrary ImageResize where
7777 arbitrary = oneof
78− [ return $! ImageResize $! \i -> (i, (image_width i, image_height i))
79− , return $! ImageResize $! \i -> (i, (image_width i, image_height i))
80− , return $! ImageResize $! \i -> (i, (image_width i, image_height i))
81− , return $! ImageResize $! \i -> (i, (image_width i, image_height i))
82− , return $! ImageResize $! \i -> (i, (image_width i, image_height i))
83− , return $! ImageResize $! \i -> (i, (image_width i, image_height i))
78+ [ return $! ImageResize $! \i -> (i, (imageWidth i, imageHeight i))
79+ , return $! ImageResize $! \i -> (i, (imageWidth i, imageHeight i))
80+ , return $! ImageResize $! \i -> (i, (imageWidth i, imageHeight i))
81+ , return $! ImageResize $! \i -> (i, (imageWidth i, imageHeight i))
82+ , return $! ImageResize $! \i -> (i, (imageWidth i, imageHeight i))
83+ , return $! ImageResize $! \i -> (i, (imageWidth i, imageHeight i))
8484 , do
8585 ImageResize f <- arbitrary
8686 WidthResize g <- arbitrary
8787 return $! ImageResize $! \i ->
88− let (i_0, (_, out_height)) = f i
88+ let (i_0, (_, outHeight)) = f i
8989 g_i = g i_0
90− in (fst g_i, (snd g_i, out_height))
90+ in (fst g_i, (snd g_i, outHeight))
9191 , do
9292 ImageResize f <- arbitrary
9393 HeightResize g <- arbitrary
9494 return $! ImageResize $! \i ->
95− let (i_0, (out_width, _)) = f i
95+ let (i_0, (outWidth, _)) = f i
9696 g_i = g i_0
97− in (fst g_i, (out_width, snd g_i))
97+ in (fst g_i, (outWidth, snd g_i))
9898 ]
9999
100100
@@ -103,59 +103,59 @@ instance Arbitrary SingleRowSingleAttrImage where
103103 -- The text must contain at least one character. Otherwise the image simplifies to the
104104 -- IdImage which has a height of 0. If this is to represent a single row then the height
105105 -- must be 1
106− single_column_row_text <- Verify.resize 16 (listOf1 arbitrary)
106+ singleColumnRowText <- Verify.resize 16 (listOf1 arbitrary)
107107 a <- arbitrary
108− let out_image = horiz_cat $ [char a c | SingleColumnChar c <- single_column_row_text]
109− out_width = length single_column_row_text
110− return $ SingleRowSingleAttrImage a out_width out_image
108+ let outImage = horizCat $ [char a c | SingleColumnChar c <- singleColumnRowText]
109+ outWidth = length singleColumnRowText
110+ return $ SingleRowSingleAttrImage a outWidth outImage
111111
112112data SingleRowTwoAttrImage
113113 = SingleRowTwoAttrImage
114− { part_0 :: SingleRowSingleAttrImage
115− , part_1 :: SingleRowSingleAttrImage
116− , join_image :: Image
114+ { part0 :: SingleRowSingleAttrImage
115+ , part1 :: SingleRowSingleAttrImage
116+ , joinImage :: Image
117117 } deriving Show
118118
119119instance Arbitrary SingleRowTwoAttrImage where
120120 arbitrary = do
121121 p0 <- arbitrary
122122 p1 <- arbitrary
123− return $ SingleRowTwoAttrImage p0 p1 (row_image p0 <|> row_image p1)
123+ return $ SingleRowTwoAttrImage p0 p1 (rowImage p0 <|> rowImage p1)
124124
125125data SingleAttrSingleSpanStack = SingleAttrSingleSpanStack
126− { stack_image :: Image
127− , stack_source_images :: [SingleRowSingleAttrImage]
128− , stack_width :: Int
129− , stack_height :: Int
126+ { stackImage :: Image
127+ , stackSourceImages :: [SingleRowSingleAttrImage]
128+ , stackWidth :: Int
129+ , stackHeight :: Int
130130 }
131131 deriving Show
132132
133133instance Arbitrary SingleAttrSingleSpanStack where
134134 arbitrary = do
135− image_list <- Verify.resize 16 (listOf1 arbitrary)
136− return $ mk_single_attr_single_span_stack image_list
135+ imageList <- Verify.resize 16 (listOf1 arbitrary)
136+ return $ mkSingleAttrSingleSpanStack imageList
137137 shrink s = do
138− image_list <- shrink $ stack_source_images s
139− if null image_list
138+ imageList <- shrink $ stackSourceImages s
139+ if null imageList
140140 then []
141− else return $ mk_single_attr_single_span_stack image_list
141+ else return $ mkSingleAttrSingleSpanStack imageList
142142
143−mk_single_attr_single_span_stack image_list =
144− let image = vert_cat [ i | SingleRowSingleAttrImage { row_image = i } <- image_list ]
145− in SingleAttrSingleSpanStack image image_list (maximum $ map expected_columns image_list)
146− (toEnum $ length image_list)
143+mkSingleAttrSingleSpanStack imageList =
144+ let image = vertCat [ i | SingleRowSingleAttrImage { rowImage = i } <- imageList ]
145+ in SingleAttrSingleSpanStack image imageList (maximum $ map expectedColumns imageList)
146+ (toEnum $ length imageList)
147147
148148instance Arbitrary Image where
149149 arbitrary = oneof
150150 [ return EmptyImage
151151 , do
152− SingleAttrSingleSpanStack {stack_image} <- Verify.resize 8 arbitrary
152+ SingleAttrSingleSpanStack {stackImage} <- Verify.resize 8 arbitrary
153153 ImageResize f <- Verify.resize 2 arbitrary
154− return $! fst $! f stack_image
154+ return $! fst $! f stackImage
155155 , do
156− SingleAttrSingleSpanStack {stack_image} <- Verify.resize 8 arbitrary
156+ SingleAttrSingleSpanStack {stackImage} <- Verify.resize 8 arbitrary
157157 ImageResize f <- Verify.resize 2 arbitrary
158− return $! fst $! f stack_image
158+ return $! fst $! f stackImage
159159 , do
160160 i_0 <- arbitrary
161161 i_1 <- arbitrary
@@ -171,28 +171,28 @@ instance Arbitrary Image where
171171 ]
172172 {-
173173 shrink i@(HorizJoin {part_left, part_right}) = do
174− let !i_alt = background_fill (image_width i) (image_height i)
174+ let !i_alt = background_fill (imageWidth i) (imageHeight i)
175175 !part_left' <- shrink part_left
176176 !part_right' <- shrink part_right
177177 [i_alt, part_left' <|> part_right']
178178 shrink i@(VertJoin {part_top, part_bottom}) = do
179− let !i_alt = background_fill (image_width i) (image_height i)
179+ let !i_alt = background_fill (imageWidth i) (imageHeight i)
180180 !part_top' <- shrink part_top
181181 !part_bottom' <- shrink part_bottom
182182 [i_alt, part_top' <-> part_bottom']
183183 shrink i@(CropRight {cropped_image, output_width}) = do
184− let !i_alt = background_fill (image_width i) (image_height i)
184+ let !i_alt = background_fill (imageWidth i) (imageHeight i)
185185 [i_alt, cropped_image]
186186 shrink i@(CropLeft {cropped_image, left_skip, output_width}) = do
187− let !i_alt = background_fill (image_width i) (image_height i)
187+ let !i_alt = background_fill (imageWidth i) (imageHeight i)
188188 [i_alt, cropped_image]
189189 shrink i@(CropBottom {cropped_image, output_height}) = do
190− let !i_alt = background_fill (image_width i) (image_height i)
190+ let !i_alt = background_fill (imageWidth i) (imageHeight i)
191191 [i_alt, cropped_image]
192192 shrink i@(CropTop {cropped_image, top_skip, output_height}) = do
193− let !i_alt = background_fill (image_width i) (image_height i)
193+ let !i_alt = background_fill (imageWidth i) (imageHeight i)
194194 [i_alt, cropped_image]
195− shrink i = [empty_image, background_fill (image_width i) (image_height i)]
195+ shrink i = [empty_image, background_fill (imageWidth i) (imageHeight i)]
196196 -}
197197
198198data CropOperation
test/Verify/Graphics/Vty/Output.hs+10−10
@@ -12,8 +12,8 @@ import Test.QuickCheck.Property
1212-- This started with a list of terminals ubuntu supported. Then those terminals that really could
1313-- not be supported were removed. Then a few more were pruned until a reasonable looking set was
1414-- made.
15−terminals_of_interest :: [String]
16−terminals_of_interest =
15+terminalsOfInterest :: [String]
16+terminalsOfInterest =
1717 [ "vt100"
1818 , "vt220"
1919 , "vt102"
@@ -47,14 +47,14 @@ terminals_of_interest =
4747 , "cygwin"
4848 ]
4949
50−compare_mock_output :: MockData -> String -> IO Result
51−compare_mock_output mock_data expected_str = do
52− out_bytes <- readIORef mock_data >>= return . UTF8.toRep
53− let expected_bytes :: BS.ByteString = UTF8.toRep $ UTF8.fromString expected_str
54− if out_bytes /= expected_bytes
55− then return $ failed { reason = "bytes\n" ++ show out_bytes
56− ++ "\nare not the expected bytes\n"
57− ++ show expected_bytes
50+compareMockOutput :: MockData -> String -> IO Result
51+compareMockOutput mockData expectedStr = do
52+ outBytes <- readIORef mockData >>= return . UTF8.toRep
53+ let expectedBytes :: BS.ByteString = UTF8.toRep $ UTF8.fromString expectedStr
54+ if outBytes /= expectedBytes
55+ then return $ failed { reason = "bytes\n" ++ show outBytes
56+ ++ "\nare not the expected bytes\n"
57+ ++ show expectedBytes
5858 }
5959 else return succeeded
6060
test/Verify/Graphics/Vty/Picture.hs+10−10
@@ -15,8 +15,8 @@ import Verify.Graphics.Vty.Image
1515import Verify
1616
1717data DefaultPic = DefaultPic
18− { default_pic :: Picture
19− , default_win :: MockWindow
18+ { defaultPic :: Picture
19+ , defaultWin :: MockWindow
2020 }
2121
2222instance Show DefaultPic where
@@ -26,27 +26,27 @@ instance Show DefaultPic where
2626instance Arbitrary DefaultPic where
2727 arbitrary = do
2828 DefaultImage image <- arbitrary
29− let win = MockWindow (image_width image) (image_height image)
30− return $ DefaultPic (pic_for_image image)
29+ let win = MockWindow (imageWidth image) (imageHeight image)
30+ return $ DefaultPic (picForImage image)
3131 win
3232
3333data PicWithBGAttr = PicWithBGAttr
34− { with_attr_pic :: Picture
35− , with_attr_win :: MockWindow
36− , with_attr_specified_attr :: Attr
34+ { withAttrPic :: Picture
35+ , withAttrWin :: MockWindow
36+ , withAttrSpecifiedAttr :: Attr
3737 } deriving ( Show )
3838
3939instance Arbitrary PicWithBGAttr where
4040 arbitrary = do
4141 DefaultImage image <- arbitrary
42− let win = MockWindow (image_width image) (image_height image)
42+ let win = MockWindow (imageWidth image) (imageHeight image)
4343 attr <- arbitrary
44− return $ PicWithBGAttr (pic_for_image image)
44+ return $ PicWithBGAttr (picForImage image)
4545 win
4646 attr
4747
4848instance Arbitrary Picture where
4949 arbitrary = do
5050 layers <- Verify.resize 20 (listOf1 arbitrary)
51− return $ pic_for_layers layers
51+ return $ picForLayers layers
5252
test/Verify/Graphics/Vty/Span.hs+6−6
@@ -14,12 +14,12 @@ import Data.Word
1414
1515import Verify
1616
17−is_attr_span_op :: SpanOp -> Bool
18−is_attr_span_op TextSpan {} = True
19−is_attr_span_op _ = False
17+isAttrSpanOp :: SpanOp -> Bool
18+isAttrSpanOp TextSpan {} = True
19+isAttrSpanOp _ = False
2020
21−verify_all_spans_have_width i spans w
22− = let v = map (\s -> (span_ops_effected_columns s /= w, s)) (Vector.toList spans)
21+verifyAllSpansHaveWidth i spans w
22+ = let v = map (\s -> (spanOpsEffectedColumns s /= w, s)) (Vector.toList spans)
2323 in case any ((== True) . fst) v of
2424 False -> succeeded
2525 True -> failed { reason = "Not all spans contained operations defining exactly "
@@ -28,7 +28,7 @@ verify_all_spans_have_width i spans w
2828 ++ (concatMap ((++ "\n") . show)) v
2929 }
3030
31−verify_ops_equality i_ops i_alt_ops =
31+verifyOpsEquality i_ops i_alt_ops =
3232 if i_ops == i_alt_ops
3333 then succeeded
3434 else failed { reason = "ops for alternate image " ++ show i_alt_ops
test/VerifyCropSpanGeneration.hs+55−55
@@ -15,79 +15,79 @@ import Verify
1515
1616import qualified Data.Vector as Vector
1717
18−crop_op_display_ops :: (Int -> Image -> Image) ->
19− Int -> Image -> (DisplayOps, Image)
20−crop_op_display_ops crop_op v i =
21− let i_out = crop_op v i
22− p = pic_for_image i_out
23− w = MockWindow (image_width i_out) (image_height i_out)
24− in (display_ops_for_pic p (region_for_window w), i_out)
25−
26−width_crop_output_columns :: (Int -> Image -> Image) ->
27− SingleAttrSingleSpanStack ->
28− NonNegative Int ->
29− Property
30−width_crop_output_columns crop_op s (NonNegative w) = stack_width s > w ==>
31− let (ops, i_out) = crop_op_display_ops crop_op w (stack_image s)
32− in verify_all_spans_have_width i_out ops w
33−
34−height_crop_output_columns :: (Int -> Image -> Image) ->
35− SingleAttrSingleSpanStack ->
36− NonNegative Int ->
37− Property
38−height_crop_output_columns crop_op s (NonNegative h) = stack_height s > h ==>
39− let (ops, _) = crop_op_display_ops crop_op h (stack_image s)
40− in display_ops_rows ops == h
41−
42−crop_right_output_columns :: SingleAttrSingleSpanStack -> NonNegative Int -> Property
43−crop_right_output_columns = width_crop_output_columns crop_right
44−
45−crop_left_output_columns :: SingleAttrSingleSpanStack -> NonNegative Int -> Property
46−crop_left_output_columns = width_crop_output_columns crop_left
47−
48−crop_top_output_rows :: SingleAttrSingleSpanStack -> NonNegative Int -> Property
49−crop_top_output_rows = height_crop_output_columns crop_top
50−
51−crop_bottom_output_rows :: SingleAttrSingleSpanStack -> NonNegative Int -> Property
52−crop_bottom_output_rows = height_crop_output_columns crop_bottom
18+cropOpDisplayOps :: (Int -> Image -> Image) ->
19+ Int -> Image -> (DisplayOps, Image)
20+cropOpDisplayOps cropOp v i =
21+ let iOut = cropOp v i
22+ p = picForImage iOut
23+ w = MockWindow (imageWidth iOut) (imageHeight iOut)
24+ in (displayOpsForPic p (regionForWindow w), iOut)
25+
26+widthCropOutputColumns :: (Int -> Image -> Image) ->
27+ SingleAttrSingleSpanStack ->
28+ NonNegative Int ->
29+ Property
30+widthCropOutputColumns cropOp s (NonNegative w) = stackWidth s > w ==>
31+ let (ops, iOut) = cropOpDisplayOps cropOp w (stackImage s)
32+ in verifyAllSpansHaveWidth iOut ops w
33+
34+heightCropOutputColumns :: (Int -> Image -> Image) ->
35+ SingleAttrSingleSpanStack ->
36+ NonNegative Int ->
37+ Property
38+heightCropOutputColumns cropOp s (NonNegative h) = stackHeight s > h ==>
39+ let (ops, _) = cropOpDisplayOps cropOp h (stackImage s)
40+ in displayOpsRows ops == h
41+
42+cropRightOutputColumns :: SingleAttrSingleSpanStack -> NonNegative Int -> Property
43+cropRightOutputColumns = widthCropOutputColumns cropRight
44+
45+cropLeftOutputColumns :: SingleAttrSingleSpanStack -> NonNegative Int -> Property
46+cropLeftOutputColumns = widthCropOutputColumns cropLeft
47+
48+cropTopOutputRows :: SingleAttrSingleSpanStack -> NonNegative Int -> Property
49+cropTopOutputRows = heightCropOutputColumns cropTop
50+
51+cropBottomOutputRows :: SingleAttrSingleSpanStack -> NonNegative Int -> Property
52+cropBottomOutputRows = heightCropOutputColumns cropBottom
5353
5454-- TODO: known benign failure.
55−crop_right_and_left_rejoined_equivalence :: SingleAttrSingleSpanStack -> Property
56−crop_right_and_left_rejoined_equivalence stack = image_width (stack_image stack) `mod` 2 == 0 ==>
57− let i = stack_image stack
55+cropRightAndLeftRejoinedEquivalence :: SingleAttrSingleSpanStack -> Property
56+cropRightAndLeftRejoinedEquivalence stack = imageWidth (stackImage stack) `mod` 2 == 0 ==>
57+ let i = stackImage stack
5858 -- the right part is made by cropping the image from the left.
59− i_r = crop_left (image_width i `div` 2) i
59+ i_r = cropLeft (imageWidth i `div` 2) i
6060 -- the left part is made by cropping the image from the right
61− i_l = crop_right (image_width i `div` 2) i
61+ i_l = cropRight (imageWidth i `div` 2) i
6262 i_alt = i_l <|> i_r
63− i_ops = display_ops_for_image i
64− i_alt_ops = display_ops_for_image i_alt
65− in verify_ops_equality i_ops i_alt_ops
63+ i_ops = displayOpsForImage i
64+ i_alt_ops = displayOpsForImage i_alt
65+ in verifyOpsEquality i_ops i_alt_ops
6666
67−crop_top_and_bottom_rejoined_equivalence :: SingleAttrSingleSpanStack -> Property
68−crop_top_and_bottom_rejoined_equivalence stack = image_height (stack_image stack) `mod` 2 == 0 ==>
69− let i = stack_image stack
67+cropTopAndBottomRejoinedEquivalence :: SingleAttrSingleSpanStack -> Property
68+cropTopAndBottomRejoinedEquivalence stack = imageHeight (stackImage stack) `mod` 2 == 0 ==>
69+ let i = stackImage stack
7070 -- the top part is made by cropping the image from the bottom.
71− i_t = crop_bottom (image_height i `div` 2) i
71+ i_t = cropBottom (imageHeight i `div` 2) i
7272 -- the bottom part is made by cropping the image from the top.
73− i_b = crop_top (image_height i `div` 2) i
73+ i_b = cropTop (imageHeight i `div` 2) i
7474 i_alt = i_t <-> i_b
75− in display_ops_for_image i == display_ops_for_image i_alt
75+ in displayOpsForImage i == displayOpsForImage i_alt
7676
7777tests :: IO [Test]
7878tests = return
7979 [ verify "cropping from the bottom produces display operations covering the expected rows"
80− crop_bottom_output_rows
80+ cropBottomOutputRows
8181 , verify "cropping from the top produces display operations covering the expected rows"
82− crop_top_output_rows
82+ cropTopOutputRows
8383 , verify "cropping from the left produces display operations covering the expected columns"
84− crop_left_output_columns
84+ cropLeftOutputColumns
8585 , verify "cropping from the right produces display operations covering the expected columns"
86− crop_right_output_columns
86+ cropRightOutputColumns
8787 -- TODO: known benign failure.
8888 -- , verify "the output of a stack is the same as that stack cropped left & right and joined together"
89− -- crop_right_and_left_rejoined_equivalence
89+ -- cropRightAndLeftRejoinedEquivalence
9090 , verify "the output of a stack is the same as that stack cropped top & bottom and joined together"
91− crop_top_and_bottom_rejoined_equivalence
91+ cropTopAndBottomRejoinedEquivalence
9292 ]
9393
test/VerifyEmptyImageProps.hs+2−2
@@ -3,11 +3,11 @@ module VerifyEmptyImageProps where
33import Verify
44
55-- should be exported by Graphics.Vty.Picture
6−import Graphics.Vty.Picture ( Image, empty_image )
6+import Graphics.Vty.Picture ( Image, emptyImage )
77
88tests :: IO [Test]
99tests = do
1010 -- should provide an image type.
11− let _ :: Image = empty_image
11+ let _ :: Image = emptyImage
1212 return []
1313
test/VerifyEvalTerminfoCaps.hs+26−26
@@ -25,7 +25,7 @@ import Foreign.Ptr (Ptr, minusPtr)
2525import Numeric
2626
2727-- If a terminal defines one of the caps then it's expected to be parsable.
28−caps_of_interest =
28+capsOfInterest =
2929 [ "cup"
3030 , "sc"
3131 , "rc"
@@ -45,45 +45,45 @@ caps_of_interest =
4545 , "sgr0"
4646 ]
4747
48−from_capname ti name = fromJust $ Terminfo.getCapability ti (Terminfo.tiGetStr name)
48+fromCapname ti name = fromJust $ Terminfo.getCapability ti (Terminfo.tiGetStr name)
4949
5050tests :: IO [Test]
5151tests = do
52− eval_buffer :: Ptr Word8 <- mallocBytes (1024 * 1024) -- Should be big enough for any termcaps ;-)
53− fmap concat $ forM terminals_of_interest $ \term_name -> do
54− putStrLn $ "adding tests for terminal: " ++ term_name
55− mti <- try $ Terminfo.setupTerm term_name
52+ evalBuffer :: Ptr Word8 <- mallocBytes (1024 * 1024) -- Should be big enough for any termcaps ;-)
53+ fmap concat $ forM terminalsOfInterest $ \termName -> do
54+ putStrLn $ "adding tests for terminal: " ++ termName
55+ mti <- try $ Terminfo.setupTerm termName
5656 case mti of
5757 Left (_e :: SomeException)
5858 -> return []
5959 Right ti -> do
60− fmap concat $ forM caps_of_interest $ \cap_name -> do
61− case Terminfo.getCapability ti (Terminfo.tiGetStr cap_name) of
62− Just cap_def -> do
63− putStrLn $ "\tadding test for cap: " ++ cap_name
64− let test_name = term_name ++ "(" ++ cap_name ++ ")"
65− case parse_cap_expression cap_def of
66− Left error -> return [verify test_name (failed {reason = "parse error " ++ show error})]
67− Right !cap_expr -> return [verify test_name (verify_eval_cap eval_buffer cap_expr)]
60+ fmap concat $ forM capsOfInterest $ \capName -> do
61+ case Terminfo.getCapability ti (Terminfo.tiGetStr capName) of
62+ Just capDef -> do
63+ putStrLn $ "\tadding test for cap: " ++ capName
64+ let testName = termName ++ "(" ++ capName ++ ")"
65+ case parseCapExpression capDef of
66+ Left error -> return [verify testName (failed {reason = "parse error " ++ show error})]
67+ Right !cap_expr -> return [verify testName (verifyEvalCap evalBuffer cap_expr)]
6868 Nothing -> do
6969 return []
7070
71−{-# NOINLINE verify_eval_cap #-}
72−verify_eval_cap :: Ptr Word8 -> CapExpression -> Int -> Property
73−verify_eval_cap eval_buffer expr !junk_int = do
74− forAll (vector 9) $ \input_values ->
75− let write = write_cap_expr expr input_values
76− !byte_count = getBound write
71+{-# NOINLINE verifyEvalCap #-}
72+verifyEvalCap :: Ptr Word8 -> CapExpression -> Int -> Property
73+verifyEvalCap evalBuffer expr !junkInt = do
74+ forAll (vector 9) $ \inputValues ->
75+ let write = writeCapExpr expr inputValues
76+ !byteCount = getBound write
7777 in liftIOResult $ do
78− let start_ptr :: Ptr Word8 = eval_buffer
79− forM_ [0..100] $ \i -> runWrite write start_ptr
80− end_ptr <- runWrite write start_ptr
81− case end_ptr `minusPtr` start_ptr of
78+ let startPtr :: Ptr Word8 = evalBuffer
79+ forM_ [0..100] $ \i -> runWrite write startPtr
80+ endPtr <- runWrite write startPtr
81+ case endPtr `minusPtr` startPtr of
8282 count | count < 0 ->
8383 return $ failed { reason = "End pointer before start pointer." }
84− | toEnum count > byte_count ->
84+ | toEnum count > byteCount ->
8585 return $ failed { reason = "End pointer past end of buffer by "
86− ++ show (toEnum count - byte_count)
86+ ++ show (toEnum count - byteCount)
8787 }
8888 | otherwise ->
8989 return succeeded
test/VerifyImageOps.hs+113−113
@@ -8,167 +8,167 @@ import Verify
88
99import Control.DeepSeq
1010
11−two_sw_horiz_concat :: SingleColumnChar -> SingleColumnChar -> Bool
12−two_sw_horiz_concat (SingleColumnChar c1) (SingleColumnChar c2) =
13− image_width (char def_attr c1 <|> char def_attr c2) == 2
11+twoSwHorizConcat :: SingleColumnChar -> SingleColumnChar -> Bool
12+twoSwHorizConcat (SingleColumnChar c1) (SingleColumnChar c2) =
13+ imageWidth (char defAttr c1 <|> char defAttr c2) == 2
1414
15−many_sw_horiz_concat :: [SingleColumnChar] -> Bool
16−many_sw_horiz_concat cs =
15+manySwHorizConcat :: [SingleColumnChar] -> Bool
16+manySwHorizConcat cs =
1717 let chars = [ char | SingleColumnChar char <- cs ]
1818 l = fromIntegral $ length cs
19− in image_width ( horiz_cat $ map (char def_attr) chars ) == l
19+ in imageWidth ( horizCat $ map (char defAttr) chars ) == l
2020
21−two_sw_vert_concat :: SingleColumnChar -> SingleColumnChar -> Bool
22−two_sw_vert_concat (SingleColumnChar c1) (SingleColumnChar c2) =
23− image_height (char def_attr c1 <-> char def_attr c2) == 2
21+twoSwVertConcat :: SingleColumnChar -> SingleColumnChar -> Bool
22+twoSwVertConcat (SingleColumnChar c1) (SingleColumnChar c2) =
23+ imageHeight (char defAttr c1 <-> char defAttr c2) == 2
2424
25−horiz_concat_sw_assoc :: SingleColumnChar -> SingleColumnChar -> SingleColumnChar -> Bool
26−horiz_concat_sw_assoc (SingleColumnChar c0) (SingleColumnChar c1) (SingleColumnChar c2) =
27− (char def_attr c0 <|> char def_attr c1) <|> char def_attr c2
25+horizConcatSwAssoc :: SingleColumnChar -> SingleColumnChar -> SingleColumnChar -> Bool
26+horizConcatSwAssoc (SingleColumnChar c0) (SingleColumnChar c1) (SingleColumnChar c2) =
27+ (char defAttr c0 <|> char defAttr c1) <|> char defAttr c2
2828 ==
29− char def_attr c0 <|> (char def_attr c1 <|> char def_attr c2)
29+ char defAttr c0 <|> (char defAttr c1 <|> char defAttr c2)
3030
31−two_dw_horiz_concat :: DoubleColumnChar -> DoubleColumnChar -> Bool
32−two_dw_horiz_concat (DoubleColumnChar c1) (DoubleColumnChar c2) =
33− image_width (char def_attr c1 <|> char def_attr c2) == 4
31+twoDwHorizConcat :: DoubleColumnChar -> DoubleColumnChar -> Bool
32+twoDwHorizConcat (DoubleColumnChar c1) (DoubleColumnChar c2) =
33+ imageWidth (char defAttr c1 <|> char defAttr c2) == 4
3434
35−many_dw_horiz_concat :: [DoubleColumnChar] -> Bool
36−many_dw_horiz_concat cs =
35+manyDwHorizConcat :: [DoubleColumnChar] -> Bool
36+manyDwHorizConcat cs =
3737 let chars = [ char | DoubleColumnChar char <- cs ]
3838 l = fromIntegral $ length cs
39− in image_width ( horiz_cat $ map (char def_attr) chars ) == l * 2
39+ in imageWidth ( horizCat $ map (char defAttr) chars ) == l * 2
4040
41−two_dw_vert_concat :: DoubleColumnChar -> DoubleColumnChar -> Bool
42−two_dw_vert_concat (DoubleColumnChar c1) (DoubleColumnChar c2) =
43− image_height (char def_attr c1 <-> char def_attr c2) == 2
41+twoDwVertConcat :: DoubleColumnChar -> DoubleColumnChar -> Bool
42+twoDwVertConcat (DoubleColumnChar c1) (DoubleColumnChar c2) =
43+ imageHeight (char defAttr c1 <-> char defAttr c2) == 2
4444
45−horiz_concat_dw_assoc :: DoubleColumnChar -> DoubleColumnChar -> DoubleColumnChar -> Bool
46−horiz_concat_dw_assoc (DoubleColumnChar c0) (DoubleColumnChar c1) (DoubleColumnChar c2) =
47− (char def_attr c0 <|> char def_attr c1) <|> char def_attr c2
45+horizConcatDwAssoc :: DoubleColumnChar -> DoubleColumnChar -> DoubleColumnChar -> Bool
46+horizConcatDwAssoc (DoubleColumnChar c0) (DoubleColumnChar c1) (DoubleColumnChar c2) =
47+ (char defAttr c0 <|> char defAttr c1) <|> char defAttr c2
4848 ==
49− char def_attr c0 <|> (char def_attr c1 <|> char def_attr c2)
49+ char defAttr c0 <|> (char defAttr c1 <|> char defAttr c2)
5050
51−vert_contat_single_row :: NonEmptyList SingleRowSingleAttrImage -> Bool
52−vert_contat_single_row (NonEmpty stack) =
53− let expected_height :: Int = length stack
54− stack_image = vert_cat [ i | SingleRowSingleAttrImage { row_image = i } <- stack ]
55− in image_height stack_image == expected_height
51+vertContatSingleRow :: NonEmptyList SingleRowSingleAttrImage -> Bool
52+vertContatSingleRow (NonEmpty stack) =
53+ let expectedHeight :: Int = length stack
54+ stackImage = vertCat [ i | SingleRowSingleAttrImage { rowImage = i } <- stack ]
55+ in imageHeight stackImage == expectedHeight
5656
57−disjoint_height_horiz_join :: NonEmptyList SingleRowSingleAttrImage
57+disjointHeightHorizJoin :: NonEmptyList SingleRowSingleAttrImage
5858 -> NonEmptyList SingleRowSingleAttrImage
5959 -> Bool
60−disjoint_height_horiz_join (NonEmpty stack_0) (NonEmpty stack_1) =
61− let expected_height :: Int = max (length stack_0) (length stack_1)
62− stack_image_0 = vert_cat [ i | SingleRowSingleAttrImage { row_image = i } <- stack_0 ]
63− stack_image_1 = vert_cat [ i | SingleRowSingleAttrImage { row_image = i } <- stack_1 ]
64− in image_height (stack_image_0 <|> stack_image_1) == expected_height
60+disjointHeightHorizJoin (NonEmpty stack_0) (NonEmpty stack_1) =
61+ let expectedHeight :: Int = max (length stack_0) (length stack_1)
62+ stackImage0 = vertCat [ i | SingleRowSingleAttrImage { rowImage = i } <- stack_0 ]
63+ stackImage1 = vertCat [ i | SingleRowSingleAttrImage { rowImage = i } <- stack_1 ]
64+ in imageHeight (stackImage0 <|> stackImage1) == expectedHeight
6565
6666
67−disjoint_height_horiz_join_bg_fill :: NonEmptyList SingleRowSingleAttrImage
67+disjointHeightHorizJoinBgFill :: NonEmptyList SingleRowSingleAttrImage
6868 -> NonEmptyList SingleRowSingleAttrImage
6969 -> Bool
70−disjoint_height_horiz_join_bg_fill (NonEmpty stack_0) (NonEmpty stack_1) =
71− let stack_image_0 = vert_cat [ i | SingleRowSingleAttrImage { row_image = i } <- stack_0 ]
72− stack_image_1 = vert_cat [ i | SingleRowSingleAttrImage { row_image = i } <- stack_1 ]
73− image = stack_image_0 <|> stack_image_1
74− expected_height = image_height image
70+disjointHeightHorizJoinBgFill (NonEmpty stack_0) (NonEmpty stack_1) =
71+ let stackImage0 = vertCat [ i | SingleRowSingleAttrImage { rowImage = i } <- stack_0 ]
72+ stackImage1 = vertCat [ i | SingleRowSingleAttrImage { rowImage = i } <- stack_1 ]
73+ image = stackImage0 <|> stackImage1
74+ expectedHeight = imageHeight image
7575 in case image of
76− HorizJoin {} -> ( expected_height == (image_height $ part_left image) )
76+ HorizJoin {} -> ( expectedHeight == (imageHeight $ partLeft image) )
7777 &&
78− ( expected_height == (image_height $ part_right image) )
78+ ( expectedHeight == (imageHeight $ partRight image) )
7979 _ -> True
8080
81−disjoint_width_vert_join :: NonEmptyList SingleRowSingleAttrImage
81+disjointWidthVertJoin :: NonEmptyList SingleRowSingleAttrImage
82+ -> NonEmptyList SingleRowSingleAttrImage
83+ -> Bool
84+disjointWidthVertJoin (NonEmpty stack_0) (NonEmpty stack_1) =
85+ let expectedWidth = maximum $ map imageWidth (stack0Images ++ stack1Images)
86+ stack0Images = [ i | SingleRowSingleAttrImage { rowImage = i } <- stack_0 ]
87+ stack1Images = [ i | SingleRowSingleAttrImage { rowImage = i } <- stack_1 ]
88+ stack0Image = vertCat stack0Images
89+ stack1Image = vertCat stack1Images
90+ image = stack0Image <-> stack1Image
91+ in imageWidth image == expectedWidth
92+
93+disjointWidthVertJoinBgFill :: NonEmptyList SingleRowSingleAttrImage
8294 -> NonEmptyList SingleRowSingleAttrImage
8395 -> Bool
84−disjoint_width_vert_join (NonEmpty stack_0) (NonEmpty stack_1) =
85− let expected_width = maximum $ map image_width (stack_0_images ++ stack_1_images)
86− stack_0_images = [ i | SingleRowSingleAttrImage { row_image = i } <- stack_0 ]
87− stack_1_images = [ i | SingleRowSingleAttrImage { row_image = i } <- stack_1 ]
88− stack_0_image = vert_cat stack_0_images
89− stack_1_image = vert_cat stack_1_images
90− image = stack_0_image <-> stack_1_image
91− in image_width image == expected_width
92−
93−disjoint_width_vert_join_bg_fill :: NonEmptyList SingleRowSingleAttrImage
94− -> NonEmptyList SingleRowSingleAttrImage
95− -> Bool
96−disjoint_width_vert_join_bg_fill (NonEmpty stack_0) (NonEmpty stack_1) =
97− let expected_width = maximum $ map image_width (stack_0_images ++ stack_1_images)
98− stack_0_images = [ i | SingleRowSingleAttrImage { row_image = i } <- stack_0 ]
99− stack_1_images = [ i | SingleRowSingleAttrImage { row_image = i } <- stack_1 ]
100− stack_0_image = vert_cat stack_0_images
101− stack_1_image = vert_cat stack_1_images
102− image = stack_0_image <-> stack_1_image
96+disjointWidthVertJoinBgFill (NonEmpty stack_0) (NonEmpty stack_1) =
97+ let expectedWidth = maximum $ map imageWidth (stack0Images ++ stack1Images)
98+ stack0Images = [ i | SingleRowSingleAttrImage { rowImage = i } <- stack_0 ]
99+ stack1Images = [ i | SingleRowSingleAttrImage { rowImage = i } <- stack_1 ]
100+ stack0Image = vertCat stack0Images
101+ stack1Image = vertCat stack1Images
102+ image = stack0Image <-> stack1Image
103103 in case image of
104− VertJoin {} -> ( expected_width == (image_width $ part_top image) )
104+ VertJoin {} -> ( expectedWidth == (imageWidth $ partTop image) )
105105 &&
106− ( expected_width == (image_width $ part_bottom image) )
106+ ( expectedWidth == (imageWidth $ partBottom image) )
107107 _ -> True
108108
109−translation_is_linear_on_out_size :: Translation -> Bool
110−translation_is_linear_on_out_size (Translation i (x,y) i') =
111− image_width i' == image_width i + x && image_height i' == image_height i + y
109+translationIsLinearOnOutSize :: Translation -> Bool
110+translationIsLinearOnOutSize (Translation i (x,y) i') =
111+ imageWidth i' == imageWidth i + x && imageHeight i' == imageHeight i + y
112112
113−padding_is_linear_on_out_size :: Image -> Gen Bool
114−padding_is_linear_on_out_size i = do
113+paddingIsLinearOnOutSize :: Image -> Gen Bool
114+paddingIsLinearOnOutSize i = do
115115 l <- offset
116116 t <- offset
117117 r <- offset
118118 b <- offset
119119 let i' = pad l t r b i
120− return $ image_width i' == image_width i + l + r && image_height i' == image_height i + t + b
120+ return $ imageWidth i' == imageWidth i + l + r && imageHeight i' == imageHeight i + t + b
121121 where offset = choose (1,1024)
122122
123−crop_left_limits_width :: Image -> Int -> Property
124−crop_left_limits_width i v = v >= 0 ==>
125− v >= image_width (crop_left v i)
123+cropLeftLimitsWidth :: Image -> Int -> Property
124+cropLeftLimitsWidth i v = v >= 0 ==>
125+ v >= imageWidth (cropLeft v i)
126126
127−crop_right_limits_width :: Image -> Int -> Property
128−crop_right_limits_width i v = v >= 0 ==>
129− v >= image_width (crop_right v i)
127+cropRightLimitsWidth :: Image -> Int -> Property
128+cropRightLimitsWidth i v = v >= 0 ==>
129+ v >= imageWidth (cropRight v i)
130130
131−crop_top_limits_height :: Image -> Int -> Property
132−crop_top_limits_height i v = v >= 0 ==>
133− v >= image_height (crop_top v i)
131+cropTopLimitsHeight :: Image -> Int -> Property
132+cropTopLimitsHeight i v = v >= 0 ==>
133+ v >= imageHeight (cropTop v i)
134134
135−crop_bottom_limits_height :: Image -> Int -> Property
136−crop_bottom_limits_height i v = v >= 0 ==>
137− v >= image_height (crop_bottom v i)
135+cropBottomLimitsHeight :: Image -> Int -> Property
136+cropBottomLimitsHeight i v = v >= 0 ==>
137+ v >= imageHeight (cropBottom v i)
138138
139139-- rediculous tests just to satisfy my desire for nice code coverage :-P
140−can_show_image :: Image -> Bool
141−can_show_image i = length (show i) > 0
140+canShowImage :: Image -> Bool
141+canShowImage i = length (show i) > 0
142142
143−can_rnf_image :: Image -> Bool
144−can_rnf_image i = rnf i == ()
143+canRnfImage :: Image -> Bool
144+canRnfImage i = rnf i == ()
145145
146−can_pp_image :: Image -> Bool
147−can_pp_image i = length (pp_image_structure i) > 0
146+canPpImage :: Image -> Bool
147+canPpImage i = length (pp_image_structure i) > 0
148148
149149tests :: IO [Test]
150150tests = return
151− [ verify "two_sw_horiz_concat" two_sw_horiz_concat
152− , verify "many_sw_horiz_concat" many_sw_horiz_concat
153− , verify "two_sw_vert_concat" two_sw_vert_concat
154− , verify "horiz_concat_sw_assoc" horiz_concat_sw_assoc
155− , verify "many_dw_horiz_concat" many_dw_horiz_concat
156− , verify "two_dw_horiz_concat" two_dw_horiz_concat
157− , verify "two_dw_vert_concat" two_dw_vert_concat
158− , verify "horiz_concat_dw_assoc" horiz_concat_dw_assoc
159− , verify "single row vert concats to correct height" vert_contat_single_row
160− , verify "disjoint_height_horiz_join" disjoint_height_horiz_join
161− , verify "disjoint_height_horiz_join BG fill" disjoint_height_horiz_join_bg_fill
162− , verify "disjoint_width_vert_join" disjoint_width_vert_join
163− , verify "disjoint_width_vert_join BG fill" disjoint_width_vert_join_bg_fill
164− , verify "translation effects output dimensions linearly" translation_is_linear_on_out_size
165− , verify "padding effects output dimensions linearly" padding_is_linear_on_out_size
166− , verify "crop left limits width" crop_left_limits_width
167− , verify "crop right limits width" crop_right_limits_width
168− , verify "crop top limits height" crop_top_limits_height
169− , verify "crop bottom limits height" crop_bottom_limits_height
170− , verify "can show image" can_show_image
171− , verify "can rnf image" can_rnf_image
172− , verify "can pp image" can_pp_image
151+ [ verify "twoSwHorizConcat" twoSwHorizConcat
152+ , verify "manySwHorizConcat" manySwHorizConcat
153+ , verify "twoSwVertConcat" twoSwVertConcat
154+ , verify "horizConcatSwAssoc" horizConcatSwAssoc
155+ , verify "manyDwHorizConcat" manyDwHorizConcat
156+ , verify "twoDwHorizConcat" twoDwHorizConcat
157+ , verify "twoDwVertConcat" twoDwVertConcat
158+ , verify "horizConcatDwAssoc" horizConcatDwAssoc
159+ , verify "single row vert concats to correct height" vertContatSingleRow
160+ , verify "disjointHeightHorizJoin" disjointHeightHorizJoin
161+ , verify "disjointHeightHorizJoin BG fill" disjointHeightHorizJoinBgFill
162+ , verify "disjointWidthVertJoin" disjointWidthVertJoin
163+ , verify "disjointWidthVertJoin BG fill" disjointWidthVertJoinBgFill
164+ , verify "translation effects output dimensions linearly" translationIsLinearOnOutSize
165+ , verify "padding effects output dimensions linearly" paddingIsLinearOnOutSize
166+ , verify "crop left limits width" cropLeftLimitsWidth
167+ , verify "crop right limits width" cropRightLimitsWidth
168+ , verify "crop top limits height" cropTopLimitsHeight
169+ , verify "crop bottom limits height" cropBottomLimitsHeight
170+ , verify "can show image" canShowImage
171+ , verify "can rnf image" canRnfImage
172+ , verify "can pp image" canPpImage
173173 ]
174174
test/VerifyImageTrans.hs+17−17
@@ -9,26 +9,26 @@ import Verify
99
1010import Data.Word
1111
12−is_horiz_text_of_columns :: Image -> Int -> Bool
13−is_horiz_text_of_columns (HorizText { output_width = in_w }) expected_w = in_w == expected_w
14−is_horiz_text_of_columns (BGFill { output_width = in_w }) expected_w = in_w == expected_w
15−is_horiz_text_of_columns _image _expected_w = False
16−
17−verify_horiz_contat_wo_attr_change_simplifies :: SingleRowSingleAttrImage -> Bool
18−verify_horiz_contat_wo_attr_change_simplifies (SingleRowSingleAttrImage _attr char_count image) =
19− is_horiz_text_of_columns image char_count
20−
21−verify_horiz_contat_w_attr_change_simplifies :: SingleRowTwoAttrImage -> Bool
22−verify_horiz_contat_w_attr_change_simplifies ( SingleRowTwoAttrImage (SingleRowSingleAttrImage attr0 char_count0 _image0)
23− (SingleRowSingleAttrImage attr1 char_count1 _image1)
24− i
12+isHorizTextOfColumns :: Image -> Int -> Bool
13+isHorizTextOfColumns (HorizText { outputWidth = inW }) expectedW = inW == expectedW
14+isHorizTextOfColumns (BGFill { outputWidth = inW }) expectedW = inW == expectedW
15+isHorizTextOfColumns _image _expectedW = False
16+
17+verifyHorizContatWoAttrChangeSimplifies :: SingleRowSingleAttrImage -> Bool
18+verifyHorizContatWoAttrChangeSimplifies (SingleRowSingleAttrImage _attr charCount image) =
19+ isHorizTextOfColumns image charCount
20+
21+verifyHorizContatWAttrChangeSimplifies :: SingleRowTwoAttrImage -> Bool
22+verifyHorizContatWAttrChangeSimplifies ( SingleRowTwoAttrImage (SingleRowSingleAttrImage attr0 charCount0 _image0)
23+ (SingleRowSingleAttrImage attr1 charCount1 _image1)
24+ i
2525 )
26− | char_count0 == 0 || char_count1 == 0 || attr0 == attr1 = is_horiz_text_of_columns i (char_count0 + char_count1)
27− | otherwise = False == is_horiz_text_of_columns i (char_count0 + char_count1)
26+ | charCount0 == 0 || charCount1 == 0 || attr0 == attr1 = isHorizTextOfColumns i (charCount0 + charCount1)
27+ | otherwise = False == isHorizTextOfColumns i (charCount0 + charCount1)
2828
2929tests :: IO [Test]
3030tests = return
31− [ verify "verify_horiz_contat_wo_attr_change_simplifies" verify_horiz_contat_wo_attr_change_simplifies
32− , verify "verify_horiz_contat_w_attr_change_simplifies" verify_horiz_contat_w_attr_change_simplifies
31+ [ verify "verifyHorizContatWoAttrChangeSimplifies" verifyHorizContatWoAttrChangeSimplifies
32+ , verify "verifyHorizContatWAttrChangeSimplifies" verifyHorizContatWAttrChangeSimplifies
3333 ]
3434
test/VerifyInline.hs+2−2
@@ -13,13 +13,13 @@ import Distribution.TestSuite
1313import System.IO
1414
1515tests :: IO [Test]
16−tests = concat <$> forM terminals_of_interest (\term_name -> return $
16+tests = concat <$> forM terminalsOfInterest (\termName -> return $
1717 [ Test $ TestInstance
1818 { name = "verify vty inline"
1919 , run = do
2020 {- disabled because I cannot get useful output out of cabal why this fails.
2121 null_out <- openFile "/dev/null" WriteMode
22− t <- TerminfoBased.reserve_terminal term_name null_out
22+ t <- TerminfoBased.reserve_terminal termName null_out
2323 put_attr_change t $ default_all
2424 release_terminal t
2525 -}
test/VerifyLayersSpanGeneration.hs+87−87
@@ -15,114 +15,114 @@ import Verify
1515
1616import qualified Data.Vector as Vector
1717
18−larger_horiz_span_occlusion :: SingleRowSingleAttrImage -> SingleRowSingleAttrImage -> Result
19−larger_horiz_span_occlusion row_0 row_1 =
20− let i_0 = row_image row_0
21− i_1 = row_image row_1
22− (i_larger, i_smaller) = if image_width i_0 > image_width i_1 then (i_0, i_1) else (i_1, i_0)
23− expected_ops = display_ops_for_image i_larger
24− p = pic_for_layers [i_larger, i_smaller]
25− ops = display_ops_for_pic p (image_width i_larger,image_height i_larger)
26− in verify_ops_equality expected_ops ops
18+largerHorizSpanOcclusion :: SingleRowSingleAttrImage -> SingleRowSingleAttrImage -> Result
19+largerHorizSpanOcclusion row0 row1 =
20+ let i0 = rowImage row0
21+ i1 = rowImage row1
22+ (iLarger, iSmaller) = if imageWidth i0 > imageWidth i1 then (i0, i1) else (i1, i0)
23+ expectedOps = displayOpsForImage iLarger
24+ p = picForLayers [iLarger, iSmaller]
25+ ops = displayOpsForPic p (imageWidth iLarger,imageHeight iLarger)
26+ in verifyOpsEquality expectedOps ops
2727
2828-- | Two rows stacked vertical is equivalent to the first row rendered as the top layer and the
2929-- second row rendered as a bottom layer with a background fill where the first row would be.
30−vert_stack_layer_equivalence_0 :: SingleRowSingleAttrImage -> SingleRowSingleAttrImage -> Result
31−vert_stack_layer_equivalence_0 row_0 row_1 =
32− let i_0 = row_image row_0
33− i_1 = row_image row_1
34− i = i_0 <-> i_1
35− p = pic_for_image i
36− i_lower = background_fill (image_width i_0) 1 <-> i_1
37− p_layered = pic_for_layers [i_0, i_lower]
38− expected_ops = display_ops_for_image i
39− ops_layered = display_ops_for_pic p_layered (image_width i_lower,image_height i_lower)
40− in verify_ops_equality expected_ops ops_layered
30+vertStackLayerEquivalence0 :: SingleRowSingleAttrImage -> SingleRowSingleAttrImage -> Result
31+vertStackLayerEquivalence0 row0 row1 =
32+ let i0 = rowImage row0
33+ i1 = rowImage row1
34+ i = i0 <-> i1
35+ p = picForImage i
36+ iLower = backgroundFill (imageWidth i0) 1 <-> i1
37+ pLayered = picForLayers [i0, iLower]
38+ expectedOps = displayOpsForImage i
39+ opsLayered = displayOpsForPic pLayered (imageWidth iLower,imageHeight iLower)
40+ in verifyOpsEquality expectedOps opsLayered
4141
42−vert_stack_layer_equivalence_1 :: SingleRowSingleAttrImage -> SingleRowSingleAttrImage -> Result
43−vert_stack_layer_equivalence_1 row_0 row_1 =
44− let i_0 = row_image row_0
45− i_1 = row_image row_1
46− i = i_0 <-> i_1
47− p = pic_for_image i
48− i_lower = i_0 <-> background_fill (image_width i_1) 1
49− i_upper = background_fill (image_width i_0) 1 <-> i_1
50− p_layered = pic_for_layers [i_upper, i_lower]
51− expected_ops = display_ops_for_image i
52− ops_layered = display_ops_for_pic p_layered (image_width i_lower,image_height i_lower)
53− in verify_ops_equality expected_ops ops_layered
42+vertStackLayerEquivalence1 :: SingleRowSingleAttrImage -> SingleRowSingleAttrImage -> Result
43+vertStackLayerEquivalence1 row0 row1 =
44+ let i0 = rowImage row0
45+ i1 = rowImage row1
46+ i = i0 <-> i1
47+ p = picForImage i
48+ iLower = i0 <-> backgroundFill (imageWidth i1) 1
49+ iUpper = backgroundFill (imageWidth i0) 1 <-> i1
50+ pLayered = picForLayers [iUpper, iLower]
51+ expectedOps = displayOpsForImage i
52+ opsLayered = displayOpsForPic pLayered (imageWidth iLower,imageHeight iLower)
53+ in verifyOpsEquality expectedOps opsLayered
5454
5555-- | Two rows horiz joined is equivalent to the first row rendered as the top layer and the
5656-- second row rendered as a bottom layer with a background fill where the first row would be.
57−horiz_join_layer_equivalence_0 :: SingleRowSingleAttrImage -> SingleRowSingleAttrImage -> Result
58−horiz_join_layer_equivalence_0 row_0 row_1 =
59− let i_0 = row_image row_0
60− i_1 = row_image row_1
61− i = i_0 <|> i_1
62− p = pic_for_image i
63− i_lower = background_fill (image_width i_0) 1 <|> i_1
64− p_layered = pic_for_layers [i_0, i_lower]
65− expected_ops = display_ops_for_image i
66− ops_layered = display_ops_for_pic p_layered (image_width i_lower,image_height i_lower)
67− in verify_ops_equality expected_ops ops_layered
57+horizJoinLayerEquivalence0 :: SingleRowSingleAttrImage -> SingleRowSingleAttrImage -> Result
58+horizJoinLayerEquivalence0 row0 row1 =
59+ let i0 = rowImage row0
60+ i1 = rowImage row1
61+ i = i0 <|> i1
62+ p = picForImage i
63+ iLower = backgroundFill (imageWidth i0) 1 <|> i1
64+ pLayered = picForLayers [i0, iLower]
65+ expectedOps = displayOpsForImage i
66+ opsLayered = displayOpsForPic pLayered (imageWidth iLower,imageHeight iLower)
67+ in verifyOpsEquality expectedOps opsLayered
6868
69−horiz_join_layer_equivalence_1 :: SingleRowSingleAttrImage -> SingleRowSingleAttrImage -> Result
70−horiz_join_layer_equivalence_1 row_0 row_1 =
71− let i_0 = row_image row_0
72− i_1 = row_image row_1
73− i = i_0 <|> i_1
74− p = pic_for_image i
75− i_lower = i_0 <|> background_fill (image_width i_1) 1
76− i_upper = background_fill (image_width i_0) 1 <|> i_1
77− p_layered = pic_for_layers [i_upper, i_lower]
78− expected_ops = display_ops_for_image i
79− ops_layered = display_ops_for_pic p_layered (image_width i_lower,image_height i_lower)
80− in verify_ops_equality expected_ops ops_layered
69+horizJoinLayerEquivalence1 :: SingleRowSingleAttrImage -> SingleRowSingleAttrImage -> Result
70+horizJoinLayerEquivalence1 row0 row1 =
71+ let i0 = rowImage row0
72+ i1 = rowImage row1
73+ i = i0 <|> i1
74+ p = picForImage i
75+ iLower = i0 <|> backgroundFill (imageWidth i1) 1
76+ iUpper = backgroundFill (imageWidth i0) 1 <|> i1
77+ pLayered = picForLayers [iUpper, iLower]
78+ expectedOps = displayOpsForImage i
79+ opsLayered = displayOpsForPic pLayered (imageWidth iLower,imageHeight iLower)
80+ in verifyOpsEquality expectedOps opsLayered
8181
82−horiz_join_alternate_0 :: Result
83−horiz_join_alternate_0 =
82+horizJoinAlternate0 :: Result
83+horizJoinAlternate0 =
8484 let size = 4
85− str_0 = replicate size 'a'
86− str_1 = replicate size 'b'
87− i_0 = string def_attr str_0
88− i_1 = string def_attr str_1
89− i = horiz_cat $ zipWith horiz_join (replicate size i_0) (replicate size i_1)
90− layer_0 = horiz_cat $ replicate size $ i_0 <|> background_fill size 1
91− layer_1 = horiz_cat $ replicate size $ background_fill size 1 <|> i_1
92− expected_ops = display_ops_for_image i
93− ops_layered = display_ops_for_pic (pic_for_layers [layer_0, layer_1])
94− (image_width i,image_height i)
95− in verify_ops_equality expected_ops ops_layered
85+ str0 = replicate size 'a'
86+ str1 = replicate size 'b'
87+ i0 = string defAttr str0
88+ i1 = string defAttr str1
89+ i = horizCat $ zipWith horizJoin (replicate size i0) (replicate size i1)
90+ layer0 = horizCat $ replicate size $ i0 <|> backgroundFill size 1
91+ layer1 = horizCat $ replicate size $ backgroundFill size 1 <|> i1
92+ expectedOps = displayOpsForImage i
93+ opsLayered = displayOpsForPic (picForLayers [layer0, layer1])
94+ (imageWidth i,imageHeight i)
95+ in verifyOpsEquality expectedOps opsLayered
9696
97−horiz_join_alternate_1 :: Result
98−horiz_join_alternate_1 =
97+horizJoinAlternate1 :: Result
98+horizJoinAlternate1 =
9999 let size = 4
100− str_0 = replicate size 'a'
101− str_1 = replicate size 'b'
102− i_0 = string def_attr str_0
103− i_1 = string def_attr str_1
104− i = horiz_cat $ zipWith horiz_join (replicate size i_0) (replicate size i_1)
105− layers = [l | b <- take 4 [0,size*2..], let l = background_fill b 1 <|> i_0 <|> i_1]
106− expected_ops = display_ops_for_image i
107− ops_layered = display_ops_for_pic (pic_for_layers layers)
108− (image_width i,image_height i)
109− in verify_ops_equality expected_ops ops_layered
100+ str0 = replicate size 'a'
101+ str1 = replicate size 'b'
102+ i0 = string defAttr str0
103+ i1 = string defAttr str1
104+ i = horizCat $ zipWith horizJoin (replicate size i0) (replicate size i1)
105+ layers = [l | b <- take 4 [0,size*2..], let l = backgroundFill b 1 <|> i0 <|> i1]
106+ expectedOps = displayOpsForImage i
107+ opsLayered = displayOpsForPic (picForLayers layers)
108+ (imageWidth i,imageHeight i)
109+ in verifyOpsEquality expectedOps opsLayered
110110
111111tests :: IO [Test]
112112tests = return
113113 [ verify "a larger horiz span occludes a smaller span on a lower layer"
114− larger_horiz_span_occlusion
114+ largerHorizSpanOcclusion
115115 , verify "two rows stack vertical equiv to first image layered on top of second with padding (0)"
116− vert_stack_layer_equivalence_0
116+ vertStackLayerEquivalence0
117117 , verify "two rows stack vertical equiv to first image layered on top of second with padding (1)"
118− vert_stack_layer_equivalence_1
118+ vertStackLayerEquivalence1
119119 -- , verify "two rows horiz joined equiv to first image layered on top of second with padding (0)"
120− -- horiz_join_layer_equivalence_0
120+ -- horizJoinLayerEquivalence0
121121 -- , verify "two rows horiz joined equiv to first image layered on top of second with padding (1)"
122− -- horiz_join_layer_equivalence_1
122+ -- horizJoinLayerEquivalence1
123123 -- , verify "alternating images using joins is the same as alternating images using layers (0)"
124− -- horiz_join_alternate_0
124+ -- horizJoinAlternate0
125125 -- , verify "alternating images using joins is the same as alternating images using layers (1)"
126− -- horiz_join_alternate_1
126+ -- horizJoinAlternate1
127127 ]
128128
test/VerifyOutput.hs+29−29
@@ -17,47 +17,47 @@ import System.Posix.Env
1717import System.IO
1818
1919tests :: IO [Test]
20−tests = concat <$> forM terminals_of_interest (\term_name -> do
20+tests = concat <$> forM terminalsOfInterest (\termName -> do
2121 -- check if that terminfo exists
22− putStrLn $ "testing end to end for terminal: " ++ term_name
23− mti <- try $ Terminfo.setupTerm term_name
22+ putStrLn $ "testing end to end for terminal: " ++ termName
23+ mti <- try $ Terminfo.setupTerm termName
2424 case mti of
2525 Left (_ :: SomeException) -> return []
26− Right _ -> return [ verify ("verify " ++ term_name ++ " could output a picture")
27− (smoke_test_term_non_mac term_name)
26+ Right _ -> return [ verify ("verify " ++ termName ++ " could output a picture")
27+ (smokeTestTermNonMac termName)
2828 -- this is excessive.
29− , verify ("verify " ++ term_name ++ " could output a picture on a Mac.")
30− (smoke_test_term_mac term_name)
29+ , verify ("verify " ++ termName ++ " could output a picture on a Mac.")
30+ (smokeTestTermMac termName)
3131 ]
3232 )
3333
34−smoke_test_term_non_mac :: String -> Image -> Property
35−smoke_test_term_non_mac term_name i = liftIOResult $ do
34+smokeTestTermNonMac :: String -> Image -> Property
35+smokeTestTermNonMac termName i = liftIOResult $ do
3636 -- unset the TERM_PROGRAM environment variable if set.
3737 -- Required to execute regression test for #42 on a mac
3838 unsetEnv "TERM_PROGRAM"
39− smoke_test_term term_name i
39+ smokeTestTerm termName i
4040
41−smoke_test_term_mac :: String -> Image -> Property
42−smoke_test_term_mac term_name i = liftIOResult $ do
41+smokeTestTermMac :: String -> Image -> Property
42+smokeTestTermMac termName i = liftIOResult $ do
4343 setEnv "TERM_PROGRAM" "Apple_Terminal" True
44− smoke_test_term term_name i
45−
46−smoke_test_term :: String -> Image -> IO Result
47−smoke_test_term term_name i = do
48− null_out <- openFile "/dev/null" WriteMode
49− t <- output_for_name_and_io term_name null_out
50− putStrLn $ "context color count: " ++ show (context_color_count t)
51− reserve_display t
52− dc <- display_context t (100,100)
44+ smokeTestTerm termName i
45+
46+smokeTestTerm :: String -> Image -> IO Result
47+smokeTestTerm termName i = do
48+ nullOut <- openFile "/dev/null" WriteMode
49+ t <- outputForNameAndIO termName nullOut
50+ putStrLn $ "context color count: " ++ show (contextColorCount t)
51+ reserveDisplay t
52+ dc <- displayContext t (100,100)
5353 -- always show the cursor to produce tests for terminals with no cursor support.
54− let pic = (pic_for_image i) { pic_cursor = Cursor 0 0 }
55− output_picture dc pic
56− set_cursor_pos t 0 0
57− when (supports_cursor_visibility t) $ do
58− hide_cursor t
59− show_cursor t
60− release_display t
61− release_terminal t
54+ let pic = (picForImage i) { picCursor = Cursor 0 0 }
55+ outputPicture dc pic
56+ setCursorPos t 0 0
57+ when (supportsCursorVisibility t) $ do
58+ hideCursor t
59+ showCursor t
60+ releaseDisplay t
61+ releaseTerminal t
6262 return succeeded
6363
test/VerifyParseTerminfoCaps.hs+45−45
@@ -16,7 +16,7 @@ import Numeric
1616
1717-- If a terminal defines one of the caps then it's expected to be parsable.
1818-- TODO: reduce duplication with terminfo terminal implementation.
19−caps_of_interest =
19+capsOfInterest =
2020 [ "cup"
2121 , "sc"
2222 , "rc"
@@ -36,66 +36,66 @@ caps_of_interest =
3636 , "sgr0"
3737 ]
3838
39−from_capname ti name = fromJust $ Terminfo.getCapability ti (Terminfo.tiGetStr name)
39+fromCapname ti name = fromJust $ Terminfo.getCapability ti (Terminfo.tiGetStr name)
4040
4141tests :: IO [Test]
4242tests = do
43− parse_tests <- concat <$> forM terminals_of_interest (\term_name ->
44− liftIO (try $ Terminfo.setupTerm term_name)
43+ parseTests <- concat <$> forM terminalsOfInterest (\termName ->
44+ liftIO (try $ Terminfo.setupTerm termName)
4545 >>= either (\(_e :: SomeException) -> return [])
46− (\ti -> concat <$> forM caps_of_interest (\cap_name -> do
47− let case_name = "\tparsing cap: " ++ cap_name
48− liftIO $ putStrLn case_name
49− return $ case Terminfo.getCapability ti (Terminfo.tiGetStr cap_name) of
50− Just cap_def -> [verify (case_name ++ " -> " ++ show cap_def)
51− (verify_parse_cap cap_def $ const succeeded)]
46+ (\ti -> concat <$> forM capsOfInterest (\capName -> do
47+ let caseName = "\tparsing cap: " ++ capName
48+ liftIO $ putStrLn caseName
49+ return $ case Terminfo.getCapability ti (Terminfo.tiGetStr capName) of
50+ Just capDef -> [verify (caseName ++ " -> " ++ show capDef)
51+ (verifyParseCap capDef $ const succeeded)]
5252 Nothing -> []
5353 )
5454 )
5555 )
56− return $ [ verify "parse_non_paramaterized_caps" non_paramaterized_caps
57− , verify "parse cap string with literal %" literal_percent_caps
58− , verify "parse cap string with %i op" inc_first_two_caps
59− , verify "parse cap string with %pN op" push_param_caps
60− ] ++ parse_tests
61−
62−verify_parse_cap cap_string on_parse =
63− case parse_cap_expression cap_string of
56+ return $ [ verify "parse_nonParamaterizedCaps" nonParamaterizedCaps
57+ , verify "parse cap string with literal %" literalPercentCaps
58+ , verify "parse cap string with %i op" incFirstTwoCaps
59+ , verify "parse cap string with %pN op" pushParamCaps
60+ ] ++ parseTests
61+
62+verifyParseCap capString onParse =
63+ case parseCapExpression capString of
6464 Left error -> failed { reason = "parse error " ++ show error }
65− Right e -> on_parse e
65+ Right e -> onParse e
6666
67−non_paramaterized_caps (NonParamCapString cap) = do
68− verify_parse_cap cap $ \e ->
69− let expected_bytes = map (toEnum . fromEnum) cap
70− out_bytes = bytes_for_range e 0 (length cap)
71− in verify_bytes_equal out_bytes expected_bytes
67+nonParamaterizedCaps (NonParamCapString cap) = do
68+ verifyParseCap cap $ \e ->
69+ let expectedBytes = map (toEnum . fromEnum) cap
70+ outBytes = bytesForRange e 0 (length cap)
71+ in verifyBytesEqual outBytes expectedBytes
7272
73−literal_percent_caps (LiteralPercentCap cap_string expected_bytes) = do
74− verify_parse_cap cap_string $ \e -> verify_bytes_equal (collect_bytes e) expected_bytes
73+literalPercentCaps (LiteralPercentCap capString expectedBytes) = do
74+ verifyParseCap capString $ \e -> verifyBytesEqual (collectBytes e) expectedBytes
7575
76−inc_first_two_caps (IncFirstTwoCap cap_string expected_bytes) = do
77− verify_parse_cap cap_string $ \e -> verify_bytes_equal (collect_bytes e) expected_bytes
76+incFirstTwoCaps (IncFirstTwoCap capString expectedBytes) = do
77+ verifyParseCap capString $ \e -> verifyBytesEqual (collectBytes e) expectedBytes
7878
79−push_param_caps (PushParamCap cap_string expected_param_count expected_bytes) = do
80− verify_parse_cap cap_string $ \e ->
81− let out_bytes = collect_bytes e
82− out_param_count = param_count e
83− in if out_param_count == expected_param_count
84− then verify_bytes_equal out_bytes expected_bytes
79+pushParamCaps (PushParamCap capString expectedParamCount expectedBytes) = do
80+ verifyParseCap capString $ \e ->
81+ let outBytes = collectBytes e
82+ outParamCount = paramCount e
83+ in if outParamCount == expectedParamCount
84+ then verifyBytesEqual outBytes expectedBytes
8585 else failed { reason = "out param count /= expected param count" }
8686
87−dec_print_param_caps (DecPrintCap cap_string expected_param_count expected_bytes) = do
88− verify_parse_cap cap_string $ \e ->
89− let out_bytes = collect_bytes e
90− out_param_count = param_count e
91− in if out_param_count == expected_param_count
92− then verify_bytes_equal out_bytes expected_bytes
87+decPrintParamCaps (DecPrintCap capString expectedParamCount expectedBytes) = do
88+ verifyParseCap capString $ \e ->
89+ let outBytes = collectBytes e
90+ outParamCount = paramCount e
91+ in if outParamCount == expectedParamCount
92+ then verifyBytesEqual outBytes expectedBytes
9393 else failed { reason = "out param count /= expected param count" }
9494
95−print_cap ti cap_name = do
96− putStrLn $ cap_name ++ ": " ++ show (from_capname ti cap_name)
95+printCap ti capName = do
96+ putStrLn $ capName ++ ": " ++ show (fromCapname ti capName)
9797
98−print_expression ti cap_name = do
99− let parse_result = parse_cap_expression $ from_capname ti cap_name
100− putStrLn $ cap_name ++ ": " ++ show parse_result
98+printExpression ti capName = do
99+ let parseResult = parseCapExpression $ fromCapname ti capName
100+ putStrLn $ capName ++ ": " ++ show parseResult
101101
test/VerifySimpleSpanGeneration.hs+154−154
@@ -15,174 +15,174 @@ import Verify
1515
1616import qualified Data.Vector as Vector
1717
18−unit_image_and_zero_window_0 :: UnitImage -> EmptyWindow -> Bool
19−unit_image_and_zero_window_0 (UnitImage _ i) (EmptyWindow w) =
20− let p = pic_for_image i
21− ops = display_ops_for_pic p (region_for_window w)
22− in display_ops_columns ops == 0 && display_ops_rows ops == 0
23−
24−unit_image_and_zero_window_1 :: UnitImage -> EmptyWindow -> Bool
25−unit_image_and_zero_window_1 (UnitImage _ i) (EmptyWindow w) =
26− let p = pic_for_image i
27− ops = display_ops_for_pic p (region_for_window w)
28− in ( span_ops_effected_rows ops == 0 ) && ( all_spans_have_width ops 0 )
29−
30−horiz_span_image_and_zero_window_0 :: SingleRowSingleAttrImage -> EmptyWindow -> Bool
31−horiz_span_image_and_zero_window_0 (SingleRowSingleAttrImage { row_image = i }) (EmptyWindow w) =
32− let p = pic_for_image i
33− ops = display_ops_for_pic p (region_for_window w)
34− in display_ops_columns ops == 0 && display_ops_rows ops == 0
35−
36−horiz_span_image_and_zero_window_1 :: SingleRowSingleAttrImage -> EmptyWindow -> Bool
37−horiz_span_image_and_zero_window_1 (SingleRowSingleAttrImage { row_image = i }) (EmptyWindow w) =
38− let p = pic_for_image i
39− ops = display_ops_for_pic p (region_for_window w)
40− in ( span_ops_effected_rows ops == 0 ) && ( all_spans_have_width ops 0 )
41−
42−horiz_span_image_and_equal_window_0 :: SingleRowSingleAttrImage -> Result
43−horiz_span_image_and_equal_window_0 (SingleRowSingleAttrImage { row_image = i, expected_columns = c }) =
44− let p = pic_for_image i
18+unitImageAndZeroWindow0 :: UnitImage -> EmptyWindow -> Bool
19+unitImageAndZeroWindow0 (UnitImage _ i) (EmptyWindow w) =
20+ let p = picForImage i
21+ ops = displayOpsForPic p (regionForWindow w)
22+ in displayOpsColumns ops == 0 && displayOpsRows ops == 0
23+
24+unitImageAndZeroWindow1 :: UnitImage -> EmptyWindow -> Bool
25+unitImageAndZeroWindow1 (UnitImage _ i) (EmptyWindow w) =
26+ let p = picForImage i
27+ ops = displayOpsForPic p (regionForWindow w)
28+ in ( spanOpsEffectedRows ops == 0 ) && ( allSpansHaveWidth ops 0 )
29+
30+horizSpanImageAndZeroWindow0 :: SingleRowSingleAttrImage -> EmptyWindow -> Bool
31+horizSpanImageAndZeroWindow0 (SingleRowSingleAttrImage { rowImage = i }) (EmptyWindow w) =
32+ let p = picForImage i
33+ ops = displayOpsForPic p (regionForWindow w)
34+ in displayOpsColumns ops == 0 && displayOpsRows ops == 0
35+
36+horizSpanImageAndZeroWindow1 :: SingleRowSingleAttrImage -> EmptyWindow -> Bool
37+horizSpanImageAndZeroWindow1 (SingleRowSingleAttrImage { rowImage = i }) (EmptyWindow w) =
38+ let p = picForImage i
39+ ops = displayOpsForPic p (regionForWindow w)
40+ in ( spanOpsEffectedRows ops == 0 ) && ( allSpansHaveWidth ops 0 )
41+
42+horizSpanImageAndEqualWindow0 :: SingleRowSingleAttrImage -> Result
43+horizSpanImageAndEqualWindow0 (SingleRowSingleAttrImage { rowImage = i, expectedColumns = c }) =
44+ let p = picForImage i
4545 w = MockWindow c 1
46− ops = display_ops_for_pic p (region_for_window w)
47− in verify_all_spans_have_width i ops c
46+ ops = displayOpsForPic p (regionForWindow w)
47+ in verifyAllSpansHaveWidth i ops c
4848
49−horiz_span_image_and_equal_window_1 :: SingleRowSingleAttrImage -> Bool
50−horiz_span_image_and_equal_window_1 (SingleRowSingleAttrImage { row_image = i, expected_columns = c }) =
51− let p = pic_for_image i
49+horizSpanImageAndEqualWindow1 :: SingleRowSingleAttrImage -> Bool
50+horizSpanImageAndEqualWindow1 (SingleRowSingleAttrImage { rowImage = i, expectedColumns = c }) =
51+ let p = picForImage i
5252 w = MockWindow c 1
53− ops = display_ops_for_pic p (region_for_window w)
54− in span_ops_effected_rows ops == 1
55−
56−horiz_span_image_and_lesser_window_0 :: SingleRowSingleAttrImage -> Result
57−horiz_span_image_and_lesser_window_0 (SingleRowSingleAttrImage { row_image = i, expected_columns = c }) =
58− let p = pic_for_image i
59− lesser_width = c `div` 2
60− w = MockWindow lesser_width 1
61− ops = display_ops_for_pic p (region_for_window w)
62− in verify_all_spans_have_width i ops lesser_width
63−
64−single_attr_single_span_stack_cropped_0 :: SingleAttrSingleSpanStack -> Result
65−single_attr_single_span_stack_cropped_0 stack =
66− let p = pic_for_image (stack_image stack)
67− w = MockWindow (stack_width stack `div` 2) (stack_height stack)
68− ops = display_ops_for_pic p (region_for_window w)
69− in verify_all_spans_have_width (stack_image stack) ops (stack_width stack `div` 2)
70−
71−single_attr_single_span_stack_cropped_1 :: SingleAttrSingleSpanStack -> Bool
72−single_attr_single_span_stack_cropped_1 stack =
73− let p = pic_for_image (stack_image stack)
74− expected_row_count = stack_height stack `div` 2
75− w = MockWindow (stack_width stack) expected_row_count
76− ops = display_ops_for_pic p (region_for_window w)
77− actual_row_count = span_ops_effected_rows ops
78− in expected_row_count == actual_row_count
79−
80−single_attr_single_span_stack_cropped_2 :: SingleAttrSingleSpanStack -> SingleAttrSingleSpanStack -> Result
81−single_attr_single_span_stack_cropped_2 stack_0 stack_1 =
82− let p = pic_for_image (stack_image stack_0 <|> stack_image stack_1)
83− w = MockWindow (stack_width stack_0) (image_height (pic_image p))
84− ops = display_ops_for_pic p (region_for_window w)
85− in verify_all_spans_have_width (pic_image p) ops (stack_width stack_0)
86−
87−single_attr_single_span_stack_cropped_3 :: SingleAttrSingleSpanStack -> SingleAttrSingleSpanStack -> Bool
88−single_attr_single_span_stack_cropped_3 stack_0 stack_1 =
89− let p = pic_for_image (stack_image stack_0 <|> stack_image stack_1)
90− w = MockWindow (image_width (pic_image p)) expected_row_count
91− ops = display_ops_for_pic p (region_for_window w)
92− expected_row_count = image_height (pic_image p) `div` 2
93− actual_row_count = span_ops_effected_rows ops
94− in expected_row_count == actual_row_count
95−
96−single_attr_single_span_stack_cropped_4 :: SingleAttrSingleSpanStack -> SingleAttrSingleSpanStack -> Result
97−single_attr_single_span_stack_cropped_4 stack_0 stack_1 =
98− let p = pic_for_image (stack_image stack_0 <-> stack_image stack_1)
99− w = MockWindow expected_width (image_height (pic_image p))
100− ops = display_ops_for_pic p (region_for_window w)
101− expected_width = image_width (pic_image p) `div` 2
102− in verify_all_spans_have_width (pic_image p) ops expected_width
103−
104−single_attr_single_span_stack_cropped_5 :: SingleAttrSingleSpanStack -> SingleAttrSingleSpanStack -> Bool
105−single_attr_single_span_stack_cropped_5 stack_0 stack_1 =
106− let p = pic_for_image (stack_image stack_0 <-> stack_image stack_1)
107− w = MockWindow (image_width (pic_image p)) (stack_height stack_0)
108− ops = display_ops_for_pic p (region_for_window w)
109− expected_row_count = stack_height stack_0
110− actual_row_count = span_ops_effected_rows ops
111− in expected_row_count == actual_row_count
112−
113−horiz_span_image_and_greater_window_0 :: SingleRowSingleAttrImage -> Result
114−horiz_span_image_and_greater_window_0 (SingleRowSingleAttrImage { row_image = i, expected_columns = c }) =
115− let p = pic_for_image i
53+ ops = displayOpsForPic p (regionForWindow w)
54+ in spanOpsEffectedRows ops == 1
55+
56+horizSpanImageAndLesserWindow0 :: SingleRowSingleAttrImage -> Result
57+horizSpanImageAndLesserWindow0 (SingleRowSingleAttrImage { rowImage = i, expectedColumns = c }) =
58+ let p = picForImage i
59+ lesserWidth = c `div` 2
60+ w = MockWindow lesserWidth 1
61+ ops = displayOpsForPic p (regionForWindow w)
62+ in verifyAllSpansHaveWidth i ops lesserWidth
63+
64+singleAttrSingleSpanStackCropped0 :: SingleAttrSingleSpanStack -> Result
65+singleAttrSingleSpanStackCropped0 stack =
66+ let p = picForImage (stackImage stack)
67+ w = MockWindow (stackWidth stack `div` 2) (stackHeight stack)
68+ ops = displayOpsForPic p (regionForWindow w)
69+ in verifyAllSpansHaveWidth (stackImage stack) ops (stackWidth stack `div` 2)
70+
71+singleAttrSingleSpanStackCropped1 :: SingleAttrSingleSpanStack -> Bool
72+singleAttrSingleSpanStackCropped1 stack =
73+ let p = picForImage (stackImage stack)
74+ expectedRowCount = stackHeight stack `div` 2
75+ w = MockWindow (stackWidth stack) expectedRowCount
76+ ops = displayOpsForPic p (regionForWindow w)
77+ actualRowCount = spanOpsEffectedRows ops
78+ in expectedRowCount == actualRowCount
79+
80+singleAttrSingleSpanStackCropped2 :: SingleAttrSingleSpanStack -> SingleAttrSingleSpanStack -> Result
81+singleAttrSingleSpanStackCropped2 stack0 stack_1 =
82+ let p = picForImage (stackImage stack0 <|> stackImage stack_1)
83+ w = MockWindow (stackWidth stack0) (imageHeight (picImage p))
84+ ops = displayOpsForPic p (regionForWindow w)
85+ in verifyAllSpansHaveWidth (picImage p) ops (stackWidth stack0)
86+
87+singleAttrSingleSpanStackCropped3 :: SingleAttrSingleSpanStack -> SingleAttrSingleSpanStack -> Bool
88+singleAttrSingleSpanStackCropped3 stack0 stack_1 =
89+ let p = picForImage (stackImage stack0 <|> stackImage stack_1)
90+ w = MockWindow (imageWidth (picImage p)) expectedRowCount
91+ ops = displayOpsForPic p (regionForWindow w)
92+ expectedRowCount = imageHeight (picImage p) `div` 2
93+ actualRowCount = spanOpsEffectedRows ops
94+ in expectedRowCount == actualRowCount
95+
96+singleAttrSingleSpanStackCropped4 :: SingleAttrSingleSpanStack -> SingleAttrSingleSpanStack -> Result
97+singleAttrSingleSpanStackCropped4 stack0 stack_1 =
98+ let p = picForImage (stackImage stack0 <-> stackImage stack_1)
99+ w = MockWindow expectedWidth (imageHeight (picImage p))
100+ ops = displayOpsForPic p (regionForWindow w)
101+ expectedWidth = imageWidth (picImage p) `div` 2
102+ in verifyAllSpansHaveWidth (picImage p) ops expectedWidth
103+
104+singleAttrSingleSpanStackCropped5 :: SingleAttrSingleSpanStack -> SingleAttrSingleSpanStack -> Bool
105+singleAttrSingleSpanStackCropped5 stack0 stack_1 =
106+ let p = picForImage (stackImage stack0 <-> stackImage stack_1)
107+ w = MockWindow (imageWidth (picImage p)) (stackHeight stack0)
108+ ops = displayOpsForPic p (regionForWindow w)
109+ expectedRowCount = stackHeight stack0
110+ actualRowCount = spanOpsEffectedRows ops
111+ in expectedRowCount == actualRowCount
112+
113+horizSpanImageAndGreaterWindow0 :: SingleRowSingleAttrImage -> Result
114+horizSpanImageAndGreaterWindow0 (SingleRowSingleAttrImage { rowImage = i, expectedColumns = c }) =
115+ let p = picForImage i
116116 -- SingleRowSingleAttrImage always has width >= 1
117− greater_width = c * 2
118− w = MockWindow greater_width 1
119− ops = display_ops_for_pic p (region_for_window w)
120− in verify_all_spans_have_width i ops greater_width
121−
122−arb_image_is_cropped :: DefaultImage -> MockWindow -> Bool
123−arb_image_is_cropped (DefaultImage image) win@(MockWindow w h) =
124− let pic = pic_for_image image
125− ops = display_ops_for_pic pic (region_for_window win)
126− in ( span_ops_effected_rows ops == h ) && ( all_spans_have_width ops w )
127−
128−span_ops_actually_fill_rows :: DefaultPic -> Bool
129−span_ops_actually_fill_rows (DefaultPic pic win) =
130− let ops = display_ops_for_pic pic (region_for_window win)
131− expected_row_count = region_height (region_for_window win)
132− actual_row_count = span_ops_effected_rows ops
133− in expected_row_count == actual_row_count
134−
135−span_ops_actually_fill_columns :: DefaultPic -> Bool
136−span_ops_actually_fill_columns (DefaultPic pic win) =
137− let ops = display_ops_for_pic pic (region_for_window win)
138− expected_column_count = region_width (region_for_window win)
139− in all_spans_have_width ops expected_column_count
140−
141−first_span_op_sets_attr :: DefaultPic -> Bool
142−first_span_op_sets_attr DefaultPic { default_pic = pic, default_win = win } =
143− let ops = display_ops_for_pic pic (region_for_window win)
144− in all ( is_attr_span_op . Vector.head ) ( Vector.toList ops )
145−
146−single_attr_single_span_stack_op_coverage :: SingleAttrSingleSpanStack -> Result
147−single_attr_single_span_stack_op_coverage stack =
148− let p = pic_for_image (stack_image stack)
149− w = MockWindow (stack_width stack) (stack_height stack)
150− ops = display_ops_for_pic p (region_for_window w)
151− in verify_all_spans_have_width (stack_image stack) ops (stack_width stack)
152−
153−image_coverage_matches_bounds :: Image -> Result
154−image_coverage_matches_bounds i =
155− let p = pic_for_image i
156− r = (image_width i,image_height i)
157− ops = display_ops_for_pic p r
158− in verify_all_spans_have_width i ops (image_width i)
117+ greaterWidth = c * 2
118+ w = MockWindow greaterWidth 1
119+ ops = displayOpsForPic p (regionForWindow w)
120+ in verifyAllSpansHaveWidth i ops greaterWidth
121+
122+arbImageIsCropped :: DefaultImage -> MockWindow -> Bool
123+arbImageIsCropped (DefaultImage image) win@(MockWindow w h) =
124+ let pic = picForImage image
125+ ops = displayOpsForPic pic (regionForWindow win)
126+ in ( spanOpsEffectedRows ops == h ) && ( allSpansHaveWidth ops w )
127+
128+spanOpsActuallyFillRows :: DefaultPic -> Bool
129+spanOpsActuallyFillRows (DefaultPic pic win) =
130+ let ops = displayOpsForPic pic (regionForWindow win)
131+ expectedRowCount = regionHeight (regionForWindow win)
132+ actualRowCount = spanOpsEffectedRows ops
133+ in expectedRowCount == actualRowCount
134+
135+spanOpsActuallyFillColumns :: DefaultPic -> Bool
136+spanOpsActuallyFillColumns (DefaultPic pic win) =
137+ let ops = displayOpsForPic pic (regionForWindow win)
138+ expectedColumnCount = regionWidth (regionForWindow win)
139+ in allSpansHaveWidth ops expectedColumnCount
140+
141+firstSpanOpSetsAttr :: DefaultPic -> Bool
142+firstSpanOpSetsAttr DefaultPic { defaultPic = pic, defaultWin = win } =
143+ let ops = displayOpsForPic pic (regionForWindow win)
144+ in all ( isAttrSpanOp . Vector.head ) ( Vector.toList ops )
145+
146+singleAttrSingleSpanStackOpCoverage :: SingleAttrSingleSpanStack -> Result
147+singleAttrSingleSpanStackOpCoverage stack =
148+ let p = picForImage (stackImage stack)
149+ w = MockWindow (stackWidth stack) (stackHeight stack)
150+ ops = displayOpsForPic p (regionForWindow w)
151+ in verifyAllSpansHaveWidth (stackImage stack) ops (stackWidth stack)
152+
153+imageCoverageMatchesBounds :: Image -> Result
154+imageCoverageMatchesBounds i =
155+ let p = picForImage i
156+ r = (imageWidth i,imageHeight i)
157+ ops = displayOpsForPic p r
158+ in verifyAllSpansHaveWidth i ops (imageWidth i)
159159
160160tests :: IO [Test]
161161tests = return
162− [ verify "unit image is cropped when window size == (0,0) [0]" unit_image_and_zero_window_0
163− , verify "unit image is cropped when window size == (0,0) [1]" unit_image_and_zero_window_1
164− , verify "horiz span image is cropped when window size == (0,0) [0]" horiz_span_image_and_zero_window_0
165− , verify "horiz span image is cropped when window size == (0,0) [1]" horiz_span_image_and_zero_window_1
166− , verify "horiz span image is not cropped when window size == size of image [width]" horiz_span_image_and_equal_window_0
167− , verify "horiz span image is not cropped when window size == size of image [height]" horiz_span_image_and_equal_window_1
168− , verify "horiz span image is not cropped when window size < size of image [width]" horiz_span_image_and_lesser_window_0
169− , verify "horiz span image is not cropped when window size > size of image [width]" horiz_span_image_and_greater_window_0
170− , verify "first span op is always to set the text attribute" first_span_op_sets_attr
162+ [ verify "unit image is cropped when window size == (0,0) [0]" unitImageAndZeroWindow0
163+ , verify "unit image is cropped when window size == (0,0) [1]" unitImageAndZeroWindow1
164+ , verify "horiz span image is cropped when window size == (0,0) [0]" horizSpanImageAndZeroWindow0
165+ , verify "horiz span image is cropped when window size == (0,0) [1]" horizSpanImageAndZeroWindow1
166+ , verify "horiz span image is not cropped when window size == size of image [width]" horizSpanImageAndEqualWindow0
167+ , verify "horiz span image is not cropped when window size == size of image [height]" horizSpanImageAndEqualWindow1
168+ , verify "horiz span image is not cropped when window size < size of image [width]" horizSpanImageAndLesserWindow0
169+ , verify "horiz span image is not cropped when window size > size of image [width]" horizSpanImageAndGreaterWindow0
170+ , verify "first span op is always to set the text attribute" firstSpanOpSetsAttr
171171 , verify "a stack of single attr text spans should define content for all the columns [output region == size of stack]"
172− single_attr_single_span_stack_op_coverage
172+ singleAttrSingleSpanStackOpCoverage
173173 , verify "a single attr text span is cropped when window size < size of stack image [width]"
174− single_attr_single_span_stack_cropped_0
174+ singleAttrSingleSpanStackCropped0
175175 , verify "a single attr text span is cropped when window size < size of stack image [height]"
176− single_attr_single_span_stack_cropped_1
176+ singleAttrSingleSpanStackCropped1
177177 , verify "single attr text span <|> single attr text span display cropped. [width]"
178− single_attr_single_span_stack_cropped_2
178+ singleAttrSingleSpanStackCropped2
179179 , verify "single attr text span <|> single attr text span display cropped. [height]"
180− single_attr_single_span_stack_cropped_3
180+ singleAttrSingleSpanStackCropped3
181181 , verify "single attr text span <-> single attr text span display cropped. [width]"
182− single_attr_single_span_stack_cropped_4
182+ singleAttrSingleSpanStackCropped4
183183 , verify "single attr text span <-> single attr text span display cropped. [height]"
184− single_attr_single_span_stack_cropped_5
184+ singleAttrSingleSpanStackCropped5
185185 , verify "an arbitrary image when rendered to a window of the same size will cover the entire window"
186− image_coverage_matches_bounds
186+ imageCoverageMatchesBounds
187187 ]
188188
test/VerifyUsingMockInput.hs+119−119
@@ -37,11 +37,11 @@ import Test.SmallCheck.Series
3737import Text.Printf
3838
3939-- processing a block of 16 chars is the largest I can do without taking too long to run the test.
40−max_block_size :: Int
41−max_block_size = 16
40+maxBlockSize :: Int
41+maxBlockSize = 16
4242
43−max_table_size :: Int
44−max_table_size = 28
43+maxTableSize :: Int
44+maxTableSize = 28
4545
4646forEachOf :: (Show a, Testable m b) => [a] -> (a -> b) -> Property m
4747forEachOf l = over (generate (\n -> take n l))
@@ -55,81 +55,81 @@ type InputSpec = [InputEvent]
5555
5656type ExpectedSpec = [Event]
5757
58−synthesize_input :: InputSpec -> Fd -> IO ()
59−synthesize_input input out_handle = forM_ input f >> (void $ fdWrite out_handle "\xFFFD")
58+synthesizeInput :: InputSpec -> Fd -> IO ()
59+synthesizeInput input outHandle = forM_ input f >> (void $ fdWrite outHandle "\xFFFD")
6060 where
61− f (Bytes str) = void $ fdWrite out_handle str
61+ f (Bytes str) = void $ fdWrite outHandle str
6262 f (Delay t) = threadDelay t
6363
64−min_detectable_delay :: Int
65−min_detectable_delay = 4000
64+minDetectableDelay :: Int
65+minDetectableDelay = 4000
6666
67−min_timout :: Int
68−min_timout = 4000000
67+minTimout :: Int
68+minTimout = 4000000
6969
70−test_key_delay :: Int
71−test_key_delay = min_detectable_delay * 4
70+testKeyDelay :: Int
71+testKeyDelay = minDetectableDelay * 4
7272
73−test_esc_sample_delay :: Int
74−test_esc_sample_delay = min_detectable_delay * 2
73+testEscSampleDelay :: Int
74+testEscSampleDelay = minDetectableDelay * 2
7575
76−gen_events_using_io_actions :: Int -> IO () -> IO () -> IO ()
77−gen_events_using_io_actions max_duration input_action output_action = do
78− let max_duration' = max min_timout max_duration
79− read_complete <- newEmptyMVar
80− write_complete <- newEmptyMVar
81− _ <- forkOS $ input_action `finally` putMVar write_complete ()
82− _ <- forkOS $ output_action `finally` putMVar read_complete ()
83− Just () <- timeout max_duration' $ takeMVar write_complete
84− Just () <- timeout max_duration' $ takeMVar read_complete
76+genEventsUsingIoActions :: Int -> IO () -> IO () -> IO ()
77+genEventsUsingIoActions maxDuration inputAction outputAction = do
78+ let maxDuration' = max minTimout maxDuration
79+ readComplete <- newEmptyMVar
80+ writeComplete <- newEmptyMVar
81+ _ <- forkOS $ inputAction `finally` putMVar writeComplete ()
82+ _ <- forkOS $ outputAction `finally` putMVar readComplete ()
83+ Just () <- timeout maxDuration' $ takeMVar writeComplete
84+ Just () <- timeout maxDuration' $ takeMVar readComplete
8585 return ()
8686
87−compare_events :: (Show a1, Show a, Eq a1) => a -> [a1] -> [a1] -> IO Bool
88−compare_events input_spec expected_events out_events = compare_events' expected_events out_events
87+compareEvents :: (Show a1, Show a, Eq a1) => a -> [a1] -> [a1] -> IO Bool
88+compareEvents inputSpec expectedEvents outEvents = compareEvents' expectedEvents outEvents
8989 where
90− compare_events' [] [] = return True
91− compare_events' [] out_events' = do
92− printf "extra events %s\n" (show out_events') :: IO ()
90+ compareEvents' [] [] = return True
91+ compareEvents' [] outEvents' = do
92+ printf "extra events %s\n" (show outEvents') :: IO ()
9393 return False
94− compare_events' expected_events' [] = do
95− printf "events %s were not produced for input %s\n" (show expected_events') (show input_spec) :: IO ()
96− printf "expected events %s\n" (show expected_events) :: IO ()
97− printf "received events %s\n" (show out_events) :: IO ()
94+ compareEvents' expectedEvents' [] = do
95+ printf "events %s were not produced for input %s\n" (show expectedEvents') (show inputSpec) :: IO ()
96+ printf "expected events %s\n" (show expectedEvents) :: IO ()
97+ printf "received events %s\n" (show outEvents) :: IO ()
9898 return False
99− compare_events' (e : expected_events') (o : out_events')
100− | e == o = compare_events' expected_events' out_events'
99+ compareEvents' (e : expectedEvents') (o : outEvents')
100+ | e == o = compareEvents' expectedEvents' outEvents'
101101 | otherwise = do
102− printf "%s expected not %s for input %s\n" (show e) (show o) (show input_spec) :: IO ()
103− printf "expected events %s\n" (show expected_events) :: IO ()
104− printf "received events %s\n" (show out_events) :: IO ()
102+ printf "%s expected not %s for input %s\n" (show e) (show o) (show inputSpec) :: IO ()
103+ printf "expected events %s\n" (show expectedEvents) :: IO ()
104+ printf "received events %s\n" (show outEvents) :: IO ()
105105 return False
106106
107−assert_events_from_syn_input :: ClassifyTable -> InputSpec -> ExpectedSpec -> IO Bool
108−assert_events_from_syn_input table input_spec expected_events = do
109− let max_duration = sum [t | Delay t <- input_spec] + min_detectable_delay
110− event_count = length expected_events
111− (write_fd, read_fd) <- openPseudoTerminal
112− (set_term_attr,_) <- attributeControl read_fd
113− set_term_attr
114− input <- initInputForFd def table read_fd
115− events_ref <- newIORef []
116− let write_wait_close = do
117− synthesize_input input_spec write_fd
118− threadDelay min_detectable_delay
119− shutdown_input input
120− threadDelay min_detectable_delay
121− closeFd write_fd
122− closeFd read_fd
107+assertEventsFromSynInput :: ClassifyTable -> InputSpec -> ExpectedSpec -> IO Bool
108+assertEventsFromSynInput table inputSpec expectedEvents = do
109+ let maxDuration = sum [t | Delay t <- inputSpec] + minDetectableDelay
110+ event_count = length expectedEvents
111+ (writeFd, readFd) <- openPseudoTerminal
112+ (setTermAttr,_) <- attributeControl readFd
113+ setTermAttr
114+ input <- initInputForFd def table readFd
115+ eventsRef <- newIORef []
116+ let writeWaitClose = do
117+ synthesizeInput inputSpec writeFd
118+ threadDelay minDetectableDelay
119+ shutdownInput input
120+ threadDelay minDetectableDelay
121+ closeFd writeFd
122+ closeFd readFd
123123 -- drain output pipe
124− let read_events = read_loop event_count
125− read_loop 0 = return ()
126− read_loop n = do
127− e <- readChan $ input^.event_channel
128− modifyIORef events_ref ((:) e)
129− read_loop (n - 1)
130− gen_events_using_io_actions max_duration write_wait_close read_events
131− out_events <- reverse <$> readIORef events_ref
132− compare_events input_spec expected_events out_events
124+ let readEvents = readLoop event_count
125+ readLoop 0 = return ()
126+ readLoop n = do
127+ e <- readChan $ input^.eventChannel
128+ modifyIORef eventsRef ((:) e)
129+ readLoop (n - 1)
130+ genEventsUsingIoActions maxDuration writeWaitClose readEvents
131+ outEvents <- reverse <$> readIORef eventsRef
132+ compareEvents inputSpec expectedEvents outEvents
133133
134134newtype InputBlocksUsingTable event
135135 = InputBlocksUsingTable ([(String,event)] -> [(String, event)])
@@ -139,74 +139,74 @@ instance Show (InputBlocksUsingTable event) where
139139
140140instance Monad m => Serial m (InputBlocksUsingTable event) where
141141 series = do
142− n :: Int <- localDepth (const max_table_size) series
142+ n :: Int <- localDepth (const maxTableSize) series
143143 return $ InputBlocksUsingTable $ \table -> concat (take n (selections table))
144144 where
145145 selections [] = []
146146 selections (x:xs) = let z = selections xs in [x] : (z ++ map ((:) x) z)
147147
148−verify_visible_syn_input_to_event :: Property IO
149−verify_visible_syn_input_to_event = forAll $ \(InputBlocksUsingTable gen) -> monadic $ do
150− let table = visible_chars
151− input_seq = gen table
152− events = map snd input_seq
153− keydowns = map (Bytes . fst) input_seq
154− input = intersperse (Delay test_key_delay) keydowns ++ [Delay test_key_delay]
155− assert_events_from_syn_input universal_table input events
156−
157−verify_caps_syn_input_to_event :: Property IO
158−verify_caps_syn_input_to_event = forAll $ \(InputBlocksUsingTable gen) ->
159− forEachOf terminals_of_interest $ \term_name -> monadic $ do
160− term <- setupTerm term_name
161− let table = caps_classify_table term keys_from_caps_table
162− input_seq = gen table
163− events = map snd input_seq
164− keydowns = map (Bytes . fst) input_seq
165− input = intersperse (Delay test_key_delay) keydowns ++ [Delay test_key_delay]
166− assert_events_from_syn_input table input events
167−
168−verify_special_syn_input_to_event :: Property IO
169−verify_special_syn_input_to_event = forAll $ \(InputBlocksUsingTable gen) -> monadic $ do
170− let table = special_support_keys
171− input_seq = gen table
172− events = map snd input_seq
173− keydowns = map (Bytes . fst) input_seq
174− input = intersperse (Delay test_key_delay) keydowns ++ [Delay test_key_delay]
175− assert_events_from_syn_input universal_table input events
176−
177−verify_full_syn_input_to_event :: Property IO
178−verify_full_syn_input_to_event = forAll $ \(InputBlocksUsingTable gen) ->
179− forEachOf terminals_of_interest $ \term_name -> monadic $ do
180− term <- setupTerm term_name
181− let table = classify_table_for_term term_name term
182− input_seq = gen table
183− events = map snd input_seq
184− keydowns = map (Bytes . fst) input_seq
185− input = intersperse (Delay test_key_delay) keydowns ++ [Delay test_key_delay]
186− assert_events_from_syn_input table input events
187−
188−verify_full_syn_input_to_event_2x :: Property IO
189−verify_full_syn_input_to_event_2x = forAll $ \(InputBlocksUsingTable gen) ->
190− forEachOf terminals_of_interest $ \term_name -> monadic $ do
191− term <- setupTerm term_name
192− let table = classify_table_for_term term_name term
193− input_seq = gen table
194− events = concatMap ((\s -> [s,s]) . snd) input_seq
195− keydowns = map (Bytes . (\s -> s ++ s) . fst) input_seq
196− input = intersperse (Delay test_key_delay) keydowns ++ [Delay test_key_delay]
197− assert_events_from_syn_input table input events
148+verifyVisibleSynInputToEvent :: Property IO
149+verifyVisibleSynInputToEvent = forAll $ \(InputBlocksUsingTable gen) -> monadic $ do
150+ let table = visibleChars
151+ inputSeq = gen table
152+ events = map snd inputSeq
153+ keydowns = map (Bytes . fst) inputSeq
154+ input = intersperse (Delay testKeyDelay) keydowns ++ [Delay testKeyDelay]
155+ assertEventsFromSynInput universalTable input events
156+
157+verifyCapsSynInputToEvent :: Property IO
158+verifyCapsSynInputToEvent = forAll $ \(InputBlocksUsingTable gen) ->
159+ forEachOf terminalsOfInterest $ \termName -> monadic $ do
160+ term <- setupTerm termName
161+ let table = capsClassifyTable term keysFromCapsTable
162+ inputSeq = gen table
163+ events = map snd inputSeq
164+ keydowns = map (Bytes . fst) inputSeq
165+ input = intersperse (Delay testKeyDelay) keydowns ++ [Delay testKeyDelay]
166+ assertEventsFromSynInput table input events
167+
168+verifySpecialSynInputToEvent :: Property IO
169+verifySpecialSynInputToEvent = forAll $ \(InputBlocksUsingTable gen) -> monadic $ do
170+ let table = specialSupportKeys
171+ inputSeq = gen table
172+ events = map snd inputSeq
173+ keydowns = map (Bytes . fst) inputSeq
174+ input = intersperse (Delay testKeyDelay) keydowns ++ [Delay testKeyDelay]
175+ assertEventsFromSynInput universalTable input events
176+
177+verifyFullSynInputToEvent :: Property IO
178+verifyFullSynInputToEvent = forAll $ \(InputBlocksUsingTable gen) ->
179+ forEachOf terminalsOfInterest $ \termName -> monadic $ do
180+ term <- setupTerm termName
181+ let table = classifyTableForTerm termName term
182+ inputSeq = gen table
183+ events = map snd inputSeq
184+ keydowns = map (Bytes . fst) inputSeq
185+ input = intersperse (Delay testKeyDelay) keydowns ++ [Delay testKeyDelay]
186+ assertEventsFromSynInput table input events
187+
188+verifyFullSynInputToEvent_2x :: Property IO
189+verifyFullSynInputToEvent_2x = forAll $ \(InputBlocksUsingTable gen) ->
190+ forEachOf terminalsOfInterest $ \termName -> monadic $ do
191+ term <- setupTerm termName
192+ let table = classifyTableForTerm termName term
193+ inputSeq = gen table
194+ events = concatMap ((\s -> [s,s]) . snd) inputSeq
195+ keydowns = map (Bytes . (\s -> s ++ s) . fst) inputSeq
196+ input = intersperse (Delay testKeyDelay) keydowns ++ [Delay testKeyDelay]
197+ assertEventsFromSynInput table input events
198198
199199main :: IO ()
200200main = defaultMain
201201 [ testProperty "synthesized typing of single visible chars translates to expected events"
202− verify_visible_syn_input_to_event
202+ verifyVisibleSynInputToEvent
203203 , testProperty "synthesized typing of keys from capabilities tables translates to expected events"
204− verify_caps_syn_input_to_event
204+ verifyCapsSynInputToEvent
205205 , testProperty "synthesized typing of hard coded special keys translates to expected events"
206− verify_special_syn_input_to_event
206+ verifySpecialSynInputToEvent
207207 , testProperty "synthesized typing of any key in the table translates to its paired event"
208− verify_full_syn_input_to_event
208+ verifyFullSynInputToEvent
209209 , testProperty "synthesized typing of 2x any key in the table translates to 2x paired event"
210− verify_full_syn_input_to_event_2x
210+ verifyFullSynInputToEvent_2x
211211 ]
212212
test/VerifyUsingMockTerminal.hs+51−51
@@ -19,82 +19,82 @@ import qualified Data.String.UTF8 as UTF8
1919
2020import System.IO
2121
22−unit_image_unit_bounds :: UnitImage -> Property
23−unit_image_unit_bounds (UnitImage _ i) = liftIOResult $ do
24− (_,t) <- mock_terminal (1,1)
25− dc <- display_bounds t >>= display_context t
26− let pic = pic_for_image i
27− output_picture dc pic
22+unitImageUnitBounds :: UnitImage -> Property
23+unitImageUnitBounds (UnitImage _ i) = liftIOResult $ do
24+ (_,t) <- mockTerminal (1,1)
25+ dc <- displayBounds t >>= displayContext t
26+ let pic = picForImage i
27+ outputPicture dc pic
2828 return succeeded
2929
30−unit_image_arb_bounds :: UnitImage -> MockWindow -> Property
31−unit_image_arb_bounds (UnitImage _ i) (MockWindow w h) = liftIOResult $ do
32− (_,t) <- mock_terminal (w,h)
33− dc <- display_bounds t >>= display_context t
34− let pic = pic_for_image i
35− output_picture dc pic
30+unitImageArbBounds :: UnitImage -> MockWindow -> Property
31+unitImageArbBounds (UnitImage _ i) (MockWindow w h) = liftIOResult $ do
32+ (_,t) <- mockTerminal (w,h)
33+ dc <- displayBounds t >>= displayContext t
34+ let pic = picForImage i
35+ outputPicture dc pic
3636 return succeeded
3737
38−single_T_row :: MockWindow -> Property
39−single_T_row (MockWindow w h) = liftIOResult $ do
40− (mock_data,t) <- mock_terminal (w,h)
41− dc <- display_bounds t >>= display_context t
38+singleTRow :: MockWindow -> Property
39+singleTRow (MockWindow w h) = liftIOResult $ do
40+ (mockData,t) <- mockTerminal (w,h)
41+ dc <- displayBounds t >>= displayContext t
4242 -- create an image that contains just the character T repeated for a single row
43− let i = horiz_cat $ replicate (fromEnum w) (char def_attr 'T')
44− pic = (pic_for_image i) { pic_background = Background 'B' def_attr }
45− output_picture dc pic
43+ let i = horizCat $ replicate (fromEnum w) (char defAttr 'T')
44+ pic = (picForImage i) { picBackground = Background 'B' defAttr }
45+ outputPicture dc pic
4646 -- The mock output string that represents the output bytes a single line containing the T
4747 -- string: Followed by h - 1 lines of a change to the background attribute and then the
4848 -- background character
4949 let expected = "HD" ++ "MA" ++ replicate (fromEnum w) 'T'
50− ++ concat (replicate (fromEnum h - 1) $ "MA" ++ replicate (fromEnum w) 'B')
51− compare_mock_output mock_data expected
50+ ++ concat (replicate (fromEnum h - 1) $ "MA" ++ replicate (fromEnum w) 'B')
51+ compareMockOutput mockData expected
5252
53−many_T_rows :: MockWindow -> Property
54−many_T_rows (MockWindow w h) = liftIOResult $ do
55− (mock_data, t) <- mock_terminal (w,h)
56− dc <- display_bounds t >>= display_context t
53+manyTRows :: MockWindow -> Property
54+manyTRows (MockWindow w h) = liftIOResult $ do
55+ (mockData, t) <- mockTerminal (w,h)
56+ dc <- displayBounds t >>= displayContext t
5757 -- create an image that contains the character 'T' repeated for all the rows
58− let i = vert_cat $ replicate (fromEnum h) $ horiz_cat $ replicate (fromEnum w) (char def_attr 'T')
59− pic = (pic_for_image i) { pic_background = Background 'B' def_attr }
60− output_picture dc pic
58+ let i = vertCat $ replicate (fromEnum h) $ horizCat $ replicate (fromEnum w) (char defAttr 'T')
59+ pic = (picForImage i) { picBackground = Background 'B' defAttr }
60+ outputPicture dc pic
6161 -- The UTF8 string that represents the output bytes is h repeats of a move, 'M', followed by an
6262 -- attribute change. 'A', followed by w 'T's
6363 let expected = "HD" ++ concat (replicate (fromEnum h) $ "MA" ++ replicate (fromEnum w) 'T')
64− compare_mock_output mock_data expected
64+ compareMockOutput mockData expected
6565
66−many_T_rows_cropped_width :: MockWindow -> Property
67−many_T_rows_cropped_width (MockWindow w h) = liftIOResult $ do
68− (mock_data,t) <- mock_terminal (w,h)
69− dc <- display_bounds t >>= display_context t
66+manyTRowsCroppedWidth :: MockWindow -> Property
67+manyTRowsCroppedWidth (MockWindow w h) = liftIOResult $ do
68+ (mockData,t) <- mockTerminal (w,h)
69+ dc <- displayBounds t >>= displayContext t
7070 -- create an image that contains the character 'T' repeated for all the rows
71− let i = vert_cat $ replicate (fromEnum h) $ horiz_cat $ replicate (fromEnum w * 2) (char def_attr 'T')
72− pic = (pic_for_image i) { pic_background = Background 'B' def_attr }
73− output_picture dc pic
71+ let i = vertCat $ replicate (fromEnum h) $ horizCat $ replicate (fromEnum w * 2) (char defAttr 'T')
72+ pic = (picForImage i) { picBackground = Background 'B' defAttr }
73+ outputPicture dc pic
7474 -- The UTF8 string that represents the output bytes is h repeats of a move, 'M', followed by an
7575 -- attribute change. 'A', followed by w 'T's
7676 let expected = "HD" ++ concat (replicate (fromEnum h) $ "MA" ++ replicate (fromEnum w) 'T')
77− compare_mock_output mock_data expected
77+ compareMockOutput mockData expected
7878
79−many_T_rows_cropped_height :: MockWindow -> Property
80−many_T_rows_cropped_height (MockWindow w h) = liftIOResult $ do
81− (mock_data,t) <- mock_terminal (w,h)
82− dc <- display_bounds t >>= display_context t
79+manyTRowsCroppedHeight :: MockWindow -> Property
80+manyTRowsCroppedHeight (MockWindow w h) = liftIOResult $ do
81+ (mockData,t) <- mockTerminal (w,h)
82+ dc <- displayBounds t >>= displayContext t
8383 -- create an image that contains the character 'T' repeated for all the rows
84− let i = vert_cat $ replicate (fromEnum h * 2) $ horiz_cat $ replicate (fromEnum w) (char def_attr 'T')
85− pic = (pic_for_image i) { pic_background = Background 'B' def_attr }
86− output_picture dc pic
84+ let i = vertCat $ replicate (fromEnum h * 2) $ horizCat $ replicate (fromEnum w) (char defAttr 'T')
85+ pic = (picForImage i) { picBackground = Background 'B' defAttr }
86+ outputPicture dc pic
8787 -- The UTF8 string that represents the output bytes is h repeats of a move, 'M', followed by an
8888 -- attribute change. 'A', followed by w count 'T's
8989 let expected = "HD" ++ concat (replicate (fromEnum h) $ "MA" ++ replicate (fromEnum w) 'T')
90− compare_mock_output mock_data expected
90+ compareMockOutput mockData expected
9191
9292tests :: IO [Test]
93−tests = return [ verify "unit_image_unit_bounds" unit_image_unit_bounds
94− , verify "unit_image_arb_bounds" unit_image_arb_bounds
95− , verify "single_T_row" single_T_row
96− , verify "many_T_rows" many_T_rows
97− , verify "many_T_rows_cropped_width" many_T_rows_cropped_width
98− , verify "many_T_rows_cropped_height" many_T_rows_cropped_height
93+tests = return [ verify "unitImageUnitBounds" unitImageUnitBounds
94+ , verify "unitImageArbBounds" unitImageArbBounds
95+ , verify "singleTRow" singleTRow
96+ , verify "manyTRows" manyTRows
97+ , verify "manyTRowsCroppedWidth" manyTRowsCroppedWidth
98+ , verify "manyTRowsCroppedHeight" manyTRowsCroppedHeight
9999 ]
100100
test/VerifyUtf8Width.hs+13−13
@@ -5,24 +5,24 @@ import Graphics.Text.Width
55import Graphics.Vty.Attributes
66import Graphics.Vty.Picture
77
8−sw_is_1_column :: SingleColumnChar -> Bool
9−sw_is_1_column (SingleColumnChar c) = image_width (char def_attr c) == 1
8+swIs1Column :: SingleColumnChar -> Bool
9+swIs1Column (SingleColumnChar c) = imageWidth (char defAttr c) == 1
1010
11−dw_is_2_column :: DoubleColumnChar -> Bool
12−dw_is_2_column (DoubleColumnChar c) = image_width (char def_attr c) == 2
11+dwIs2Column :: DoubleColumnChar -> Bool
12+dwIs2Column (DoubleColumnChar c) = imageWidth (char defAttr c) == 2
1313
14−dc_string_is_even :: NonEmptyList DoubleColumnChar -> Bool
15−dc_string_is_even (NonEmpty dw_list) =
16− even $ safe_wcswidth [ c | DoubleColumnChar c <- dw_list ]
14+dcStringIsEven :: NonEmptyList DoubleColumnChar -> Bool
15+dcStringIsEven (NonEmpty dw_list) =
16+ even $ safeWcswidth [ c | DoubleColumnChar c <- dw_list ]
1717
18−safe_wcwidth_for_control_chars :: Bool
19−safe_wcwidth_for_control_chars = 0 == safe_wcwidth '\NUL'
18+safeWcwidthForControlChars :: Bool
19+safeWcwidthForControlChars = 0 == safeWcwidth '\NUL'
2020
2121tests :: IO [Test]
2222tests = return
23− [ verify "sw_is_1_column" sw_is_1_column
24− , verify "dw_is_2_column" dw_is_2_column
25− , verify "a string of double characters is an even width" dc_string_is_even
26− , verify "safe_wcwidth provides a width of 0 for chars without widths" safe_wcwidth_for_control_chars
23+ [ verify "swIs1Column" swIs1Column
24+ , verify "dwIs2Column" dwIs2Column
25+ , verify "a string of double characters is an even width" dcStringIsEven
26+ , verify "safeWcwidth provides a width of 0 for chars without widths" safeWcwidthForControlChars
2727 ]
2828
test/benchmark.hs+21−21
@@ -20,11 +20,11 @@ import Verify
2020
2121main = do
2222 args <- getArgs
23− let benches = [ ("no-diff-opt-0", BenchNoDiffOpt.bench_0)
24− , ("render-char-0", BenchRenderChar.bench_0)
25− , ("render-char-1", BenchRenderChar.bench_1)
26− , ("vertical-scroll-0", BenchVerticalScroll.bench_0)
27− , ("image-fuzz-0", BenchImageFuzz.bench_0) ]
23+ let benches = [ ("no-diff-opt-0", BenchNoDiffOpt.bench0)
24+ , ("render-char-0", BenchRenderChar.bench0)
25+ , ("render-char-1", BenchRenderChar.bench1)
26+ , ("vertical-scroll-0", BenchVerticalScroll.bench0)
27+ , ("image-fuzz-0", BenchImageFuzz.bench0) ]
2828 help = forM_ benches $ \(b,_) -> putStrLn $ "--" ++ b
2929 case args of
3030 ["--help"] -> help
@@ -34,23 +34,23 @@ main = do
3434 then map (drop 2) args
3535 else map fst benches
3636 -- drop the dash-dash "--"
37− results <- forM args' $ \b_name -> do
38− case lookup b_name benches of
39− Just b -> bench b_name b
40− Nothing -> fail $ "No benchmark named " ++ b_name
37+ results <- forM args' $ \bName -> do
38+ case lookup bName benches of
39+ Just b -> bench bName b
40+ Nothing -> fail $ "No benchmark named " ++ bName
4141 print results
4242 return ()
4343
44−bench b_name b = do
45− putStrLn $ "starting " ++ b_name
46− Bench b_data_gen b_proc <- b
47− b_data <- b_data_gen
48− start_times <- b_data `deepseq` getProcessTimes
49− b_proc b_data
50− end_times <- getProcessTimes
51− let user_time = userTime end_times - userTime start_times
52− system_time = systemTime end_times - systemTime start_times
53− putStrLn $ "user time: " ++ show user_time
54− putStrLn $ "system time: " ++ show system_time
55− return (b_name, user_time, system_time)
44+bench bName b = do
45+ putStrLn $ "starting " ++ bName
46+ Bench bDataGen bProc <- b
47+ bData <- bDataGen
48+ startTimes <- bData `deepseq` getProcessTimes
49+ bProc bData
50+ endTimes <- getProcessTimes
51+ let ut = userTime endTimes - userTime startTimes
52+ st = systemTime endTimes - systemTime startTimes
53+ putStrLn $ "user time: " ++ show ut
54+ putStrLn $ "system time: " ++ show st
55+ return (bName, ut, st)
5656
test/interactive_terminal_test.hs+557−557
@@ -25,11 +25,11 @@ import qualified System.Environment as Env
2525import System.IO ( hFlush, hPutStr, hPutBuf, stdout )
2626
2727main = do
28− print_intro
28+ printIntro
2929
30−output_file_path = "test_results.list"
30+outputFilePath = "test_results.list"
3131
32−print_intro = do
32+printIntro = do
3333 putStr $ [s|
3434This is an interactive verification program for the terminal input and output
3535support of the VTY library. This will ask a series of questions about what you
@@ -37,7 +37,7 @@ see on screen. The goal is to verify that VTY's output and input support
3737performs as expected with your terminal.
3838
3939This program produces a file named
40− |] ++ output_file_path ++ [s|
40+ |] ++ outputFilePath ++ [s|
4141in the current directory that contains the results for each test assertion. This
4242can be emailed to coreyoconnor@gmail.com and used by the VTY authors to improve
4343support for your terminal. No personal information is contained in the report.
@@ -72,35 +72,35 @@ with the test_results.list file pasted into the issue. The issue summary can
7272mention the specific tests that failed or just say "interactive terminal test
7373failure".
7474|]
75− wait_for_return
76− results <- do_test_menu 1
77− env_attributes <- mapM ( \env_name -> Control.Exception.catch ( Env.getEnv env_name >>= return . (,) env_name )
75+ waitForReturn
76+ results <- doTestMenu 1
77+ envAttributes <- mapM ( \env_name -> Control.Exception.catch ( Env.getEnv env_name >>= return . (,) env_name )
7878 ( \ (_ :: SomeException) -> return (env_name, "") )
79− )
80− [ "TERM", "COLORTERM", "LANG", "TERM_PROGRAM", "XTERM_VERSION" ]
81− t <- output_for_current_terminal
82− let results_txt = show env_attributes ++ "\n"
83− ++ terminal_ID t ++ "\n"
84− ++ show results ++ "\n"
85− release_terminal t
86− writeFile output_file_path results_txt
87−
88−wait_for_return = do
79+ )
80+ [ "TERM", "COLORTERM", "LANG", "TERM_PROGRAM", "XTERM_VERSION" ]
81+ t <- outputForCurrentTerminal
82+ let resultsTxt = show envAttributes ++ "\n"
83+ ++ terminalID t ++ "\n"
84+ ++ show results ++ "\n"
85+ releaseTerminal t
86+ writeFile outputFilePath resultsTxt
87+
88+waitForReturn = do
8989 putStr "\n(press return to continue)"
9090 hFlush stdout
9191 getLine
9292
93−test_menu :: [(String, Test)]
94−test_menu = zip (map show [1..]) all_tests
93+testMenu :: [(String, Test)]
94+testMenu = zip (map show [1..]) allTests
9595
96−do_test_menu :: Int -> IO [(String, Bool)]
97−do_test_menu next_ID
98− | next_ID > length all_tests = do
99− putStrLn $ "Done! Please email the " ++ output_file_path ++ " file to coreyoconnor@gmail.com"
96+doTestMenu :: Int -> IO [(String, Bool)]
97+doTestMenu nextID
98+ | nextID > length allTests = do
99+ putStrLn $ "Done! Please email the " ++ outputFilePath ++ " file to coreyoconnor@gmail.com"
100100 return []
101101 | otherwise = do
102− display_test_menu
103− putStrLn $ "Press return to start with #" ++ show next_ID ++ "."
102+ displayTestMenu
103+ putStrLn $ "Press return to start with #" ++ show nextID ++ "."
104104 putStrLn "Enter a test number to perform only that test."
105105 putStrLn "q (or control-C) to quit."
106106 putStr "> "
@@ -109,98 +109,98 @@ do_test_menu next_ID
109109 case s of
110110 "q" -> return mempty
111111 "" -> do
112− r <- run_test $ show next_ID
113− rs <- do_test_menu ( next_ID + 1 )
112+ r <- runTest $ show nextID
113+ rs <- doTestMenu ( nextID + 1 )
114114 return $ r : rs
115− i | isJust ( lookup i test_menu ) -> do
116− r <- run_test i
117− rs <- do_test_menu ( read i + 1 )
115+ i | isJust ( lookup i testMenu ) -> do
116+ r <- runTest i
117+ rs <- doTestMenu ( read i + 1 )
118118 return $ r : rs
119119 where
120− display_test_menu
121− = mapM_ display_test_menu' test_menu
122− display_test_menu' ( i, t )
123− = putStrLn $ ( if i == show next_ID
120+ displayTestMenu
121+ = mapM_ displayTestMenu' testMenu
122+ displayTestMenu' ( i, t )
123+ = putStrLn $ ( if i == show nextID
124124 then "> "
125125 else " "
126− ) ++ i ++ ". " ++ test_name t
127−
128−run_test :: String -> IO (String, Bool)
129−run_test i = do
130− let t = fromJust $ lookup i test_menu
131− print_summary t
132− wait_for_return
133− test_action t
134− r <- confirm_results t
135− return (test_ID t, r)
136−
137−default_success_confirm_results = do
126+ ) ++ i ++ ". " ++ testName t
127+
128+runTest :: String -> IO (String, Bool)
129+runTest i = do
130+ let t = fromJust $ lookup i testMenu
131+ printSummary t
132+ waitForReturn
133+ testAction t
134+ r <- confirmResults t
135+ return (testID t, r)
136+
137+defaultSuccessConfirmResults = do
138138 putStr "\n"
139139 putStr "[Y/n] "
140140 hFlush stdout
141141 r <- getLine
142142 case r of
143− "" -> return True
143+ "" -> return True
144144 "y" -> return True
145145 "Y" -> return True
146146 "n" -> return False
147147
148148data Test = Test
149− { test_name :: String
150− , test_ID :: String
151− , test_action :: IO ()
152− , print_summary :: IO ()
153− , confirm_results :: IO Bool
149+ { testName :: String
150+ , testID :: String
151+ , testAction :: IO ()
152+ , printSummary :: IO ()
153+ , confirmResults :: IO Bool
154154 }
155155
156−all_tests
157− = [ reserve_output_test
158− , display_bounds_test_0
159− , display_bounds_test_1
160− , display_bounds_test_2
161− , display_bounds_test_3
162− , unicode_single_width_0
163− , unicode_single_width_1
164− , unicode_double_width_0
165− , unicode_double_width_1
166− , attributes_test_0
167− , attributes_test_1
168− , attributes_test_2
169− , attributes_test_3
170− , attributes_test_4
171− , attributes_test_5
172− , inline_test_0
173− , inline_test_1
174− , inline_test_2
175− , cursor_hide_test_0
176− , vert_crop_test_0
177− , vert_crop_test_1
178− , vert_crop_test_2
179− , vert_crop_test_3
180− , horiz_crop_test_0
181− , horiz_crop_test_1
182− , horiz_crop_test_2
183− , horiz_crop_test_3
184− , layer_0
185− , layer_1
156+allTests
157+ = [ reserveOutputTest
158+ , displayBoundsTest0
159+ , displayBoundsTest1
160+ , displayBoundsTest2
161+ , displayBoundsTest3
162+ , unicodeSingleWidth0
163+ , unicodeSingleWidth1
164+ , unicodeDoubleWidth0
165+ , unicodeDoubleWidth1
166+ , attributesTest0
167+ , attributesTest1
168+ , attributesTest2
169+ , attributesTest3
170+ , attributesTest4
171+ , attributesTest5
172+ , inlineTest0
173+ , inlineTest1
174+ , inlineTest2
175+ , cursorHideTest0
176+ , vertCropTest0
177+ , vertCropTest1
178+ , vertCropTest2
179+ , vertCropTest3
180+ , horizCropTest0
181+ , horizCropTest1
182+ , horizCropTest2
183+ , horizCropTest3
184+ , layer0
185+ , layer1
186186 ]
187187
188−reserve_output_test = Test
189− { test_name = "Initialize and reserve terminal output then restore previous state."
190− , test_ID = "reserve_output_test"
191− , test_action = do
192− t <- output_for_current_terminal
193− reserve_display t
188+reserveOutputTest = Test
189+ { testName = "Initialize and reserve terminal output then restore previous state."
190+ , testID = "reserveOutputTest"
191+ , testAction = do
192+ t <- outputForCurrentTerminal
193+ reserveDisplay t
194194 putStrLn "Line 1"
195195 putStrLn "Line 2"
196196 putStrLn "Line 3"
197197 putStrLn "Line 4 (press return)"
198198 hFlush stdout
199199 getLine
200− release_display t
201− release_terminal t
200+ releaseDisplay t
201+ releaseTerminal t
202202 return ()
203− , print_summary = do
203+ , printSummary = do
204204 putStr $ [s|
205205Once return is pressed:
206206 0. The screen will be cleared.
@@ -211,123 +211,123 @@ After return is pressed for the second time this test then:
211211 * The screen containing the test summary should be restored;
212212 * The cursor is visible.
213213|]
214− , confirm_results = do
214+ , confirmResults = do
215215 putStr $ [s|
216216Did the test output match the description?
217217|]
218− default_success_confirm_results
218+ defaultSuccessConfirmResults
219219 }
220220
221−display_bounds_test_0 = Test
222− { test_name = "Verify display bounds are correct test 0: Using spaces."
223− , test_ID = "display_bounds_test_0"
224− , test_action = do
225− t <- output_for_current_terminal
226− reserve_display t
227− (w,h) <- display_bounds t
228− let row_0 = replicate (fromEnum w) 'X' ++ "\n"
229− row_h = replicate (fromEnum w - 1) 'X'
230− row_n = "X" ++ replicate (fromEnum w - 2) ' ' ++ "X\n"
231− image = row_0 ++ (concat $ replicate (fromEnum h - 2) row_n) ++ row_h
221+displayBoundsTest0 = Test
222+ { testName = "Verify display bounds are correct test 0: Using spaces."
223+ , testID = "displayBoundsTest0"
224+ , testAction = do
225+ t <- outputForCurrentTerminal
226+ reserveDisplay t
227+ (w,h) <- displayBounds t
228+ let row0 = replicate (fromEnum w) 'X' ++ "\n"
229+ rowH = replicate (fromEnum w - 1) 'X'
230+ rowN = "X" ++ replicate (fromEnum w - 2) ' ' ++ "X\n"
231+ image = row0 ++ (concat $ replicate (fromEnum h - 2) rowN) ++ rowH
232232 putStr image
233233 hFlush stdout
234234 getLine
235− release_display t
236− release_terminal t
235+ releaseDisplay t
236+ releaseTerminal t
237237 return ()
238− , print_summary = display_bounds_test_summary True
239− , confirm_results = generic_output_match_confirm
238+ , printSummary = displayBoundsTestSummary True
239+ , confirmResults = genericOutputMatchConfirm
240240 }
241241
242−display_bounds_test_1 = Test
243− { test_name = "Verify display bounds are correct test 0: Using cursor movement."
244− , test_ID = "display_bounds_test_1"
245− , test_action = do
246− t <- output_for_current_terminal
247− reserve_display t
248− (w,h) <- display_bounds t
249− set_cursor_pos t 0 0
250− let row_0 = replicate (fromEnum w) 'X' ++ "\n"
251− putStr row_0
242+displayBoundsTest1 = Test
243+ { testName = "Verify display bounds are correct test 0: Using cursor movement."
244+ , testID = "displayBoundsTest1"
245+ , testAction = do
246+ t <- outputForCurrentTerminal
247+ reserveDisplay t
248+ (w,h) <- displayBounds t
249+ setCursorPos t 0 0
250+ let row0 = replicate (fromEnum w) 'X' ++ "\n"
251+ putStr row0
252252 forM_ [1 .. h - 2] $ \y -> do
253− set_cursor_pos t 0 y
253+ setCursorPos t 0 y
254254 putStr "X"
255255 hFlush stdout
256− set_cursor_pos t (w - 1) y
256+ setCursorPos t (w - 1) y
257257 putStr "X"
258258 hFlush stdout
259− set_cursor_pos t 0 (h - 1)
260− let row_h = replicate (fromEnum w - 1) 'X'
261− putStr row_h
259+ setCursorPos t 0 (h - 1)
260+ let rowH = replicate (fromEnum w - 1) 'X'
261+ putStr rowH
262262 hFlush stdout
263263 getLine
264− release_display t
265− release_terminal t
264+ releaseDisplay t
265+ releaseTerminal t
266266 return ()
267− , print_summary = display_bounds_test_summary True
268− , confirm_results = generic_output_match_confirm
267+ , printSummary = displayBoundsTestSummary True
268+ , confirmResults = genericOutputMatchConfirm
269269 }
270270
271−display_bounds_test_2 = Test
272− { test_name = "Verify display bounds are correct test 0: Using Image ops."
273− , test_ID = "display_bounds_test_2"
274− , test_action = do
275− t <- output_for_current_terminal
276− reserve_display t
277− bounds@(w,h) <- display_bounds t
278− let first_row = horiz_cat $ replicate (fromEnum w) (char def_attr 'X')
279− middle_rows = vert_cat $ replicate (fromEnum h - 2) middle_row
280− middle_row = (char def_attr 'X') <|> background_fill (w - 2) 1 <|> (char def_attr 'X')
281− end_row = first_row
282− image = first_row <-> middle_rows <-> end_row
283− pic = (pic_for_image image) { pic_cursor = Cursor (w - 1) (h - 1) }
284− d <- display_context t bounds
285− output_picture d pic
271+displayBoundsTest2 = Test
272+ { testName = "Verify display bounds are correct test 0: Using Image ops."
273+ , testID = "displayBoundsTest2"
274+ , testAction = do
275+ t <- outputForCurrentTerminal
276+ reserveDisplay t
277+ bounds@(w,h) <- displayBounds t
278+ let firstRow = horizCat $ replicate (fromEnum w) (char defAttr 'X')
279+ middleRows = vertCat $ replicate (fromEnum h - 2) middleRow
280+ middleRow = (char defAttr 'X') <|> backgroundFill (w - 2) 1 <|> (char defAttr 'X')
281+ endRow = firstRow
282+ image = firstRow <-> middleRows <-> endRow
283+ pic = (picForImage image) { picCursor = Cursor (w - 1) (h - 1) }
284+ d <- displayContext t bounds
285+ outputPicture d pic
286286 getLine
287− release_display t
288− release_terminal t
287+ releaseDisplay t
288+ releaseTerminal t
289289 return ()
290− , print_summary = display_bounds_test_summary True
291− , confirm_results = generic_output_match_confirm
290+ , printSummary = displayBoundsTestSummary True
291+ , confirmResults = genericOutputMatchConfirm
292292 }
293293
294−display_bounds_test_3 = Test
295− { test_name = "Verify display bounds are correct test 0: Hide cursor; Set cursor pos."
296− , test_ID = "display_bounds_test_3"
297− , test_action = do
298− t <- output_for_current_terminal
299− reserve_display t
300− (w,h) <- display_bounds t
301− hide_cursor t
302− set_cursor_pos t 0 0
303− let row_0 = replicate (fromEnum w) 'X'
304− putStrLn row_0
294+displayBoundsTest3 = Test
295+ { testName = "Verify display bounds are correct test 0: Hide cursor; Set cursor pos."
296+ , testID = "displayBoundsTest3"
297+ , testAction = do
298+ t <- outputForCurrentTerminal
299+ reserveDisplay t
300+ (w,h) <- displayBounds t
301+ hideCursor t
302+ setCursorPos t 0 0
303+ let row0 = replicate (fromEnum w) 'X'
304+ putStrLn row0
305305 forM_ [1 .. h - 2] $ \y -> do
306− set_cursor_pos t 0 y
306+ setCursorPos t 0 y
307307 putStr "X"
308308 hFlush stdout
309− set_cursor_pos t (w - 1) y
309+ setCursorPos t (w - 1) y
310310 putStr "X"
311311 hFlush stdout
312− set_cursor_pos t 0 (h - 1)
313− let row_h = row_0
314− putStr row_h
312+ setCursorPos t 0 (h - 1)
313+ let rowH = row0
314+ putStr rowH
315315 hFlush stdout
316316 getLine
317− show_cursor t
318− release_display t
319− release_terminal t
317+ showCursor t
318+ releaseDisplay t
319+ releaseTerminal t
320320 return ()
321− , print_summary = display_bounds_test_summary False
322− , confirm_results = generic_output_match_confirm
321+ , printSummary = displayBoundsTestSummary False
322+ , confirmResults = genericOutputMatchConfirm
323323 }
324324
325−display_bounds_test_summary has_cursor = do
325+displayBoundsTestSummary hasCursor = do
326326 putStr $ [s|
327327Once return is pressed:
328328 0. The screen will be cleared.
329329|]
330− if has_cursor
330+ if hasCursor
331331 then putStr " 1. The cursor will be visible."
332332 else putStr " 1. The cursor will NOT be visible."
333333 putStr [s|
@@ -338,7 +338,7 @@ Once return is pressed:
338338 |XXXXXXXXXXXXX|
339339 |X X||]
340340
341− if has_cursor
341+ if hasCursor
342342 then putStr $ [s|
343343
344344 |XXXXXXXXXXXXC| |]
@@ -359,11 +359,11 @@ After return is pressed for the second time:
359359 1. The cursor should be visible.
360360|]
361361
362−generic_output_match_confirm = do
362+genericOutputMatchConfirm = do
363363 putStr $ [s|
364364Did the test output match the description?
365365|]
366− default_success_confirm_results
366+ defaultSuccessConfirmResults
367367
368368-- Explicitely definethe bytes that encode each example text.
369369-- This avoids any issues with how the compiler represents string literals.
@@ -376,21 +376,21 @@ Did the test output match the description?
376376--
377377-- txt_0 = ↑↑↓↓←→←→BA
378378
379−utf8_txt_0 :: [[Word8]]
380−utf8_txt_0 = [ [ 0xe2 , 0x86 , 0x91 ]
381− , [ 0xe2 , 0x86 , 0x91 ]
382− , [ 0xe2 , 0x86 , 0x93 ]
383− , [ 0xe2 , 0x86 , 0x93 ]
384− , [ 0xe2 , 0x86 , 0x90 ]
385− , [ 0xe2 , 0x86 , 0x92 ]
386− , [ 0xe2 , 0x86 , 0x90 ]
387− , [ 0xe2 , 0x86 , 0x92 ]
388− , [ 0x42 ]
389− , [ 0x41 ]
390− ]
391−
392−iso_10646_txt_0 :: String
393−iso_10646_txt_0 = map toEnum
379+utf8Txt0 :: [[Word8]]
380+utf8Txt0 = [ [ 0xe2 , 0x86 , 0x91 ]
381+ , [ 0xe2 , 0x86 , 0x91 ]
382+ , [ 0xe2 , 0x86 , 0x93 ]
383+ , [ 0xe2 , 0x86 , 0x93 ]
384+ , [ 0xe2 , 0x86 , 0x90 ]
385+ , [ 0xe2 , 0x86 , 0x92 ]
386+ , [ 0xe2 , 0x86 , 0x90 ]
387+ , [ 0xe2 , 0x86 , 0x92 ]
388+ , [ 0x42 ]
389+ , [ 0x41 ]
390+ ]
391+
392+iso10646Txt0 :: String
393+iso10646Txt0 = map toEnum
394394 [ 8593
395395 , 8593
396396 , 8595
@@ -403,46 +403,46 @@ iso_10646_txt_0 = map toEnum
403403 , 65
404404 ]
405405
406−unicode_single_width_0 = Test
407− { test_name = "Verify terminal can display unicode single-width characters. (Direct UTF-8)"
408− , test_ID = "unicode_single_width_0"
409− , test_action = do
410− t <- output_for_current_terminal
411− reserve_display t
412− hide_cursor t
413− withArrayLen (concat utf8_txt_0) (flip $ hPutBuf stdout)
406+unicodeSingleWidth0 = Test
407+ { testName = "Verify terminal can display unicode single-width characters. (Direct UTF-8)"
408+ , testID = "unicodeSingleWidth0"
409+ , testAction = do
410+ t <- outputForCurrentTerminal
411+ reserveDisplay t
412+ hideCursor t
413+ withArrayLen (concat utf8Txt0) (flip $ hPutBuf stdout)
414414 hPutStr stdout "\n"
415415 hPutStr stdout "0123456789\n"
416416 hFlush stdout
417417 getLine
418− release_display t
419− release_terminal t
418+ releaseDisplay t
419+ releaseTerminal t
420420 return ()
421− , print_summary = unicode_single_width_summary
422− , confirm_results = generic_output_match_confirm
421+ , printSummary = unicodeSingleWidthSummary
422+ , confirmResults = genericOutputMatchConfirm
423423 }
424424
425−unicode_single_width_1 = Test
426− { test_name = "Verify terminal can display unicode single-width characters. (Image ops)"
427− , test_ID = "unicode_single_width_1"
428− , test_action = do
429− t <- output_for_current_terminal
430− reserve_display t
431− let pic = pic_for_image image
432− image = line_0 <-> line_1
433− line_0 = iso_10646_string def_attr iso_10646_txt_0
434− line_1 = string def_attr "0123456789"
435− d <- display_bounds t >>= display_context t
436− output_picture d pic
425+unicodeSingleWidth1 = Test
426+ { testName = "Verify terminal can display unicode single-width characters. (Image ops)"
427+ , testID = "unicodeSingleWidth1"
428+ , testAction = do
429+ t <- outputForCurrentTerminal
430+ reserveDisplay t
431+ let pic = picForImage image
432+ image = line0 <-> line1
433+ line0 = iso10646String defAttr iso10646Txt0
434+ line1 = string defAttr "0123456789"
435+ d <- displayBounds t >>= displayContext t
436+ outputPicture d pic
437437 getLine
438− release_display t
439− release_terminal t
438+ releaseDisplay t
439+ releaseTerminal t
440440 return ()
441− , print_summary = unicode_single_width_summary
442− , confirm_results = generic_output_match_confirm
441+ , printSummary = unicodeSingleWidthSummary
442+ , confirmResults = genericOutputMatchConfirm
443443 }
444444
445−unicode_single_width_summary = putStr [s|
445+unicodeSingleWidthSummary = putStr [s|
446446Once return is pressed:
447447 0. The screen will be cleared.
448448 1. The cursor will be hidden.
@@ -476,55 +476,55 @@ After return is pressed for the second time:
476476
477477-- The second example is a unicode string containing double-width glyphs
478478-- 你好吗
479−utf8_txt_1 :: [[Word8]]
480−utf8_txt_1 = [ [0xe4,0xbd,0xa0]
481− , [0xe5,0xa5,0xbd]
482− , [0xe5,0x90,0x97]
483− ]
484−
485−iso_10646_txt_1 :: String
486−iso_10646_txt_1 = map toEnum [20320,22909,21527]
487−
488−unicode_double_width_0 = Test
489− { test_name = "Verify terminal can display unicode double-width characters. (Direct UTF-8)"
490− , test_ID = "unicode_double_width_0"
491− , test_action = do
492− t <- output_for_current_terminal
493− reserve_display t
494− hide_cursor t
495− withArrayLen (concat utf8_txt_1) (flip $ hPutBuf stdout)
479+utf8Txt1 :: [[Word8]]
480+utf8Txt1 = [ [0xe4,0xbd,0xa0]
481+ , [0xe5,0xa5,0xbd]
482+ , [0xe5,0x90,0x97]
483+ ]
484+
485+iso10646Txt1 :: String
486+iso10646Txt1 = map toEnum [20320,22909,21527]
487+
488+unicodeDoubleWidth0 = Test
489+ { testName = "Verify terminal can display unicode double-width characters. (Direct UTF-8)"
490+ , testID = "unicodeDoubleWidth0"
491+ , testAction = do
492+ t <- outputForCurrentTerminal
493+ reserveDisplay t
494+ hideCursor t
495+ withArrayLen (concat utf8Txt1) (flip $ hPutBuf stdout)
496496 hPutStr stdout "\n"
497497 hPutStr stdout "012345\n"
498498 hFlush stdout
499499 getLine
500− release_display t
501− release_terminal t
500+ releaseDisplay t
501+ releaseTerminal t
502502 return ()
503− , print_summary = unicode_double_width_summary
504− , confirm_results = generic_output_match_confirm
503+ , printSummary = unicodeDoubleWidthSummary
504+ , confirmResults = genericOutputMatchConfirm
505505 }
506506
507−unicode_double_width_1 = Test
508− { test_name = "Verify terminal can display unicode double-width characters. (Image ops)"
509− , test_ID = "unicode_double_width_1"
510− , test_action = do
511− t <- output_for_current_terminal
512− reserve_display t
513− let pic = pic_for_image image
514− image = line_0 <-> line_1
515− line_0 = iso_10646_string def_attr iso_10646_txt_1
516− line_1 = string def_attr "012345"
517− d <- display_bounds t >>= display_context t
518− output_picture d pic
507+unicodeDoubleWidth1 = Test
508+ { testName = "Verify terminal can display unicode double-width characters. (Image ops)"
509+ , testID = "unicodeDoubleWidth1"
510+ , testAction = do
511+ t <- outputForCurrentTerminal
512+ reserveDisplay t
513+ let pic = picForImage image
514+ image = line0 <-> line1
515+ line0 = iso10646String defAttr iso10646Txt1
516+ line1 = string defAttr "012345"
517+ d <- displayBounds t >>= displayContext t
518+ outputPicture d pic
519519 getLine
520− release_display t
521− release_terminal t
520+ releaseDisplay t
521+ releaseTerminal t
522522 return ()
523− , print_summary = unicode_double_width_summary
524− , confirm_results = generic_output_match_confirm
523+ , printSummary = unicodeDoubleWidthSummary
524+ , confirmResults = genericOutputMatchConfirm
525525 }
526526
527−unicode_double_width_summary = putStr [s|
527+unicodeDoubleWidthSummary = putStr [s|
528528Once return is pressed:
529529 0. The screen will be cleared.
530530 1. The cursor will be hidden.
@@ -551,32 +551,32 @@ After return is pressed for the second time:
551551 1. The cursor should be visible.
552552|]
553553
554−all_colors = zip [ black, red, green, yellow, blue, magenta, cyan, white ]
555− [ "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white" ]
554+allColors = zip [ black, red, green, yellow, blue, magenta, cyan, white ]
555+ [ "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white" ]
556556
557−all_bright_colors
558− = zip [ bright_black, bright_red, bright_green, bright_yellow, bright_blue, bright_magenta, bright_cyan, bright_white ]
557+allBrightColors
558+ = zip [ brightBlack, brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite ]
559559 [ "bright black", "bright red", "bright green", "bright yellow", "bright blue", "bright magenta", "bright cyan", "bright white" ]
560560
561−attributes_test_0 = Test
562− { test_name = "Character attributes: foreground colors."
563− , test_ID = "attributes_test_0"
564− , test_action = do
565− t <- output_for_current_terminal
566− reserve_display t
567− let pic = pic_for_image image
568− image = border <|> column_0 <|> border <|> column_1 <|> border
569− column_0 = vert_cat $ map line_with_color all_colors
570− border = vert_cat $ replicate (length all_colors) $ string def_attr " | "
571− column_1 = vert_cat $ map (string def_attr . snd) all_colors
572− line_with_color (c, c_name) = string (def_attr `with_fore_color` c) c_name
573− d <- display_bounds t >>= display_context t
574− output_picture d pic
561+attributesTest0 = Test
562+ { testName = "Character attributes: foreground colors."
563+ , testID = "attributesTest0"
564+ , testAction = do
565+ t <- outputForCurrentTerminal
566+ reserveDisplay t
567+ let pic = picForImage image
568+ image = border <|> column0 <|> border <|> column1 <|> border
569+ column0 = vertCat $ map lineWithColor allColors
570+ border = vertCat $ replicate (length allColors) $ string defAttr " | "
571+ column1 = vertCat $ map (string defAttr . snd) allColors
572+ lineWithColor (c, cName) = string (defAttr `withForeColor` c) cName
573+ d <- displayBounds t >>= displayContext t
574+ outputPicture d pic
575575 getLine
576− release_display t
577− release_terminal t
576+ releaseDisplay t
577+ releaseTerminal t
578578 return ()
579− , print_summary = do
579+ , printSummary = do
580580 putStr $ [s|
581581Once return is pressed:
582582 0. The screen will be cleared.
@@ -597,32 +597,32 @@ After return is pressed for the second time:
597597 0. The screen containing the test summary should be restored.
598598 1. The cursor should be visible.
599599|]
600− , confirm_results = do
600+ , confirmResults = do
601601 putStr $ [s|
602602Did the test output match the description?
603603|]
604− default_success_confirm_results
604+ defaultSuccessConfirmResults
605605 }
606606
607−attributes_test_1 = Test
608− { test_name = "Character attributes: background colors."
609− , test_ID = "attributes_test_1"
610− , test_action = do
611− t <- output_for_current_terminal
612− reserve_display t
613− let pic = pic_for_image image
614− image = border <|> column_0 <|> border <|> column_1 <|> border
615− column_0 = vert_cat $ map line_with_color all_colors
616− border = vert_cat $ replicate (length all_colors) $ string def_attr " | "
617− column_1 = vert_cat $ map (string def_attr . snd) all_colors
618− line_with_color (c, c_name) = string (def_attr `with_back_color` c) c_name
619− d <- display_bounds t >>= display_context t
620− output_picture d pic
607+attributesTest1 = Test
608+ { testName = "Character attributes: background colors."
609+ , testID = "attributesTest1"
610+ , testAction = do
611+ t <- outputForCurrentTerminal
612+ reserveDisplay t
613+ let pic = picForImage image
614+ image = border <|> column0 <|> border <|> column1 <|> border
615+ column0 = vertCat $ map lineWithColor allColors
616+ border = vertCat $ replicate (length allColors) $ string defAttr " | "
617+ column1 = vertCat $ map (string defAttr . snd) allColors
618+ lineWithColor (c, cName) = string (defAttr `withBackColor` c) cName
619+ d <- displayBounds t >>= displayContext t
620+ outputPicture d pic
621621 getLine
622− release_display t
623− release_terminal t
622+ releaseDisplay t
623+ releaseTerminal t
624624 return ()
625− , print_summary = do
625+ , printSummary = do
626626 putStr $ [s|
627627Once return is pressed:
628628 0. The screen will be cleared.
@@ -652,34 +652,34 @@ After return is pressed for the second time:
652652 0. The screen containing the test summary should be restored.
653653 1. The cursor should be visible.
654654|]
655− , confirm_results = do
655+ , confirmResults = do
656656 putStr $ [s|
657657Did the test output match the description?
658658|]
659− default_success_confirm_results
659+ defaultSuccessConfirmResults
660660 }
661661
662−attributes_test_2 = Test
663− { test_name = "Character attributes: Vivid foreground colors."
664− , test_ID = "attributes_test_2"
665− , test_action = do
666− t <- output_for_current_terminal
667− reserve_display t
668− let pic = pic_for_image image
669− image = horiz_cat [border, column_0, border, column_1, border, column_2, border]
670− border = vert_cat $ replicate (length all_colors) $ string def_attr " | "
671− column_0 = vert_cat $ map line_with_color_0 all_colors
672− column_1 = vert_cat $ map line_with_color_1 all_bright_colors
673− column_2 = vert_cat $ map (string def_attr . snd) all_colors
674− line_with_color_0 (c, c_name) = string (def_attr `with_fore_color` c) c_name
675− line_with_color_1 (c, c_name) = string (def_attr `with_fore_color` c) c_name
676− d <- display_bounds t >>= display_context t
677− output_picture d pic
662+attributesTest2 = Test
663+ { testName = "Character attributes: Vivid foreground colors."
664+ , testID = "attributesTest2"
665+ , testAction = do
666+ t <- outputForCurrentTerminal
667+ reserveDisplay t
668+ let pic = picForImage image
669+ image = horizCat [border, column0, border, column1, border, column2, border]
670+ border = vertCat $ replicate (length allColors) $ string defAttr " | "
671+ column0 = vertCat $ map lineWithColor0 allColors
672+ column1 = vertCat $ map lineWithColor1 allBrightColors
673+ column2 = vertCat $ map (string defAttr . snd) allColors
674+ lineWithColor0 (c, cName) = string (defAttr `withForeColor` c) cName
675+ lineWithColor1 (c, cName) = string (defAttr `withForeColor` c) cName
676+ d <- displayBounds t >>= displayContext t
677+ outputPicture d pic
678678 getLine
679− release_display t
680− release_terminal t
679+ releaseDisplay t
680+ releaseTerminal t
681681 return ()
682− , print_summary = do
682+ , printSummary = do
683683 putStr $ [s|
684684Once return is pressed:
685685 0. The screen will be cleared.
@@ -711,34 +711,34 @@ After return is pressed for the second time:
711711 0. The screen containing the test summary should be restored.
712712 1. The cursor should be visible.
713713|]
714− , confirm_results = do
714+ , confirmResults = do
715715 putStr $ [s|
716716Did the test output match the description?
717717|]
718− default_success_confirm_results
718+ defaultSuccessConfirmResults
719719 }
720720
721−attributes_test_3 = Test
722− { test_name = "Character attributes: Vivid background colors."
723− , test_ID = "attributes_test_3"
724− , test_action = do
725− t <- output_for_current_terminal
726− reserve_display t
727− let pic = pic_for_image image
728− image = horiz_cat [border, column_0, border, column_1, border, column_2, border]
729− border = vert_cat $ replicate (length all_colors) $ string def_attr " | "
730− column_0 = vert_cat $ map line_with_color_0 all_colors
731− column_1 = vert_cat $ map line_with_color_1 all_bright_colors
732− column_2 = vert_cat $ map (string def_attr . snd) all_colors
733− line_with_color_0 (c, c_name) = string (def_attr `with_back_color` c) c_name
734− line_with_color_1 (c, c_name) = string (def_attr `with_back_color` c) c_name
735− d <- display_bounds t >>= display_context t
736− output_picture d pic
721+attributesTest3 = Test
722+ { testName = "Character attributes: Vivid background colors."
723+ , testID = "attributesTest3"
724+ , testAction = do
725+ t <- outputForCurrentTerminal
726+ reserveDisplay t
727+ let pic = picForImage image
728+ image = horizCat [border, column0, border, column1, border, column2, border]
729+ border = vertCat $ replicate (length allColors) $ string defAttr " | "
730+ column0 = vertCat $ map lineWithColor0 allColors
731+ column1 = vertCat $ map lineWithColor1 allBrightColors
732+ column2 = vertCat $ map (string defAttr . snd) allColors
733+ lineWithColor0 (c, cName) = string (defAttr `withBackColor` c) cName
734+ lineWithColor1 (c, cName) = string (defAttr `withBackColor` c) cName
735+ d <- displayBounds t >>= displayContext t
736+ outputPicture d pic
737737 getLine
738− release_display t
739− release_terminal t
738+ releaseDisplay t
739+ releaseTerminal t
740740 return ()
741− , print_summary = do
741+ , printSummary = do
742742 putStr $ [s|
743743Once return is pressed:
744744 0. The screen will be cleared.
@@ -778,43 +778,43 @@ After return is pressed for the second time:
778778 0. The screen containing the test summary should be restored.
779779 1. The cursor should be visible.
780780|]
781− , confirm_results = do
781+ , confirmResults = do
782782 putStr $ [s|
783783Did the test output match the description?
784784|]
785− default_success_confirm_results
785+ defaultSuccessConfirmResults
786786 }
787787
788−attr_combos =
788+attrCombos =
789789 [ ( "default", id )
790− , ( "bold", flip with_style bold )
791− , ( "blink", flip with_style blink )
792− , ( "underline", flip with_style underline )
793− , ( "bold + blink", flip with_style (bold + blink) )
794− , ( "bold + underline", flip with_style (bold + underline) )
795− , ( "underline + blink", flip with_style (underline + blink) )
796− , ( "bold + blink + underline", flip with_style (bold + blink + underline) )
790+ , ( "bold", flip withStyle bold )
791+ , ( "blink", flip withStyle blink )
792+ , ( "underline", flip withStyle underline )
793+ , ( "bold + blink", flip withStyle (bold + blink) )
794+ , ( "bold + underline", flip withStyle (bold + underline) )
795+ , ( "underline + blink", flip withStyle (underline + blink) )
796+ , ( "bold + blink + underline", flip withStyle (bold + blink + underline) )
797797 ]
798798
799−attributes_test_4 = Test
800− { test_name = "Character attributes: Bold; Blink; Underline."
801− , test_ID = "attributes_test_4"
802− , test_action = do
803− t <- output_for_current_terminal
804− reserve_display t
805− let pic = pic_for_image image
806− image = horiz_cat [border, column_0, border, column_1, border]
807− border = vert_cat $ replicate (length attr_combos) $ string def_attr " | "
808− column_0 = vert_cat $ map line_with_attrs attr_combos
809− column_1 = vert_cat $ map (string def_attr . fst) attr_combos
810− line_with_attrs (desc, attr_f) = string (attr_f def_attr) desc
811− d <- display_bounds t >>= display_context t
812− output_picture d pic
799+attributesTest4 = Test
800+ { testName = "Character attributes: Bold; Blink; Underline."
801+ , testID = "attributesTest4"
802+ , testAction = do
803+ t <- outputForCurrentTerminal
804+ reserveDisplay t
805+ let pic = picForImage image
806+ image = horizCat [border, column0, border, column1, border]
807+ border = vertCat $ replicate (length attrCombos) $ string defAttr " | "
808+ column0 = vertCat $ map lineWithAttrs attrCombos
809+ column1 = vertCat $ map (string defAttr . fst) attrCombos
810+ lineWithAttrs (desc, attrF) = string (attrF defAttr) desc
811+ d <- displayBounds t >>= displayContext t
812+ outputPicture d pic
813813 getLine
814− release_display t
815− release_terminal t
814+ releaseDisplay t
815+ releaseTerminal t
816816 return ()
817− , print_summary = do
817+ , printSummary = do
818818 putStr $ [s|
819819Once return is pressed:
820820 0. The screen will be cleared.
@@ -841,31 +841,31 @@ After return is pressed for the second time:
841841 0. The screen containing the test summary should be restored.
842842 1. The cursor should be visible.
843843|]
844− , confirm_results = do
844+ , confirmResults = do
845845 putStr $ [s|
846846Did the test output match the description?
847847|]
848− default_success_confirm_results
848+ defaultSuccessConfirmResults
849849 }
850850
851−attributes_test_5 = Test
852− { test_name = "Character attributes: 240 color palette"
853− , test_ID = "attributes_test_5"
854− , test_action = do
855− t <- output_for_current_terminal
856− reserve_display t
857− let pic = pic_for_image image
858− image = vert_cat $ map horiz_cat $ split_color_images color_images
859− color_images = map (\i -> string (current_attr `with_back_color` Color240 i) " ") [0..239]
860− split_color_images [] = []
861− split_color_images is = (take 20 is ++ [string def_attr " "]) : (split_color_images (drop 20 is))
862− d <- display_bounds t >>= display_context t
863− output_picture d pic
851+attributesTest5 = Test
852+ { testName = "Character attributes: 240 color palette"
853+ , testID = "attributesTest5"
854+ , testAction = do
855+ t <- outputForCurrentTerminal
856+ reserveDisplay t
857+ let pic = picForImage image
858+ image = vertCat $ map horizCat $ splitColorImages colorImages
859+ colorImages = map (\i -> string (currentAttr `withBackColor` Color240 i) " ") [0..239]
860+ splitColorImages [] = []
861+ splitColorImages is = (take 20 is ++ [string defAttr " "]) : (splitColorImages (drop 20 is))
862+ d <- displayBounds t >>= displayContext t
863+ outputPicture d pic
864864 getLine
865− release_display t
866− release_terminal t
865+ releaseDisplay t
866+ releaseTerminal t
867867 return ()
868− , print_summary = do
868+ , printSummary = do
869869 putStr $ [s|
870870Once return is pressed:
871871 0. The screen will be cleared.
@@ -879,290 +879,290 @@ After return is pressed for the second time:
879879 0. The screen containing the test summary should be restored.
880880 1. The cursor should be visible.
881881|]
882− , confirm_results = do
882+ , confirmResults = do
883883 putStr $ [s|
884884Did the test output match the description?
885885|]
886− default_success_confirm_results
886+ defaultSuccessConfirmResults
887887 }
888888
889−inline_test_0 = Test
890− { test_name = "Verify styled output can be performed without clearing the screen."
891− , test_ID = "inline_test_0"
892− , test_action = do
889+inlineTest0 = Test
890+ { testName = "Verify styled output can be performed without clearing the screen."
891+ , testID = "inlineTest0"
892+ , testAction = do
893893 putStrLn "line 1."
894− put_attr_change_ $ back_color red >> apply_style underline
894+ putAttrChange_ $ backColor red >> applyStyle underline
895895 putStrLn "line 2."
896− put_attr_change_ $ default_all
896+ putAttrChange_ $ defaultAll
897897 putStrLn "line 3."
898− , print_summary = putStr $ [s|
898+ , printSummary = putStr $ [s|
899899lines are in order.
900900The second line "line 2" should have a red background and the text underline.
901901The third line "line 3" should be drawn in the same style as the first line.
902902|]
903903
904− , confirm_results = generic_output_match_confirm
904+ , confirmResults = genericOutputMatchConfirm
905905 }
906906
907−inline_test_1 = Test
908− { test_name = "Verify styled output can be performed without clearing the screen."
909− , test_ID = "inline_test_1"
910− , test_action = do
907+inlineTest1 = Test
908+ { testName = "Verify styled output can be performed without clearing the screen."
909+ , testID = "inlineTest1"
910+ , testAction = do
911911 putStr "Not styled. "
912− put_attr_change_ $ back_color red >> apply_style underline
912+ putAttrChange_ $ backColor red >> applyStyle underline
913913 putStr " Styled! "
914− put_attr_change_ $ default_all
914+ putAttrChange_ $ defaultAll
915915 putStrLn "Not styled."
916− , print_summary = putStr $ [s|
916+ , printSummary = putStr $ [s|
917917|]
918918
919− , confirm_results = generic_output_match_confirm
919+ , confirmResults = genericOutputMatchConfirm
920920 }
921921
922−inline_test_2 = Test
923− { test_name = "Verify styled output can be performed without clearing the screen."
924− , test_ID = "inline_test_1"
925− , test_action = do
922+inlineTest2 = Test
923+ { testName = "Verify styled output can be performed without clearing the screen."
924+ , testID = "inlineTest1"
925+ , testAction = do
926926 putStr "Not styled. "
927− put_attr_change_ $ back_color red >> apply_style underline
927+ putAttrChange_ $ backColor red >> applyStyle underline
928928 putStr " Styled! "
929− put_attr_change_ $ default_all
929+ putAttrChange_ $ defaultAll
930930 putStr "Not styled.\n"
931− , print_summary = putStr $ [s|
931+ , printSummary = putStr $ [s|
932932|]
933− , confirm_results = generic_output_match_confirm
933+ , confirmResults = genericOutputMatchConfirm
934934 }
935935
936−cursor_hide_test_0 :: Test
937−cursor_hide_test_0 = Test
938− { test_name = "Verify the cursor is hid and re-shown. issue #7"
939− , test_ID = "cursor_hide_test_0"
940− , test_action = do
936+cursorHideTest0 :: Test
937+cursorHideTest0 = Test
938+ { testName = "Verify the cursor is hid and re-shown. issue #7"
939+ , testID = "cursorHideTest0"
940+ , testAction = do
941941 vty <- mkVty def
942− show_cursor $ output_iface vty
943− set_cursor_pos (output_iface vty) 5 5
944− next_event vty
945− hide_cursor $ output_iface vty
946− next_event vty
942+ showCursor $ outputIface vty
943+ setCursorPos (outputIface vty) 5 5
944+ nextEvent vty
945+ hideCursor $ outputIface vty
946+ nextEvent vty
947947 shutdown vty
948948 return ()
949− , print_summary = putStr $ [s|
949+ , printSummary = putStr $ [s|
950950 1. verify the cursor is displayed.
951951 2. press enter
952952 3. verify the cursor is hid.
953953 4. press enter.
954954 5. the display should return to the state before the test.
955955|]
956− , confirm_results = generic_output_match_confirm
956+ , confirmResults = genericOutputMatchConfirm
957957 }
958958
959−output_image_and_wait :: Image -> IO ()
960−output_image_and_wait image = do
961− let pic = pic_for_image image
962− output_pic_and_wait pic
963−
964−output_pic_and_wait :: Picture -> IO ()
965−output_pic_and_wait pic = do
966− t <- output_for_current_terminal
967− reserve_display t
968− d <- display_bounds t >>= display_context t
969− output_picture d pic
959+outputImageAndWait :: Image -> IO ()
960+outputImageAndWait image = do
961+ let pic = picForImage image
962+ outputPicAndWait pic
963+
964+outputPicAndWait :: Picture -> IO ()
965+outputPicAndWait pic = do
966+ t <- outputForCurrentTerminal
967+ reserveDisplay t
968+ d <- displayBounds t >>= displayContext t
969+ outputPicture d pic
970970 getLine
971− release_display t
972− release_terminal t
971+ releaseDisplay t
972+ releaseTerminal t
973973 return ()
974974
975−vert_crop_test_0 :: Test
976−vert_crop_test_0 = Test
977− { test_name = "Verify bottom cropping works as expected with single column chars"
978− , test_ID = "crop_test_0"
979− , test_action = do
980− let block_0 = crop_bottom 2 $ vert_cat $ map (string def_attr) lorum_ipsum
981− block_1 = vert_cat $ map (string def_attr) $ take 2 lorum_ipsum
982− image = block_0 <-> background_fill 10 2 <-> block_1
983− output_image_and_wait image
984− , print_summary = putStr $ [s|
975+vertCropTest0 :: Test
976+vertCropTest0 = Test
977+ { testName = "Verify bottom cropping works as expected with single column chars"
978+ , testID = "crop_test_0"
979+ , testAction = do
980+ let block0 = cropBottom 2 $ vertCat $ map (string defAttr) lorumIpsum
981+ block1 = vertCat $ map (string defAttr) $ take 2 lorumIpsum
982+ image = block0 <-> backgroundFill 10 2 <-> block1
983+ outputImageAndWait image
984+ , printSummary = putStr $ [s|
985985 1. Verify the two text blocks are identical.
986986 2. press enter.
987987 3. the display should return to the state before the test.
988988|]
989− , confirm_results = generic_output_match_confirm
989+ , confirmResults = genericOutputMatchConfirm
990990 }
991991
992−vert_crop_test_1 :: Test
993−vert_crop_test_1 = Test
994− { test_name = "Verify bottom cropping works as expected with double column chars"
995− , test_ID = "crop_test_0"
996− , test_action = do
997− let block_0 = crop_bottom 2 $ vert_cat $ map (string def_attr) lorum_ipsum_chinese
998− block_1 = vert_cat $ map (string def_attr) $ take 2 lorum_ipsum_chinese
999− image = block_0 <-> background_fill 10 2 <-> block_1
1000− output_image_and_wait image
1001− , print_summary = putStr $ [s|
992+vertCropTest1 :: Test
993+vertCropTest1 = Test
994+ { testName = "Verify bottom cropping works as expected with double column chars"
995+ , testID = "crop_test_0"
996+ , testAction = do
997+ let block0 = cropBottom 2 $ vertCat $ map (string defAttr) lorumIpsumChinese
998+ block1 = vertCat $ map (string defAttr) $ take 2 lorumIpsumChinese
999+ image = block0 <-> backgroundFill 10 2 <-> block1
1000+ outputImageAndWait image
1001+ , printSummary = putStr $ [s|
10021002 1. Verify the two text blocks are identical.
10031003 2. press enter.
10041004 3. the display should return to the state before the test.
10051005|]
1006− , confirm_results = generic_output_match_confirm
1006+ , confirmResults = genericOutputMatchConfirm
10071007 }
10081008
1009−vert_crop_test_2 :: Test
1010−vert_crop_test_2 = Test
1011− { test_name = "Verify top cropping works as expected with single column chars"
1012− , test_ID = "crop_test_0"
1013− , test_action = do
1014− let block_0 = crop_top 2 $ vert_cat $ map (string def_attr) lorum_ipsum
1015− block_1 = vert_cat $ map (string def_attr) $ drop (length lorum_ipsum - 2) lorum_ipsum
1016− image = block_0 <-> background_fill 10 2 <-> block_1
1017− output_image_and_wait image
1018− , print_summary = putStr $ [s|
1009+vertCropTest2 :: Test
1010+vertCropTest2 = Test
1011+ { testName = "Verify top cropping works as expected with single column chars"
1012+ , testID = "crop_test_2"
1013+ , testAction = do
1014+ let block0 = cropTop 2 $ vertCat $ map (string defAttr) lorumIpsum
1015+ block1 = vertCat $ map (string defAttr) $ drop (length lorumIpsum - 2) lorumIpsum
1016+ image = block0 <-> backgroundFill 10 2 <-> block1
1017+ outputImageAndWait image
1018+ , printSummary = putStr $ [s|
10191019 1. Verify the two text blocks are identical.
10201020 2. press enter.
10211021 3. the display should return to the state before the test.
10221022|]
1023− , confirm_results = generic_output_match_confirm
1023+ , confirmResults = genericOutputMatchConfirm
10241024 }
10251025
1026−vert_crop_test_3 :: Test
1027−vert_crop_test_3 = Test
1028− { test_name = "Verify top cropping works as expected with double column chars"
1029− , test_ID = "crop_test_0"
1030− , test_action = do
1031− let block_0 = crop_top 2 $ vert_cat $ map (string def_attr) lorum_ipsum_chinese
1032− block_1 = vert_cat $ map (string def_attr) $ drop (length lorum_ipsum_chinese - 2 ) lorum_ipsum_chinese
1033− image = block_0 <-> background_fill 10 2 <-> block_1
1034− output_image_and_wait image
1035− , print_summary = putStr $ [s|
1026+vertCropTest3 :: Test
1027+vertCropTest3 = Test
1028+ { testName = "Verify top cropping works as expected with double column chars"
1029+ , testID = "crop_test_0"
1030+ , testAction = do
1031+ let block0 = cropTop 2 $ vertCat $ map (string defAttr) lorumIpsumChinese
1032+ block1 = vertCat $ map (string defAttr) $ drop (length lorumIpsumChinese - 2 ) lorumIpsumChinese
1033+ image = block0 <-> backgroundFill 10 2 <-> block1
1034+ outputImageAndWait image
1035+ , printSummary = putStr $ [s|
10361036 1. Verify the two text blocks are identical.
10371037 2. press enter.
10381038 3. the display should return to the state before the test.
10391039|]
1040− , confirm_results = generic_output_match_confirm
1040+ , confirmResults = genericOutputMatchConfirm
10411041 }
10421042
1043−horiz_crop_test_0 :: Test
1044−horiz_crop_test_0 = Test
1045− { test_name = "Verify right cropping works as expected with single column chars"
1046− , test_ID = "crop_test_0"
1047− , test_action = do
1048− let base_image = vert_cat $ map (string def_attr) lorum_ipsum
1049− cropped_image = crop_right (image_width base_image `div` 2) base_image
1050− image = base_image <-> background_fill 10 2 <-> cropped_image
1051− output_image_and_wait image
1052− , print_summary = putStr $ [s|
1043+horizCropTest0 :: Test
1044+horizCropTest0 = Test
1045+ { testName = "Verify right cropping works as expected with single column chars"
1046+ , testID = "crop_test_0"
1047+ , testAction = do
1048+ let baseImage = vertCat $ map (string defAttr) lorumIpsum
1049+ croppedImage = cropRight (imageWidth baseImage `div` 2) baseImage
1050+ image = baseImage <-> backgroundFill 10 2 <-> croppedImage
1051+ outputImageAndWait image
1052+ , printSummary = putStr $ [s|
10531053 1. Verify the bottom text block is about half the width of the top text block.
10541054 2. press enter.
10551055 3. the display should return to the state before the test.
10561056|]
1057− , confirm_results = generic_output_match_confirm
1057+ , confirmResults = genericOutputMatchConfirm
10581058 }
10591059
1060−horiz_crop_test_1 :: Test
1061−horiz_crop_test_1 = Test
1062− { test_name = "Verify right cropping works as expected with double column chars"
1063− , test_ID = "crop_test_0"
1064− , test_action = do
1065− let base_image = vert_cat $ map (string def_attr) lorum_ipsum_chinese
1066− cropped_image = crop_right (image_width base_image `div` 2) base_image
1067− image = base_image <-> background_fill 10 2 <-> cropped_image
1068− output_image_and_wait image
1069− , print_summary = putStr $ [s|
1060+horizCropTest1 :: Test
1061+horizCropTest1 = Test
1062+ { testName = "Verify right cropping works as expected with double column chars"
1063+ , testID = "crop_test_0"
1064+ , testAction = do
1065+ let baseImage = vertCat $ map (string defAttr) lorumIpsumChinese
1066+ croppedImage = cropRight (imageWidth baseImage `div` 2) baseImage
1067+ image = baseImage <-> backgroundFill 10 2 <-> croppedImage
1068+ outputImageAndWait image
1069+ , printSummary = putStr $ [s|
10701070 1. Verify the bottom text block is the left half of the top block. Ellipses on the right edge are OK.
10711071 2. press enter.
10721072 3. the display should return to the state before the test.
10731073|]
1074− , confirm_results = generic_output_match_confirm
1074+ , confirmResults = genericOutputMatchConfirm
10751075 }
10761076
1077−horiz_crop_test_2 :: Test
1078−horiz_crop_test_2 = Test
1079− { test_name = "Verify left cropping works as expected with single column chars"
1080− , test_ID = "crop_test_0"
1081− , test_action = do
1082− let base_image = vert_cat $ map (string def_attr) lorum_ipsum
1083− cropped_image = crop_left (image_width base_image `div` 2) base_image
1084− image = base_image <-> background_fill 10 2 <-> cropped_image
1085− output_image_and_wait image
1086− , print_summary = putStr $ [s|
1077+horizCropTest2 :: Test
1078+horizCropTest2 = Test
1079+ { testName = "Verify left cropping works as expected with single column chars"
1080+ , testID = "crop_test_0"
1081+ , testAction = do
1082+ let baseImage = vertCat $ map (string defAttr) lorumIpsum
1083+ croppedImage = cropLeft (imageWidth baseImage `div` 2) baseImage
1084+ image = baseImage <-> backgroundFill 10 2 <-> croppedImage
1085+ outputImageAndWait image
1086+ , printSummary = putStr $ [s|
10871087 1. Verify the bottom text block is the right half of the top text block.
10881088 2. press enter.
10891089 3. the display should return to the state before the test.
10901090|]
1091− , confirm_results = generic_output_match_confirm
1091+ , confirmResults = genericOutputMatchConfirm
10921092 }
10931093
1094−horiz_crop_test_3 :: Test
1095−horiz_crop_test_3 = Test
1096− { test_name = "Verify right cropping works as expected with double column chars"
1097− , test_ID = "crop_test_0"
1098− , test_action = do
1099− let base_image = vert_cat $ map (string def_attr) lorum_ipsum_chinese
1100− cropped_image = crop_left (image_width base_image `div` 2) base_image
1101− image = base_image <-> background_fill 10 2 <-> cropped_image
1102− output_image_and_wait image
1103− , print_summary = putStr $ [s|
1094+horizCropTest3 :: Test
1095+horizCropTest3 = Test
1096+ { testName = "Verify right cropping works as expected with double column chars"
1097+ , testID = "crop_test_0"
1098+ , testAction = do
1099+ let baseImage = vertCat $ map (string defAttr) lorumIpsumChinese
1100+ croppedImage = cropLeft (imageWidth baseImage `div` 2) baseImage
1101+ image = baseImage <-> backgroundFill 10 2 <-> croppedImage
1102+ outputImageAndWait image
1103+ , printSummary = putStr $ [s|
11041104 1. Verify the bottom text block is the right half of the top block. Ellipses on the left edge are OK.
11051105 2. press enter.
11061106 3. the display should return to the state before the test.
11071107|]
1108− , confirm_results = generic_output_match_confirm
1108+ , confirmResults = genericOutputMatchConfirm
11091109 }
11101110
1111−layer_0 :: Test
1112−layer_0 = Test
1113− { test_name = "verify layer 0"
1114− , test_ID = "layer_0"
1115− , test_action = do
1116− let upper_image = vert_cat $ map (string def_attr) lorum_ipsum_chinese
1117− lower_image = vert_cat $ map (string def_attr) lorum_ipsum
1118− p = pic_for_layers [upper_image, lower_image]
1119− output_pic_and_wait p
1120− , print_summary = putStr $ [s|
1111+layer0 :: Test
1112+layer0 = Test
1113+ { testName = "verify layer 0"
1114+ , testID = "layer0"
1115+ , testAction = do
1116+ let upperImage = vertCat $ map (string defAttr) lorumIpsumChinese
1117+ lowerImage = vertCat $ map (string defAttr) lorumIpsum
1118+ p = picForLayers [upperImage, lowerImage]
1119+ outputPicAndWait p
1120+ , printSummary = putStr $ [s|
11211121 1. Verify the text block appears to be Chinese text placed on top Latin text.
11221122 2. press enter.
11231123 3. the display should return to the state before the test.
11241124|]
1125− , confirm_results = generic_output_match_confirm
1125+ , confirmResults = genericOutputMatchConfirm
11261126 }
11271127
1128−layer_1 :: Test
1129−layer_1 = Test
1130− { test_name = "verify layer 1"
1131− , test_ID = "layer_1"
1132− , test_action = do
1133− let upper_image = vert_cat $ map (string def_attr) lorum_ipsum_chinese
1134− block = resize 10 10 upper_image
1135− layer_0 = vert_cat $ map (string def_attr) lorum_ipsum
1136− layer_1 = char_fill (def_attr `with_back_color` blue) '#' 1000 1000
1137− cheesy_anim_0 block [layer_0, layer_1]
1138− , print_summary = putStr $ [s|
1128+layer1 :: Test
1129+layer1 = Test
1130+ { testName = "verify layer 1"
1131+ , testID = "layer1"
1132+ , testAction = do
1133+ let upperImage = vertCat $ map (string defAttr) lorumIpsumChinese
1134+ block = resize 10 10 upperImage
1135+ layer0 = vertCat $ map (string defAttr) lorumIpsum
1136+ layer1 = charFill (defAttr `withBackColor` blue) '#' 1000 1000
1137+ cheesyAnim0 block [layer0, layer1]
1138+ , printSummary = putStr $ [s|
11391139 1. Verify the text block appears to be Chinese text moving on top a Latin text.
11401140 Which is all on a background of '#' characters over blue.
11411141 2. press enter.
11421142 3. the display should return to the state before the test.
11431143|]
1144− , confirm_results = generic_output_match_confirm
1144+ , confirmResults = genericOutputMatchConfirm
11451145 }
11461146
1147−cheesy_anim_0 :: Image -> [Image] -> IO ()
1148−cheesy_anim_0 i background = do
1149− t <- output_for_current_terminal
1150− reserve_display t
1151− bounds <- display_bounds t
1152− d <- display_context t bounds
1147+cheesyAnim0 :: Image -> [Image] -> IO ()
1148+cheesyAnim0 i background = do
1149+ t <- outputForCurrentTerminal
1150+ reserveDisplay t
1151+ bounds <- displayBounds t
1152+ d <- displayContext t bounds
11531153 forM_ [0..100] $ \t -> do
11541154 let i_offset = translate (t `mod` fst bounds)
11551155 (t `div` 2 `mod` snd bounds)
11561156 i
1157− let pic = pic_for_layers $ i_offset : background
1158− output_picture d pic
1157+ let pic = picForLayers $ i_offset : background
1158+ outputPicture d pic
11591159 threadDelay 50000
1160− release_display t
1161− release_terminal t
1160+ releaseDisplay t
1161+ releaseTerminal t
11621162 return ()
11631163
1164−lorum_ipsum :: [String]
1165−lorum_ipsum = lines [s|
1164+lorumIpsum :: [String]
1165+lorumIpsum = lines [s|
11661166Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium,
11671167totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae
11681168dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit,
@@ -1174,8 +1174,8 @@ commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate v
11741174molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
11751175|]
11761176
1177−lorum_ipsum_chinese :: [String]
1178−lorum_ipsum_chinese = lines [s|
1177+lorumIpsumChinese :: [String]
1178+lorumIpsumChinese = lines [s|
11791179輐銛 螷蟞覮 裌覅詵 暕 鴅噮 槶 惝掭掝 婸媥媕 耏胠臿, 汫汭沎 忕汌卣 蚡袀 僣 蒮 瀁瀎瀊 渮湸湤 緌翢,
11801180腠腶舝 糲蘥蠩 樏殣氀 蒮 蹢鎒 滍 鸄齴 櫧櫋瀩 鬄鵊鵙 莃荶衒, 毸溠 橀 簎艜薤 莃荶衒 翣聜蒢
11811181斔櫅檷 晛桼桾 拻敁柧 犿玒 膣, 墐 笓粊紒 bacon 鼀齕, 蔝蓶蓨 顊顃餭 姴怤 骱 暕 蹢鎒鎛 藒襓謥 鄻鎟霣
test/vty-examples.cabal+6−6
@@ -27,7 +27,7 @@ executable vty-interactive-terminal-test
2727 default-extensions: ScopedTypeVariables
2828 ghc-options: -threaded
2929
30− build-depends: vty,
30+ build-depends: vty == 5.*,
3131 base >= 4 && < 5,
3232 bytestring,
3333 containers,
@@ -38,7 +38,7 @@ executable vty-interactive-terminal-test
3838 parallel >= 2.2 && < 3.3,
3939 parsec >= 2 && < 4,
4040 string-qq,
41− terminfo >= 0.3 && < 0.4,
41+ terminfo >= 0.3 && < 0.5,
4242 text >= 0.11.3,
4343 unix,
4444 utf8-string >= 0.3 && < 0.4,
@@ -51,7 +51,7 @@ executable vty-event-echo
5151 default-extensions: ScopedTypeVariables
5252 ghc-options: -threaded
5353
54− build-depends: vty,
54+ build-depends: vty == 5.*,
5555 base >= 4 && < 5,
5656 array >= 0.4 && < 2.0,
5757 bytestring,
@@ -71,7 +71,7 @@ executable vty-rouge
7171 default-extensions: ScopedTypeVariables
7272 ghc-options: -threaded
7373
74− build-depends: vty,
74+ build-depends: vty == 5.*,
7575 base >= 4 && < 5,
7676 array >= 0.4 && < 2.0,
7777 bytestring,
@@ -92,7 +92,7 @@ executable vty-benchmark
9292 default-extensions: ScopedTypeVariables
9393 ghc-options: -threaded
9494
95− build-depends: vty,
95+ build-depends: vty == 5.*,
9696 base >= 4 && < 5,
9797 bytestring,
9898 Cabal == 1.18.*,
@@ -106,7 +106,7 @@ executable vty-benchmark
106106 QuickCheck >= 2.4,
107107 random == 1.0.*,
108108 string-qq,
109− terminfo >= 0.3 && < 0.4,
109+ terminfo >= 0.3 && < 0.5,
110110 text >= 0.11.3,
111111 unix,
112112 utf8-string >= 0.3 && < 0.4,
test/vty_inline_example.hs+2−2
@@ -3,7 +3,7 @@ import Graphics.Vty.Inline
33
44main = do
55 putStr "Not styled. "
6− put_attr_change_ t $ back_color red >> apply_style underline
6+ putAttrChange_ t $ backColor red >> applyStyle underline
77 putStr " Styled! "
8− put_attr_change_ t $ default_all
8+ putAttrChange_ t $ defaultAll
99 putStrLn "Not styled."