{-# LINE 1 "libraries\\ghci\\GHCi\\Utils.hsc" #-}
{-# LANGUAGE CPP #-}
module GHCi.Utils
  ( getGhcHandle
  , readGhcHandle
  )
where

import Prelude
import Foreign.C
import GHC.IO.Handle (Handle())

{-# LINE 12 "libraries\\ghci\\GHCi\\Utils.hsc" #-}
import Foreign.Ptr (ptrToIntPtr,wordPtrToPtr)
import GHC.IO (onException)
import GHC.IO.Handle.FD (fdToHandle)
import GHC.Windows (HANDLE)
import GHC.IO.SubSystem ((<!>))
import GHC.IO.Handle.Windows (mkHandleFromHANDLE)
import GHC.IO.Device as IODevice
import GHC.IO.Encoding (getLocaleEncoding)
import GHC.IO.IOMode
import GHC.IO.Windows.Handle (fromHANDLE, Io(), NativeHandle())




{-# LINE 28 "libraries\\ghci\\GHCi\\Utils.hsc" #-}

-- | Gets a GHC Handle File description from the given OS Handle or POSIX fd.



{-# LINE 32 "libraries\\ghci\\GHCi\\Utils.hsc" #-}
getGhcHandle :: HANDLE -> IO Handle
getGhcHandle :: Ptr () -> IO Handle
getGhcHandle = Ptr () -> IO Handle
getGhcHandlePOSIX (Ptr () -> IO Handle)
-> (Ptr () -> IO Handle) -> Ptr () -> IO Handle
forall a. a -> a -> a
<!> Ptr () -> IO Handle
getGhcHandleNative

getGhcHandlePOSIX :: HANDLE -> IO Handle
getGhcHandlePOSIX :: Ptr () -> IO Handle
getGhcHandlePOSIX Ptr ()
handle = do
  let intptr :: IntPtr
intptr = Ptr () -> IntPtr
forall a. Ptr a -> IntPtr
ptrToIntPtr Ptr ()
handle
  CInt -> CInt -> IO CInt
_open_osfhandle (IntPtr -> CInt
forall a b. (Integral a, Num b) => a -> b
fromIntegral IntPtr
intptr) (CInt
32768) IO CInt -> (CInt -> IO Handle) -> IO Handle
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CInt -> IO Handle
fdToHandle
{-# LINE 39 "libraries\\ghci\\GHCi\\Utils.hsc" #-}

getGhcHandleNative :: HANDLE -> IO Handle
getGhcHandleNative :: Ptr () -> IO Handle
getGhcHandleNative Ptr ()
hwnd =
  do mb_codec <- (TextEncoding -> Maybe TextEncoding)
-> IO TextEncoding -> IO (Maybe TextEncoding)
forall a b. (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap TextEncoding -> Maybe TextEncoding
forall a. a -> Maybe a
Just IO TextEncoding
getLocaleEncoding
     let iomode = IOMode
ReadWriteMode
         native_handle = Ptr () -> Io NativeHandle
forall a. RawHandle a => Ptr () -> a
fromHANDLE Ptr ()
hwnd :: Io NativeHandle
     hw_type <- IODevice.devType $ native_handle
     mkHandleFromHANDLE native_handle hw_type (show hwnd) iomode mb_codec
       `onException` IODevice.close native_handle

foreign import ccall "io.h _open_osfhandle" _open_osfhandle ::
    CInt -> CInt -> IO CInt

{-# LINE 55 "libraries\\ghci\\GHCi\\Utils.hsc" #-}

-- | Read a handle passed on the command-line and prepare it to be used with the IO manager

readGhcHandle :: String -> IO Handle
readGhcHandle :: FilePath -> IO Handle
readGhcHandle FilePath
s = do

{-# LINE 60 "libraries\\ghci\\GHCi\\Utils.hsc" #-}
  let fd = wordPtrToPtr (Prelude.read s)

{-# LINE 67 "libraries\\ghci\\GHCi\\Utils.hsc" #-}

{-# LINE 70 "libraries\\ghci\\GHCi\\Utils.hsc" #-}
  getGhcHandle fd