pydiffit 0.9.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pydiffit/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """pydiffit: Python port of the DIFFIT peak-fitting program (T. Brueckel)."""
2
+
3
+ __version__ = "0.9.1"
pydiffit/__main__.py ADDED
@@ -0,0 +1,181 @@
1
+ """Start pydiffit (Qt interface, PySide6).
2
+
3
+ python -m pydiffit [file or folder]
4
+ python -m pydiffit --info version, Python, Qt and display checks
5
+ python -m pydiffit --run p63.json DATA [--scans 1,20,1] [--out DIR]
6
+ run a saved procedure without a window
7
+ python -m pydiffit --install-desktop Linux: application menu entry and icon
8
+ python -m pydiffit --uninstall-desktop Linux: remove them again
9
+ """
10
+
11
+ import os
12
+ import sys
13
+
14
+
15
+ def info():
16
+ """pydiffit --info: version, location, Python and GUI toolkits (no window)."""
17
+ import pathlib
18
+
19
+ from . import __version__
20
+
21
+ print(f"pydiffit {__version__} in {pathlib.Path(__file__).resolve().parent}")
22
+ print(f"Python {sys.version.split()[0]} at {sys.executable}")
23
+ try:
24
+ import PySide6
25
+ from PySide6 import QtWidgets
26
+
27
+ del QtWidgets # imported only to check that the Qt libraries load
28
+
29
+ print(f"PySide6 {PySide6.__version__}: OK")
30
+ except Exception as exc: # ImportError or missing system libraries
31
+ print(f"PySide6 not usable: {exc}")
32
+ print(f"DISPLAY={os.environ.get('DISPLAY', '(not set)')}")
33
+ if sys.platform.startswith("linux"):
34
+ print(f"WAYLAND_DISPLAY={os.environ.get('WAYLAND_DISPLAY', '(not set)')} "
35
+ f"QT_QPA_PLATFORM={os.environ.get('QT_QPA_PLATFORM', '(not set)')}")
36
+ hints = linux_display_problems()
37
+ print("\n".join(hints) if hints else "Display checks: OK")
38
+
39
+
40
+ def linux_display_problems(env=None, find_library=None):
41
+ """Hints for the usual reasons why Qt does not start on Linux, before Qt aborts
42
+ with 'Could not load the Qt platform plugin ...'."""
43
+ import ctypes.util
44
+
45
+ env = os.environ if env is None else env
46
+ find_library = find_library or ctypes.util.find_library
47
+ platform = env.get("QT_QPA_PLATFORM", "")
48
+ if platform.startswith(("offscreen", "minimal", "vnc")):
49
+ return []
50
+ hints = []
51
+ if not env.get("DISPLAY") and not env.get("WAYLAND_DISPLAY"):
52
+ hints.append("No display (DISPLAY and WAYLAND_DISPLAY are not set): start pydiffit in "
53
+ "a desktop session, or log in with 'ssh -X' (or -Y).")
54
+ elif env.get("DISPLAY") and (platform.startswith("xcb") or not env.get("WAYLAND_DISPLAY")):
55
+ conda_lib = os.path.join(sys.prefix, "lib", "libxcb-cursor.so.0")
56
+ if not find_library("xcb-cursor") and not os.path.exists(conda_lib):
57
+ hints.append("libxcb-cursor is missing, which Qt 6.5 or newer needs for X11: "
58
+ "'sudo apt install libxcb-cursor0' (Debian/Ubuntu), 'sudo dnf install "
59
+ "xcb-util-cursor' (RHEL/Fedora), or in the conda environment "
60
+ "'conda install -c conda-forge xcb-util-cursor'.")
61
+ return hints
62
+
63
+
64
+ DESKTOP_ENTRY = """[Desktop Entry]
65
+ Type=Application
66
+ Name=pydiffit
67
+ GenericName=Peak fitting
68
+ Comment=Peak fitting of diffraction scans (DIFFIT)
69
+ Exec=env PYTHONPATH="{root}" "{python}" -m pydiffit %f
70
+ Icon=pydiffit
71
+ Terminal=false
72
+ Categories=Science;Physics;Education;
73
+ StartupWMClass=pydiffit
74
+ """
75
+
76
+
77
+ def desktop_paths(data_home=None):
78
+ data_home = data_home or os.environ.get("XDG_DATA_HOME") or \
79
+ os.path.expanduser("~/.local/share")
80
+ return (os.path.join(data_home, "applications", "pydiffit.desktop"),
81
+ os.path.join(data_home, "icons", "hicolor", "512x512", "apps", "pydiffit.png"))
82
+
83
+
84
+ def install_desktop(data_home=None, platform=None, uninstall=False):
85
+ """Linux: application menu entry (freedesktop .desktop file) and icon for the
86
+ current user. The entry starts pydiffit with this Python and this source
87
+ folder, so it also works from a conda environment or a git checkout."""
88
+ import shutil
89
+ import subprocess
90
+
91
+ if not (platform or sys.platform).startswith("linux"):
92
+ print("--install-desktop is for Linux desktops (GNOME, KDE, Xfce, ...).")
93
+ return 1
94
+ entry, icon = desktop_paths(data_home)
95
+ if uninstall:
96
+ for p in (entry, icon):
97
+ if os.path.exists(p):
98
+ os.remove(p)
99
+ print(f"removed {p}")
100
+ return 0
101
+ pkg = os.path.dirname(os.path.abspath(__file__))
102
+ os.makedirs(os.path.dirname(entry), exist_ok=True)
103
+ os.makedirs(os.path.dirname(icon), exist_ok=True)
104
+ shutil.copyfile(os.path.join(pkg, "icon.png"), icon)
105
+ with open(entry, "w") as f:
106
+ f.write(DESKTOP_ENTRY.format(root=os.path.dirname(pkg), python=sys.executable))
107
+ for cmd in (["update-desktop-database", os.path.dirname(entry)],
108
+ ["gtk-update-icon-cache", "-q", "-t", os.path.dirname(os.path.dirname(
109
+ os.path.dirname(os.path.dirname(icon))))]):
110
+ try: # refresh the menus where the tools exist; harmless otherwise
111
+ subprocess.run(cmd, check=False, capture_output=True, timeout=20)
112
+ except (OSError, subprocess.SubprocessError):
113
+ pass
114
+ print(f"Installed {entry}\nand {icon}.\npydiffit is now in the application menu "
115
+ "(log out and in if it does not show up yet).")
116
+ return 0
117
+
118
+
119
+ def set_macos_app_name(name="pydiffit"):
120
+ """Show `name` instead of "Python" in the macOS menu bar.
121
+
122
+ Must run before the QApplication is created.
123
+ """
124
+ if sys.platform != "darwin":
125
+ return
126
+ try:
127
+ import ctypes
128
+ import ctypes.util
129
+
130
+ objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("objc"))
131
+ ctypes.cdll.LoadLibrary(ctypes.util.find_library("Foundation"))
132
+ objc.objc_getClass.restype = ctypes.c_void_p
133
+ objc.sel_registerName.restype = ctypes.c_void_p
134
+ msg = objc.objc_msgSend
135
+ msg.restype = ctypes.c_void_p
136
+
137
+ def send(obj, sel, *args):
138
+ msg.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + [ctypes.c_void_p] * len(args)
139
+ return msg(obj, objc.sel_registerName(sel), *args)
140
+
141
+ def nsstr(text):
142
+ msg.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_char_p]
143
+ return msg(objc.objc_getClass(b"NSString"),
144
+ objc.sel_registerName(b"stringWithUTF8String:"), text.encode())
145
+
146
+ bundle = send(objc.objc_getClass(b"NSBundle"), b"mainBundle")
147
+ info = send(bundle, b"localizedInfoDictionary") or send(bundle, b"infoDictionary")
148
+ if info:
149
+ send(info, b"setObject:forKey:", nsstr(name), nsstr("CFBundleName"))
150
+ except Exception: # cosmetic only; never block startup
151
+ pass
152
+
153
+
154
+ def main():
155
+ if "--info" in sys.argv or "--version" in sys.argv:
156
+ info()
157
+ return
158
+ if len(sys.argv) > 1 and sys.argv[1] == "--run":
159
+ from .procedure import run_cli
160
+
161
+ sys.exit(run_cli(sys.argv[2:]))
162
+ if "--install-desktop" in sys.argv or "--uninstall-desktop" in sys.argv:
163
+ sys.exit(install_desktop(uninstall="--uninstall-desktop" in sys.argv))
164
+ try:
165
+ import importlib
166
+
167
+ importlib.import_module("PySide6") # only checks availability
168
+ except ImportError:
169
+ sys.exit("pydiffit needs PySide6 (Qt): conda install -c conda-forge pyside6, "
170
+ "or python -m pip install PySide6. Details: pydiffit --info")
171
+ if sys.platform.startswith("linux"):
172
+ for hint in linux_display_problems(): # shown before Qt may abort
173
+ print("pydiffit: " + hint, file=sys.stderr)
174
+ set_macos_app_name()
175
+ from .gui_qt import main as run
176
+
177
+ run()
178
+
179
+
180
+ if __name__ == "__main__":
181
+ main()