{-# LANGUAGE ForeignFunctionInterface #-}
module Graphics.X11.XTest
  (fakeMotion,
   fakeButtonPress,
   movePointer)
  where

import Graphics.X11.Xlib
import Foreign.C.Types

-- FFI imports

-- XTestFakeButtonEvent(display, button, is_press, delay)
foreign import ccall unsafe "X11/extensions/XTest.h XTestFakeButtonEvent"
    xFakeButtonEvent :: Display -> Button -> Bool -> Time -> IO Status

foreign import ccall unsafe "X11/extensions/XTest.h XTestFakeMotionEvent"
    xFakeMotionEvent :: Display -> CInt -> CInt -> CInt -> Time -> IO Status

-- | Create fake pointer motion event.
fakeMotion :: Display      -- 
           -> ScreenNumber --
           -> Int          -- ^ X
           -> Int          -- ^ Y
           -> IO ()
fakeMotion dpy sid x y = do
  xFakeMotionEvent dpy (fromIntegral sid) (fromIntegral x) (fromIntegral y) 0
  return ()

-- | Create fake mouse button click event.
fakeButtonPress :: Display
                -> Button  -- ^ Mouse button number
                -> IO ()
fakeButtonPress dpy button = do
  xFakeButtonEvent dpy button True 0
  xFakeButtonEvent dpy button False 0
  return ()

-- | Move mouse pointer.
movePointer :: Display
            -> ScreenNumber
            -> XID          -- ^ Root window XID
            -> Int          -- ^ delta X
            -> Int          -- ^ delta Y
            -> IO ()
movePointer dpy sid root dx dy = do
 (_,_,_,x,y,_,_,_) <- queryPointer dpy root
 fakeMotion dpy sid (fromIntegral x + dx) (fromIntegral y + dy)