aboutsummaryrefslogtreecommitdiff
path: root/src/xdg_pipe_menu_scanner.erl
blob: 44c0a590984692b67b81a1b7bf35843c2936ba91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
%%%-------------------------------------------------------------------
%% @doc Locates .desktop files under the XDG application directories.
%%
%% Directory precedence follows the XDG Base Directory Specification:
%% the user's data home (most specific, so its entries should win over
%% system ones downstream) is searched first, then each directory in
%% `XDG_DATA_DIRS'. Each of `XDG_DATA_HOME' and `XDG_DATA_DIRS' falls
%% back to its spec-defined default independently when unset or empty
%% -- so a Flatpak-aware `XDG_DATA_DIRS' (which typically adds
%% `~/.local/share/flatpak/exports/share') is honored in place of the
%% default rather than merged with it.
%% @end
%%%-------------------------------------------------------------------

-module(xdg_pipe_menu_scanner).

-export([data_dirs/0, find_desktop_files/0, find_desktop_files/1]).

-define(DEFAULT_DATA_DIRS, ["/usr/local/share", "/usr/share"]).

-spec data_dirs() -> [file:filename_all()].
data_dirs() ->
    [filename:join(Dir, "applications") || Dir <- data_home() ++ data_dirs_list()].

-spec find_desktop_files() -> [file:filename_all()].
find_desktop_files() ->
    find_desktop_files(data_dirs()).

-spec find_desktop_files([file:filename_all()]) -> [file:filename_all()].
find_desktop_files(Dirs) ->
    lists:flatmap(fun find_in_dir/1, Dirs).

find_in_dir(Dir) ->
    case filelib:is_dir(Dir) of
        true -> filelib:wildcard(filename:join(Dir, "**/*.desktop"));
        false -> []
    end.

data_home() ->
    case env("XDG_DATA_HOME") of
        undefined ->
            case env("HOME") of
                undefined -> [];
                Home -> [filename:join([Home, ".local", "share"])]
            end;
        Dir ->
            [Dir]
    end.

data_dirs_list() ->
    case env("XDG_DATA_DIRS") of
        undefined -> ?DEFAULT_DATA_DIRS;
        Value -> [D || D <- string:split(Value, ":", all), D =/= ""]
    end.

%% The spec treats an unset and an empty variable the same way.
env(Name) ->
    case os:getenv(Name) of
        false -> undefined;
        "" -> undefined;
        Value -> Value
    end.