AutoForms-0.4.0: src/Graphics/UI/AF/General/EditFile.hs
module Graphics.UI.AF.General.EditFile
( editFile
)
where
import Graphics.UI.AF.General.AutoForm
import Graphics.UI.AF.General.Misc
import Graphics.UI.AF.General.MySYB
import Graphics.UI.AF.General.CustomTypes
import Control.Monad.Error
editFile :: ( Read t, AutoForm wxAct comH builder satCxt com
, Sat (satCxt t), Eq t, Show t, MonadIO builder, MonadIO wxAct
, TypePresentation t wxAct comH builder satCxt com) =>
FilePath
-> t
-> builder ()
editFile filename defaultValue =
do entry <- fromFile filename defaultValue (errorDialog "Error loading file")
entryHandle <- builderCom entry -- FIXME: should be changed to mkCom laiter
chState <- makeChangedState entryHandle
let saveFile = do x <- getValue entryHandle
liftIO $ writeFile filename $ show x
setValue chState $ Unchanged x
button "Save" saveFile >>= enabledWhen chState (== Changed)
-- FIXME: missing saveAs button
button "Quit" closeWindow
return ()
-- |Tries to read a file from disc. If an error occurs the 'onError' function is called.
fromFile :: (MonadIO m, Read a)
=> FilePath -- ^The file to read.
-> a -- ^Default value.
-> (String -> m ()) -- ^This is called if an error occurs while trying to read the file.
-> m a
fromFile filename defaultValue onError =
do entry <- liftIO $ (do entryText <- readFile filename
e <- readIO entryText
return $ Right e
) `catch` (return . Left . show)
case entry of
Left "" -> return defaultValue
Left s -> do onError s
return defaultValue
Right x -> return x