module System.Terminal
( getTerminalWidth
) where
import Foreign
import Foreign.C.Types
newtype WindowWidth = WindowWidth CUShort
deriving (Eq, Ord, Show)
instance Storable WindowWidth where
sizeOf _ = ((8))
alignment _ = (2)
peek p = WindowWidth <$> ((\hsc_ptr -> peekByteOff hsc_ptr 2)) p
poke p (WindowWidth w) = do
((\hsc_ptr -> pokeByteOff hsc_ptr 2)) p w
foreign import ccall "sys/ioctl.h ioctl"
ioctl :: CInt -> CInt -> Ptr WindowWidth -> IO CInt
getTerminalWidth :: IO (Maybe Int)
getTerminalWidth =
alloca $ \p -> do
errno <- ioctl (1) (21523) p
if errno < 0
then return Nothing
else do
WindowWidth w <- peek p
return . Just . fromIntegral $ w