pybed 0.1.0__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.
pybed/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ '''
2
+ pybed: run Python scripts as macOS apps with no packaging
3
+ '''
4
+
5
+ from pybed._pybed import Pybed
6
+
7
+ __all__ = ['Pybed']
pybed/_icon.py ADDED
@@ -0,0 +1,45 @@
1
+ '''
2
+ pybed: icon conversion to ICNS using macOS sips/iconutil
3
+ '''
4
+
5
+ from __future__ import annotations
6
+
7
+ import shutil
8
+ import subprocess
9
+ import tempfile
10
+ from pathlib import Path
11
+
12
+ # _ICONSET_SIZES: (filename, pixel size) pairs for a complete .iconset
13
+ _ICONSET_SIZES: tuple[tuple[str, int], ...] = (
14
+ ('icon_16x16.png', 16),
15
+ ('icon_16x16@2x.png', 32),
16
+ ('icon_32x32.png', 32),
17
+ ('icon_32x32@2x.png', 64),
18
+ ('icon_128x128.png', 128),
19
+ ('icon_128x128@2x.png', 256),
20
+ ('icon_256x256.png', 256),
21
+ ('icon_256x256@2x.png', 512),
22
+ ('icon_512x512.png', 512),
23
+ ('icon_512x512@2x.png', 1024),
24
+ )
25
+
26
+
27
+ # to_icns: write an .icns file for the given image (png, jpg, etc) or .icns source
28
+ def to_icns(source: Path, destination: Path) -> None:
29
+ if source.suffix.lower() == '.icns':
30
+ shutil.copyfile(source, destination)
31
+ return
32
+ with tempfile.TemporaryDirectory() as tmp:
33
+ iconset = Path(tmp) / 'icon.iconset'
34
+ iconset.mkdir()
35
+ for filename, size in _ICONSET_SIZES:
36
+ subprocess.run(
37
+ ['sips', '-s', 'format', 'png', '-z', str(size), str(size), str(source), '--out', str(iconset / filename)],
38
+ check=True,
39
+ capture_output=True,
40
+ )
41
+ subprocess.run(
42
+ ['iconutil', '-c', 'icns', str(iconset), '-o', str(destination)],
43
+ check=True,
44
+ capture_output=True,
45
+ )
pybed/_pybed.py ADDED
@@ -0,0 +1,248 @@
1
+ '''
2
+ pybed: Pybed dataclass definition and run entry point
3
+ '''
4
+
5
+ from __future__ import annotations
6
+
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import plistlib
11
+ import re
12
+ import shlex
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ from collections.abc import Callable
17
+ from dataclasses import asdict, dataclass
18
+ from pathlib import Path
19
+ from typing import TypeVar
20
+
21
+ from pybed._icon import to_icns
22
+
23
+ _T = TypeVar('_T')
24
+
25
+
26
+ # _ROOT: directory to store generated stub bundles
27
+ _ROOT = Path.home() / 'Library' / 'Application Support' / 'pybed'
28
+
29
+ # _PLACEHOLDER_ICON: icon used when the user supplies none
30
+ _PLACEHOLDER_ICON = Path(__file__).parent / 'assets' / 'pybed-logo.icns'
31
+
32
+ # _LSREGISTER: LaunchServices registration tool
33
+ _LSREGISTER = '/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister'
34
+
35
+ # _about_target: objc target whose showAbout: opens the standard About panel
36
+ _ABOUT_TARGET = None
37
+
38
+ # _STANDARD_MENUS: default top-level menu titles stripped unless listed in keep_menus
39
+ _STANDARD_MENUS = ('File', 'Edit', 'Format', 'View', 'Window', 'Help')
40
+
41
+
42
+ # Pybed: user-facing definition of the app (name, icon, etc) and how to run it
43
+ @dataclass(frozen=True)
44
+ class Pybed:
45
+ name: str
46
+ icon: str | os.PathLike[str] | None = None
47
+ bundle_id: str | None = None
48
+ show_in_dock: bool = True # False sets LSUIElement (no dock icon or menu bar)
49
+ keep_bundle: bool = True # False deletes the bundle on exit
50
+ keep_menus: tuple[str, ...] = () # standard menu titles to keep, e.g. ('Window', 'Help')
51
+ about_text: str | None = None # shown as credits in the About panel
52
+ version: str | None = None # shown as the version in the About panel
53
+
54
+ # run: call main directly off macOS or inside the stub, otherwise relaunch via the stub
55
+ def run(self, main: Callable[[], _T]) -> _T | None:
56
+ if sys.platform != 'darwin':
57
+ return main()
58
+ if os.environ.get('PYBED_ACTIVE'):
59
+ _apply_runtime_identity()
60
+ return main()
61
+
62
+ _ROOT.mkdir(parents=True, exist_ok=True)
63
+ bundle = self._build()
64
+ result = subprocess.run(['open', '-W', '-n', str(bundle), '--args', *sys.argv[1:]], check=False)
65
+ if not self.keep_bundle:
66
+ subprocess.run([_LSREGISTER, '-u', str(bundle)], capture_output=True, check=False)
67
+ shutil.rmtree(bundle, ignore_errors=True)
68
+ sys.exit(result.returncode)
69
+
70
+ # _icon_path: resolved absolute icon path, falling back to the bundled placeholder
71
+ def _icon_path(self) -> Path:
72
+ if self.icon is None:
73
+ return _PLACEHOLDER_ICON
74
+ path = Path(self.icon).expanduser().resolve()
75
+ if not path.is_file():
76
+ raise FileNotFoundError(f'icon file not found: {str(path)!r}')
77
+ return path
78
+
79
+ # _launch: everything about the current process which launcher bakes in
80
+ def _launch(self) -> dict[str, str]:
81
+ icon = self._icon_path()
82
+ return {
83
+ 'python': sys.executable,
84
+ 'entry': shlex.join(_entry()),
85
+ 'cwd': os.getcwd(),
86
+ 'path': os.environ.get('PATH', '/usr/bin:/bin'),
87
+ 'icon_digest': hashlib.sha256(icon.read_bytes()).hexdigest(),
88
+ }
89
+
90
+ # _fingerprint: stable hash of the definition and launch context, decides whether to rebuild
91
+ def _fingerprint(self, launch: dict[str, str]) -> str:
92
+ fields = {k: str(v) for k, v in asdict(self).items()}
93
+ payload = json.dumps([fields, launch], sort_keys=True).encode()
94
+ return hashlib.sha256(payload).hexdigest()
95
+
96
+ # _launcher_script: shell script used as the bundle executable
97
+ def _launcher_script(self, launch: dict[str, str]) -> str:
98
+ lines = [
99
+ '#!/bin/sh',
100
+ f'cd {shlex.quote(launch["cwd"])} || exit 1',
101
+ f'export PATH={shlex.quote(launch["path"])}',
102
+ 'export PYBED_ACTIVE=1',
103
+ f'export PYBED_NAME={shlex.quote(self.name)}',
104
+ f'export PYBED_KEEP_MENUS={shlex.quote(json.dumps(list(self.keep_menus)))}',
105
+ f'export PYBED_ABOUT_TEXT={shlex.quote(self.about_text or "")}',
106
+ f'export PYBED_VERSION={shlex.quote(self.version or "")}',
107
+ ]
108
+ lines.append('export PYBED_ICON="$(dirname "$0")/../Resources/icon.icns"')
109
+ lines.append(f'exec {shlex.quote(launch["python"])} {launch["entry"]} "$@"')
110
+ return '\n'.join(lines) + '\n'
111
+
112
+ # _build: create (or reuse) the stub bundle under _ROOT and return its path
113
+ def _build(self) -> Path:
114
+ bundle = _ROOT / f'{self.name}.app'
115
+ stamp = bundle / 'Contents' / 'Resources' / 'pybed.json'
116
+ launch = self._launch()
117
+ fingerprint = self._fingerprint(launch)
118
+ if stamp.exists() and json.loads(stamp.read_text()).get('fingerprint') == fingerprint:
119
+ return bundle
120
+
121
+ shutil.rmtree(bundle, ignore_errors=True)
122
+ macos_dir = bundle / 'Contents' / 'MacOS'
123
+ resources_dir = bundle / 'Contents' / 'Resources'
124
+ macos_dir.mkdir(parents=True)
125
+ resources_dir.mkdir(parents=True)
126
+
127
+ info: dict[str, object] = {
128
+ 'CFBundleName': self.name,
129
+ 'CFBundleDisplayName': self.name,
130
+ 'CFBundleIdentifier': self.bundle_id or f'local.pybed.{_slug(self.name)}',
131
+ 'CFBundleExecutable': 'launcher',
132
+ 'CFBundleIconFile': 'icon',
133
+ 'CFBundlePackageType': 'APPL',
134
+ 'CFBundleVersion': '1.0',
135
+ 'CFBundleShortVersionString': '1.0',
136
+ 'NSHighResolutionCapable': True,
137
+ 'LSUIElement': not self.show_in_dock,
138
+ }
139
+ to_icns(self._icon_path(), resources_dir / 'icon.icns')
140
+ (bundle / 'Contents' / 'Info.plist').write_bytes(plistlib.dumps(info))
141
+
142
+ launcher = macos_dir / 'launcher'
143
+ launcher.write_text(self._launcher_script(launch))
144
+ launcher.chmod(0o755)
145
+ stamp.write_text(json.dumps({'fingerprint': fingerprint}))
146
+
147
+ # apply ad-hoc signature (Apple Silicon refuses unsigned code)
148
+ if shutil.which('codesign'):
149
+ subprocess.run(['codesign', '--force', '--deep', '--sign', '-', str(bundle)], check=True, capture_output=True)
150
+ return bundle
151
+
152
+
153
+ # _slug: lowercase identifier-safe version of a name
154
+ def _slug(name: str) -> str:
155
+ return re.sub(r'[^a-z0-9]+', '-', name.lower()).strip('-') or 'app'
156
+
157
+
158
+ # _entry: how to re-run the current program (module or script path)
159
+ def _entry() -> tuple[str, ...]:
160
+ spec = getattr(sys.modules['__main__'], '__spec__', None)
161
+ if spec is not None and spec.name:
162
+ module = spec.name
163
+ module = module.removesuffix('.__main__')
164
+ return ('-m', module)
165
+ return (str(Path(sys.argv[0]).resolve()),)
166
+
167
+
168
+ # _apply_runtime_identity: best-effort process name fix inside the stub
169
+ def _apply_runtime_identity() -> None:
170
+ try:
171
+ from Foundation import NSBundle, NSProcessInfo, NSTimer
172
+ except ImportError:
173
+ return
174
+ name = os.environ.get('PYBED_NAME')
175
+ if name:
176
+ info = NSBundle.mainBundle().infoDictionary()
177
+ info['CFBundleName'] = name
178
+ # menu bar items (About, Hide, Quit) read the process name
179
+ NSProcessInfo.processInfo().setProcessName_(name)
180
+ # toolkits rebuild menus on startup, focus and window changes, so re-tidy for the app's lifetime
181
+ def _tick(_timer: object) -> None:
182
+ _tidy_menu_bar()
183
+ _set_app_icon()
184
+ NSTimer.scheduledTimerWithTimeInterval_repeats_block_(0.5, True, _tick)
185
+
186
+
187
+ # _set_app_icon: apply PYBED_ICON as the application icon (about panel and dock)
188
+ def _set_app_icon() -> None:
189
+ icon = os.environ.get('PYBED_ICON')
190
+ if not icon:
191
+ return
192
+ from AppKit import NSApplication, NSImage
193
+ NSApplication.sharedApplication().setApplicationIconImage_(NSImage.alloc().initWithContentsOfFile_(icon))
194
+
195
+
196
+ # _about_target: lazily build the shared objc target (class defined once)
197
+ def _about_target() -> object:
198
+ global _ABOUT_TARGET
199
+ if _ABOUT_TARGET is None:
200
+ from AppKit import NSApplication, NSAttributedString, NSImage, NSObject
201
+ class _AboutTarget(NSObject):
202
+ def showAbout_(self, _sender: object) -> None:
203
+ options: dict[str, object] ={}
204
+ icon = os.environ.get('PYBED_ICON')
205
+ if icon:
206
+ options['ApplicationIcon'] = NSImage.alloc().initWithContentsOfFile_(icon)
207
+ if text := os.environ.get('PYBED_ABOUT_TEXT'):
208
+ options['Credits'] = NSAttributedString.alloc().initWithString_(text)
209
+ if version := os.environ.get('PYBED_VERSION'):
210
+ options['ApplicationVersion'] = version
211
+ NSApplication.sharedApplication().orderFrontStandardAboutPanelWithOptions_(options)
212
+ _ABOUT_TARGET = _AboutTarget.alloc().init()
213
+ return _ABOUT_TARGET
214
+
215
+
216
+ # _removable_menus: indices of top-level menus to drop; index 0 (app menu) is never removed
217
+ def _removable_menus(titles: list[str], keep: set[str]) -> list[int]:
218
+ return [i for i, title in enumerate(titles) if i > 0 and title in _STANDARD_MENUS and title not in keep]
219
+
220
+
221
+ # _tidy_menu_bar: drop standard top-level menus (unless kept), rebuild About <name>, and ignore user-added menus
222
+ def _tidy_menu_bar() -> None:
223
+ try:
224
+ from AppKit import NSApplication, NSMenuItem
225
+ except ImportError:
226
+ return
227
+ app = NSApplication.sharedApplication()
228
+ main_menu = app.mainMenu()
229
+ if main_menu is None or main_menu.numberOfItems() == 0:
230
+ return
231
+ titles = [str(main_menu.itemAtIndex_(i).title()) for i in range(main_menu.numberOfItems())]
232
+ keep = set(json.loads(os.environ.get('PYBED_KEEP_MENUS', '[]')))
233
+ for i in reversed(_removable_menus(titles, keep)):
234
+ main_menu.removeItemAtIndex_(i)
235
+ app_menu = main_menu.itemAtIndex_(0).submenu()
236
+ # qt re-adds its own About items; drop them so only ours remains
237
+ for k in reversed(range(app_menu.numberOfItems())):
238
+ if str(app_menu.itemAtIndex_(k).title()).startswith('About'):
239
+ app_menu.removeItemAtIndex_(k)
240
+ name = os.environ.get('PYBED_NAME', 'App')
241
+ about = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(f'About {name}', 'showAbout:', '')
242
+ about.setTarget_(_about_target())
243
+ about.setEnabled_(True)
244
+ about.setHidden_(False)
245
+ sep = NSMenuItem.separatorItem()
246
+ sep.setHidden_(False)
247
+ app_menu.insertItem_atIndex_(about, 0)
248
+ app_menu.insertItem_atIndex_(sep, 1)
Binary file
pybed/py.typed ADDED
File without changes
@@ -0,0 +1,132 @@
1
+ Metadata-Version: 2.4
2
+ Name: pybed
3
+ Version: 0.1.0
4
+ Summary: Run Python scripts as macOS apps with no packaging.
5
+ Keywords: macos,pyobjc,app,packaging
6
+ Author: Sam Holland
7
+ Author-email: Sam Holland <hol_sam@icloud.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Operating System :: MacOS
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Dist: pyobjc-framework-cocoa>=11.1 ; sys_platform == 'darwin'
14
+ Requires-Python: >=3.10
15
+ Project-URL: Homepage, https://github.com/holsam/pybed
16
+ Project-URL: Repository, https://github.com/holsam/pybed
17
+ Project-URL: Issues, https://github.com/holsam/pybed/issues
18
+ Description-Content-Type: text/markdown
19
+
20
+ # pybed
21
+
22
+ Run Python scripts as macOS apps with no packaging.
23
+
24
+ pybed wraps a Python GUI script in a generated `.app` bundle, so it shows up in Finder, the Dock and Cmd-Tab using its own name and icon, without needing an Xcode project, a `setup.py` for py2app, or a PyInstaller spec.
25
+
26
+ ![hello-pybed-example running as a macOS app](https://raw.githubusercontent.com/holsam/pybed/main/assets/hello-pybed-example.png)
27
+
28
+
29
+ ## Installation
30
+
31
+ ### Requirements
32
+ - Python >= 3.10
33
+
34
+ ### Install
35
+ ```sh
36
+ pip install pybed
37
+ # or
38
+ uv add pybed
39
+ ```
40
+
41
+ ### Quick start
42
+
43
+ ```python
44
+ # hello-pybed.py
45
+ import tkinter as tk
46
+
47
+ from pybed import Pybed
48
+
49
+
50
+ def main() -> None:
51
+ root = tk.Tk()
52
+ root.title('Hello')
53
+ tk.Label(root, text='Hello from a Mac app').pack(padx=40, pady=40)
54
+ root.mainloop()
55
+
56
+
57
+ if __name__ == '__main__':
58
+ Pybed('Hello').run(main)
59
+ ```
60
+
61
+ Run it:
62
+
63
+ ```sh
64
+ python hello.py
65
+ ```
66
+
67
+ The first run builds and launches a stub `.app`, then runs the script inside that app. Later runs can reuse the same stubbed `.app` bundle unless something it depends on has changed (in which case it is regenerated).
68
+
69
+ ![hello-pybed-example running as a macOS app](https://raw.githubusercontent.com/holsam/pybed/main/assets/hello-pybed-example.png)
70
+
71
+ To configure the `.app` options separately from the call:
72
+
73
+ ```python
74
+ pm = Pybed('My App', icon='path/to/icon.png')
75
+ pm.run(main)
76
+ ```
77
+
78
+ ### Supported toolkits
79
+ pybed has been tested with `tkinter`, `PySide6` and `PyQt` GUI toolkits, but is expected to work with others.
80
+
81
+ ## How it works
82
+
83
+ `Pybed(...).run(main)` does one of two things:
84
+
85
+ - **On macOS, outside the stub:** builds (or reuses) a `.app` bundle whose executable re-runs your script with the same interpreter, working directory and `PATH`, then launches it with `open -W` and waits for it to exit.
86
+ - **On macOS, inside the stub, or on any other platform:** calls `main()` directly.
87
+
88
+ Scripts written this way run on every platform. Only the wrapper, icon and menu behaviour are macOS-specific.
89
+
90
+ ### Options
91
+
92
+ `Pybed` is a frozen dataclass which supports the following keyword arguments:
93
+
94
+ Option | Default | Purpose
95
+ -- | -- | --
96
+ `name` | required | App name shown in the menu bar, Dock and About panel. |
97
+ `icon` | bundled pybed logo | Path to an image (`.png` or `.icns`) used as the app icon *(relative paths resolve against the working directory when `run()` is called therefore absolute paths are recommended)*.
98
+ `bundle_id` | `local.pybed.<slug of name>` | `CFBundleIdentifier`.
99
+ `show_in_dock` | `True` | `False` hides the Dock icon and menu bar.
100
+ `keep_bundle` | `True` | `False` deletes the generated bundle when the app exits.
101
+ `keep_menus` | `()` | Standard menus to keep, for example `('Window', 'Help')`. pybed removes 'File', 'Edit', 'Format', 'View', 'Window' and 'Help' unless listed here.
102
+ `about_text` | `None` | Credits text shown in the About panel.
103
+ `version` | `None` | Version shown in the About panel.
104
+
105
+ Example:
106
+
107
+ ```python
108
+ Pybed(
109
+ 'My Tool',
110
+ icon='assets/icon.png',
111
+ about_text='Renames photos by date',
112
+ version='1.2.0',
113
+ keep_menus=('Window',),
114
+ ).run(main)
115
+ ```
116
+
117
+ ## Comparison with other tools
118
+
119
+ &nbsp; | pybed | py2app | PyInstaller | Briefcase
120
+ -- | -- | -- | -- | --
121
+ **Build config needed** | None | `setup.py` or `setup.cfg` | Spec file or CLI flags | `pyproject.toml` section
122
+ **Output** | `.app` generated at first run | Standalone `.app` | Executable or `.app` | `.app` or installer
123
+ **Bundles Python** | No, uses the interpreter that runs the script | Yes | Yes | Yes
124
+ **Platforms** | macOS (app wrapper), any OS (script runs) | macOS only | macOS, Windows, Linux | macOS, Windows, Linux, iOS, Android
125
+ **Best for** | Giving a GUI script its own app identity (name, icon, menus, About panel) with no build step | Distributing a Mac app | Distributing a single executable across platforms | Distributing a GUI app with its own packaging
126
+ **Setup effort** | Add one `Pybed(...).run(main)` call | Write and maintain a build script | Write and tune a spec or long CLI command | Configure a project and packaging metadata
127
+
128
+ pybed is a simple alternative for styling a GUI without needing to run any packaging steps like other tools. The generated app runs with the Python and packages on the machine that built it, so the generated `.app` is not distributable (e.g. to somebody without a Python setup), but will be generated for users on their own machines.
129
+
130
+ ## Licence
131
+
132
+ pybed is free, open source software made available under the MIT license. See [`./LICENSE`](LICENSE) for more information.
@@ -0,0 +1,9 @@
1
+ pybed/__init__.py,sha256=ODrVUmQbmglfp-YX5IDDEwbf7uB73iE4nbRdP9pc5z0,119
2
+ pybed/_icon.py,sha256=uIEMghLRO8UFLF2pvYa4xcFlk7QVcDl6eaogx1u4aKY,1413
3
+ pybed/_pybed.py,sha256=ZnSicjok4XYhs7m60SskYoVPXKgLN1C93l4Yxx2FMsY,10399
4
+ pybed/assets/pybed-logo.icns,sha256=ZJ_vrO6yfJ-Fufv4QJLlmPBpW1Xw-KR6Xh9jbIDjEP0,1509273
5
+ pybed/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ pybed-0.1.0.dist-info/licenses/LICENSE,sha256=90k-wemtrEaZ7k9EIUFDlX4XVzRltfLUlhyFkkJpje8,1078
7
+ pybed-0.1.0.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
8
+ pybed-0.1.0.dist-info/METADATA,sha256=5d0On7FN6jEWWMSIr-WV_Z85xND_o_D4qGV7Q21d0Qk,5190
9
+ pybed-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.13
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Samuel Holland
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.