Debian Codegraph @

DisplayCAL/postinstall.py

raw
1 """Post-install and uninstall tasks for DisplayCAL on Windows, macOS, and Linux.
2
3 It includes functions to create shortcuts, manage installed files, and update
4 system resources such as icons and desktop menu entries.
5 """
6
7 from __future__ import annotations
8
9 import contextlib
10 import os
11 import shutil
12 import sys
13 import traceback
14 from io import StringIO
15 from os.path import basename, splitext
16 from subprocess import call
17
18 from DisplayCAL.meta import NAME
19 from DisplayCAL.util_os import safe_glob, which
20
21 RECORD_FILE_NAME = "INSTALLED_FILES"
22
23 if sys.stdout and hasattr(sys.stdout, "isatty") and not sys.stdout.isatty():
24 sys.stdout = StringIO()
25
26 if sys.platform == "win32":
27 if "create_shortcut" not in globals():
28 # this function is only available within bdist_wininst installers
29 try:
30 import win32con
31 from pythoncom import (
32 CLSCTX_INPROC_SERVER,
33 CoCreateInstance,
34 IID_IPersistFile,
35 )
36 from win32com.shell import shell
37 except ImportError:
38
39 def create_shortcut(*args) -> None:
40 """Dummy function to create a Windows shortcut."""
41
42 else:
43
44 def create_shortcut(*args) -> None:
45 """Create a Windows shortcut."""
46 shortcut = CoCreateInstance(
47 shell.CLSID_ShellLink,
48 None,
49 CLSCTX_INPROC_SERVER,
50 shell.IID_IShellLink,
51 )
52 shortcut.SetPath(args[0])
53 shortcut.SetDescription(args[1])
54 if len(args) > 3:
55 shortcut.SetArguments(args[3])
56 if len(args) > 4:
57 shortcut.SetWorkingDirectory(args[4])
58 if len(args) > 5:
59 shortcut.SetIconLocation(args[5], args[6] if len(args) > 6 else 0)
60 shortcut.SetShowCmd(win32con.SW_SHOWNORMAL)
61 shortcut.QueryInterface(IID_IPersistFile).Save(args[2], 0)
62
63 if "directory_created" not in globals():
64 # this function is only available within bdist_wininst installers
65
66 def directory_created(path: str) -> None:
67 """Dummy function to record directory creation.
68
69 Args:
70 path (str): The path of the directory that was created.
71 """
72
73 if "file_created" not in globals():
74 # this function is only available within bdist_wininst installers
75 try:
76 import win32api
77 except ImportError:
78
79 def file_created(path: str) -> None:
80 """Dummy function to record file creation.
81
82 Args:
83 path (str): The path of the file that was created.
84 """
85
86 else:
87
88 def file_created(path: str) -> None:
89 """Record the file creation in the installed files record.
90
91 Args:
92 path (str): The path of the file that was created.
93 """
94 if not os.path.exists(RECORD_FILE_NAME):
95 return
96 installed_files = []
97 if os.path.exists(RECORD_FILE_NAME):
98 with open(RECORD_FILE_NAME) as record_file:
99 installed_files.extend(
100 line.rstrip("\n") for line in record_file
101 )
102 try:
103 path.encode("ASCII")
104 except (UnicodeDecodeError, UnicodeEncodeError):
105 # the contents of the record file used by distutils
106 # must be ASCII GetShortPathName allows us to avoid
107 # any issues with encoding because it returns the
108 # short path as 7-bit string (while still being a
109 # valid path)
110 path = win32api.GetShortPathName(path)
111 installed_files.append(path)
112 with open(RECORD_FILE_NAME, "w") as record_file:
113 record_file.write("\n".join(installed_files))
114
115 if "get_special_folder_path" not in globals():
116 # this function is only available within bdist_wininst installers
117 try:
118 from win32com.shell import shell, shellcon
119 except ImportError:
120
121 def get_special_folder_path(csidl_string: str) -> None:
122 """Implement the dummy version of getting the path to a special folder.
123
124 Args:
125 csidl_string (str): The CSIDL string representing the
126 special folder.
127
128 Returns:
129 None: Returns None.
130 """
131
132 else:
133
134 def get_special_folder_path(csidl_string: str) -> str:
135 """Get the path to a special folder.
136
137 Args:
138 csidl_string (str): The CSIDL string representing the
139 special folder.
140
141 Returns:
142 str: The path to the special folder.
143 """
144 return shell.SHGetSpecialFolderPath(
145 0, getattr(shellcon, csidl_string), 1
146 )
147
148
149 def postinstall_macos(prefix: None | str = None) -> None:
150 """Do postinstall actions for macOS.
151
152 Args:
153 prefix (None | str, optional): The installation prefix. Defaults to None.
154 """
155 # TODO: implement
156
157
158 def postinstall_windows(prefix: str) -> None:
159 """Do postinstall actions for Windows.
160
161 Args:
162 prefix (str): The installation prefix.
163 """
164 # assume we are running from bdist_wininst installer if prefix is None,
165 # otherwise assume we are running from source dir, or from install dir
166 module_path = (
167 os.path.dirname(os.path.abspath(__file__)) if prefix is None else prefix
168 )
169 if not os.path.exists(module_path):
170 print("warning - '{}' not found".format(module_path.encode("MBCS", "replace")))
171 return
172
173 create_installed_files_record(module_path)
174 main_icon = get_main_icon(module_path)
175 if not main_icon:
176 return
177
178 try:
179 start_menu_programs_common = get_special_folder_path("CSIDL_COMMON_PROGRAMS")
180 start_menu_programs = get_special_folder_path("CSIDL_PROGRAMS")
181 start_menu_common = get_special_folder_path("CSIDL_COMMON_start_menu")
182 start_menu = get_special_folder_path("CSIDL_start_menu")
183 except OSError:
184 traceback.print_exc()
185 return
186
187 create_start_menu_shortcuts(
188 module_path,
189 main_icon,
190 start_menu_programs_common,
191 start_menu_programs,
192 start_menu_common,
193 start_menu,
194 )
195
196
197 def create_installed_files_record(module_path: str) -> None:
198 """Create the installed files record.
199
200 Args:
201 module_path (str): The module path.
202 """
203 if not os.path.exists(RECORD_FILE_NAME):
204 return
205 installed_record_file_path = os.path.join(module_path, RECORD_FILE_NAME)
206 # touch - create the file
207 with open(installed_record_file_path, "w"):
208 pass
209 file_created(installed_record_file_path)
210 shutil.copy2(RECORD_FILE_NAME, installed_record_file_path)
211
212
213 def get_main_icon(module_path: str) -> None | str:
214 """Get the main icon for the application.
215
216 Args:
217 module_path (str): The module path.
218
219 Returns:
220 None | str: The path to the main icon, or None if not found.
221 """
222 main_icon = os.path.join(module_path, "theme", "icons", f"{NAME}.ico")
223 if not os.path.exists(main_icon):
224 print("warning - '{}' not found".format(main_icon.encode("MBCS", "replace")))
225 return None
226 return main_icon
227
228
229 def create_start_menu_shortcuts(
230 module_path: str,
231 main_icon: str,
232 start_menu_programs_common: str,
233 start_menu_programs: str,
234 start_menu_common: str,
235 start_menu: str,
236 ) -> None:
237 """Create start menu shortcuts for the application.
238
239 Args:
240 module_path (str): The module path.
241 main_icon (str): The path to the main icon.
242 start_menu_programs_common (str): The path to the common programs
243 start menu.
244 start_menu_programs (str): The path to the user's programs start menu.
245 start_menu_common (str): The path to the common start menu.
246 start_menu (str): The path to the user's start menu.
247 """
248 filenames = [
249 filename
250 for filename in safe_glob(os.path.join(sys.prefix, "Scripts", f"{NAME}*"))
251 if not filename.endswith("-script.py")
252 and not filename.endswith("-script.pyw")
253 and not filename.endswith(".manifest")
254 and not filename.endswith(".pyc")
255 and not filename.endswith(".pyo")
256 and not filename.endswith("_postinstall.py")
257 ] + ["LICENSE.txt", "README.html", "Uninstall"]
258 installed_shortcuts = []
259 for path in (start_menu_programs_common, start_menu_programs):
260 if not path:
261 continue
262
263 group, group_path = create_group_path(
264 path,
265 start_menu_programs,
266 start_menu_common,
267 start_menu,
268 )
269 if not group_path:
270 continue
271
272 directory_created(group_path)
273
274 create_shortcut_files(
275 filenames, group, group_path, module_path, main_icon, installed_shortcuts
276 )
277
278 if installed_shortcuts == filenames:
279 break
280
281
282 def create_group_path(
283 path: str, start_menu_programs: str, start_menu_common: str, start_menu: str
284 ) -> tuple[str, None | str]:
285 """Create the group path for the start menu.
286
287 Args:
288 path (str): The path to create the group in.
289 start_menu_programs (str): The path to the user's programs start menu.
290 start_menu_common (str): The path to the common start menu.
291 start_menu (str): The path to the user's start menu.
292
293 Returns:
294 tuple[str, None | str]: The group name and the group path, or None if
295 creation failed.
296 """
297 group_path = os.path.join(path, NAME)
298 if path == start_menu_programs:
299 group = os.path.relpath(group_path, start_menu)
300 else:
301 group = os.path.relpath(group_path, start_menu_common)
302
303 if not os.path.exists(group_path):
304 with contextlib.suppress(Exception):
305 os.makedirs(group_path)
306 # maybe insufficient privileges?
307
308 if os.path.exists(group_path):
309 print(
310 ("Created start menu group '{}' in {}").format(
311 NAME,
312 (
313 str(path, "MBCS", "replace") if not isinstance(path, str) else path
314 ).encode("MBCS", "replace"),
315 )
316 )
317 else:
318 print(
319 ("Failed to create start menu group '{}' in {}").format(
320 NAME,
321 (
322 str(path, "MBCS", "replace") if not isinstance(path, str) else path
323 ).encode("MBCS", "replace"),
324 )
325 )
326 return group_path, None
327 return group, group_path
328
329
330 def create_shortcut_files(
331 filenames: list,
332 group: str,
333 group_path: str,
334 module_path: str,
335 main_icon: str,
336 installed_shortcuts: list,
337 ) -> None:
338 """Create shortcut files in the specified group path.
339
340 Args:
341 filenames (list): List of filenames to create shortcuts for.
342 group (str): The name of the group.
343 group_path (str): The path to the group directory.
344 module_path (str): The module path.
345 main_icon (str): The path to the main icon.
346 installed_shortcuts (list): List to store installed shortcuts.
347 """
348 for filename in filenames:
349 link_name = splitext(basename(filename))[0]
350 link_path = os.path.join(group_path, f"{link_name}.lnk")
351 if os.path.exists(link_path):
352 try:
353 os.remove(link_path)
354 except Exception:
355 # maybe insufficient privileges?
356 print(
357 ("Failed to create start menu entry '{}' in {}").format(
358 link_name,
359 (
360 str(group_path, "MBCS", "replace")
361 if not isinstance(group_path, str)
362 else group_path
363 ).encode("MBCS", "replace"),
364 )
365 )
366 continue
367
368 if os.path.exists(link_path):
369 file_created(link_path)
370 installed_shortcuts.append(filename)
371 continue
372
373 if link_name != "Uninstall":
374 target_path = os.path.join(module_path, filename)
375
376 try:
377 if link_name == "Uninstall":
378 uninstaller = os.path.join(sys.prefix, f"Remove{NAME}.exe")
379 if os.path.exists(uninstaller):
380 create_shortcut(
381 uninstaller,
382 link_name,
383 link_path,
384 f'-u "{os.path.join(sys.prefix, NAME)}-wininst.log"',
385 sys.prefix,
386 os.path.join(
387 module_path,
388 "theme",
389 "icons",
390 f"{NAME}-uninstall.ico",
391 ),
392 )
393 else:
394 # When running from a bdist_wininst or bdist_msi installer,
395 # sys.executable points to the installer executable,
396 # not python.exe
397 create_shortcut(
398 os.path.join(sys.prefix, "python.exe"),
399 link_name,
400 link_path,
401 '"{}" uninstall --record="{}"'.format(
402 os.path.join(module_path, "setup.py"),
403 os.path.join(module_path, RECORD_FILE_NAME),
404 ),
405 sys.prefix,
406 os.path.join(
407 module_path,
408 "theme",
409 "icons",
410 f"{NAME}-uninstall.ico",
411 ),
412 )
413 elif link_name.startswith(NAME):
414 # When running from a bdist_wininst or bdist_msi installer,
415 # sys.executable points to the installer executable,
416 # not python.exe
417 icon = os.path.join(
418 module_path,
419 "theme",
420 "icons",
421 f"{link_name}.ico",
422 )
423 icon = main_icon if not os.path.isfile(icon) else icon
424 if filename.endswith(".exe"):
425 exe = filename
426 args = ""
427 else:
428 exe = os.path.join(sys.prefix, "pythonw.exe")
429 args = f'"{target_path}"'
430 create_shortcut(
431 exe,
432 link_name,
433 link_path,
434 args,
435 module_path,
436 icon,
437 )
438 else:
439 create_shortcut(target_path, link_name, link_path, "", module_path)
440 except Exception:
441 # maybe insufficient privileges?
442 print(
443 ("Failed to create start menu entry '{}' in {}").format(
444 link_name,
445 (
446 str(group_path, "MBCS", "replace")
447 if not isinstance(group_path, str)
448 else group_path
449 ).encode("MBCS", "replace"),
450 )
451 )
452 continue
453 print(
454 ("Installed start menu entry '{}' to {}").format(
455 link_name,
456 (
457 str(group, "MBCS", "replace")
458 if not isinstance(group, str)
459 else group
460 ).encode("MBCS", "replace"),
461 )
462 )
463 file_created(link_path)
464 installed_shortcuts.append(filename)
465
466
467 def postinstall_linux(prefix: None | str = None) -> None:
468 """Do postinstall actions for Linux.
469
470 Args:
471 prefix (None | str, optional): The installation prefix. Defaults to
472 None.
473 """
474 # Linux/Unix
475 if prefix is None:
476 prefix = sys.prefix
477 if which("touch"):
478 call(["touch", "--no-create", f"{prefix}/share/icons/hicolor"]) # noqa: S607
479 if which("xdg-icon-resource"):
480 # print("installing icon resources...")
481 # for size in [16, 22, 24, 32, 48, 256]:
482 # call([
483 # "xdg-icon-resource",
484 # "install",
485 # "--noupdate",
486 # "--novendor",
487 # "--size",
488 # str(size),
489 # f"{prefix}/share/{name}/theme/icons/{size}x{size}/{name}.png"
490 # ])
491 call(["xdg-icon-resource", "forceupdate"]) # noqa: S607
492 if which("xdg-desktop-menu"):
493 # print("installing desktop menu entry...")
494 # call([
495 # "xdg-desktop-menu",
496 # "install",
497 # "--novendor",
498 # f"{prefix}/share/{name}/{name}.desktop"
499 # ])
500 call(["xdg-desktop-menu", "forceupdate"]) # noqa: S607
501
502
503 def postinstall(prefix: None | str = None) -> None:
504 """Do postinstall actions.
505
506 Args:
507 prefix (None | str, optional): The installation prefix. Defaults to
508 None.
509 """
510 if sys.platform == "darwin":
511 postinstall_macos()
512 elif sys.platform == "win32":
513 postinstall_windows(prefix)
514 else:
515 postinstall_linux(prefix)
516
517
518 def postuninstall(prefix: None | str = None) -> None:
519 """Do postuninstall actions.
520
521 Args:
522 prefix (None | str, optional): The installation prefix. Defaults to
523 None.
524 """
525 if sys.platform == "darwin":
526 # TODO: implement
527 pass
528 elif sys.platform == "win32":
529 # nothing to do
530 pass
531 else:
532 # Linux/Unix
533 if prefix is None:
534 prefix = sys.prefix
535 if which("xdg-desktop-menu"):
536 # print("uninstalling desktop menu entry...")
537 # call(["xdg-desktop-menu", "uninstall", prefix +
538 # (f"/share/applications/{name}.desktop")])
539 call(["xdg-desktop-menu", "forceupdate"]) # noqa: S607
540 if which("xdg-icon-resource"):
541 # print("uninstalling icon resources...")
542 # for size in [16, 22, 24, 32, 48, 256]:
543 # call(["xdg-icon-resource", "uninstall", "--noupdate", "--size",
544 # str(size), name])
545 call(["xdg-icon-resource", "forceupdate"]) # noqa: S607
546
547
548 def main() -> None:
549 """Main function to handle post-installation and uninstallation tasks."""
550 prefix = None
551 for arg in sys.argv[1:]:
552 arg = arg.split("=")
553 if len(arg) == 2 and arg[0] == "--prefix":
554 prefix = arg[1]
555 try:
556 if "-remove" in sys.argv[1:]:
557 postuninstall(prefix)
558 else:
559 postinstall(prefix)
560 except Exception:
561 traceback.print_exc()
562
563
564 if __name__ == "__main__":
565 main()