Search code examples
windowshaskellpermissionsclipboard

Permission denied when reading from clipboard


I wrote a small program to track my clipboard activity and print it to the terminal using reactive-banana and System.Clipboard.

module Main where

import Reactive.Banana
import Reactive.Banana.Frameworks
import System.Clipboard
import Data.Maybe(fromJust)

main :: IO ()
main = do
    sources <- (,) <$> newAddHandler <*> newAddHandler
    network <- setupNetwork sources
    actuate network
    s <- getClipboardString
    loop s sources

loop s (epop, epush) = do
    c <- getClipboardString
    if s /= c then
        snd epush [fromJust c]
    else
        loop s (epop, epush)

setupNetwork (epop, epush) = compile $ do
    ePop <- fromAddHandler $ fst epop
    ePush <- fromAddHandler $ fst epush

    bStack <- accumB [""] $ (++) <$> ePush
    eStack <- changes bStack

    reactimate' $ fmap print <$> eStack

When I run it, I move to another window (like chrome) and copy some text. When I do that I get Main.hs: CloseClipboard: invalid argument (Thread does not have a clipboard open.). I am running this on windows. Any help would be great!

Cheers


Solution

  • After a bit of research I believe I found the cause to the problem. What happened was that when I copied a new text into the clipboard the program locked the program so no other changes would occur to it. During this lock time my program tried to access the clipboard and got an error. To solve this I wrapped the call to getClipboardString with in Either using try from Control.Exception and then pattern matched the errors away.

    c <- try getClipboardString :: IO (Either SomeException (Maybe String))
    case c of
        Left err -> loop s (epop, epush) --ignore
        Right clip -> --do something usefull