Debian Codegraph @

src/System/Console/Terminal/Posix.hsc

raw
1 {-# LANGUAGE CApiFFI #-}
2
3 module System.Console.Terminal.Posix
4 ( size, fdSize, hSize
5 ) where
6
7 import System.Console.Terminal.Common
8 import Control.Exception (catch)
9 import Data.Typeable (cast)
10 import Foreign
11 import Foreign.C.Error
12 import Foreign.C.Types
13 import GHC.IO.FD (FD(FD, fdFD))
14 import GHC.IO.Handle.Internals (withHandle_)
15 import GHC.IO.Handle.Types (Handle, Handle__(Handle__, haDevice))
16 #if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ < 706)
17 import Prelude hiding (catch)
18 #endif
19 import System.Posix.Types (Fd(Fd))
20
21 #include <sys/ioctl.h>
22 #include <unistd.h>
23
24 #if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ < 800)
25 #let alignment t = "%lu", (unsigned long)offsetof(struct {char x__; t (y__); }, y__)
26 #endif
27
28 -- Interesting part of @struct winsize@
29 data CWin = CWin CUShort CUShort
30
31 instance Storable CWin where
32 sizeOf _ = (#size struct winsize)
33 alignment _ = (#alignment struct winsize)
34 peek ptr = do
35 row <- (#peek struct winsize, ws_row) ptr
36 col <- (#peek struct winsize, ws_col) ptr
37 return $ CWin row col
38 poke ptr (CWin row col) = do
39 (#poke struct winsize, ws_row) ptr row
40 (#poke struct winsize, ws_col) ptr col
41
42
43 fdSize :: Integral n => Fd -> IO (Maybe (Window n))
44 fdSize (Fd fd) = with (CWin 0 0) $ \ws -> do
45 throwErrnoIfMinus1 "ioctl" $
46 ioctl fd (#const TIOCGWINSZ) ws
47 CWin row col <- peek ws
48 return . Just $ Window (fromIntegral row) (fromIntegral col)
49 `catch`
50 handler
51 where
52 handler :: IOError -> IO (Maybe (Window h))
53 handler _ = return Nothing
54
55 foreign import capi "sys/ioctl.h ioctl"
56 ioctl :: CInt -> CULong -> Ptr CWin -> IO CInt
57
58 size :: Integral n => IO (Maybe (Window n))
59 size = fdSize (Fd (#const STDOUT_FILENO))
60
61 hSize :: Integral n => Handle -> IO (Maybe (Window n))
62 hSize h = withHandle_ "hSize" h $ \Handle__ { haDevice = dev } ->
63 case cast dev of
64 Nothing -> return Nothing
65 Just FD { fdFD = fd } -> fdSize (Fd fd)