Debian Codegraph @

DisplayCAL/setup.py

raw
1 """DisplayCAL setup.py script.
2
3 Can be used with setuptools or pure distutils (the latter can be forced
4 with the --use-distutils option, otherwise it will try to use setuptools
5 by default).
6
7 Also supported in addition to standard distutils/setuptools commands,
8 are the bdist_bbfreeze, py2app and py2exe commands (if the appropriate
9 packages are installed), which makes this file your all-around building/
10 bundling powerhouse for DisplayCAL. In the case of py2exe, special care
11 is taken of Python 2.6+ and the Microsoft.VC90.CRT assembly dependency,
12 so if building an executable on Windows with Python 2.6+ you should
13 preferably use py2exe. Please note that bdist_bbfreeze and py2app
14 *require* setuptools.
15
16 IMPORTANT NOTE:
17 If called from within the installed package, should only be used to
18 uninstall (setup.py uninstall --record=INSTALLED_FILES), otherwise use
19 the wrapper script in the root directory of the source tar.gz/zip
20
21 """
22
23 # Standard Library Imports
24 from __future__ import annotations
25
26 import ctypes.util
27 import distutils.core
28 import functools
29 import os
30 import platform
31 import re
32 import shutil
33 import sys
34 from configparser import ConfigParser
35 from distutils.command.install import install
36 from distutils.util import change_root, get_platform
37 from fnmatch import fnmatch
38 from time import strftime
39 from typing import TYPE_CHECKING, Callable
40
41 if TYPE_CHECKING:
42 from modulegraph.modulegraph import Package
43
44
45 # Borrowed from setuptools
46 def _find_all_simple(path: str) -> list[str]:
47 """Find all files under 'path'.
48
49 Returns:
50 list[str]: A list of all file paths found under 'path'.
51 """
52 results = (
53 os.path.join(base, file)
54 for base, dirs, files in os.walk(path, followlinks=True)
55 for file in files
56 )
57 return list(filter(os.path.isfile, results))
58
59
60 def findall(directory: str = os.curdir) -> list[str]:
61 """Find all files under 'dir' and return the list of full filenames.
62
63 Unless dir is '.', return full filenames with dir prepended.
64
65 Args:
66 directory (str): The directory to search. Default is os.curdir.
67 """
68 files = _find_all_simple(directory)
69 if directory == os.curdir:
70 make_rel = functools.partial(os.path.relpath, start=directory)
71 files = map(make_rel, files)
72 return list(files)
73
74
75 import distutils.filelist
76
77 distutils.filelist.findall = findall # Fix findall bug in distutils
78
79
80 from DisplayCAL.defaultpaths import AUTOSTART, AUTOSTART_HOME
81 from DisplayCAL.meta import (
82 APPSTREAM_ID,
83 AUTHOR,
84 AUTHOR_ASCII,
85 AUTHOR_EMAIL,
86 DESCRIPTION,
87 DEVELOPMENT_HOME_PAGE,
88 DOMAIN,
89 LONG_DESCRIPTION,
90 NAME,
91 PY_MAXVERSION,
92 PY_MINVERSION,
93 VERSION_STRING,
94 VERSION_TUPLE,
95 WX_MINVERSION,
96 script2pywname,
97 )
98 from DisplayCAL.util_os import getenvu, safe_glob
99 from DisplayCAL.util_str import safe_str
100
101 appname = NAME
102
103 bits = platform.architecture()[0][:2]
104 pypath = os.path.abspath(__file__)
105 pydir = os.path.dirname(pypath)
106 source_dir = os.path.dirname(pydir)
107
108
109 if sys.platform in ("darwin", "win32"):
110 # Adjust PATH so ctypes.util.find_library can find SDL2 DLLs (if present)
111 pth = getenvu("PATH")
112 libpth = os.path.join(pydir, "lib")
113 if not pth.startswith(libpth + os.pathsep):
114 pth = libpth + os.pathsep + pth
115 os.environ["PATH"] = safe_str(pth)
116
117 config = {
118 "data": ["tests/*.icc"],
119 "doc": [
120 "CHANGES.html",
121 "LICENSE.txt",
122 "README.html",
123 "README-fr.html",
124 "screenshots/*.png",
125 "theme/*.png",
126 "theme/*.css",
127 "theme/*.js",
128 "theme/*.svg",
129 "theme/icons/favicon.ico",
130 "theme/slimbox2/*.css",
131 "theme/slimbox2/*.js",
132 ],
133 # Excludes for .app/.exe builds
134 # numpy.lib.utils imports pydoc, which imports Tkinter, but
135 # numpy.lib.utils is not even used by DisplayCAL, so omit all
136 # Tk stuff
137 # Use pyglet with OpenAL as audio backend. pyglet 2.x media import paths
138 # pull in additional submodules dynamically, so don't exclude pyglet.*
139 "excludes": {
140 "all": [
141 "Tkconstants",
142 "Tkinter",
143 "pygame",
144 "pyo",
145 "setuptools",
146 "tcl",
147 "test",
148 "yaml",
149 ],
150 "darwin": ["gdbm"],
151 "win32": ["gi", "win32com.client.genpy"],
152 },
153 "package_data": {
154 NAME: [
155 "beep.wav",
156 "camera_shutter.wav",
157 "ColorLookupTable.fx",
158 "lang/*.yaml",
159 "linear.cal",
160 "pnp.ids",
161 "presets/*.icc",
162 "ref/*.cie",
163 "ref/*.gam",
164 "ref/*.icm",
165 "ref/*.ti1",
166 "report/*.css",
167 "report/*.html",
168 "report/*.js",
169 "test.cal",
170 "theme/*.png",
171 "theme/*.wav",
172 "theme/icons/10x10/*.png",
173 "theme/icons/16x16/*.png",
174 "theme/icons/32x32/*.png",
175 "theme/icons/48x48/*.png",
176 "theme/icons/72x72/*.png",
177 "theme/icons/128x128/*.png",
178 "theme/icons/256x256/*.png",
179 "theme/icons/512x512/*.png",
180 "theme/jet_anim/*.png",
181 "theme/patch_anim/*.png",
182 "theme/splash_anim/*.png",
183 "theme/shutter_anim/*.png",
184 "ti1/*.ti1",
185 "x3d-viewer/*.css",
186 "x3d-viewer/*.html",
187 "x3d-viewer/*.js",
188 "xrc/*.xrc",
189 "VERSION",
190 ]
191 },
192 "xtra_package_data": {NAME: {"win32": [f"theme/icons/{NAME}-uninstall.ico"]}},
193 }
194
195
196 msiversion = ".".join(
197 (
198 str(VERSION_TUPLE[0]),
199 str(VERSION_TUPLE[1]),
200 str(VERSION_TUPLE[2]),
201 )
202 )
203
204 plist_dict = {
205 "CFBundleDevelopmentRegion": "English",
206 "CFBundleExecutable": NAME,
207 "CFBundleGetInfoString": VERSION_STRING,
208 "CFBundleIdentifier": ".".join(reversed(DOMAIN.split("."))) + "." + NAME,
209 "CFBundleInfoDictionaryVersion": "6.0",
210 "CFBundleLongVersionString": VERSION_STRING,
211 "CFBundleName": NAME,
212 "CFBundlePackageType": "APPL",
213 "CFBundleShortVersionString": VERSION_STRING,
214 "CFBundleSignature": "????",
215 "CFBundleVersion": ".".join(map(str, VERSION_TUPLE)),
216 "NSHumanReadableCopyright": f"© {strftime('%Y')} {AUTHOR}",
217 "LSMinimumSystemVersion": "11.0", # Required for native ARM64 support
218 "com.apple.security.cs.disable-library-validation": True, # Critical fix
219 "com.apple.security.cs.allow-unsigned-executable-memory": True,
220 }
221
222
223 class Target:
224 """A class representing a target for installation."""
225
226 def __init__(self, **kwargs) -> None:
227 self.__dict__.update(kwargs)
228
229
230 def create_app_symlinks(dist_dir: str, scripts: list[tuple[str, str]]) -> None:
231 """Create symlinks for the app bundle and standalone tools.
232
233 Args:
234 dist_dir (str): The distribution directory.
235 scripts (list[tuple[str, str]]): List of tuples containing script names
236 and their descriptions.
237 """
238 main_contents_rel = os.path.join(f"{NAME}.app", "Contents")
239 # Create ref, ReadMe and license symlinks in directory
240 # containing the app bundle
241 for src, tgt in [
242 ("ref", "Reference"),
243 ("CHANGES.html", "CHANGES.html"),
244 ("README.html", "README.html"),
245 ("README-fr.html", "README-fr.html"),
246 ("LICENSE.txt", "LICENSE.txt"),
247 ]:
248 tgt = os.path.join(dist_dir, tgt)
249 if os.path.islink(tgt):
250 os.unlink(tgt)
251 os.symlink(os.path.join(main_contents_rel, "Resources", src), tgt)
252 # Create standalone tools app bundles by symlinking to the main bundle
253 scripts = [(script2pywname(script), desc) for script, desc in scripts]
254 tool_scripts = [
255 script for script in [script for script, desc in scripts] if script != NAME
256 ]
257 for script, desc in scripts:
258 if script in (
259 NAME,
260 f"{NAME}-apply-profiles",
261 f"{NAME}-eeColor-to-madVR-converter",
262 ) or script.endswith("-console"):
263 continue
264 tool_name = desc.replace(NAME, "").strip()
265 tool_app = os.path.join(dist_dir, f"{tool_name}.app")
266 if os.path.isdir(tool_app):
267 if (
268 input(
269 f'WARNING: The output directory "{tool_app}" and ALL ITS '
270 "CONTENTS will be REMOVED! Continue? (y/n)"
271 ).lower()
272 == "y"
273 ):
274 print("Removing dir", tool_app)
275 shutil.rmtree(tool_app)
276 else:
277 raise SystemExit("User aborted")
278 tool_script = os.path.join(dist_dir, main_contents_rel, "MacOS", script)
279 has_tool_script = os.path.exists(tool_script)
280 tool_contents = os.path.join(tool_app, "Contents")
281 os.makedirs(tool_contents)
282 # Always include MacOS so the tool binary lives inside the tool app's
283 # own bundle — py2app resolves Resources relative to the executable's
284 # physical location, so placing it in the main app's MacOS would make
285 # it load the main app's Resources instead of the tool's.
286 subdirs = ["Frameworks", "Resources", "MacOS"]
287 for entry in os.listdir(os.path.join(dist_dir, main_contents_rel)):
288 if entry in subdirs:
289 os.makedirs(os.path.join(tool_contents, entry))
290 for subentry in os.listdir(
291 os.path.join(dist_dir, main_contents_rel, entry)
292 ):
293 src = os.path.join(dist_dir, main_contents_rel, entry, subentry)
294 tgt = os.path.join(tool_contents, entry, subentry)
295 if subentry == "main.py":
296 # py2app
297 with open(src) as main_in:
298 py = main_in.read()
299 py = py.replace("main()", f"main({script[len(NAME) + 1 :]!r})")
300 with open(tgt, "wb") as main_out:
301 main_out.write(py.encode())
302 continue
303 if subentry in ("__boot__.py", "site.py", "site.pyc"):
304 shutil.copy(src, tgt)
305 continue
306 if subentry == f"{NAME}.icns":
307 shutil.copy(
308 os.path.join(pydir, "theme", "icons", f"{script}.icns"),
309 os.path.join(tool_contents, entry, f"{script}.icns"),
310 )
311 continue
312 if subentry == script:
313 # PyInstaller: move binary from main app's MacOS to tool app's MacOS
314 os.rename(src, tgt)
315 elif (
316 entry == "MacOS"
317 and not has_tool_script
318 and subentry != appname
319 and not os.path.islink(src)
320 ):
321 # py2app: the bundled Python interpreter in
322 # Contents/MacOS (named "python") must be a real file,
323 # not a symlink. The py2app launcher only sets
324 # PYTHONHOME to the bundle's Resources when
325 # Contents/MacOS/python is NOT a symlink (see lstat /
326 # S_IFLNK check in py2app's main.c). A symlinked
327 # interpreter makes the tool app fall back to the system
328 # Python framework and fail to find its stdlib
329 # ("No module named 'encodings'").
330 shutil.copy(src, tgt)
331 elif subentry not in tool_scripts:
332 os.symlink(
333 os.path.join(
334 "..", "..", "..", main_contents_rel, entry, subentry
335 ),
336 tgt,
337 )
338 if entry == "MacOS" and not has_tool_script:
339 # py2app: the main app only has one launcher binary (appname).
340 # Copy it into the tool app's own MacOS directory under the
341 # tool's name so py2app resolves Resources from the tool app's
342 # bundle, not the main app's.
343 shutil.copy(
344 os.path.join(dist_dir, main_contents_rel, "MacOS", appname),
345 os.path.join(tool_contents, "MacOS", script),
346 )
347 elif entry == "Info.plist":
348 with open(
349 os.path.join(dist_dir, main_contents_rel, entry),
350 "r",
351 encoding="utf-8",
352 ) as info_in:
353 info_xml = info_in.read()
354 # TODO: use an XML library to manipulate the data!
355 # CFBundleName / CFBundleDisplayName
356 info_xml = re.sub(
357 rf"(Name</key>\s*<string>){NAME}",
358 lambda match, toolname=tool_name: match.group(1) + toolname,
359 info_xml,
360 )
361 # CFBundleIdentifier
362 info_xml = info_xml.replace(f".{NAME}</string>", f".{script}</string>")
363 # CFBundleIconFile
364 info_xml = info_xml.replace(
365 f"{NAME}.icns</string>", f"{script}.icns</string>"
366 )
367 # CFBundleExecutable
368 info_xml = re.sub(
369 rf"(Executable</key>\s*<string>){NAME}",
370 lambda match, script=script: match.group(1) + script,
371 info_xml,
372 )
373 with open(
374 os.path.join(tool_contents, entry), "w", encoding="utf-8"
375 ) as info_out:
376 info_out.write(info_xml)
377 else:
378 os.symlink(
379 os.path.join("..", "..", main_contents_rel, entry),
380 os.path.join(tool_contents, entry),
381 )
382
383
384 def get_data(
385 tgt_dir: str,
386 key: str,
387 pkgname: None | str = None,
388 subkey: None | str = None,
389 excludes: None | list[str] = None,
390 ) -> list[tuple[str, list[str]]]:
391 """Return configured data files.
392
393 Args:
394 tgt_dir (str): The target directory.
395 key (str): The config key.
396 pkgname (None | str): Name of the package. Default is None.
397 subkey (None | str): Name of the subkey. Default is None.
398 excludes (None | list[str]): List of files to exclude. Default is None.
399
400 Returns:
401 list[tuple[str, list[str]]]: A list of tuples which contains the
402 normalized path of the data files and the list of paths of the
403 data files.
404 """
405 files = config[key]
406 src_dir = source_dir
407 if pkgname:
408 files = files[pkgname]
409 # modifying the src_dir is not working with py2app, so disabling it.
410 # src_dir = os.path.join(src_dir, pkgname)
411 if subkey:
412 files = files.get(subkey, [])
413 data = []
414 for pth in files:
415 if not [exclude for exclude in excludes or [] if fnmatch(pth, exclude)]:
416 normalized_path = os.path.normpath(
417 os.path.join(tgt_dir, os.path.dirname(pth))
418 )
419 safe_path = [
420 os.path.relpath(p, src_dir)
421 for p in safe_glob(os.path.join(src_dir, pth))
422 ]
423 if pkgname:
424 # try looking for the "{src_dir}/{pkgname}/{pth}" too
425 safe_path += [
426 os.path.relpath(p, src_dir)
427 for p in safe_glob(os.path.join(src_dir, pkgname, pth))
428 ]
429 data.append((normalized_path, safe_path))
430 return data
431
432
433 def get_scripts(excludes: None | list[str] = None) -> list[tuple[str, str]]:
434 """Return a list of scripts with their descriptions.
435
436 Args:
437 excludes (None | list[str]): List of scripts to exclude. Default is
438 None.
439
440 Returns:
441 list[tuple[str, str]]: List of tuples containing script names and their
442 descriptions.
443 """
444 # It is required that each script has an accompanying .desktop file
445 scripts_with_desc = []
446 scripts = safe_glob(os.path.join(pydir, "..", "scripts", f"{appname.lower()}*"))
447
448 def sortbyname(a: str, b: str) -> int:
449 """Sort two script names by their base names."""
450 a, b = [os.path.splitext(v)[0] for v in (a, b)]
451 if a > b:
452 return 1
453 if a < b:
454 return -1
455 return 0
456
457 import functools
458
459 scripts = sorted(scripts, key=functools.cmp_to_key(sortbyname))
460 for script in scripts:
461 script = os.path.basename(script)
462 if script == f"{appname.lower()}-apply-profiles-launcher":
463 continue
464 desktop_file = os.path.join(pydir, "..", "misc", f"{script}.desktop")
465 if os.path.isfile(desktop_file):
466 cfg = ConfigParser()
467 cfg.read(desktop_file)
468 script = cfg.get("Desktop Entry", "Exec").split()[0]
469 desc = cfg.get("Desktop Entry", "Name")
470 else:
471 desc = ""
472 if not [exclude for exclude in excludes or [] if fnmatch(script, exclude)]:
473 scripts_with_desc.append((script, desc))
474 return scripts_with_desc
475
476
477 def setup() -> None:
478 """Setup function for DisplayCAL."""
479 print("***", os.path.abspath(sys.argv[0]), " ".join(sys.argv[1:]))
480
481 bdist_bbfreeze = "bdist_bbfreeze" in sys.argv[1:]
482 bdist_dumb = "bdist_dumb" in sys.argv[1:]
483 bdist_win = "bdist_msi" in sys.argv[1:] or "bdist_wininst" in sys.argv[1:]
484 debug = 0
485 do_full_install = False
486 do_install = False
487 do_py2app = "py2app" in sys.argv[1:]
488 do_py2exe = "py2exe" in sys.argv[1:]
489 do_uninstall = "uninstall" in sys.argv[1:]
490 doc_layout = "deb" if os.path.exists("/etc/debian_version") else ""
491 dry_run = "-n" in sys.argv[1:] or "--dry-run" in sys.argv[1:]
492 print_help = False
493 install_data = None # data files install path (only if given)
494 is_rpm_build = "bdist_rpm" in sys.argv[1:] or os.path.abspath(sys.argv[0]).endswith(
495 os.path.join(
496 os.path.sep,
497 "rpm",
498 "BUILD",
499 f"{NAME}-{VERSION_STRING}",
500 os.path.basename(os.path.abspath(sys.argv[0])),
501 )
502 )
503 prefix = ""
504 recordfile_name = None # record installed files to this file
505 sdist = "sdist" in sys.argv[1:]
506 setuptools = None
507 skip_postinstall = "--skip-postinstall" in sys.argv[1:]
508 use_distutils = not bdist_bbfreeze and not do_py2app
509 use_setuptools = (
510 not use_distutils
511 or "--use-setuptools" in sys.argv[1:]
512 or (os.path.exists("use-setuptools") and "--use-distutils" not in sys.argv[1:])
513 )
514 use_sdl = "--use-sdl" in sys.argv[1:]
515
516 sys.path.insert(1, os.path.join(os.path.dirname(pydir), "util"))
517
518 current_findall = distutils.filelist.findall
519
520 if use_setuptools:
521 if "--use-setuptools" in sys.argv[1:] and not os.path.exists("use-setuptools"):
522 open("use-setuptools", "w").close()
523 try:
524 from setuptools import find_packages, setup
525
526 setuptools = True
527 print("using setuptools")
528 current_findall = find_packages
529 except ImportError:
530 pass
531 elif os.path.exists("use-setuptools"):
532 os.remove("use-setuptools")
533
534 if distutils.filelist.findall is current_findall:
535 # Fix traversing unneeded dirs which can take a long time (minutes)
536 def findall(
537 directory: str = os.curdir,
538 original: Callable = distutils.filelist.findall,
539 listdir: Callable = os.listdir,
540 basename: str = os.path.basename,
541 ) -> list[str]:
542 """Find all files under 'dir' and return the list of full filenames.
543
544 Unless dir is '.', return full filenames with dir prepended.
545
546 Args:
547 directory (str): The directory to search. Default is os.curdir.
548 original (Callable): The original findall function.
549 listdir (Callable): The os.listdir function.
550 basename (str): The os.path.basename function.
551
552 Returns:
553 list[str]: List of full filenames found under 'dir'.
554 """
555 os.listdir = lambda path: [
556 entry
557 for entry in listdir(path)
558 if entry not in ("build", "dist") and not entry.startswith(".")
559 ]
560 try:
561 return original(directory)
562 finally:
563 os.listdir = listdir
564
565 distutils.filelist.findall = findall
566
567 if not setuptools:
568 from distutils.core import setup
569
570 print("using distutils")
571
572 if do_uninstall:
573 i = sys.argv.index("uninstall")
574 sys.argv = [*sys.argv[:i], "install", *sys.argv[i + 1 :]]
575 install.create_home_path = lambda self: None
576
577 if (
578 skip_instrument_conf_files := "--skip-instrument-configuration-files"
579 in sys.argv[1:]
580 ):
581 i = sys.argv.index("--skip-instrument-configuration-files")
582 sys.argv = sys.argv[:i] + sys.argv[i + 1 :]
583
584 if not is_rpm_build:
585 skip_instrument_conf_files = True
586
587 if skip_postinstall:
588 i = sys.argv.index("--skip-postinstall")
589 sys.argv = sys.argv[:i] + sys.argv[i + 1 :]
590
591 if "--use-distutils" in sys.argv[1:]:
592 i = sys.argv.index("--use-distutils")
593 sys.argv = sys.argv[:i] + sys.argv[i + 1 :]
594
595 if "--use-setuptools" in sys.argv[1:]:
596 i = sys.argv.index("--use-setuptools")
597 sys.argv = sys.argv[:i] + sys.argv[i + 1 :]
598
599 argv = list(sys.argv[1:])
600 for i, arg in enumerate(reversed(argv)):
601 n = len(sys.argv) - i - 1
602 if arg in (
603 "install",
604 "install_lib",
605 "install_headers",
606 "install_scripts",
607 "install_data",
608 ):
609 if arg == "install":
610 do_full_install = True
611 do_install = True
612 elif arg == "-d" and len(sys.argv[1:]) > i:
613 dist_dir = sys.argv[i + 2]
614 else:
615 arg = arg.split("=")
616 if arg[0] == "--debug":
617 debug = 1 if len(arg) == 1 else int(arg[1])
618 sys.argv = sys.argv[:n] + sys.argv[n + 1 :]
619 elif len(arg) == 2:
620 if arg[0] == "--dist-dir":
621 dist_dir = arg[1]
622 elif arg[0] == "--doc-layout":
623 doc_layout = arg[1]
624 sys.argv = sys.argv[:n] + sys.argv[n + 1 :]
625 elif arg[0] == "--install-data":
626 install_data = arg[1]
627 elif arg[0] == "--prefix":
628 prefix = arg[1]
629 elif arg[0] == "--record":
630 recordfile_name = arg[1]
631 elif arg[0] == "-h" or arg[0].startswith("--help"):
632 print_help = True
633
634 if not recordfile_name and (do_full_install or do_uninstall):
635 recordfile_name = "INSTALLED_FILES"
636 # if not do_uninstall:
637 # sys.argv.append("--record=" + "INSTALLED_FILES")
638
639 if sys.platform in ("darwin", "win32") or "bdist_egg" in sys.argv[1:]:
640 doc = data = "." if do_py2app or do_py2exe or bdist_bbfreeze else NAME
641 else:
642 # Linux/Unix
643 data = NAME
644 if doc_layout.startswith("deb"):
645 doc = os.path.join("doc", NAME.lower())
646 elif "suse" in doc_layout:
647 doc = os.path.join("doc", "packages", NAME)
648 else:
649 doc = os.path.join("doc", f"{NAME}-{VERSION_STRING}")
650
651 if not install_data:
652 data = os.path.join("share", data)
653 doc = os.path.join("share", doc)
654 if is_rpm_build:
655 doc = os.path.join(os.path.sep, "usr", doc)
656
657 # Use CA file from certifi project
658 if do_py2app or do_py2exe:
659 import certifi
660
661 cacert = certifi.where()
662 if cacert:
663 shutil.copyfile(cacert, os.path.join(pydir, "cacert.pem"))
664 config["package_data"][NAME].append("cacert.pem")
665 else:
666 print("WARNING: cacert.pem from certifi project not found!")
667
668 # on Mac OS X and Windows, we want data files in the package dir
669 # (package_data will be ignored when using py2exe)
670 package_data = {
671 NAME: (
672 config["package_data"][NAME]
673 if sys.platform in ("darwin", "win32") and not do_py2app and not do_py2exe
674 else []
675 )
676 }
677 if sdist and sys.platform in ("darwin", "win32"):
678 package_data[NAME].extend(
679 ["theme/icons/22x22/*.png", "theme/icons/24x24/*.png"]
680 )
681 if sys.platform == "win32" and not do_py2exe:
682 package_data[NAME].append("theme/icons/*.ico")
683 # Scripts
684 if sys.platform == "darwin":
685 scripts = get_scripts(excludes=[appname.lower() + "-apply-profiles"])
686 else:
687 scripts = get_scripts()
688 # Doc files
689 data_files = []
690 if not is_rpm_build or doc_layout.startswith("deb"):
691 data_files += get_data(doc, "doc", excludes=["LICENSE.txt"])
692 if data_files:
693 data_files.append((doc, [os.path.join(pydir, "..", "dist", "copyright")]))
694 data_files.append(
695 (
696 os.path.join(os.path.dirname(data), "doc-base"),
697 [os.path.join(pydir, "..", "misc", appname.lower() + "-readme")],
698 )
699 )
700 data_files.append(
701 (
702 doc,
703 [os.path.relpath(os.path.join(pydir, "..", "LICENSE.txt"), source_dir)],
704 )
705 )
706
707 # metainfo / appdata.xml
708 data_files.append(
709 (
710 os.path.join(os.path.dirname(data), "metainfo"),
711 [
712 os.path.relpath(
713 os.path.normpath(
714 os.path.join(pydir, "..", "dist", f"{APPSTREAM_ID}.appdata.xml")
715 ),
716 source_dir,
717 )
718 ],
719 )
720 )
721
722 if sys.platform not in ("darwin", "win32") or do_py2app or do_py2exe:
723 # Linux/Unix or py2app/py2exe
724 data_files += get_data(data, "package_data", NAME, excludes=["theme/icons/*"])
725 data_files += get_data(data, "data")
726 data_files += get_data(data, "xtra_package_data", NAME, sys.platform)
727 if sys.platform == "win32":
728 # Add python and pythonw
729 data_files.extend(
730 [
731 (
732 os.path.join(data, "lib"),
733 [
734 sys.executable,
735 os.path.join(
736 os.path.dirname(sys.executable), "pythonw.exe"
737 ),
738 ],
739 )
740 ]
741 )
742 if use_sdl:
743 # SDL DLLs for audio module
744 sdl2 = ctypes.util.find_library("SDL2")
745 sdl2_mixer = ctypes.util.find_library("SDL2_mixer")
746 if sdl2:
747 sdl2_libs = [sdl2]
748 if sdl2_mixer:
749 sdl2_libs.append(sdl2_mixer)
750 data_files.append((os.path.join(data, "lib"), sdl2_libs))
751 config["excludes"]["all"].append("pyglet")
752 else:
753 print("WARNING: SDL2_mixer not found!")
754 else:
755 print("WARNING: SDL2 not found!")
756 if "pyglet" not in config["excludes"]["all"]:
757 # OpenAL DLLs for pyglet
758 openal32 = ctypes.util.find_library("OpenAL32.dll")
759 wrap_oal = ctypes.util.find_library("wrap_oal.dll")
760 if openal32:
761 oal = [openal32]
762 if wrap_oal:
763 oal.append(wrap_oal)
764 else:
765 print("WARNING: wrap_oal.dll not found!")
766 data_files.append((data, oal))
767 else:
768 print("WARNING: OpenAL32.dll not found!")
769 elif sys.platform != "darwin":
770 # Linux
771 data_files.append(
772 (
773 os.path.join(os.path.dirname(data), "applications"),
774 [
775 os.path.join(pydir, "..", "misc", f"{NAME.lower()}.desktop"),
776 *safe_glob(
777 os.path.join(
778 pydir, "..", "misc", f"{NAME.lower()}-*.desktop"
779 )
780 ),
781 ],
782 )
783 )
784 data_files.append(
785 (
786 (
787 AUTOSTART
788 if os.geteuid() == 0 or prefix.startswith("/")
789 else AUTOSTART_HOME
790 ),
791 [
792 os.path.join(
793 pydir,
794 "..",
795 "misc",
796 f"z-{NAME.lower()}-apply-profiles.desktop",
797 )
798 ],
799 )
800 )
801 data_files.append(
802 (
803 os.path.join(os.path.dirname(data), "man", "man1"),
804 safe_glob(os.path.join(pydir, "..", "man", "*.1")),
805 )
806 )
807 if not skip_instrument_conf_files:
808 # device configuration / permission stuff
809 if is_rpm_build:
810 # RPM postinstall script will install these to the correct
811 # locations. This allows us compatibility with Argyll
812 # packages which may also contain same udev rules / hotplug
813 # scripts, thus avoiding file conflicts
814 data_files.append(
815 (
816 os.path.join(data, "usb"),
817 [os.path.join(pydir, "..", "misc", "45-Argyll.rules")],
818 )
819 )
820 data_files.append(
821 (
822 os.path.join(data, "usb"),
823 [os.path.join(pydir, "..", "misc", "55-Argyll.rules")],
824 )
825 )
826 data_files.append(
827 (
828 os.path.join(data, "usb"),
829 [os.path.join(pydir, "..", "misc", "Argyll")],
830 )
831 )
832 data_files.append(
833 (
834 os.path.join(data, "usb"),
835 [os.path.join(pydir, "..", "misc", "Argyll.usermap")],
836 )
837 )
838 else:
839 devconf_files = []
840 if os.path.isdir("/etc/udev/rules.d"):
841 if safe_glob("/dev/bus/usb/*/*"):
842 # USB and serial instruments using udev, where udev
843 # already creates /dev/bus/usb/00X/00X devices
844 devconf_files.append(
845 (
846 "/etc/udev/rules.d",
847 [
848 os.path.join(
849 pydir, "..", "misc", "55-Argyll.rules"
850 )
851 ],
852 )
853 )
854 else:
855 # USB using udev, where there are NOT /dev/bus/usb/00X/00X
856 # devices
857 devconf_files.append(
858 (
859 "/etc/udev/rules.d",
860 [
861 os.path.join(
862 pydir, "..", "misc", "45-Argyll.rules"
863 )
864 ],
865 )
866 )
867 elif os.path.isdir("/etc/hotplug"):
868 # USB using hotplug and Serial using udev
869 # (older versions of Linux)
870 devconf_files.append(
871 (
872 "/etc/hotplug/usb",
873 [
874 os.path.join(pydir, "..", "misc", fname)
875 for fname in ["Argyll", "Argyll.usermap"]
876 ],
877 )
878 )
879 for entry in devconf_files:
880 for fname in entry[1]:
881 if os.path.isfile(fname):
882 data_files.extend([(entry[0], [fname])])
883 for dname in (
884 "10x10",
885 "16x16",
886 "22x22",
887 "24x24",
888 "32x32",
889 "48x48",
890 "64x64",
891 "72x72",
892 "128x128",
893 "256x256",
894 "512x512",
895 ):
896 # Get all the icons needed, depending on platform
897 # Only the icon sizes 10, 16, 32, 72, 256 and 512 include icons
898 # that are used exclusively for UI elements.
899 # These should be installed in an app-specific location, e.g.
900 # under Linux $XDG_DATA_DIRS/DisplayCAL/theme/icons/
901 # The app icon sizes 16, 32, 48 and 256 (128 under Mac OS X),
902 # which are used for taskbar icons and the like, as well as the
903 # other sizes can be installed in a generic location, e.g.
904 # under Linux $XDG_DATA_DIRS/icons/hicolor/<size>/apps/
905 # Generally, icon filenames starting with the lowercase app name
906 # should be installed in the generic location.
907 icons = []
908 desktopicons = []
909 if sys.platform == "darwin":
910 largest_iconbundle_icon_size = "128x128"
911 else:
912 largest_iconbundle_icon_size = "256x256"
913 for iconpath in safe_glob(
914 os.path.join(pydir, "theme", "icons", dname, "*.png")
915 ):
916 if not os.path.basename(iconpath).startswith(NAME.lower()) or (
917 sys.platform in ("darwin", "win32")
918 and dname
919 in ("16x16", "32x32", "48x48", largest_iconbundle_icon_size)
920 ):
921 # In addition to UI element icons, we also need all the app
922 # icons we use in get_icon_bundle under macOS/Windows,
923 # otherwise they wouldn't be included (under Linux, these
924 # are included for installation to the system-wide icon
925 # theme location instead)
926 icons.append(iconpath)
927 elif sys.platform not in ("darwin", "win32"):
928 desktopicons.append(iconpath)
929 if icons:
930 data_files.append((os.path.join(data, "theme", "icons", dname), icons))
931 if desktopicons:
932 data_files.append(
933 (
934 os.path.join(
935 os.path.dirname(data), "icons", "hicolor", dname, "apps"
936 ),
937 desktopicons,
938 )
939 )
940 if do_py2app:
941 data_files.append(
942 (
943 os.path.join(data, "scripts"),
944 [
945 os.path.join(
946 pydir,
947 "..",
948 "scripts",
949 f"{NAME.lower()}-eecolor-to-madvr-converter",
950 )
951 ],
952 )
953 )
954
955 # sources = []
956 # if sys.platform == "win32":
957 # macros = [("NT", None)]
958 # libraries = ["user32", "gdi32"]
959 # link_args = None
960 # elif sys.platform == "darwin":
961 # macros = [("__APPLE__", None), ("UNIX", None)]
962 # libraries = None
963 # # XXX: Not sure which macOS version exactly removed the need
964 # # to specify -framework
965 # if intlist(platform.mac_ver()[0].split(".")) >= [10, 7]:
966 # link_args = None
967 # else:
968 # link_args = [
969 # "-framework Carbon",
970 # "-framework CoreFoundation",
971 # "-framework Python",
972 # "-framework IOKit",
973 # ]
974 # else:
975 # macros = [("UNIX", None)]
976 # libraries = ["X11", "Xinerama", "Xrandr", "Xxf86vm"]
977 # link_args = None
978
979 ext_modules = []
980
981 requires = []
982 if not setuptools or sys.platform != "win32":
983 # wxPython windows installer doesn't add egg-info entry, so
984 # a dependency check from pkg_resources would always fail
985 requires.append(
986 "wxPython (>= {})".format(".".join(str(n) for n in WX_MINVERSION))
987 )
988 if sys.platform == "win32":
989 requires.append("pywin32 (>= 213.0)")
990
991 packages = [NAME, f"{NAME}.lib", f"{NAME}.lib.agw"]
992
993 attrs = {
994 "author": AUTHOR_ASCII,
995 "author_email": AUTHOR_EMAIL,
996 "classifiers": [
997 "Development Status :: 5 - Production/Stable",
998 "Environment :: MacOS X",
999 "Environment :: Win32 (MS Windows)",
1000 "Environment :: X11 Applications",
1001 "Intended Audience :: End Users/Desktop",
1002 "License :: OSI Approved :: GNU General Public License v3 "
1003 "or later (GPLv3+)",
1004 "Operating System :: OS Independent",
1005 "Programming Language :: Python :: 3.9",
1006 "Programming Language :: Python :: 3.10",
1007 "Programming Language :: Python :: 3.11",
1008 "Programming Language :: Python :: 3.12",
1009 "Programming Language :: Python :: 3.13",
1010 "Programming Language :: Python :: 3.14",
1011 "Topic :: Multimedia :: Graphics",
1012 ],
1013 "data_files": data_files,
1014 "description": DESCRIPTION,
1015 "download_url": f"{DEVELOPMENT_HOME_PAGE}/releases/download/"
1016 f"{VERSION_STRING}/{NAME}-{VERSION_STRING}.tar.gz",
1017 "ext_modules": ext_modules,
1018 "license": "GPL v3",
1019 "long_description": LONG_DESCRIPTION,
1020 "long_description_content_type": "text/x-rst",
1021 "name": NAME,
1022 "packages": packages,
1023 "package_data": package_data,
1024 "package_dir": {NAME: NAME},
1025 "platforms": [
1026 "Python >= {} <= {}".format(
1027 ".".join(str(n) for n in PY_MINVERSION),
1028 ".".join(str(n) for n in PY_MAXVERSION),
1029 ),
1030 "Linux/Unix with X11",
1031 "Mac OS X >= 10.4",
1032 "Windows 2000 and newer",
1033 ],
1034 "requires": requires,
1035 "provides": [NAME],
1036 "scripts": [],
1037 "url": f"https://{DOMAIN}/",
1038 "version": msiversion if "bdist_msi" in sys.argv[1:] else VERSION_STRING,
1039 }
1040
1041 if setuptools:
1042 attrs["entry_points"] = {
1043 "gui_scripts": [
1044 "{} = {}.main:main{}".format(
1045 script,
1046 NAME,
1047 (
1048 ""
1049 if script == NAME.lower()
1050 else script[len(NAME) :].lower().replace("-", "_")
1051 ),
1052 )
1053 for script, desc in scripts
1054 ]
1055 }
1056 attrs["exclude_package_data"] = {NAME: []}
1057 attrs["include_package_data"] = (
1058 sys.platform in ("darwin", "win32") and not do_py2app
1059 )
1060 # Modern py2app build flow errors out when install_requires is present.
1061 # Keep runtime metadata for normal installs, but skip it for app/exe bundling.
1062 if not do_py2app and not do_py2exe:
1063 install_requires = [
1064 req.replace("(", "").replace(")", "") for req in requires
1065 ]
1066 attrs["install_requires"] = install_requires
1067 attrs["zip_safe"] = False
1068 else:
1069 attrs["scripts"].extend(
1070 os.path.join("scripts", script)
1071 for script, desc in [
1072 script_desc
1073 for script_desc in scripts
1074 if script_desc[0] != f"{NAME.lower()}-apply-profiles"
1075 or sys.platform != "darwin"
1076 ]
1077 )
1078
1079 if bdist_bbfreeze:
1080 attrs["setup_requires"] = ["bbfreeze"]
1081
1082 if "bdist_wininst" in sys.argv[1:]:
1083 attrs["scripts"].append(os.path.join("util", f"{NAME}_postinstall.py"))
1084
1085 if do_py2app:
1086 mainpy = os.path.join(source_dir, "main.py")
1087 if not os.path.exists(mainpy):
1088 shutil.copy(os.path.join(source_dir, "scripts", NAME.lower()), mainpy)
1089 attrs["app"] = [mainpy]
1090 dist_dir = os.path.join(
1091 pydir,
1092 "..",
1093 "dist",
1094 f"py2app.{get_platform()}-py{sys.version_info[0]}.{sys.version_info[1]}",
1095 f"{NAME}-{VERSION_STRING}",
1096 )
1097 import py2app.build_app as py2app_build_app
1098 from py2app.build_app import py2app as py2app_cls
1099 from py2app import util as py2app_util
1100
1101 def _skip_codesign_adhoc(bundle: str) -> None:
1102 print(f"Skipping ad-hoc codesign for bundle: {bundle}")
1103
1104 py2app_util.codesign_adhoc = _skip_codesign_adhoc
1105 py2app_build_app.codesign_adhoc = _skip_codesign_adhoc
1106
1107 class DisplayCALPy2App(py2app_cls):
1108 """py2app wrapper that tolerates PEP 621 dependencies metadata."""
1109
1110 def finalize_options(self) -> None:
1111 # py2app 0.28+ errors out when install_requires is populated.
1112 # Under setuptools+pyproject, install_requires can be injected
1113 # from project.dependencies even if setup.py does not set it.
1114 self.distribution.install_requires = []
1115 if hasattr(self.distribution.metadata, "requires_dist"):
1116 self.distribution.metadata.requires_dist = []
1117 super().finalize_options()
1118
1119 py2app_cls._copy_package_data = py2app_cls.copy_package_data
1120
1121 def copy_package_data(
1122 self: py2app_cls, package: Package, target_dir: str
1123 ) -> None:
1124 """Override copy_package_data to skip package data from other packages.
1125
1126 Copy any package data in a python package into the target_dir.
1127
1128 This is a bit of a hack, it would be better to identify python eggs
1129 and copy those in whole.
1130
1131 Args:
1132 self (py2app_cls): The py2app class instance.
1133 package (Package): The package to copy data from.
1134 target_dir (str): The target directory to copy data to.
1135 """
1136 # Skip package data which is already included as data files
1137 if package.identifier.split(".")[0] != NAME:
1138 self._copy_package_data(package, target_dir)
1139
1140 py2app_cls.copy_package_data = copy_package_data
1141 attrs.setdefault("cmdclass", {})
1142 attrs["cmdclass"]["py2app"] = DisplayCALPy2App
1143 attrs["options"] = {
1144 "py2app": {
1145 "argv_emulation": False,
1146 "dist_dir": dist_dir,
1147 "excludes": config["excludes"]["all"] + config["excludes"]["darwin"],
1148 "iconfile": os.path.join(pydir, "theme", "icons", f"{NAME}.icns"),
1149 "no_strip": True,
1150 "optimize": 0,
1151 "plist": plist_dict,
1152 }
1153 }
1154 if use_sdl:
1155 attrs["options"]["py2app"]["frameworks"] = ["SDL2", "SDL2_mixer"]
1156 attrs["setup_requires"] = ["py2app"]
1157
1158 if do_py2exe:
1159 import wx
1160 from winmanifest_util import getmanifestxml
1161
1162 machine = platform.machine().lower()
1163 if "arm" in machine or "aarch64" in machine:
1164 arch = "arm64"
1165 elif "64" in platform.architecture()[0]:
1166 arch = "amd64"
1167 else:
1168 arch = "x86"
1169 manifest_xml = getmanifestxml(
1170 os.path.join(
1171 pydir,
1172 "..",
1173 "misc",
1174 NAME
1175 + (
1176 f".exe.{arch}.VC90.manifest"
1177 if hasattr(sys, "version_info") and sys.version_info[:2] >= (3, 8)
1178 else ".exe.manifest"
1179 ),
1180 )
1181 )
1182 tmp_scripts_dir = os.path.join(source_dir, "build", "temp.scripts")
1183 if not os.path.isdir(tmp_scripts_dir):
1184 os.makedirs(tmp_scripts_dir)
1185 apply_profiles_launcher = (
1186 f"{appname.lower()}-apply-profiles-launcher",
1187 f"{appname} Profile Loader Launcher",
1188 )
1189 for script, _desc in [*scripts, apply_profiles_launcher]:
1190 shutil.copy(
1191 os.path.join(source_dir, "scripts", script),
1192 os.path.join(tmp_scripts_dir, script2pywname(script)),
1193 )
1194 attrs["windows"] = [
1195 Target(
1196 script=os.path.join(tmp_scripts_dir, script2pywname(script)),
1197 icon_resources=[
1198 (
1199 1,
1200 os.path.join(
1201 pydir,
1202 "theme",
1203 "icons",
1204 os.path.splitext(os.path.basename(script))[0] + ".ico",
1205 ),
1206 )
1207 ],
1208 other_resources=[(24, 1, manifest_xml)],
1209 copyright=f"© {strftime('%Y')} {AUTHOR}",
1210 description=desc,
1211 )
1212 for script, desc in [
1213 script_desc1
1214 for script_desc1 in scripts
1215 if script_desc1[0] != appname.lower() + "-eecolor-to-madvr-converter"
1216 and not script_desc1[0].endswith("-console")
1217 ]
1218 ]
1219
1220 # Add profile loader launcher
1221 attrs["windows"].append(
1222 Target(
1223 script=os.path.join(
1224 tmp_scripts_dir, script2pywname(apply_profiles_launcher[0])
1225 ),
1226 icon_resources=[
1227 (
1228 1,
1229 os.path.join(
1230 pydir,
1231 "theme",
1232 "icons",
1233 appname + "-apply-profiles" + ".ico",
1234 ),
1235 )
1236 ],
1237 other_resources=[(24, 1, manifest_xml)],
1238 copyright=f"© {strftime('%Y')} {AUTHOR}",
1239 description=apply_profiles_launcher[1],
1240 )
1241 )
1242
1243 # Programs that can run with and without GUI
1244 console_scripts = [f"{NAME}-VRML-to-X3D-converter"] # No "-console" suffix!
1245 for console_script in console_scripts:
1246 console_script_path = os.path.join(
1247 tmp_scripts_dir, console_script + "-console"
1248 )
1249 if not os.path.isfile(console_script_path):
1250 shutil.copy(
1251 os.path.join(
1252 source_dir, "scripts", console_script.lower() + "-console"
1253 ),
1254 console_script_path,
1255 )
1256 attrs["console"] = [
1257 Target(
1258 script=os.path.join(
1259 tmp_scripts_dir, script2pywname(script) + "-console"
1260 ),
1261 icon_resources=[
1262 (
1263 1,
1264 os.path.join(
1265 pydir,
1266 "theme",
1267 "icons",
1268 os.path.splitext(os.path.basename(script))[0] + ".ico",
1269 ),
1270 )
1271 ],
1272 other_resources=[(24, 1, manifest_xml)],
1273 copyright=f"© {strftime('%Y')} {AUTHOR}",
1274 description=desc,
1275 )
1276 for script, desc in [
1277 script_desc2
1278 for script_desc2 in scripts
1279 if script2pywname(script_desc2[0]) in console_scripts
1280 ]
1281 ]
1282
1283 # Programs without GUI
1284 attrs["console"].append(
1285 Target(
1286 script=os.path.join(
1287 tmp_scripts_dir, appname + "-eeColor-to-madVR-converter"
1288 ),
1289 icon_resources=[
1290 (
1291 1,
1292 os.path.join(
1293 pydir, "theme", "icons", appname + "-3DLUT-maker.ico"
1294 ),
1295 )
1296 ],
1297 other_resources=[(24, 1, manifest_xml)],
1298 copyright=f"© {strftime('%Y')} {AUTHOR}",
1299 description="Convert eeColor 65^3 to madVR 256^3 3D LUT "
1300 "(video levels in, video levels out)",
1301 )
1302 )
1303
1304 dist_dir = os.path.join(
1305 pydir,
1306 "..",
1307 "dist",
1308 f"py2exe.{get_platform()}-py{sys.version_info[0]}.{sys.version_info[1]}",
1309 f"{NAME}-{VERSION_STRING}",
1310 )
1311 attrs["options"] = {
1312 "py2exe": {
1313 "dist_dir": dist_dir,
1314 "dll_excludes": [
1315 "iertutil.dll",
1316 "MPR.dll",
1317 "msvcm90.dll",
1318 "msvcp90.dll",
1319 "msvcr90.dll",
1320 "mswsock.dll",
1321 "urlmon.dll",
1322 "w9xpopen.exe",
1323 "gdiplus.dll",
1324 "mfc90.dll",
1325 ],
1326 "excludes": config["excludes"]["all"] + config["excludes"]["win32"],
1327 "bundle_files": 3 if wx.VERSION >= (2, 8, 10, 1) else 1,
1328 "compressed": 1,
1329 "optimize": 0, # 0 = don't optimize (generate .pyc)
1330 # 1 = normal optimization (like python -O)
1331 # 2 = extra optimization (like python -OO)
1332 }
1333 }
1334 if debug:
1335 attrs["options"]["py2exe"].update(
1336 {"bundle_files": 3, "compressed": 0, "optimize": 0, "skip_archive": 1}
1337 )
1338 if setuptools:
1339 attrs["setup_requires"] = ["py2exe"]
1340 attrs["zipfile"] = os.path.join("lib", "library.zip")
1341
1342 if (do_uninstall or do_install or bdist_win or bdist_dumb) and not print_help:
1343 distutils.core._setup_stop_after = "commandline"
1344 dist = setup(**attrs)
1345 distutils.core._setup_stop_after = None
1346 cmd = install(dist).get_finalized_command("install")
1347 if debug > 0:
1348 for attrname in [
1349 "base",
1350 "data",
1351 "headers",
1352 "lib",
1353 "libbase",
1354 "platbase",
1355 "platlib",
1356 "prefix",
1357 "purelib",
1358 "root",
1359 "scripts",
1360 "userbase",
1361 ]:
1362 if attrname not in ["prefix", "root"]:
1363 attrname = "install_" + attrname
1364 if hasattr(cmd, attrname):
1365 print(attrname, getattr(cmd, attrname))
1366 if debug > 1:
1367 try:
1368 from util.ppdir import ppdir
1369 except ImportError:
1370 pass
1371 else:
1372 ppdir(cmd, types=[dict, list, str, tuple, type, str])
1373 if not install_data:
1374 if sys.platform in ("darwin", "win32"):
1375 # on Mac OS X and Windows, we want data files in the package dir
1376 data_basedir = cmd.install_lib
1377 else:
1378 data_basedir = cmd.install_data
1379 else:
1380 data_basedir = install_data
1381
1382 data = change_root(data_basedir, data)
1383 doc = change_root(data_basedir, doc)
1384 # determine in which cases we want to make data file paths relative to
1385 # site-packages (on Mac and Windows) and when we want to make them
1386 # absolute (Linux)
1387 linux = sys.platform not in ("darwin", "win32") and (
1388 not cmd.root and setuptools
1389 )
1390 dar_win = (
1391 sys.platform in ("darwin", "win32") and (cmd.root or not setuptools)
1392 ) or bdist_win
1393 if (
1394 not do_uninstall
1395 and not install_data
1396 and (linux or dar_win)
1397 and attrs["data_files"]
1398 ):
1399 if data_basedir.startswith(cmd.install_data + os.path.sep):
1400 data_basedir = os.path.relpath(data_basedir, cmd.install_data)
1401 for i, f in enumerate(attrs["data_files"]):
1402 if isinstance(f, str):
1403 attrs["data_files"][i] = change_root(data_basedir, f)
1404 else:
1405 attrs["data_files"][i] = (change_root(data_basedir, f[0]), f[1])
1406
1407 if do_uninstall and not print_help:
1408 # Quick and dirty uninstall
1409 if dry_run:
1410 print("dry run - nothing will be removed")
1411 else:
1412 from DisplayCAL.postinstall import postuninstall
1413
1414 # Yeah, yeah - its actually pre-uninstall
1415 if cmd.root:
1416 postuninstall(prefix=change_root(cmd.root, cmd.prefix))
1417 else:
1418 postuninstall(prefix=cmd.prefix)
1419
1420 removed = []
1421 visited = []
1422
1423 if os.path.exists(recordfile_name):
1424 with open(recordfile_name) as f:
1425 paths = [
1426 (
1427 change_root(cmd.root, line.rstrip("\n"))
1428 if cmd.root
1429 else line.rstrip("\n")
1430 )
1431 for line in f
1432 ]
1433 else:
1434 paths = []
1435
1436 if not paths:
1437 # If the installed files have not been recorded, use some fallback
1438 # logic to find them
1439 paths = safe_glob(os.path.join(cmd.install_scripts, NAME))
1440 if sys.platform == "win32":
1441 if setuptools:
1442 paths += safe_glob(os.path.join(cmd.install_scripts, f"{NAME}.exe"))
1443 paths += safe_glob(
1444 os.path.join(cmd.install_scripts, f"{NAME}-script.py")
1445 )
1446 else:
1447 paths += safe_glob(os.path.join(cmd.install_scripts, f"{NAME}.cmd"))
1448 paths += safe_glob(
1449 os.path.join(cmd.install_scripts, f"{NAME}_postinstall.py")
1450 )
1451 for attrname in ["data", "headers", "lib", "libbase", "platlib", "purelib"]:
1452 path = os.path.join(getattr(cmd, f"install_{attrname}"), NAME)
1453 if path not in paths:
1454 # Using sys.version in this way is consistent with
1455 # setuptools
1456 paths += (
1457 safe_glob(path)
1458 + safe_glob(
1459 f"{path}-{VERSION_STRING}-py{sys.version_info[0]}.{sys.version_info[1]}*.egg"
1460 )
1461 + safe_glob(
1462 f"{path}-{VERSION_STRING}-py{sys.version_info[0]}.{sys.version_info[1]}*.egg-info"
1463 )
1464 )
1465
1466 if os.path.isabs(data) and data not in paths:
1467 for fname in [
1468 "lang",
1469 "presets",
1470 "ref",
1471 "report",
1472 "screenshots",
1473 "theme",
1474 "ti1",
1475 "x3d-viewer",
1476 "CHANGES.html",
1477 "LICENSE.txt",
1478 "README.html",
1479 "README-fr.html",
1480 "beep.wav",
1481 "cacert.pem",
1482 "camera_shutter.wav",
1483 "ColorLookupTable.fx",
1484 f"{NAME.lower()}.desktop",
1485 f"{NAME.lower()}-3dlut-maker.desktop",
1486 f"{NAME.lower()}-curve-viewer.desktop",
1487 f"{NAME.lower()}-profile-info.desktop",
1488 f"{NAME.lower()}-scripting-client.desktop",
1489 f"{NAME.lower()}-synthprofile.desktop",
1490 f"{NAME.lower()}-testchart-editor.desktop",
1491 "pnp.ids",
1492 "quirk.json",
1493 "linear.cal",
1494 "test.cal",
1495 ]:
1496 path = os.path.join(data, fname)
1497 if path not in paths:
1498 paths += safe_glob(path)
1499 if os.path.isabs(doc) and doc not in paths:
1500 for fname in [
1501 "screenshots",
1502 "theme",
1503 "CHANGES.html",
1504 "LICENSE.txt",
1505 "README.html",
1506 "README-fr.html",
1507 ]:
1508 path = os.path.join(doc, fname)
1509 if path not in paths:
1510 paths += safe_glob(path)
1511 if sys.platform == "win32":
1512 from DisplayCAL.postinstall import get_special_folder_path
1513
1514 startmenu_programs_common = get_special_folder_path(
1515 "CSIDL_COMMON_PROGRAMS"
1516 )
1517 startmenu_programs = get_special_folder_path("CSIDL_PROGRAMS")
1518 for path in (startmenu_programs_common, startmenu_programs):
1519 if path:
1520 for filename in (
1521 NAME,
1522 "CHANGES",
1523 "LICENSE",
1524 "README",
1525 "Uninstall",
1526 ):
1527 paths += safe_glob(
1528 os.path.join(path, NAME, f"{filename}.lnk")
1529 )
1530
1531 for path in paths:
1532 if os.path.exists(path):
1533 if path in visited:
1534 continue
1535 visited.append(path)
1536 if dry_run:
1537 print(path)
1538 continue
1539 try:
1540 if os.path.isfile(path):
1541 os.remove(path)
1542 elif os.path.isdir(path):
1543 os.rmdir(path)
1544 except Exception as exception:
1545 print("could'nt remove", path)
1546 print(" ", exception)
1547 else:
1548 print("removed", path)
1549 removed.append(path)
1550 while path != os.path.dirname(path):
1551 # remove parent directories if empty
1552 # could also use os.removedirs(path) but we want some status
1553 # info
1554 path = os.path.dirname(path)
1555 if os.path.isdir(path):
1556 if len(os.listdir(path)) == 0:
1557 if path in visited:
1558 continue
1559 visited.append(path)
1560 if dry_run:
1561 print(path)
1562 continue
1563 try:
1564 os.rmdir(path)
1565 except Exception as exception:
1566 print("could'nt remove", path)
1567 print(" ", exception)
1568 else:
1569 print("removed", path)
1570 removed.append(path)
1571 else:
1572 break
1573
1574 if not removed:
1575 print(len(visited), "entries found")
1576 else:
1577 print(len(removed), "entries removed")
1578
1579 else:
1580 # To have a working sdist and bdist_rpm when using distutils,
1581 # we go to the length of generating MANIFEST.in from scratch everytime,
1582 # using the information available from setup.
1583 manifest_in = ["# This file will be re-generated by setup.py - do not edit"]
1584 manifest_in.extend(
1585 [
1586 "include LICENSE.txt",
1587 "include DisplayCAL/VERSION",
1588 "include MANIFEST.in",
1589 "include README.html",
1590 "include README-fr.html",
1591 "include CHANGES.html",
1592 f"include {NAME}*.pyw",
1593 f"include {NAME}-*.pyw",
1594 f"include {NAME}-*.py",
1595 ]
1596 )
1597 for _datadir, datafiles in attrs.get("data_files", []):
1598 manifest_in.extend(
1599 "include {}".format(
1600 os.path.relpath(os.path.sep.join(datafile.split("/")), source_dir)
1601 or datafile
1602 )
1603 for datafile in datafiles
1604 )
1605 for extmod in attrs.get("ext_modules", []):
1606 manifest_in.extend(
1607 "include " + os.path.sep.join(src.split("/")) for src in extmod.sources
1608 )
1609 for pkg in attrs.get("packages", []):
1610 pkg = os.path.join(*pkg.split("."))
1611 pkgdir = os.path.sep.join(
1612 attrs.get("package_dir", {}).get(pkg, pkg).split("/")
1613 )
1614 manifest_in.append("include " + os.path.join(pkgdir, "*.py"))
1615 # manifest_in.append("include " + os.path.join(pkgdir, "*.pyd"))
1616 # manifest_in.append("include " + os.path.join(pkgdir, "*.so"))
1617 manifest_in.extend(
1618 f"include {os.path.sep.join([pkgdir, *obj.split('/')])}"
1619 for obj in attrs.get("package_data", {}).get(pkg, [])
1620 )
1621 manifest_in.extend(
1622 "include {}".format(os.path.join(*pymod.split(".")))
1623 for pymod in attrs.get("py_modules", [])
1624 )
1625 manifest_in.append(
1626 "include {}".format(os.path.join(NAME, "theme", "theme-info.txt"))
1627 )
1628 manifest_in.append(
1629 "recursive-include {} {} {}".format(
1630 os.path.join(NAME, "theme", "icons"), "*.icns", "*.ico"
1631 )
1632 )
1633 manifest_in.append("include {}".format(os.path.join("man", "*.1")))
1634 manifest_in.append("recursive-include misc *")
1635 if skip_instrument_conf_files:
1636 manifest_in.extend(
1637 [
1638 "exclude misc/Argyll",
1639 "exclude misc/*.rules",
1640 "exclude misc/*.usermap",
1641 ]
1642 )
1643 manifest_in.append("include {}".format(os.path.join("screenshots", "*.png")))
1644 manifest_in.append("include {}".format(os.path.join("scripts", "*")))
1645 manifest_in.append("include {}".format(os.path.join("tests", "*")))
1646 manifest_in.append("recursive-include theme *")
1647 manifest_in.append("recursive-include util *.cmd *.py *.sh")
1648 if sys.platform == "win32" and not setuptools:
1649 # Only needed under Windows
1650 manifest_in.append("global-exclude .svn/*")
1651 manifest_in.append("global-exclude *~")
1652 manifest_in.append("global-exclude *.backup")
1653 manifest_in.append("global-exclude */__pycache__/*")
1654 manifest_in.append("global-exclude *.bak")
1655 if not dry_run:
1656 with open("MANIFEST.in", "w") as manifest:
1657 manifest.write("\n".join(manifest_in))
1658 if os.path.exists("MANIFEST"):
1659 os.remove("MANIFEST")
1660
1661 if bdist_bbfreeze:
1662 i = sys.argv.index("bdist_bbfreeze")
1663 if "-d" not in sys.argv[i + 1 :] and "--dist-dir" not in sys.argv[i + 1 :]:
1664 dist_dir = os.path.join(
1665 pydir,
1666 "..",
1667 "dist",
1668 f"bbfreeze.{get_platform()}-py{sys.version_info[0]}.{sys.version_info[1]}",
1669 )
1670 sys.argv.insert(i + 1, f"--dist-dir={dist_dir}")
1671 if "egg_info" not in sys.argv[1:i]:
1672 sys.argv.insert(i, "egg_info")
1673
1674 if do_py2app or do_py2exe:
1675 sys.path.insert(1, pydir)
1676 i = sys.argv.index("py2app" if do_py2app else "py2exe")
1677 if "build_ext" not in sys.argv[1:i]:
1678 sys.argv.insert(i, "build_ext")
1679
1680 setup(**attrs)
1681
1682 if dry_run or print_help:
1683 return
1684
1685 if do_py2app:
1686 frameworks_dir = os.path.join(
1687 dist_dir, f"{NAME}.app", "Contents", "Frameworks"
1688 )
1689 lib_dynload_dir = os.path.join(
1690 dist_dir,
1691 f"{NAME}.app",
1692 "Contents",
1693 "Resources",
1694 "lib",
1695 "python{}.{}".format(*sys.version_info[:2]),
1696 "lib-dynload",
1697 )
1698 # Fix Pillow (PIL) dylibs not being included
1699 pil_dylibs = os.path.join(lib_dynload_dir, "PIL", ".dylibs")
1700 if not os.path.isdir(pil_dylibs):
1701 import PIL
1702
1703 pil_installed_dylibs = os.path.join(
1704 os.path.dirname(PIL.__file__), ".dylibs"
1705 )
1706 print("Copying", pil_installed_dylibs, "->", pil_dylibs)
1707 shutil.copytree(pil_installed_dylibs, pil_dylibs)
1708 # ADD THIS: Remove existing signatures so the later deep-sign works properly
1709 for root, dirs, files in os.walk(pil_dylibs):
1710 for file in files:
1711 if file.endswith(".dylib"):
1712 os.system(
1713 f"codesign --remove-signature '{os.path.join(root, file)}'"
1714 )
1715 for entry in os.listdir(pil_dylibs):
1716 print(os.path.join(pil_dylibs, entry))
1717 # Remove wrongly included frameworks
1718 dylibs_entries = os.listdir(pil_installed_dylibs)
1719 for entry in os.listdir(frameworks_dir):
1720 if entry in dylibs_entries:
1721 dylib = os.path.join(frameworks_dir, entry)
1722 print("Removing", dylib)
1723 os.remove(dylib)
1724 import wx
1725
1726 if wx.VERSION >= (4,):
1727 # Fix wxPython 4 dylibs being included in wrong location
1728 wx_dylibs = os.path.join(lib_dynload_dir, "wx")
1729 for entry in os.listdir(frameworks_dir):
1730 if entry.startswith("libwx"):
1731 dylib = os.path.join(frameworks_dir, entry)
1732 lib_dylib = os.path.join(wx_dylibs, entry)
1733 print("Moving", dylib, "->", lib_dylib)
1734 shutil.move(dylib, lib_dylib)
1735
1736 create_app_symlinks(dist_dir, scripts)
1737
1738 if do_py2exe:
1739 shutil.copy(
1740 os.path.join(
1741 dist_dir, f"python{sys.version_info[0]}{sys.version_info[1]}.dll"
1742 ),
1743 os.path.join(
1744 dist_dir,
1745 "lib",
1746 f"python{sys.version_info[0]}{sys.version_info[1]}.dll",
1747 ),
1748 )
1749
1750 if (bdist_bbfreeze and sys.platform == "win32") or do_py2exe:
1751 from vc90crt import vc90crt_copy_files
1752
1753 if do_py2exe:
1754 vc90crt_copy_files(dist_dir)
1755 vc90crt_copy_files(os.path.join(dist_dir, "lib"))
1756 else:
1757 vc90crt_copy_files(os.path.join(dist_dir, NAME + "-" + VERSION_STRING))
1758
1759 if do_full_install and not is_rpm_build and not skip_postinstall:
1760 from DisplayCAL.postinstall import postinstall
1761
1762 if sys.platform == "win32":
1763 path = os.path.join(cmd.install_lib, NAME)
1764 # Using sys.version in this way is consistent with setuptools
1765 for path_ in safe_glob(path) + safe_glob(
1766 os.path.join(
1767 f"{path}-{VERSION_STRING}-py{sys.version_info[0]}.{sys.version_info[1]}*.egg",
1768 NAME,
1769 )
1770 ):
1771 if cmd.root:
1772 postinstall(prefix=change_root(cmd.root, path_))
1773 else:
1774 postinstall(prefix=path_)
1775
1776 elif cmd.root:
1777 postinstall(prefix=change_root(cmd.root, cmd.prefix))
1778 else:
1779 postinstall(prefix=cmd.prefix)
1780
1781
1782 if __name__ == "__main__":
1783 setup()