{-# LINE 1 "src/System/Terminal/Utils.hsc" #-}
{-# LANGUAGE ForeignFunctionInterface #-}

module System.Terminal.Utils (
  getTerminalSize,
) where

import Foreign
import Foreign.C.Types
import Foreign.Marshal.Alloc ( alloca )


-- | Try to get the number of rows and columns respectively in the terminal
getTerminalSize :: IO (Maybe (Int,Int))


{-# LINE 20 "src/System/Terminal/Utils.hsc" #-}




getTerminalSize = alloca $ \ws -> do
  res <- ioctl (1) (1074295912) ws
{-# LINE 26 "src/System/Terminal/Utils.hsc" #-}
  if res == -1
    then pure Nothing
    else do
      WinSize row col <- peek ws
      pure (Just (fromIntegral row, fromIntegral col))

-- | @ioctl@ fills the struct at the pointer you passed in with the size info
foreign import ccall "sys/ioctl.h ioctl"
  ioctl :: CInt -> CInt -> Ptr WinSize -> IO CInt

-- | Match @struct winsize@ in @sys/ioctl.h@.
data WinSize = WinSize CUShort CUShort

instance Storable WinSize where
  sizeOf _ = ((8))
{-# LINE 41 "src/System/Terminal/Utils.hsc" #-}
  alignment _ = (2)
{-# LINE 42 "src/System/Terminal/Utils.hsc" #-}
  peek ptr = do
    row <- ((\hsc_ptr -> peekByteOff hsc_ptr 0)) ptr
{-# LINE 44 "src/System/Terminal/Utils.hsc" #-}
    col <- ((\hsc_ptr -> peekByteOff hsc_ptr 2)) ptr
{-# LINE 45 "src/System/Terminal/Utils.hsc" #-}
    pure (WinSize row col)
  poke ptr (WinSize row col) = do
    ((\hsc_ptr -> pokeByteOff hsc_ptr 0)) ptr row
{-# LINE 48 "src/System/Terminal/Utils.hsc" #-}
    ((\hsc_ptr -> pokeByteOff hsc_ptr 2)) ptr col
{-# LINE 49 "src/System/Terminal/Utils.hsc" #-}


{-# LINE 51 "src/System/Terminal/Utils.hsc" #-}