@@ 0,0 1,54 @@
+module Network.URI.XDG.MimeApps(HandlersConfig, loadHandlers, queryHandlers) where
+
+import System.Environment (lookupEnv)
+import Control.Monad (forM)
+import System.FilePath
+import Data.List (nub, (\\))
+
+import Network.URI.XDG.Ini
+
+type HandlersConfig = [INI]
+
+loadHandlers :: IO HandlersConfig
+loadHandlers = do
+ desktop <- lookupEnv "XDG_CURRENT_DESKTOP"
+ dir0 <- mimeAppsDirs "XDG_CONFIG"
+ dir1 <- mimeAppsDirs "XDG_DATA"
+ let filepaths = mimeAppsFiles (dir0 ++ map (</> "applications") dir1) desktop
+ files <- forM filepaths readFile
+ return $ map parseIni files
+
+mimeAppsDirs envPrefix = do
+ home <- lookupEnv (envPrefix ++ "_HOME")
+ dirs <- lookupEnv (envPrefix ++ "_DIRS")
+ let dirs' = (case dirs of
+ Just x -> filter (/= "") $ split ':' x
+ Nothing -> [])
+ return $ case home of
+ Just home' -> home' : dirs'
+ Nothing -> dirs'
+
+mimeAppsFiles (dir:dirs) (Just desktop) = (dir </> desktop ++ "-mimeapps.list") :
+ (dir </> "mimeapps.list") : (mimeAppsFiles dirs $ Just desktop)
+mimeAppsFiles (dir:dirs) Nothing = (dir </> "mimeapps.list") : mimeAppsFiles dirs Nothing
+mimeAppsFiles [] _ = []
+
+split b (a:as) | a == b = [] : split b as
+ | (head':tail') <- split b as = (a:head') : tail'
+split _ [] = [[]]
+
+---
+
+queryHandlers :: HandlersConfig -> String -> [String]
+-- TODO Expand MIMEtypes in reference to the local MIMEtypes database.
+queryHandlers config mime = nub (
+ queryHandlers' "default applications" config mime ++
+ (queryHandlers' "added associations" config mime \\
+ queryHandlers' "removed associations" config mime)
+ )
+
+queryHandlers' group (config:configs) mime =
+ queryHandlers'' group config mime ++ queryHandlers' group configs mime
+queryHandlers'' group config mime
+ | Just apps <- iniLookup group mime config = filter (/= "") $ split ';' apps
+ | otherwise = []