| 1 |
module System.Console.Terminal.Windows(size, hSize) where |
| 2 |
|
| 3 |
import System.Console.Terminal.Common |
| 4 |
|
| 5 |
import System.Exit |
| 6 |
import System.IO |
| 7 |
import System.IO.Error (catchIOError) |
| 8 |
import System.Process |
| 9 |
import System.Win32.Console |
| 10 |
( CONSOLE_SCREEN_BUFFER_INFO(srWindow) |
| 11 |
, SMALL_RECT(..) |
| 12 |
, getConsoleScreenBufferInfo |
| 13 |
) |
| 14 |
import System.Win32.Types (HANDLE, withHandleToHANDLE) |
| 15 |
|
| 16 |
size :: Integral n => IO (Maybe (Window n)) |
| 17 |
size = hSize stdout |
| 18 |
|
| 19 |
hSize :: Integral n => Handle -> IO (Maybe (Window n)) |
| 20 |
hSize hdl = |
| 21 |
withHandleToHANDLE hdl nativeSize |
| 22 |
`catchIOError` \_ -> do |
| 23 |
-- Fallback to use for Cygwin or MSYS |
| 24 |
let stty = (shell "stty size") { |
| 25 |
std_in = UseHandle hdl |
| 26 |
, std_out = CreatePipe |
| 27 |
, std_err = CreatePipe |
| 28 |
} |
| 29 |
(_, mbStdout, _, rStty) <- createProcess stty |
| 30 |
exStty <- waitForProcess rStty |
| 31 |
case exStty of |
| 32 |
ExitFailure _ -> return Nothing |
| 33 |
ExitSuccess -> |
| 34 |
maybe (return Nothing) |
| 35 |
(\out -> do |
| 36 |
sizeStr <- hGetContents out |
| 37 |
let [r, c] = map read $ words sizeStr :: [Int] |
| 38 |
return $ Just $ Window (fromIntegral r) (fromIntegral c) |
| 39 |
) |
| 40 |
mbStdout |
| 41 |
|
| 42 |
nativeSize :: Integral n => HANDLE -> IO (Maybe (Window n)) |
| 43 |
nativeSize hdl = do |
| 44 |
rect <- srWindow <$> getConsoleScreenBufferInfo hdl |
| 45 |
return $ Just $ Window |
| 46 |
{ height = fromIntegral (1 + bottomPos rect - topPos rect) |
| 47 |
, width = fromIntegral (1 + rightPos rect - leftPos rect) |
| 48 |
} |