File: defaultpaths.py

package info (click to toggle)
displaycal-py3 3.9.16-1
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 29,120 kB
  • sloc: python: 115,777; javascript: 11,540; xml: 598; sh: 257; makefile: 173
file content (284 lines) | stat: -rw-r--r-- 10,146 bytes parent folder | download
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# -*- coding: utf-8 -*-


import os
import sys

if sys.platform not in ("darwin", "win32"):
    # Linux
    import codecs
    import locale
    import gettext

    LOCALEDIR = os.path.join(sys.prefix, "share", "locale")

elif sys.platform == "win32":
    try:
        from win32comext.shell.shell import SHGetSpecialFolderPath
        from win32comext.shell.shellcon import (
            CSIDL_APPDATA,
            CSIDL_COMMON_APPDATA,
            CSIDL_COMMON_STARTUP,
            CSIDL_LOCAL_APPDATA,
            CSIDL_PROFILE,
            CSIDL_PROGRAMS,
            CSIDL_COMMON_PROGRAMS,
            CSIDL_PROGRAM_FILES_COMMON,
            CSIDL_STARTUP,
            CSIDL_SYSTEM,
        )
    except ImportError:
        import ctypes

        (
            CSIDL_APPDATA,
            CSIDL_COMMON_APPDATA,
            CSIDL_COMMON_STARTUP,
            CSIDL_LOCAL_APPDATA,
            CSIDL_PROFILE,
            CSIDL_PROGRAMS,
            CSIDL_COMMON_PROGRAMS,
            CSIDL_PROGRAM_FILES_COMMON,
            CSIDL_STARTUP,
            CSIDL_SYSTEM,
        ) = (26, 35, 24, 28, 40, 43, 2, 23, 7, 37)
        MAX_PATH = 260

        def SHGetSpecialFolderPath(hwndOwner, nFolder, create=0):
            """ctypes wrapper around shell32.SHGetSpecialFolderPathW"""
            buffer = ctypes.create_unicode_buffer("\0" * MAX_PATH)
            ctypes.windll.shell32.SHGetSpecialFolderPathW(0, buffer, nFolder, create)
            return buffer.value


from DisplayCAL.util_os import expanduseru, expandvarsu, getenvu, waccess


home = expanduseru("~")
if sys.platform == "win32":
    # Always specify create=1 for SHGetSpecialFolderPath so we don't get an
    # exception if the folder does not yet exist
    try:
        library_home = appdata = SHGetSpecialFolderPath(0, CSIDL_APPDATA, 1)
    except Exception as exception:
        raise Exception(
            "FATAL - Could not get/create user application data folder: %s" % exception
        )
    try:
        localappdata = SHGetSpecialFolderPath(0, CSIDL_LOCAL_APPDATA, 1)
    except Exception:
        localappdata = os.path.join(appdata, "Local")
    cache = localappdata
    # Argyll CMS uses ALLUSERSPROFILE for local system wide app related data
    # Note: On Windows Vista and later, ALLUSERSPROFILE and COMMON_APPDATA
    # are actually the same ('C:\ProgramData'), but under Windows XP the former
    # points to 'C:\Documents and Settings\All Users' while COMMON_APPDATA
    # points to 'C:\Documents and Settings\All Users\Application Data'
    allusersprofile = getenvu("ALLUSERSPROFILE")
    if allusersprofile:
        commonappdata = [allusersprofile]
    else:
        try:
            commonappdata = [SHGetSpecialFolderPath(0, CSIDL_COMMON_APPDATA, 1)]
        except Exception as exception:
            raise Exception(
                "FATAL - Could not get/create common application data folder: %s"
                % exception
            )
    library = commonappdata[0]
    try:
        commonprogramfiles = SHGetSpecialFolderPath(0, CSIDL_PROGRAM_FILES_COMMON, 1)
    except Exception as exception:
        raise Exception(
            "FATAL - Could not get/create common program files folder: %s" % exception
        )
    try:
        autostart = SHGetSpecialFolderPath(0, CSIDL_COMMON_STARTUP, 1)
    except Exception:
        autostart = None
    try:
        autostart_home = SHGetSpecialFolderPath(0, CSIDL_STARTUP, 1)
    except Exception:
        autostart_home = None
    try:
        iccprofiles = [
            os.path.join(
                SHGetSpecialFolderPath(0, CSIDL_SYSTEM), "spool", "drivers", "color"
            )
        ]
    except Exception as exception:
        raise Exception("FATAL - Could not get system folder: %s" % exception)
    iccprofiles_home = iccprofiles
    try:
        programs = SHGetSpecialFolderPath(0, CSIDL_PROGRAMS, 1)
    except Exception:
        programs = None
    try:
        commonprograms = [SHGetSpecialFolderPath(0, CSIDL_COMMON_PROGRAMS, 1)]
    except Exception:
        commonprograms = []
elif sys.platform == "darwin":
    library_home = os.path.join(home, "Library")
    cache = os.path.join(library_home, "Caches")
    library = os.path.join(os.path.sep, "Library")
    prefs = os.path.join(os.path.sep, "Library", "Preferences")
    prefs_home = os.path.join(home, "Library", "Preferences")
    appdata = os.path.join(home, "Library", "Application Support")
    commonappdata = [os.path.join(os.path.sep, "Library", "Application Support")]
    autostart = autostart_home = None
    iccprofiles = [
        os.path.join(os.path.sep, "Library", "ColorSync", "Profiles"),
        os.path.join(os.path.sep, "System", "Library", "ColorSync", "Profiles"),
    ]
    iccprofiles_home = [os.path.join(home, "Library", "ColorSync", "Profiles")]
    programs = os.path.join(os.path.sep, "Applications")
    commonprograms = []
else:
    # Linux

    class XDG:
        # TODO: This class is a complete hack and it should be refactored,
        #       and no hacks like relaying on `locals()` should be used.

        cache_home = getenvu("XDG_CACHE_HOME", expandvarsu("$HOME/.cache"))
        config_home = getenvu("XDG_CONFIG_HOME", expandvarsu("$HOME/.config"))
        config_dir_default = "/etc/xdg"
        config_dirs = list(
            map(
                os.path.normpath,
                getenvu("XDG_CONFIG_DIRS", config_dir_default).split(os.pathsep),
            )
        )
        if config_dir_default not in config_dirs:
            config_dirs.append(config_dir_default)
        data_home_default = expandvarsu("$HOME/.local/share")
        data_home = getenvu("XDG_DATA_HOME", data_home_default)
        data_dirs_default = "/usr/local/share:/usr/share:/var/lib"
        data_dirs = list(
            map(
                os.path.normpath,
                getenvu("XDG_DATA_DIRS", data_dirs_default).split(os.pathsep),
            )
        )
        data_dirs.extend(
            list(
                filter(
                    lambda data_dir, data_dirs=data_dirs: data_dir not in data_dirs,
                    data_dirs_default.split(os.pathsep),
                )
            )
        )

        @staticmethod
        def set_translation(obj):
            locale_dir = LOCALEDIR

            if not os.path.isdir(locale_dir):
                for path in XDG.data_dirs:
                    path = os.path.join(path, "locale")
                    if os.path.isdir(path):
                        locale_dir = path
                        break

            # codeset is deprecated with python 3.11
            try:
                obj.translation = gettext.translation(
                    obj.GETTEXT_PACKAGE, locale_dir, codeset="UTF-8"
                )
            except TypeError:
                try:
                    obj.translation = gettext.translation(
                        obj.GETTEXT_PACKAGE, locale_dir
                    )
                except FileNotFoundError as exc:
                    print("XDG:", exc)
                    obj.translation = gettext.NullTranslations()
                    return False
            except IOError as exception:
                print("XDG:", exception)
                obj.translation = gettext.NullTranslations()
                return False
            return True

        @staticmethod
        def is_true(s):
            return s == "1" or s.startswith("True") or s.startswith("true")

        @staticmethod
        def get_config_files(filename):
            paths = []

            for xdg_config_dir in [XDG.config_home] + XDG.config_dirs:
                path = os.path.join(xdg_config_dir, filename)
                if os.path.isfile(path):
                    paths.append(path)

            return paths

        @staticmethod
        def shell_unescape(s):
            a = [c for i, c in enumerate(s) if c != "\\" or len(s) <= i + 1]
            return "".join(a)

        @staticmethod
        def config_file_parser(f):
            for line in f:
                line = line.strip()
                if line.startswith("#") or "=" not in line:
                    continue
                yield tuple(s.strip() for s in line.split("=", 1))

        @staticmethod
        def process_config_file(path, fn):
            try:
                with open(path, "r") as f:
                    for key, value in XDG.config_file_parser(f):
                        fn(key, value)
            except EnvironmentError as exception:
                print("XDG: Couldn't read '%s':" % path, exception)
                return False
            return True

    for name in dir(XDG):
        attr = getattr(XDG, name)
        if isinstance(attr, (str, list)):
            # TODO: Using `locals()` is not a good practice.
            locals()["xdg_" + name] = attr
    del name, attr

    cache = XDG.cache_home
    library_home = appdata = XDG.data_home
    commonappdata = XDG.data_dirs
    library = commonappdata[0]
    autostart = None
    for dir_ in XDG.config_dirs:
        if os.path.isdir(dir_):
            autostart = os.path.join(dir_, "autostart")
            break
    if not autostart:
        autostart = os.path.join(XDG.config_dir_default, "autostart")
    autostart_home = os.path.join(XDG.config_home, "autostart")
    iccprofiles = []
    for dir_ in XDG.data_dirs:
        if os.path.isdir(dir_):
            iccprofiles.append(os.path.join(dir_, "color", "icc"))
    iccprofiles.append("/var/lib/color")
    iccprofiles_home = [
        os.path.join(XDG.data_home, "color", "icc"),
        os.path.join(XDG.data_home, "icc"),
        expandvarsu("$HOME/.color/icc"),
    ]
    programs = os.path.join(XDG.data_home, "applications")
    commonprograms = [os.path.join(dir_, "applications") for dir_ in XDG.data_dirs]

if sys.platform in ("darwin", "win32"):
    iccprofiles_display = iccprofiles
    iccprofiles_display_home = iccprofiles_home
else:
    iccprofiles_display = [
        os.path.join(dir_, "devices", "display") for dir_ in iccprofiles
    ]
    iccprofiles_display_home = [
        os.path.join(dir_, "devices", "display") for dir_ in iccprofiles_home
    ]
    del dir_