pybed 0.1.0__tar.gz
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-0.1.0/LICENSE +9 -0
- pybed-0.1.0/PKG-INFO +132 -0
- pybed-0.1.0/README.md +113 -0
- pybed-0.1.0/pyproject.toml +36 -0
- pybed-0.1.0/pyproject.toml.orig +34 -0
- pybed-0.1.0/src/pybed/__init__.py +7 -0
- pybed-0.1.0/src/pybed/_icon.py +45 -0
- pybed-0.1.0/src/pybed/_pybed.py +248 -0
- pybed-0.1.0/src/pybed/assets/pybed-logo.icns +0 -0
- pybed-0.1.0/src/pybed/py.typed +0 -0
pybed-0.1.0/LICENSE
ADDED
|
@@ -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.
|
pybed-0.1.0/PKG-INFO
ADDED
|
@@ -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
|
+

|
|
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
|
+

|
|
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
|
+
| 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.
|
pybed-0.1.0/README.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# pybed
|
|
2
|
+
|
|
3
|
+
Run Python scripts as macOS apps with no packaging.
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
### Requirements
|
|
13
|
+
- Python >= 3.10
|
|
14
|
+
|
|
15
|
+
### Install
|
|
16
|
+
```sh
|
|
17
|
+
pip install pybed
|
|
18
|
+
# or
|
|
19
|
+
uv add pybed
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
### Quick start
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
# hello-pybed.py
|
|
26
|
+
import tkinter as tk
|
|
27
|
+
|
|
28
|
+
from pybed import Pybed
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def main() -> None:
|
|
32
|
+
root = tk.Tk()
|
|
33
|
+
root.title('Hello')
|
|
34
|
+
tk.Label(root, text='Hello from a Mac app').pack(padx=40, pady=40)
|
|
35
|
+
root.mainloop()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
if __name__ == '__main__':
|
|
39
|
+
Pybed('Hello').run(main)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Run it:
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
python hello.py
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
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).
|
|
49
|
+
|
|
50
|
+

|
|
51
|
+
|
|
52
|
+
To configure the `.app` options separately from the call:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
pm = Pybed('My App', icon='path/to/icon.png')
|
|
56
|
+
pm.run(main)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Supported toolkits
|
|
60
|
+
pybed has been tested with `tkinter`, `PySide6` and `PyQt` GUI toolkits, but is expected to work with others.
|
|
61
|
+
|
|
62
|
+
## How it works
|
|
63
|
+
|
|
64
|
+
`Pybed(...).run(main)` does one of two things:
|
|
65
|
+
|
|
66
|
+
- **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.
|
|
67
|
+
- **On macOS, inside the stub, or on any other platform:** calls `main()` directly.
|
|
68
|
+
|
|
69
|
+
Scripts written this way run on every platform. Only the wrapper, icon and menu behaviour are macOS-specific.
|
|
70
|
+
|
|
71
|
+
### Options
|
|
72
|
+
|
|
73
|
+
`Pybed` is a frozen dataclass which supports the following keyword arguments:
|
|
74
|
+
|
|
75
|
+
Option | Default | Purpose
|
|
76
|
+
-- | -- | --
|
|
77
|
+
`name` | required | App name shown in the menu bar, Dock and About panel. |
|
|
78
|
+
`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)*.
|
|
79
|
+
`bundle_id` | `local.pybed.<slug of name>` | `CFBundleIdentifier`.
|
|
80
|
+
`show_in_dock` | `True` | `False` hides the Dock icon and menu bar.
|
|
81
|
+
`keep_bundle` | `True` | `False` deletes the generated bundle when the app exits.
|
|
82
|
+
`keep_menus` | `()` | Standard menus to keep, for example `('Window', 'Help')`. pybed removes 'File', 'Edit', 'Format', 'View', 'Window' and 'Help' unless listed here.
|
|
83
|
+
`about_text` | `None` | Credits text shown in the About panel.
|
|
84
|
+
`version` | `None` | Version shown in the About panel.
|
|
85
|
+
|
|
86
|
+
Example:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
Pybed(
|
|
90
|
+
'My Tool',
|
|
91
|
+
icon='assets/icon.png',
|
|
92
|
+
about_text='Renames photos by date',
|
|
93
|
+
version='1.2.0',
|
|
94
|
+
keep_menus=('Window',),
|
|
95
|
+
).run(main)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Comparison with other tools
|
|
99
|
+
|
|
100
|
+
| pybed | py2app | PyInstaller | Briefcase
|
|
101
|
+
-- | -- | -- | -- | --
|
|
102
|
+
**Build config needed** | None | `setup.py` or `setup.cfg` | Spec file or CLI flags | `pyproject.toml` section
|
|
103
|
+
**Output** | `.app` generated at first run | Standalone `.app` | Executable or `.app` | `.app` or installer
|
|
104
|
+
**Bundles Python** | No, uses the interpreter that runs the script | Yes | Yes | Yes
|
|
105
|
+
**Platforms** | macOS (app wrapper), any OS (script runs) | macOS only | macOS, Windows, Linux | macOS, Windows, Linux, iOS, Android
|
|
106
|
+
**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
|
|
107
|
+
**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
|
|
108
|
+
|
|
109
|
+
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.
|
|
110
|
+
|
|
111
|
+
## Licence
|
|
112
|
+
|
|
113
|
+
pybed is free, open source software made available under the MIT license. See [`./LICENSE`](LICENSE) for more information.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "pybed"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Run Python scripts as macOS apps with no packaging."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
keywords = [
|
|
10
|
+
"macos",
|
|
11
|
+
"pyobjc",
|
|
12
|
+
"app",
|
|
13
|
+
"packaging",
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Operating System :: MacOS",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
]
|
|
20
|
+
dependencies = ["pyobjc-framework-cocoa>=11.1 ; sys_platform == 'darwin'"]
|
|
21
|
+
|
|
22
|
+
[[project.authors]]
|
|
23
|
+
name = "Sam Holland"
|
|
24
|
+
email = "hol_sam@icloud.com"
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/holsam/pybed"
|
|
28
|
+
Repository = "https://github.com/holsam/pybed"
|
|
29
|
+
Issues = "https://github.com/holsam/pybed/issues"
|
|
30
|
+
|
|
31
|
+
[build-system]
|
|
32
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
33
|
+
build-backend = "uv_build"
|
|
34
|
+
|
|
35
|
+
[dependency-groups]
|
|
36
|
+
dev = ["pytest>=8.4.2"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "pybed"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Run Python scripts as macOS apps with no packaging."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "Sam Holland", email = "hol_sam@icloud.com" }
|
|
8
|
+
]
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
keywords = ["macos", "pyobjc", "app", "packaging"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 4 - Beta",
|
|
15
|
+
"Operating System :: MacOS",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
]
|
|
18
|
+
dependencies = [
|
|
19
|
+
"pyobjc-framework-cocoa>=11.1 ; sys_platform == 'darwin'",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://github.com/holsam/pybed"
|
|
24
|
+
Repository = "https://github.com/holsam/pybed"
|
|
25
|
+
Issues = "https://github.com/holsam/pybed/issues"
|
|
26
|
+
|
|
27
|
+
[build-system]
|
|
28
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
29
|
+
build-backend = "uv_build"
|
|
30
|
+
|
|
31
|
+
[dependency-groups]
|
|
32
|
+
dev = [
|
|
33
|
+
"pytest>=8.4.2",
|
|
34
|
+
]
|
|
@@ -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
|
+
)
|
|
@@ -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
|
|
File without changes
|