module System.Console.Haskeline.Backend.Posix.Encoder (
ExternalHandle(eH),
externalHandle,
withCodingMode,
openInCodingMode,
) where
import System.IO
import System.Console.Haskeline.Monads
import GHC.IO.Encoding (initLocaleEncoding)
import System.Console.Haskeline.Recover
data ExternalHandle = ExternalHandle
{ externalMode :: ExternalMode
, eH :: Handle
}
data ExternalMode = CodingMode | OtherMode
externalHandle :: Handle -> ExternalHandle
externalHandle = ExternalHandle OtherMode
withCodingMode :: ExternalHandle -> IO a -> IO a
withCodingMode ExternalHandle {externalMode=CodingMode} act = act
withCodingMode (ExternalHandle OtherMode h) act = do
bracket (liftIO $ hGetEncoding h)
(liftIO . hSetBinOrEncoding h)
$ const $ do
hSetEncoding h haskelineEncoding
act
hSetBinOrEncoding :: Handle -> Maybe TextEncoding -> IO ()
hSetBinOrEncoding h Nothing = hSetBinaryMode h True
hSetBinOrEncoding h (Just enc) = hSetEncoding h enc
haskelineEncoding :: TextEncoding
haskelineEncoding = transliterateFailure initLocaleEncoding
openInCodingMode :: FilePath -> IOMode -> IO ExternalHandle
openInCodingMode path iomode = do
h <- openFile path iomode
hSetEncoding h haskelineEncoding
return $ ExternalHandle CodingMode h