~alcinnz/hurl

da4f67a27b662c70dd6b16b23ea591ecaddfd2e5 — Adrian Cochrane 4 years ago 0c50ae1
Draft logic for looking apps to dispatch MIMEtypes & URI schemes to on XDG platforms
1 files changed, 54 insertions(+), 0 deletions(-)

A src/Network/URI/XDG/MimeApps.hs
A src/Network/URI/XDG/MimeApps.hs => src/Network/URI/XDG/MimeApps.hs +54 -0
@@ 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 = []