softforge 1.0.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.
- softforge/__init__.py +72 -0
- softforge/__main__.py +6 -0
- softforge/build.py +243 -0
- softforge/cli.py +282 -0
- softforge/config.py +218 -0
- softforge/icon.py +189 -0
- softforge/installer.py +187 -0
- softforge/py.typed +0 -0
- softforge/resource.py +58 -0
- softforge/runtime.py +48 -0
- softforge/scaffold.py +90 -0
- softforge/setupapp.py +483 -0
- softforge/wizard.py +126 -0
- softforge-1.0.0.dist-info/METADATA +302 -0
- softforge-1.0.0.dist-info/RECORD +19 -0
- softforge-1.0.0.dist-info/WHEEL +5 -0
- softforge-1.0.0.dist-info/entry_points.txt +2 -0
- softforge-1.0.0.dist-info/licenses/LICENSE +21 -0
- softforge-1.0.0.dist-info/top_level.txt +1 -0
softforge/config.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""项目模型:从 softforge.toml / pyproject.toml 读配置,缺的项给出合理默认值。"""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import tomllib
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
_GUI_MARKERS = ("tkinter", "customtkinter", "PyQt5", "PyQt6", "PySide2", "PySide6",
|
|
12
|
+
"wx.", "import gi", "kivy", "pygame")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _as_bool(value, default: bool) -> bool:
|
|
16
|
+
if value is None:
|
|
17
|
+
return default
|
|
18
|
+
if isinstance(value, bool):
|
|
19
|
+
return value
|
|
20
|
+
return str(value).strip().lower() in ("1", "true", "yes", "on")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _load_toml(path: Path) -> dict:
|
|
24
|
+
"""读 toml,顺手吃掉记事本加的 UTF-8 BOM(标准库 tomllib 不认 BOM)"""
|
|
25
|
+
raw = path.read_bytes()
|
|
26
|
+
if raw.startswith(b"\xef\xbb\xbf"):
|
|
27
|
+
raw = raw[3:]
|
|
28
|
+
return tomllib.loads(raw.decode("utf-8"))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _read_config(base: Path) -> dict:
|
|
32
|
+
"""优先 softforge.toml,其次 pyproject.toml 的 [tool.softforge]"""
|
|
33
|
+
for name, picker in (
|
|
34
|
+
("softforge.toml", lambda d: d.get("app", d)),
|
|
35
|
+
("pyproject.toml", lambda d: d.get("tool", {}).get("softforge", {})),
|
|
36
|
+
):
|
|
37
|
+
path = base / name
|
|
38
|
+
if not path.is_file():
|
|
39
|
+
continue
|
|
40
|
+
try:
|
|
41
|
+
data = _load_toml(path)
|
|
42
|
+
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as exc:
|
|
43
|
+
raise ValueError(f"读不懂 {path.name}:{exc}") from exc
|
|
44
|
+
picked = picker(data)
|
|
45
|
+
if picked:
|
|
46
|
+
picked = dict(picked)
|
|
47
|
+
picked["__config__"] = str(path)
|
|
48
|
+
return picked
|
|
49
|
+
return {}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _guess_entry(base: Path) -> Path:
|
|
53
|
+
"""没写 entry 时:优先 app.py / main.py / __main__.py,其次目录里唯一的 .py"""
|
|
54
|
+
for name in ("app.py", "main.py", "__main__.py"):
|
|
55
|
+
if (base / name).is_file():
|
|
56
|
+
return base / name
|
|
57
|
+
scripts = [p for p in base.glob("*.py")
|
|
58
|
+
if p.name not in ("setup.py", "conftest.py")
|
|
59
|
+
and not p.name.startswith("_")]
|
|
60
|
+
if len(scripts) == 1:
|
|
61
|
+
return scripts[0]
|
|
62
|
+
if scripts:
|
|
63
|
+
return sorted(scripts, key=lambda p: p.stat().st_size, reverse=True)[0]
|
|
64
|
+
raise ValueError(f"{base} 里找不到可打包的 .py 入口,请用 entry 指定")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _looks_gui(entry: Path) -> bool:
|
|
68
|
+
try:
|
|
69
|
+
text = entry.read_text(encoding="utf-8", errors="replace")
|
|
70
|
+
except OSError:
|
|
71
|
+
return False
|
|
72
|
+
head = "\n".join(text.splitlines()[:120])
|
|
73
|
+
return any(marker in head for marker in _GUI_MARKERS)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class Project:
|
|
78
|
+
"""一个待打包项目的全部参数"""
|
|
79
|
+
name: str
|
|
80
|
+
entry: Path
|
|
81
|
+
root: Path
|
|
82
|
+
version: str = "1.0.0"
|
|
83
|
+
company: str = ""
|
|
84
|
+
description: str = ""
|
|
85
|
+
icon: Path | None = None
|
|
86
|
+
onefile: bool = True
|
|
87
|
+
console: bool | None = None # None = 按入口代码自动判断
|
|
88
|
+
dist_dir: Path = Path("dist")
|
|
89
|
+
build_dir: Path = Path("build")
|
|
90
|
+
data: dict[str, str] = field(default_factory=dict)
|
|
91
|
+
hidden_imports: list[str] = field(default_factory=list)
|
|
92
|
+
collect_all: list[str] = field(default_factory=list)
|
|
93
|
+
extra_args: list[str] = field(default_factory=list)
|
|
94
|
+
config_file: Path | None = None
|
|
95
|
+
wizard: dict[str, object] = field(default_factory=dict) # 安装向导里能改的文字/默认值
|
|
96
|
+
|
|
97
|
+
# ---------------------------------------------------------------- 读
|
|
98
|
+
@classmethod
|
|
99
|
+
def load(cls, path: str | os.PathLike = ".", *,
|
|
100
|
+
name: str | None = None, entry: str | None = None,
|
|
101
|
+
version: str | None = None, icon: str | None = None,
|
|
102
|
+
onefile: bool | None = None, console: bool | None = None) -> "Project":
|
|
103
|
+
base = Path(path).expanduser().resolve()
|
|
104
|
+
if base.is_file():
|
|
105
|
+
cfg = base
|
|
106
|
+
base = cfg.parent
|
|
107
|
+
if cfg.name == "softforge.toml":
|
|
108
|
+
data = dict(_load_toml(cfg).get("app", {}))
|
|
109
|
+
data["__config__"] = str(cfg)
|
|
110
|
+
else:
|
|
111
|
+
data = dict(_load_toml(cfg).get("tool", {}).get("softforge", {}))
|
|
112
|
+
data["__config__"] = str(cfg)
|
|
113
|
+
else:
|
|
114
|
+
data = _read_config(base)
|
|
115
|
+
|
|
116
|
+
entry_path = Path(entry).resolve() if entry else (
|
|
117
|
+
(base / str(data["entry"])).resolve() if data.get("entry") else _guess_entry(base))
|
|
118
|
+
if not entry_path.is_file():
|
|
119
|
+
raise ValueError(f"入口文件不存在:{entry_path}")
|
|
120
|
+
|
|
121
|
+
icon_path = None
|
|
122
|
+
icon_value = icon or data.get("icon")
|
|
123
|
+
if icon_value:
|
|
124
|
+
icon_path = (base / str(icon_value)).resolve()
|
|
125
|
+
if not icon_path.is_file():
|
|
126
|
+
raise ValueError(f"图标不存在:{icon_path}")
|
|
127
|
+
|
|
128
|
+
company = str(data.get("company") or "")
|
|
129
|
+
app_name = name or str(data.get("name") or entry_path.stem)
|
|
130
|
+
app_version = version or str(data.get("version") or "1.0.0")
|
|
131
|
+
description = str(data.get("description") or "")
|
|
132
|
+
|
|
133
|
+
dist = Path(str(data.get("dist_dir") or "dist"))
|
|
134
|
+
build = Path(str(data.get("build_dir") or "build"))
|
|
135
|
+
dist = dist if dist.is_absolute() else (base / dist)
|
|
136
|
+
build = build if build.is_absolute() else (base / build)
|
|
137
|
+
|
|
138
|
+
raw_data = data.get("data") or {}
|
|
139
|
+
if not isinstance(raw_data, dict):
|
|
140
|
+
raise ValueError("data 必须是 表(源路径 = 打包后的目录)")
|
|
141
|
+
|
|
142
|
+
raw_wizard = data.get("wizard") or {}
|
|
143
|
+
if not isinstance(raw_wizard, dict):
|
|
144
|
+
raise ValueError("wizard 必须是表(见文档「安装向导可改内容」)")
|
|
145
|
+
wizard = {str(k): v for k, v in raw_wizard.items()}
|
|
146
|
+
license_value = wizard.pop("license_file", None)
|
|
147
|
+
if license_value:
|
|
148
|
+
lic = Path(str(license_value))
|
|
149
|
+
if not lic.is_absolute():
|
|
150
|
+
lic = base / lic
|
|
151
|
+
if not lic.is_file():
|
|
152
|
+
raise ValueError(f"许可协议文件不存在:{lic}")
|
|
153
|
+
wizard["license"] = lic.read_text(encoding="utf-8", errors="replace")
|
|
154
|
+
|
|
155
|
+
return cls(
|
|
156
|
+
name=app_name,
|
|
157
|
+
entry=entry_path,
|
|
158
|
+
root=base,
|
|
159
|
+
version=app_version,
|
|
160
|
+
company=company,
|
|
161
|
+
description=description,
|
|
162
|
+
icon=icon_path,
|
|
163
|
+
onefile=_as_bool(data.get("onefile"), True) if onefile is None else bool(onefile),
|
|
164
|
+
console=(console if console is not None else
|
|
165
|
+
(None if data.get("console") is None else _as_bool(data.get("console"), True))),
|
|
166
|
+
dist_dir=dist,
|
|
167
|
+
build_dir=build,
|
|
168
|
+
data={str(k): str(v) for k, v in raw_data.items()},
|
|
169
|
+
hidden_imports=[str(x) for x in (data.get("hidden_imports") or [])],
|
|
170
|
+
collect_all=[str(x) for x in (data.get("collect_all") or [])],
|
|
171
|
+
extra_args=[str(x) for x in (data.get("extra_args") or [])],
|
|
172
|
+
config_file=Path(data["__config__"]) if data.get("__config__") else None,
|
|
173
|
+
wizard=wizard,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
# ---------------------------------------------------------------- 派生
|
|
177
|
+
@property
|
|
178
|
+
def exe_name(self) -> str:
|
|
179
|
+
return self.name if self.name.lower().endswith(".exe") else f"{self.name}.exe"
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def exe_path(self) -> Path:
|
|
183
|
+
if self.onefile:
|
|
184
|
+
return self.dist_dir / self.exe_name
|
|
185
|
+
return self.dist_dir / self.name / self.exe_name
|
|
186
|
+
|
|
187
|
+
@property
|
|
188
|
+
def is_gui(self) -> bool:
|
|
189
|
+
if self.console is not None:
|
|
190
|
+
return not self.console
|
|
191
|
+
return _looks_gui(self.entry)
|
|
192
|
+
|
|
193
|
+
def normalized_version(self) -> tuple[int, int, int, int]:
|
|
194
|
+
nums = re.findall(r"\d+", self.version)[:4]
|
|
195
|
+
nums += ["0"] * (4 - len(nums))
|
|
196
|
+
return tuple(int(n) for n in nums) # type: ignore[return-value]
|
|
197
|
+
|
|
198
|
+
def describe(self) -> str:
|
|
199
|
+
lines = [
|
|
200
|
+
f"名称 {self.name}",
|
|
201
|
+
f"版本 {self.version}",
|
|
202
|
+
f"入口 {self.entry}",
|
|
203
|
+
f"输出 {self.exe_path}",
|
|
204
|
+
f"形态 {'单文件' if self.onefile else '目录(onedir)'} · "
|
|
205
|
+
f"{'无控制台窗口(GUI)' if self.is_gui else '带控制台窗口'}",
|
|
206
|
+
f"图标 {self.icon or '自动生成'}",
|
|
207
|
+
]
|
|
208
|
+
if self.data:
|
|
209
|
+
lines.append("附带数据 " + "、".join(f"{k} → {v}" for k, v in self.data.items()))
|
|
210
|
+
if self.hidden_imports:
|
|
211
|
+
lines.append("隐式依赖 " + "、".join(self.hidden_imports))
|
|
212
|
+
if self.collect_all:
|
|
213
|
+
lines.append("整包收集 " + "、".join(self.collect_all))
|
|
214
|
+
if self.wizard:
|
|
215
|
+
keys = "、".join(sorted(self.wizard))
|
|
216
|
+
lines.append(f"安装向导 {len(self.wizard)} 项自定义:{keys}")
|
|
217
|
+
lines.append(f"配置来源 {self.config_file or '命令行 / 默认推断'}")
|
|
218
|
+
return "\n".join(lines)
|
softforge/icon.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""图标:纯标准库画一枚软件图标,输出 PNG + 多尺寸 ICO。
|
|
3
|
+
|
|
4
|
+
不依赖 Pillow —— 图形全部用「有符号距离场 + 覆盖率」现场算出来,
|
|
5
|
+
所以同一份代码在任何装了 Python 的机器上都能生成图标,
|
|
6
|
+
小尺寸也不会因为缩图而糊成一团。
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
import os
|
|
12
|
+
import struct
|
|
13
|
+
import zlib
|
|
14
|
+
|
|
15
|
+
ICO_SIZES = (256, 64, 48, 32, 16)
|
|
16
|
+
|
|
17
|
+
_BG_TOP = (59, 123, 255)
|
|
18
|
+
_BG_BOTTOM = (27, 62, 158)
|
|
19
|
+
_WHITE = (255, 255, 255)
|
|
20
|
+
_BAR = (30, 64, 175)
|
|
21
|
+
_DOT = (59, 123, 255)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
# ---------------------------------------------------------------- 几何
|
|
25
|
+
def _round_rect_sdf(px: float, py: float, cx: float, cy: float,
|
|
26
|
+
hw: float, hh: float, r: float) -> float:
|
|
27
|
+
"""圆角矩形的有符号距离:<0 在内部,>0 在外部"""
|
|
28
|
+
dx = abs(px - cx) - hw + r
|
|
29
|
+
dy = abs(py - cy) - hh + r
|
|
30
|
+
ax = dx if dx > 0 else 0.0
|
|
31
|
+
ay = dy if dy > 0 else 0.0
|
|
32
|
+
return math.hypot(ax, ay) + min(max(dx, dy), 0.0) - r
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _circle_sdf(px: float, py: float, cx: float, cy: float, r: float) -> float:
|
|
36
|
+
return math.hypot(px - cx, py - cy) - r
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _cover(sdf: float, scale: float = 1.0) -> float:
|
|
40
|
+
"""把距离换成 0~1 的覆盖率;scale=像素边长,边缘一像素内做抗锯齿"""
|
|
41
|
+
v = 0.5 - sdf * scale
|
|
42
|
+
if v <= 0.0:
|
|
43
|
+
return 0.0
|
|
44
|
+
if v >= 1.0:
|
|
45
|
+
return 1.0
|
|
46
|
+
return v
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _over(dst, color, a: float):
|
|
50
|
+
"""颜色 color 以透明度 a 盖在 dst(RGBA, 0~255) 上"""
|
|
51
|
+
if a <= 0.0:
|
|
52
|
+
return dst
|
|
53
|
+
r, g, b, da = dst
|
|
54
|
+
da_f = da / 255.0
|
|
55
|
+
na = a + da_f * (1.0 - a)
|
|
56
|
+
if na <= 0.0:
|
|
57
|
+
return (0, 0, 0, 0)
|
|
58
|
+
k = da_f * (1.0 - a)
|
|
59
|
+
return (
|
|
60
|
+
int(round((color[0] * a + r * k) / na)),
|
|
61
|
+
int(round((color[1] * a + g * k) / na)),
|
|
62
|
+
int(round((color[2] * a + b * k) / na)),
|
|
63
|
+
int(round(na * 255)),
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _render(size: int) -> list[tuple[int, int, int, int]]:
|
|
68
|
+
"""现场画一枚图标,返回按行展开的 RGBA 像素"""
|
|
69
|
+
pixels: list[tuple[int, int, int, int]] = []
|
|
70
|
+
s = float(size)
|
|
71
|
+
for y in range(size):
|
|
72
|
+
for x in range(size):
|
|
73
|
+
u = (x + 0.5) / s
|
|
74
|
+
v = (y + 0.5) / s
|
|
75
|
+
# 底:圆角方块 + 纵向渐变
|
|
76
|
+
a = _cover(_round_rect_sdf(u, v, 0.5, 0.5, 0.5, 0.5, 0.22), s)
|
|
77
|
+
t = 0.0 if v <= 0.0 else (1.0 if v >= 1.0 else v)
|
|
78
|
+
col = (
|
|
79
|
+
int(_BG_TOP[0] + (_BG_BOTTOM[0] - _BG_TOP[0]) * t),
|
|
80
|
+
int(_BG_TOP[1] + (_BG_BOTTOM[1] - _BG_TOP[1]) * t),
|
|
81
|
+
int(_BG_TOP[2] + (_BG_BOTTOM[2] - _BG_TOP[2]) * t),
|
|
82
|
+
)
|
|
83
|
+
px = (col[0], col[1], col[2], int(round(a * 255)))
|
|
84
|
+
|
|
85
|
+
# 窗口:白色圆角矩形
|
|
86
|
+
wa = _cover(_round_rect_sdf(u, v, 0.5, 0.5, 0.315, 0.275, 0.07), s) * a
|
|
87
|
+
px = _over(px, _WHITE, wa)
|
|
88
|
+
|
|
89
|
+
# 窗口标题栏上的三个小点
|
|
90
|
+
for cx in (0.30, 0.365, 0.43):
|
|
91
|
+
da = _cover(_circle_sdf(u, v, cx, 0.315, 0.0165), s) * a
|
|
92
|
+
px = _over(px, _DOT, da)
|
|
93
|
+
|
|
94
|
+
# 窗口里的三根数据柱,一根比一根高
|
|
95
|
+
for cx, h in ((0.385, 0.10), (0.5, 0.16), (0.615, 0.22)):
|
|
96
|
+
ba = _cover(_round_rect_sdf(u, v, cx, 0.70 - h / 2.0,
|
|
97
|
+
0.034, h / 2.0, 0.022), s) * a
|
|
98
|
+
px = _over(px, _BAR, ba)
|
|
99
|
+
|
|
100
|
+
pixels.append(px)
|
|
101
|
+
return pixels
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# ---------------------------------------------------------------- 编码
|
|
105
|
+
def _chunk(tag: bytes, data: bytes) -> bytes:
|
|
106
|
+
return (struct.pack(">I", len(data)) + tag + data
|
|
107
|
+
+ struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _png_bytes(pixels, size: int) -> bytes:
|
|
111
|
+
raw = bytearray()
|
|
112
|
+
for y in range(size):
|
|
113
|
+
raw.append(0) # 每行 filter=None
|
|
114
|
+
for x in range(size):
|
|
115
|
+
raw.extend(pixels[y * size + x])
|
|
116
|
+
ihdr = struct.pack(">IIBBBBB", size, size, 8, 6, 0, 0, 0) # 8bit RGBA
|
|
117
|
+
return (b"\x89PNG\r\n\x1a\n"
|
|
118
|
+
+ _chunk(b"IHDR", ihdr)
|
|
119
|
+
+ _chunk(b"IDAT", zlib.compress(bytes(raw), 9))
|
|
120
|
+
+ _chunk(b"IEND", b""))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _dib_bytes(pixels, size: int) -> bytes:
|
|
124
|
+
"""ICO 里的一个画面:BITMAPINFOHEADER + 32 位 BGRA(自下而上)+ AND 掩码"""
|
|
125
|
+
rows = bytearray()
|
|
126
|
+
for y in range(size - 1, -1, -1):
|
|
127
|
+
for x in range(size):
|
|
128
|
+
r, g, b, a = pixels[y * size + x]
|
|
129
|
+
rows.extend((b, g, r, a))
|
|
130
|
+
mask_row = ((size + 31) // 32) * 4
|
|
131
|
+
header = struct.pack("<IiiHHIIiiII", 40, size, size * 2, 1, 32, 0,
|
|
132
|
+
len(rows), 0, 0, 0, 0)
|
|
133
|
+
return header + bytes(rows) + bytes(mask_row * size)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _ico_bytes(frames: list[tuple[int, list]]) -> bytes:
|
|
137
|
+
count = len(frames)
|
|
138
|
+
out = struct.pack("<HHH", 0, 1, count)
|
|
139
|
+
entries = bytearray()
|
|
140
|
+
blobs = bytearray()
|
|
141
|
+
offset = 6 + 16 * count
|
|
142
|
+
for size, pixels in frames:
|
|
143
|
+
blob = _dib_bytes(pixels, size)
|
|
144
|
+
dim = 0 if size >= 256 else size
|
|
145
|
+
entries.extend(struct.pack("<BBBBHHII", dim, dim, 0, 0, 1, 32,
|
|
146
|
+
len(blob), offset + len(blobs)))
|
|
147
|
+
blobs.extend(blob)
|
|
148
|
+
return out + bytes(entries) + bytes(blobs)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# ---------------------------------------------------------------- 对外
|
|
152
|
+
def generate_png(path: str, size: int = 256) -> str:
|
|
153
|
+
"""画一张 PNG 图标"""
|
|
154
|
+
path = os.path.abspath(path)
|
|
155
|
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
|
156
|
+
with open(path, "wb") as fh:
|
|
157
|
+
fh.write(_png_bytes(_render(int(size)), int(size)))
|
|
158
|
+
return path
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def generate_icon(path: str, sizes=ICO_SIZES) -> str:
|
|
162
|
+
"""画一枚多尺寸 ICO(256 / 64 / 48 / 32 / 16)"""
|
|
163
|
+
path = os.path.abspath(path)
|
|
164
|
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
|
165
|
+
frames = [(int(s), _render(int(s))) for s in sizes]
|
|
166
|
+
with open(path, "wb") as fh:
|
|
167
|
+
fh.write(_ico_bytes(frames))
|
|
168
|
+
return path
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def ico_from_image(image_path: str, out_path: str, sizes=ICO_SIZES) -> str:
|
|
172
|
+
"""把一张现成的 PNG/JPG 转成多尺寸 ICO(需要 Pillow)"""
|
|
173
|
+
try:
|
|
174
|
+
from PIL import Image
|
|
175
|
+
except ImportError as exc: # pragma: no cover - 取决于环境
|
|
176
|
+
raise RuntimeError("把图片转 ICO 需要 Pillow:pip install pillow") from exc
|
|
177
|
+
sizes = sorted({int(s) for s in sizes}, reverse=True)
|
|
178
|
+
with Image.open(image_path) as im:
|
|
179
|
+
base = im.convert("RGBA")
|
|
180
|
+
base = base.resize((max(sizes), max(sizes)), Image.Resampling.LANCZOS)
|
|
181
|
+
out_path = os.path.abspath(out_path)
|
|
182
|
+
os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
|
|
183
|
+
base.save(out_path, "ICO", sizes=[(s, s) for s in sizes])
|
|
184
|
+
# Pillow 写出的 ICO 会把 256 存成 PNG 帧,这里校验一下文件头
|
|
185
|
+
with open(out_path, "rb") as fh:
|
|
186
|
+
head = fh.read(6)
|
|
187
|
+
if head[:2] != b"\x00\x00" or len(head) < 6:
|
|
188
|
+
raise RuntimeError("ICO 写出后校验失败")
|
|
189
|
+
return out_path
|
softforge/installer.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""安装 / 卸载:把 exe 变成「桌面上有图标、开始菜单里有条目、设置里能卸载」的应用。
|
|
3
|
+
|
|
4
|
+
装到 %LOCALAPPDATA%\\Programs\\<名字>\\,不写系统目录、不要管理员权限。
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import os
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
import winreg
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
_UNINSTALL_KEY = r"Software\Microsoft\Windows\CurrentVersion\Uninstall"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _shell_folder(name: str, fallback: Path) -> Path:
|
|
19
|
+
"""桌面可能在 OneDrive 里,优先问注册表"""
|
|
20
|
+
try:
|
|
21
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
|
|
22
|
+
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") as key:
|
|
23
|
+
value, _ = winreg.QueryValueEx(key, name)
|
|
24
|
+
path = Path(os.path.expandvars(value))
|
|
25
|
+
if path.is_dir():
|
|
26
|
+
return path
|
|
27
|
+
except OSError:
|
|
28
|
+
pass
|
|
29
|
+
return fallback
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def desktop_dir() -> Path:
|
|
33
|
+
return _shell_folder("Desktop", Path.home() / "Desktop")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def startmenu_dir() -> Path:
|
|
37
|
+
base = Path(os.environ.get("APPDATA", str(Path.home())))
|
|
38
|
+
return base / "Microsoft" / "Windows" / "Start Menu" / "Programs"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def programs_dir() -> Path:
|
|
42
|
+
base = Path(os.environ.get("LOCALAPPDATA", str(Path.home())))
|
|
43
|
+
return base / "Programs"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _q(text) -> str:
|
|
47
|
+
return "'" + str(text).replace("'", "''") + "'"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _powershell(script: str) -> subprocess.CompletedProcess:
|
|
51
|
+
return subprocess.run(
|
|
52
|
+
["powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
|
|
53
|
+
"-Command", script],
|
|
54
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def make_shortcut(lnk: Path, target: Path, workdir: Path, icon: Path | None = None,
|
|
58
|
+
description: str = "") -> Path:
|
|
59
|
+
"""用 WScript.Shell 建一个 .lnk(比手写二进制短链文件可靠)"""
|
|
60
|
+
lnk.parent.mkdir(parents=True, exist_ok=True)
|
|
61
|
+
icon_path = f"{icon},0" if icon else f"{target},0"
|
|
62
|
+
script = (
|
|
63
|
+
"$ws = New-Object -ComObject WScript.Shell;"
|
|
64
|
+
f"$s = $ws.CreateShortcut({_q(lnk)});"
|
|
65
|
+
f"$s.TargetPath = {_q(target)};"
|
|
66
|
+
f"$s.WorkingDirectory = {_q(workdir)};"
|
|
67
|
+
f"$s.IconLocation = {_q(icon_path)};"
|
|
68
|
+
f"$s.Description = {_q(description)};"
|
|
69
|
+
"$s.Save()"
|
|
70
|
+
)
|
|
71
|
+
done = _powershell(script)
|
|
72
|
+
if done.returncode != 0 or not lnk.is_file():
|
|
73
|
+
raise RuntimeError(f"创建快捷方式失败:{done.stderr.strip() or done.stdout.strip()}")
|
|
74
|
+
return lnk
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def shortcut_target(lnk: Path) -> str:
|
|
78
|
+
script = (f"$ws = New-Object -ComObject WScript.Shell;"
|
|
79
|
+
f"$ws.CreateShortcut({_q(lnk)}).TargetPath")
|
|
80
|
+
done = _powershell(script)
|
|
81
|
+
return done.stdout.strip()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _uninstall_script(name: str, folder: Path, links: list[Path]) -> str:
|
|
85
|
+
lines = ["$ErrorActionPreference='SilentlyContinue'"]
|
|
86
|
+
for link in links:
|
|
87
|
+
lines.append(f"Remove-Item -LiteralPath {_q(link)} -Force")
|
|
88
|
+
lines.append(f"Remove-Item -LiteralPath {_q(f'Registry::HKEY_CURRENT_USER\\{_UNINSTALL_KEY}\\softforge-{name}')} -Recurse -Force")
|
|
89
|
+
# 自己删自己:交给 cmd 延迟 2 秒再删目录
|
|
90
|
+
lines.append(f"Start-Process -FilePath 'cmd.exe' -WindowStyle Hidden -ArgumentList "
|
|
91
|
+
f"'/c','timeout /t 2 >nul & rmdir /s /q \"{folder}\"';")
|
|
92
|
+
return ";".join(lines)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _uninstall_command(name: str, folder: Path, links: list[Path]) -> str:
|
|
96
|
+
script = _uninstall_script(name, folder, links)
|
|
97
|
+
encoded = base64.b64encode(script.encode("utf-16le")).decode("ascii")
|
|
98
|
+
return f'powershell -NoProfile -ExecutionPolicy Bypass -EncodedCommand {encoded}'
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def install(project, *, desktop: bool = True, start_menu: bool = True,
|
|
102
|
+
register: bool = True, dest_dir: Path | None = None,
|
|
103
|
+
desktop_dir_override: Path | None = None,
|
|
104
|
+
startmenu_dir_override: Path | None = None,
|
|
105
|
+
log=print) -> dict:
|
|
106
|
+
"""把项目打出来的 exe 装成应用;返回装了哪些东西"""
|
|
107
|
+
src = Path(project.exe_path)
|
|
108
|
+
if not src.is_file():
|
|
109
|
+
raise RuntimeError(f"还没打包:{src} 不存在,先跑 softforge build")
|
|
110
|
+
|
|
111
|
+
target_dir = Path(dest_dir) if dest_dir else programs_dir() / project.name
|
|
112
|
+
target_dir.mkdir(parents=True, exist_ok=True)
|
|
113
|
+
if project.onefile:
|
|
114
|
+
dest_exe = target_dir / src.name
|
|
115
|
+
shutil.copy2(src, dest_exe)
|
|
116
|
+
else:
|
|
117
|
+
# onedir:整个目录搬过去
|
|
118
|
+
for item in src.parent.iterdir():
|
|
119
|
+
dst = target_dir / item.name
|
|
120
|
+
if item.is_dir():
|
|
121
|
+
if dst.exists():
|
|
122
|
+
shutil.rmtree(dst, ignore_errors=True)
|
|
123
|
+
shutil.copytree(item, dst)
|
|
124
|
+
else:
|
|
125
|
+
shutil.copy2(item, dst)
|
|
126
|
+
dest_exe = target_dir / src.parent.name / src.name
|
|
127
|
+
if not dest_exe.is_file():
|
|
128
|
+
dest_exe = target_dir / src.name
|
|
129
|
+
|
|
130
|
+
links: list[Path] = []
|
|
131
|
+
if desktop:
|
|
132
|
+
links.append(make_shortcut(
|
|
133
|
+
(Path(desktop_dir_override) if desktop_dir_override else desktop_dir()) / f"{project.name}.lnk",
|
|
134
|
+
dest_exe, dest_exe.parent, dest_exe, project.description or project.name))
|
|
135
|
+
log(f"桌面图标:{links[-1]}")
|
|
136
|
+
if start_menu:
|
|
137
|
+
links.append(make_shortcut(
|
|
138
|
+
(Path(startmenu_dir_override) if startmenu_dir_override else startmenu_dir()) / f"{project.name}.lnk",
|
|
139
|
+
dest_exe, dest_exe.parent, dest_exe, project.description or project.name))
|
|
140
|
+
log(f"开始菜单:{links[-1]}")
|
|
141
|
+
|
|
142
|
+
if register:
|
|
143
|
+
key_path = f"{_UNINSTALL_KEY}\\softforge-{project.name}"
|
|
144
|
+
with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, key_path, 0,
|
|
145
|
+
winreg.KEY_WRITE) as key:
|
|
146
|
+
items = {
|
|
147
|
+
"DisplayName": project.name,
|
|
148
|
+
"DisplayVersion": project.version,
|
|
149
|
+
"Publisher": project.company or "",
|
|
150
|
+
"InstallLocation": str(target_dir),
|
|
151
|
+
"DisplayIcon": f"{dest_exe},0",
|
|
152
|
+
"UninstallString": _uninstall_command(project.name, target_dir, links),
|
|
153
|
+
"NoModify": 1,
|
|
154
|
+
"NoRepair": 1,
|
|
155
|
+
}
|
|
156
|
+
for k, v in items.items():
|
|
157
|
+
winreg.SetValueEx(key, k, 0, winreg.REG_DWORD if isinstance(v, int) else winreg.REG_SZ, v)
|
|
158
|
+
log(f"设置→应用 已登记:softforge-{project.name}")
|
|
159
|
+
|
|
160
|
+
return {"exe": dest_exe, "folder": target_dir, "links": links,
|
|
161
|
+
"registered": bool(register)}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def uninstall(name: str, *, keep_files: bool = False, log=print) -> dict:
|
|
165
|
+
"""按软件名卸载(桌面 / 开始菜单 / 注册表 / 文件)"""
|
|
166
|
+
folder = programs_dir() / name
|
|
167
|
+
links = [desktop_dir() / f"{name}.lnk", startmenu_dir() / f"{name}.lnk"]
|
|
168
|
+
if keep_files:
|
|
169
|
+
for link in links:
|
|
170
|
+
if link.is_file():
|
|
171
|
+
link.unlink()
|
|
172
|
+
try:
|
|
173
|
+
winreg.DeleteKey(winreg.HKEY_CURRENT_USER, f"{_UNINSTALL_KEY}\\softforge-{name}")
|
|
174
|
+
except OSError:
|
|
175
|
+
pass
|
|
176
|
+
else:
|
|
177
|
+
_powershell(_uninstall_script(name, folder, links))
|
|
178
|
+
log(f"已卸载:{name}" + ("(程序文件保留)" if keep_files else ""))
|
|
179
|
+
return {"folder": folder, "links": links}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def is_installed(name: str) -> bool:
|
|
183
|
+
try:
|
|
184
|
+
winreg.OpenKey(winreg.HKEY_CURRENT_USER, f"{_UNINSTALL_KEY}\\softforge-{name}").Close()
|
|
185
|
+
return True
|
|
186
|
+
except OSError:
|
|
187
|
+
return False
|
softforge/py.typed
ADDED
|
File without changes
|
softforge/resource.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Windows 版本信息资源:让 exe 在「属性 → 详细信息」里显示名称、版本、公司。"""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _escape(text: str) -> str:
|
|
9
|
+
return (text or "").replace("\\", "\\\\").replace("'", "\\'")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def version_tuple(version: str) -> tuple[int, int, int, int]:
|
|
13
|
+
nums = re.findall(r"\d+", version or "")[:4]
|
|
14
|
+
nums += ["0"] * (4 - len(nums))
|
|
15
|
+
return tuple(int(n) for n in nums) # type: ignore[return-value]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def version_file_text(name: str, version: str, company: str = "",
|
|
19
|
+
description: str = "", exe_name: str = "") -> str:
|
|
20
|
+
"""生成 PyInstaller --version-file 需要的文本
|
|
21
|
+
|
|
22
|
+
用 0804(简体中文)+ 1200(Unicode)代码页,资源管理器里显示中文不会乱码。
|
|
23
|
+
"""
|
|
24
|
+
major, minor, patch, build = version_tuple(version)
|
|
25
|
+
ver_tuple = f"({major}, {minor}, {patch}, {build})"
|
|
26
|
+
product = _escape(name)
|
|
27
|
+
company = _escape(company or "")
|
|
28
|
+
desc = _escape(description or name)
|
|
29
|
+
internal = _escape(exe_name or f"{name}.exe")
|
|
30
|
+
original = _escape(name)
|
|
31
|
+
return f"""VSVersionInfo(
|
|
32
|
+
ffi=FixedFileInfo(
|
|
33
|
+
filevers={ver_tuple},
|
|
34
|
+
prodvers={ver_tuple},
|
|
35
|
+
mask=0x3f,
|
|
36
|
+
flags=0x0,
|
|
37
|
+
OS=0x40004,
|
|
38
|
+
fileType=0x1,
|
|
39
|
+
subtype=0x0,
|
|
40
|
+
date=(0, 0)
|
|
41
|
+
),
|
|
42
|
+
kids=[
|
|
43
|
+
StringFileInfo([
|
|
44
|
+
StringTable(
|
|
45
|
+
'080404b0',
|
|
46
|
+
[StringStruct('CompanyName', '{company}'),
|
|
47
|
+
StringStruct('FileDescription', '{desc}'),
|
|
48
|
+
StringStruct('FileVersion', '{_escape(version)}'),
|
|
49
|
+
StringStruct('InternalName', '{internal}'),
|
|
50
|
+
StringStruct('LegalCopyright', '{company}'),
|
|
51
|
+
StringStruct('OriginalFilename', '{original}.exe'),
|
|
52
|
+
StringStruct('ProductName', '{product}'),
|
|
53
|
+
StringStruct('ProductVersion', '{_escape(version)}')])
|
|
54
|
+
]),
|
|
55
|
+
VarFileInfo([VarStruct('Translation', [2052, 1200])])
|
|
56
|
+
]
|
|
57
|
+
)
|
|
58
|
+
"""
|