1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
|
{-# LANGUAGE CPP #-}
{-# OPTIONS -#include HSCursesUtils.h -#include <signal.h> #-}
--
-- Copyright (C) 2005-2011 Stefan Wehr
--
-- Derived from: yi/Curses/UI.hs
-- Copyright (C) 2004 Don Stewart - http://www.cse.unsw.edu.au/~dons
-- Released under the GPL, granted permission to release this module
-- under the LGPL.
--
-- Derived from: riot/UI.hs
-- Copyright (c) Tuomo Valkonen 2004.
-- Released under the GPL, granted permission to release this module
-- under the LGPL.
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
module UI.HSCurses.CursesHelper (
-- * UI initialisation
start, end, suspend, resizeui,
-- * Input
getKey,
-- * Drawing
drawLine, drawCursor,
-- * Navigation
gotoTop,
-- * Colors
ForegroundColor(..), BackgroundColor(..),
defaultColor, black, red, green, yellow, blue, magenta, cyan, white,
-- * Attributes
Attribute(..), convertAttributes,
-- * Style
Style(..), CursesStyle, mkCursesStyle, changeCursesStyle,
setStyle, resetStyle, convertStyles,
defaultStyle, defaultCursesStyle, withStyle,
-- * Keys
displayKey,
-- * Helpers
withCursor, withProgram
) where
import UI.HSCurses.Curses hiding ( refresh, Window )
import UI.HSCurses.Logging
import UI.HSCurses.MonadException
import qualified UI.HSCurses.Curses as Curses
import Data.Char
import Data.Maybe
import Data.List
import Control.Monad.Trans
#ifndef mingw32_HOST_OS
import System.Posix.Signals
#endif
--
--
--
-- | @start@ initializes the UI and grabs the keyboard.
--
-- This function installs a handler for the SIGWINCH signal
-- which writes the KEY_RESIZE key to the input queue (if KEY_RESIZE and
-- and SIGWINCH are both available).
--
start :: IO ()
start = do
Curses.initCurses -- initialise the screen
Curses.resetParams
Curses.keypad Curses.stdScr True -- grab the keyboard
case (Curses.cursesSigWinch, Curses.keyResizeCode) of
#ifndef mingw32_HOST_OS
(Just sig, Just key) ->
do installHandler sig (Catch $ sigwinch sig key) Nothing
return ()
#endif
_ -> debug ("cannot install SIGWINCH handler: signal=" ++
show Curses.cursesSigWinch ++ ", KEY_RESIZE=" ++
show Curses.keyResizeCode)
#ifndef mingw32_HOST_OS
where sigwinch sig key =
do debug "SIGWINCH signal received"
Curses.ungetCh key
installHandler sig (Catch $ sigwinch sig key) Nothing
return ()
#endif
--
-- | Clean up and go home.
--
end :: IO ()
end = do Curses.endWin
-- Refresh is needed on linux. grr.
#if NCURSES_UPDATE_AFTER_END
Curses.update
#endif
--
-- | Suspend the program.
--
suspend :: IO ()
#ifndef mingw32_HOST_OS
suspend = raiseSignal sigTSTP
#else
suspend = return ()
#endif
--
-- | @getKey refresh@ reads a key.
--
-- The @refresh@ function is used to redraw the screen when the terminal size
-- changes (see the documentatio of @start@ for a discussion of the problem).
--
getKey :: MonadIO m => m () -> m Key
getKey refresh = do
k <- liftIO $ Curses.getCh
debug ("getKey: " ++ show k)
case k of
KeyResize ->
do refresh
getKey refresh
_ -> return k
--
-- | @drawLine n s@ draws @n@ characters of string @s@.
--
drawLine :: Int -> String -> IO ()
-- lazy version is faster than calculating length of s
drawLine w s = Curses.wAddStr Curses.stdScr $! take w (s ++ repeat ' ')
--
-- | Draw the cursor at the given position.
--
drawCursor :: (Int,Int) -> (Int, Int) -> IO ()
drawCursor (o_y,o_x) (y,x) = withCursor Curses.CursorVisible $ do
gotoTop
(h,w) <- scrSize
Curses.wMove Curses.stdScr (min (h-1) (o_y + y)) (min (w-1) (o_x + x))
--
-- | Move cursor to origin of stdScr.
--
gotoTop :: IO ()
gotoTop = Curses.wMove Curses.stdScr 0 0
--
-- | Resize the window
-- From "Writing Programs with NCURSES", by Eric S. Raymond and
-- Zeyd M. Ben-Halim
--
--
resizeui :: IO (Int,Int)
resizeui = do
Curses.endWin
Curses.refresh
Curses.scrSize
------------------------------------------------------------------------
--
-- | Basic colors.
--
defaultColor :: Curses.Color
defaultColor = fromJust $ Curses.color "default"
black, red, green, yellow, blue, magenta, cyan, white :: Curses.Color
black = fromJust $ Curses.color "black"
red = fromJust $ Curses.color "red"
green = fromJust $ Curses.color "green"
yellow = fromJust $ Curses.color "yellow"
blue = fromJust $ Curses.color "blue"
magenta = fromJust $ Curses.color "magenta"
cyan = fromJust $ Curses.color "cyan"
white = fromJust $ Curses.color "white"
--
-- | Converts a list of 'Curses.Color' pairs (foreground color and
-- background color) into the curses representation 'Curses.Pair'.
--
-- You should call this function exactly once, at application startup.
--
-- (not visible outside this module)
colorsToPairs :: [(Curses.Color, Curses.Color)] -> IO [Curses.Pair]
colorsToPairs cs =
do p <- Curses.colorPairs
let nColors = length cs
blackWhite = p < nColors
if blackWhite
then trace ("Terminal does not support enough colors. Number of " ++
" colors requested: " ++ show nColors ++
". Number of colors supported: " ++ show p)
return $ take nColors (repeat (Curses.Pair 0))
else mapM toPairs (zip [1..] cs)
where toPairs (n, (fg, bg)) =
let p = Curses.Pair n
in do Curses.initPair p fg bg
return p
------------------------------------------------------------------------
-- Nicer, user-visible color defs.
--
-- We separate colors into dark and bright colors, to prevent users
-- from erroneously constructing bright colors for dark backgrounds,
-- which doesn't work.
--
-- | Foreground colors.
--
data ForegroundColor
= BlackF
| GreyF
| DarkRedF
| RedF
| DarkGreenF
| GreenF
| BrownF
| YellowF
| DarkBlueF
| BlueF
| PurpleF
| MagentaF
| DarkCyanF
| CyanF
| WhiteF
| BrightWhiteF
| DefaultF
deriving (Eq, Show)
--
-- | Background colors.
--
data BackgroundColor
= BlackB
| DarkRedB
| DarkGreenB
| BrownB
| DarkBlueB
| PurpleB
| DarkCyanB
| WhiteB
| DefaultB
deriving (Eq, Show)
--
-- | Mapping abstract colours to ncurses attributes and colours
--
-- (not visible outside this module)
convertBg :: BackgroundColor -> ([Attribute], Curses.Color)
convertBg c = case c of
BlackB -> ([], black)
DarkRedB -> ([], red)
DarkGreenB -> ([], green)
BrownB -> ([], yellow)
DarkBlueB -> ([], blue)
PurpleB -> ([], magenta)
DarkCyanB -> ([], cyan)
WhiteB -> ([], white)
DefaultB -> ([], defaultColor)
convertFg :: ForegroundColor -> ([Attribute], Curses.Color)
convertFg c = case c of
BlackF -> ([], black)
GreyF -> ([Bold], black)
DarkRedF -> ([], red)
RedF -> ([Bold], red)
DarkGreenF -> ([], green)
GreenF -> ([Bold], green)
BrownF -> ([], yellow)
YellowF -> ([Bold], yellow)
DarkBlueF -> ([], blue)
BlueF -> ([Bold], blue)
PurpleF -> ([], magenta)
MagentaF -> ([Bold], magenta)
DarkCyanF -> ([], cyan)
CyanF -> ([Bold], cyan)
WhiteF -> ([], white)
BrightWhiteF -> ([Bold], white)
DefaultF -> ([], defaultColor)
------------------------------------------------------------------------
--
-- | Abstractions for some commonly used attributes.
--
data Attribute = Bold
| Underline
| Dim
| Reverse
| Blink
deriving (Eq, Show)
--
-- | Converts an abstract attribute list into its curses representation.
--
convertAttributes :: [Attribute] -> Curses.Attr
convertAttributes =
foldr setAttrs Curses.attr0
where setAttrs Bold = setBoldA
setAttrs Underline = setUnderlineA
setAttrs Dim = setDimA
setAttrs Reverse = setReverseA
setAttrs Blink = setBlinkA
setBoldA, setUnderlineA, setDimA,
setReverseA, setBlinkA :: Curses.Attr -> Curses.Attr
setBoldA = flip Curses.setBold True
setUnderlineA = flip Curses.setUnderline True
setDimA = flip Curses.setDim True
setReverseA = flip Curses.setReverse True
setBlinkA = flip Curses.setBlink True
------------------------------------------------------------------------
--
-- | A humand-readable style.
--
data Style = Style ForegroundColor BackgroundColor
| AttributeStyle [Attribute] ForegroundColor BackgroundColor
| ColorlessStyle [Attribute]
deriving (Eq, Show)
defaultStyle :: Style
defaultStyle = Style DefaultF DefaultB
--
-- | A style which uses the internal curses representations for
-- attributes and colors.
--
data CursesStyle = CursesStyle Curses.Attr Curses.Pair
| ColorlessCursesStyle Curses.Attr
deriving (Eq, Show)
{-
instance Show CursesStyle where
show (CursesStyle _ _) = "CursesStyle"
show (ColorlessCursesStyle _) = "ColorlessCursesStyle"
-}
mkCursesStyle :: [Attribute] -> CursesStyle
mkCursesStyle attrs = ColorlessCursesStyle (convertAttributes attrs)
--
-- | Changes the attributes of the given CursesStyle.
--
changeCursesStyle :: CursesStyle -> [Attribute] -> CursesStyle
changeCursesStyle (CursesStyle _ p) attrs =
CursesStyle (convertAttributes attrs) p
changeCursesStyle _ attrs = ColorlessCursesStyle (convertAttributes attrs)
defaultCursesStyle :: CursesStyle
defaultCursesStyle = CursesStyle Curses.attr0 (Curses.Pair 0)
--
-- | Reset the screen to normal values
--
resetStyle :: IO ()
resetStyle = setStyle defaultCursesStyle
--
-- | Manipulate the current style of the standard screen
--
setStyle :: CursesStyle -> IO ()
setStyle (CursesStyle a p) = Curses.wAttrSet Curses.stdScr (a, p)
setStyle (ColorlessCursesStyle a) =
do (_, p) <- Curses.wAttrGet Curses.stdScr
Curses.wAttrSet Curses.stdScr (a, p)
withStyle :: MonadExcIO m => CursesStyle -> m a -> m a
withStyle style action =
bracketM
(liftIO $ do old <- Curses.wAttrGet Curses.stdScr -- before
setStyle style
return old)
(\old -> liftIO $ Curses.wAttrSet Curses.stdScr old) -- after
(\_ -> action) -- do this
--
-- | Converts a list of human-readable styles into the corresponding
-- curses representation.
--
-- This function should be called exactly once at application startup
-- for all styles of the application.
convertStyles :: [Style] -> IO [CursesStyle]
convertStyles styleList =
do let (attrs, cs) = unzip $ map convertStyle styleList
cursesAttrs = map convertAttributes attrs
cursesPairs <- colorsToPairs' cs
let res = zipWith toCursesStyle cursesAttrs cursesPairs
trace ("convertStyles: " ++ show (zip styleList res)) (return res)
where convertStyle (Style fg bg) = convertStyle (AttributeStyle [] fg bg)
convertStyle (AttributeStyle attrs fg bg) =
let (afg, cfg) = convertFg fg
(abg, cbg) = convertBg bg
in (afg ++ abg ++ attrs, Just (cfg, cbg))
convertStyle (ColorlessStyle attrs) = (attrs, Nothing)
colorsToPairs' cs =
do pairs <- colorsToPairs (catMaybes cs)
return $ mergeNothing cs pairs
mergeNothing (Just _:crest) (p:prest) = Just p
: mergeNothing crest prest
mergeNothing (Nothing:crest) ps = Nothing : mergeNothing crest ps
mergeNothing [] [] = []
toCursesStyle cursesAttrs Nothing =
ColorlessCursesStyle cursesAttrs
toCursesStyle cursesAttrs (Just cursesPair) =
CursesStyle cursesAttrs cursesPair
------------------------------------------------------------------------
--
-- | Converting keys to humand-readable strings
--
displayKey :: Key -> String
displayKey (KeyChar ' ') = "<Space>"
displayKey (KeyChar '\t') = "<Tab>"
displayKey (KeyChar '\r') = "<Enter>"
displayKey (KeyChar c)
| isPrint c = [c]
displayKey (KeyChar c) -- Control
| ord '\^A' <= ord c && ord c <= ord '\^Z'
= let c' = chr $ ord c - ord '\^A' + ord 'a'
in '^':[toUpper c']
displayKey (KeyChar c) = show c
displayKey KeyDown = "<Down>"
displayKey KeyUp = "<Up>"
displayKey KeyLeft = "<Left>"
displayKey KeyRight = "<Right>"
displayKey KeyHome = "<Home>"
displayKey KeyBackspace = "<BS>"
displayKey (KeyF i) = 'F' : show i
displayKey KeyNPage = "<NPage>"
displayKey KeyPPage = "<PPage>"
displayKey KeyEnter = "<Return>"
displayKey KeyEnd = "<End>"
displayKey KeyIC = "<Insert>"
displayKey KeyDC = "<Delete>"
displayKey k = show k
------------------------------------------------------------------------
--
-- | Other helpers
--
--
-- | set the cursor, and do action
--
withCursor :: MonadExcIO m => CursorVisibility -> m a -> m a
withCursor nv action =
bracketM
(liftIO $ Curses.cursSet nv) -- before
(\vis -> liftIO $ Curses.cursSet vis) -- after
(\_ -> action) -- do this
withProgram :: MonadExcIO m => m a -> m a
withProgram action = withCursor CursorVisible $
bracketM_ (liftIO endWin) (liftIO flushinp) action
|