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/runtime.py ADDED
@@ -0,0 +1,48 @@
1
+ # -*- coding: utf-8 -*-
2
+ """给「被打包出来的软件」用的运行时小工具。
3
+
4
+ 在被打包的 app 里写一行:
5
+
6
+ import softforge.runtime as rt
7
+ rt.add_cli("我的软件", "1.0.0", selftest=selftest)
8
+
9
+ 就自动获得三个开关,方便验证打出来的 exe 真的是能跑的程序:
10
+
11
+ 我的软件.exe --version 打印 名字 版本
12
+ 我的软件.exe --about 打印 名字 / 版本 / 说明 / 解释器
13
+ 我的软件.exe --selftest 跑你给的 selftest(),返回码 0 即正常
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import sys
18
+
19
+
20
+ def add_cli(name: str, version: str, description: str = "", selftest=None) -> None:
21
+ """命令行开关命中就处理并退出;没命中就原样返回,继续走界面。"""
22
+ argv = sys.argv[1:]
23
+ if not argv:
24
+ return
25
+ flag = argv[0].lower()
26
+ if flag in ("--version", "-v", "version"):
27
+ print(f"{name} {version}")
28
+ raise SystemExit(0)
29
+ if flag in ("--about", "about"):
30
+ import platform
31
+ lines = [
32
+ f"{name} {version}",
33
+ description or "",
34
+ f"Python {platform.python_version()} · {platform.system()} {platform.release()}",
35
+ f"打包方式 softforge · 单文件运行环境 {sys.executable}",
36
+ ]
37
+ print("\n".join(line for line in lines if line))
38
+ raise SystemExit(0)
39
+ if flag == "--selftest":
40
+ if selftest is None:
41
+ print(f"{name} {version} 没有提供 selftest,跳过")
42
+ raise SystemExit(0)
43
+ try:
44
+ code = selftest()
45
+ except Exception as exc: # 自检里出错也要给出可读原因
46
+ print(f"自检失败:{type(exc).__name__}: {exc}")
47
+ raise SystemExit(1) from exc
48
+ raise SystemExit(int(code or 0))
softforge/scaffold.py ADDED
@@ -0,0 +1,90 @@
1
+ # -*- coding: utf-8 -*-
2
+ """新建一个「能被 softforge 打包成软件」的项目骨架。"""
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ _APP = '''# -*- coding: utf-8 -*-
8
+ """__NAME__ —— 由 softforge 生成的示例软件"""
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ import tkinter as tk
13
+
14
+ import softforge.runtime as rt
15
+
16
+ APP_NAME = "__NAME__"
17
+ VERSION = "__VERSION__"
18
+
19
+
20
+ def selftest() -> int:
21
+ print("tkinter 可导入")
22
+ print(f"解释器 {sys.version.split()[0]}")
23
+ return 0
24
+
25
+
26
+ def main() -> int:
27
+ rt.add_cli(APP_NAME, VERSION, description="softforge 示例软件", selftest=selftest)
28
+
29
+ root = tk.Tk()
30
+ root.title(f"{APP_NAME} v{VERSION}")
31
+ root.geometry("560x320")
32
+ root.configure(bg="#f4f6fb")
33
+ tk.Label(root, text="这是一个真正的桌面软件", bg="#f4f6fb", fg="#1f2937",
34
+ font=("Microsoft YaHei", 18, "bold")).pack(pady=(40, 10))
35
+ tk.Label(root, text="双击 exe 就能打开,不需要目标电脑装 Python",
36
+ bg="#f4f6fb", fg="#64748b", font=("Microsoft YaHei", 10)).pack()
37
+ tk.Button(root, text="关闭", command=root.destroy, bg="#2F6BFF", fg="#ffffff",
38
+ bd=0, font=("Microsoft YaHei", 10), padx=24, pady=8,
39
+ cursor="hand2").pack(pady=32)
40
+ root.mainloop()
41
+ return 0
42
+
43
+
44
+ if __name__ == "__main__":
45
+ raise SystemExit(main())
46
+ '''
47
+
48
+ _TOML = '''[app]
49
+ name = "__NAME__"
50
+ entry = "app.py"
51
+ version = "__VERSION__"
52
+ company = ""
53
+ description = "__NAME__ —— 由 softforge 打包成 Windows 软件"
54
+ onefile = true
55
+
56
+ # 需要一起打包的资源(源路径 = 包内目录),没有就删掉这一段
57
+ # [app.data]
58
+ # "assets" = "assets"
59
+ '''
60
+
61
+ _README = '''# __NAME__
62
+
63
+ 由 `softforge` 生成的桌面软件项目。
64
+
65
+ ```bash
66
+ softforge build . # 产出 dist\\__NAME__.exe
67
+ ```
68
+
69
+ - 界面在 `app.py`
70
+ - 打包参数在 `softforge.toml`
71
+ - 图标不填会自动生成,也可以用 `softforge icon` 自己画或从图片转
72
+ '''
73
+
74
+ _GITIGNORE = "build/\ndist/\n__pycache__/\n*.pyc\n"
75
+
76
+
77
+ def scaffold(target: str, name: str | None = None, version: str = "1.0.0") -> Path:
78
+ """在 target 目录生成项目骨架,返回目录路径"""
79
+ folder = Path(target).expanduser().resolve()
80
+ if folder.exists() and any(folder.iterdir()) and not (folder / "app.py").exists():
81
+ raise ValueError(f"{folder} 不是空目录,换个位置或先清空")
82
+ folder.mkdir(parents=True, exist_ok=True)
83
+ app_name = name or folder.name
84
+ (folder / "app.py").write_text(
85
+ _APP.replace("__NAME__", app_name).replace("__VERSION__", version), encoding="utf-8")
86
+ (folder / "softforge.toml").write_text(
87
+ _TOML.replace("__NAME__", app_name).replace("__VERSION__", version), encoding="utf-8")
88
+ (folder / "README.md").write_text(_README.replace("__NAME__", app_name), encoding="utf-8")
89
+ (folder / ".gitignore").write_text(_GITIGNORE, encoding="utf-8")
90
+ return folder
softforge/setupapp.py ADDED
@@ -0,0 +1,483 @@
1
+ # -*- coding: utf-8 -*-
2
+ """安装向导本体(会成为 `软件名-安装包.exe`)。
3
+
4
+ 参数不写死,从随包带的 payload/app.json 读:
5
+ {"name": "锻造示例", "version": "1.0.0", "company": "浩正",
6
+ "description": "...", "exe": "锻造示例.exe", "onefile": true, "subdir": ""}
7
+
8
+ 无界面安装(给测试/批量用):
9
+ 安装包.exe --auto [目标目录] [--no-desktop] [--no-startmenu] [--no-registry]
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ import json
15
+ import os
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+ import tkinter as tk
20
+ from pathlib import Path
21
+ from tkinter import filedialog, ttk
22
+
23
+ _UNINSTALL_KEY = r"Software\Microsoft\Windows\CurrentVersion\Uninstall"
24
+
25
+
26
+ # ---------------------------------------------------------------- 环境
27
+ def base_dir() -> Path:
28
+ return Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))
29
+
30
+
31
+ def payload_dir() -> Path:
32
+ env = os.environ.get("SOFTFORGE_SETUP_PAYLOAD")
33
+ return Path(env) if env else base_dir() / "payload"
34
+
35
+
36
+ def load_config() -> dict:
37
+ with open(payload_dir() / "app.json", encoding="utf-8") as fh:
38
+ return json.load(fh)
39
+
40
+
41
+ def default_target(cfg: dict) -> Path:
42
+ """默认装到 %LOCALAPPDATA%\\Programs\\<名字>;wizard.default_dir 可以改"""
43
+ custom = (cfg.get("wizard") or {}).get("default_dir")
44
+ if custom:
45
+ text = (str(custom).replace("{name}", cfg["name"])
46
+ .replace("{version}", cfg["version"])
47
+ .replace("{company}", cfg.get("company") or "独立开发者"))
48
+ text = os.path.expandvars(text)
49
+ if text.strip():
50
+ return Path(text)
51
+ base = Path(os.environ.get("LOCALAPPDATA", str(Path.home())))
52
+ return base / "Programs" / cfg["name"]
53
+
54
+
55
+ def desktop_dir() -> Path:
56
+ try:
57
+ import winreg
58
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
59
+ r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") as key:
60
+ value, _ = winreg.QueryValueEx(key, "Desktop")
61
+ path = Path(os.path.expandvars(value))
62
+ if path.is_dir():
63
+ return path
64
+ except Exception:
65
+ pass
66
+ return Path.home() / "Desktop"
67
+
68
+
69
+ def startmenu_dir() -> Path:
70
+ base = Path(os.environ.get("APPDATA", str(Path.home())))
71
+ return base / "Microsoft" / "Windows" / "Start Menu" / "Programs"
72
+
73
+
74
+ # ---------------------------------------------------------------- 系统动作
75
+ def _q(text) -> str:
76
+ return "'" + str(text).replace("'", "''") + "'"
77
+
78
+
79
+ def powershell(script: str) -> subprocess.CompletedProcess:
80
+ return subprocess.run(
81
+ ["powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
82
+ "-Command", script],
83
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60)
84
+
85
+
86
+ def make_shortcut(lnk: Path, target: Path, workdir: Path, description: str) -> None:
87
+ lnk.parent.mkdir(parents=True, exist_ok=True)
88
+ script = (
89
+ "$ws = New-Object -ComObject WScript.Shell;"
90
+ f"$s = $ws.CreateShortcut({_q(lnk)});"
91
+ f"$s.TargetPath = {_q(target)};"
92
+ f"$s.WorkingDirectory = {_q(workdir)};"
93
+ f"$s.IconLocation = {_q(f'{target},0')};"
94
+ f"$s.Description = {_q(description)};"
95
+ "$s.Save()"
96
+ )
97
+ done = powershell(script)
98
+ if done.returncode != 0 or not lnk.is_file():
99
+ raise RuntimeError(done.stderr.strip() or "建快捷方式失败")
100
+
101
+
102
+ def uninstall_command(cfg: dict, folder: Path, links: list[Path]) -> str:
103
+ lines = ["$ErrorActionPreference='SilentlyContinue'"]
104
+ for link in links:
105
+ lines.append(f"Remove-Item -LiteralPath {_q(link)} -Force")
106
+ lines.append("Remove-Item -LiteralPath "
107
+ f"{_q('Registry::HKEY_CURRENT_USER' + '\\' + _UNINSTALL_KEY + '\\softforge-' + cfg['name'])} "
108
+ "-Recurse -Force")
109
+ lines.append("Start-Process -FilePath 'cmd.exe' -WindowStyle Hidden -ArgumentList "
110
+ f"'/c','timeout /t 2 >nul & rmdir /s /q \"{folder}\"'")
111
+ encoded = base64.b64encode(";".join(lines).encode("utf-16le")).decode("ascii")
112
+ return f"powershell -NoProfile -ExecutionPolicy Bypass -EncodedCommand {encoded}"
113
+
114
+
115
+ def register(cfg: dict, folder: Path, exe: Path, links: list[Path]) -> None:
116
+ import winreg
117
+ key_path = f"{_UNINSTALL_KEY}\\softforge-{cfg['name']}"
118
+ with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_WRITE) as key:
119
+ values = {
120
+ "DisplayName": cfg["name"],
121
+ "DisplayVersion": cfg["version"],
122
+ "Publisher": cfg.get("company") or "",
123
+ "InstallLocation": str(folder),
124
+ "DisplayIcon": f"{exe},0",
125
+ "UninstallString": uninstall_command(cfg, folder, links),
126
+ "NoModify": 1,
127
+ "NoRepair": 1,
128
+ }
129
+ for k, v in values.items():
130
+ winreg.SetValueEx(key, k, 0,
131
+ winreg.REG_DWORD if isinstance(v, int) else winreg.REG_SZ, v)
132
+
133
+
134
+ def remove_registry(cfg: dict) -> None:
135
+ import winreg
136
+ try:
137
+ winreg.DeleteKey(winreg.HKEY_CURRENT_USER, f"{_UNINSTALL_KEY}\\softforge-{cfg['name']}")
138
+ except OSError:
139
+ pass
140
+
141
+
142
+ def install(cfg: dict, target: Path, *, desktop: bool, startmenu: bool,
143
+ registry: bool = True, log=None) -> dict:
144
+ log = log or (lambda msg: None)
145
+ src_root = payload_dir()
146
+ target.mkdir(parents=True, exist_ok=True)
147
+
148
+ if cfg.get("onefile", True):
149
+ src = src_root / cfg["exe"]
150
+ log("正在复制程序…")
151
+ shutil.copy2(src, target / cfg["exe"])
152
+ exe = target / cfg["exe"]
153
+ else:
154
+ src = src_root / (cfg.get("subdir") or "app")
155
+ log("正在复制程序文件…")
156
+ shutil.copytree(src, target, dirs_exist_ok=True)
157
+ exe = target / cfg["exe"]
158
+ if not exe.is_file():
159
+ raise RuntimeError(f"复制后找不到 {exe}")
160
+
161
+ links: list[Path] = []
162
+ if desktop:
163
+ log("正在创建桌面快捷方式…")
164
+ lnk = desktop_dir() / f"{cfg['name']}.lnk"
165
+ make_shortcut(lnk, exe, exe.parent, cfg.get("description") or cfg["name"])
166
+ links.append(lnk)
167
+ if startmenu:
168
+ log("正在创建开始菜单项…")
169
+ lnk = startmenu_dir() / f"{cfg['name']}.lnk"
170
+ make_shortcut(lnk, exe, exe.parent, cfg.get("description") or cfg["name"])
171
+ links.append(lnk)
172
+ if registry:
173
+ log("正在登记卸载信息…")
174
+ register(cfg, target, exe, links)
175
+ return {"exe": exe, "links": links, "folder": target}
176
+
177
+
178
+ # ---------------------------------------------------------------- 界面
179
+ # 向导上所有固定文字都在这里;app.json 的 "wizard" 表里同名字段会盖掉它们。
180
+ DEFAULTS = {
181
+ "title": "{name} {version} 安装程序",
182
+ "heading": "安装 {name}",
183
+ "subtitle": "版本 {version} · {company}",
184
+ "welcome_title": "准备把「{name}」装到这台电脑上。",
185
+ "welcome_body": "{description}",
186
+ "welcome_hint": "安装位置可以改,改完点「下一步」。",
187
+ "label_dir": "安装到",
188
+ "browse": "浏览…",
189
+ "hint_safe": "不会写系统目录,也不需要管理员权限。",
190
+ "options_title": "安装选项",
191
+ "option_desktop": "在桌面放一个图标",
192
+ "option_startmenu": "添加到开始菜单",
193
+ "option_run": "安装完成后立即运行",
194
+ "options_target": "将安装到:{target}",
195
+ "progress_title": "正在安装…",
196
+ "finish_title": "安装完成",
197
+ "finish_body": "「{name}」已装到\n{target}",
198
+ "finish_tip_run": "点「完成」会顺便把它打开。",
199
+ "finish_tip": "点「完成」结束安装。",
200
+ "btn_next": "下一步",
201
+ "btn_install": "安装",
202
+ "btn_finish": "完成",
203
+ "btn_cancel": "取消",
204
+ "btn_close": "关闭",
205
+ "btn_wait": "请稍候",
206
+ "license": "",
207
+ "license_title": "许可协议",
208
+ "license_hint": "读完并勾选下面的方框,「下一步」才会亮。",
209
+ "license_accept": "我已阅读并同意以上条款",
210
+ "default_dir": "",
211
+ "desktop_default": True,
212
+ "startmenu_default": True,
213
+ "run_default": True,
214
+ }
215
+
216
+ BG = "#ffffff"
217
+
218
+
219
+ def _flag(table: dict, key: str, default: bool) -> bool:
220
+ """表里的值可能是 True/False,也可能是字符串 'true' / '0'"""
221
+ if key not in table:
222
+ return default
223
+ value = table[key]
224
+ if isinstance(value, bool):
225
+ return value
226
+ return str(value).strip().lower() in ("1", "true", "yes", "on")
227
+
228
+
229
+ def wizard_texts(cfg: dict) -> dict:
230
+ """默认文案叠上 app.json 里的 wizard 表,得到这次安装包用的整套文字"""
231
+ text = dict(DEFAULTS)
232
+ text.update({k: v for k, v in (cfg.get("wizard") or {}).items() if k in DEFAULTS})
233
+ return text
234
+
235
+
236
+ HEAD = "#2F6BFF"
237
+ TEXT = "#101828"
238
+ SUB = "#5b6b82"
239
+ FONT = "Microsoft YaHei"
240
+
241
+
242
+ class Wizard(tk.Tk):
243
+ def __init__(self, cfg: dict):
244
+ super().__init__()
245
+ self.cfg = cfg
246
+ self.wiz = dict(cfg.get("wizard") or {})
247
+ self.text = wizard_texts(cfg)
248
+ self.title(self.t("title"))
249
+ self.resizable(False, False)
250
+ self.configure(bg=BG)
251
+ self.geometry("560x430")
252
+ self.target = tk.StringVar(value=str(default_target(cfg)))
253
+ self.opt_desktop = tk.BooleanVar(value=_flag(self.wiz, "desktop_default", True))
254
+ self.opt_start = tk.BooleanVar(value=_flag(self.wiz, "startmenu_default", True))
255
+ self.opt_run = tk.BooleanVar(value=_flag(self.wiz, "run_default", True))
256
+ self.opt_license = tk.BooleanVar(value=False)
257
+ self.finished = False
258
+
259
+ head = tk.Frame(self, bg=HEAD, height=96)
260
+ head.pack(fill="x")
261
+ tk.Label(head, text=self.t("heading"), bg=HEAD, fg="#ffffff",
262
+ font=(FONT, 20, "bold"), anchor="w").pack(fill="x", padx=26, pady=(20, 0))
263
+ tk.Label(head, text=self.t("subtitle"),
264
+ bg=HEAD, fg="#dce6ff", font=(FONT, 10), anchor="w").pack(fill="x", padx=26, pady=(2, 16))
265
+
266
+ self.body = tk.Frame(self, bg=BG)
267
+ self.body.pack(fill="both", expand=True, padx=26, pady=16)
268
+
269
+ foot = tk.Frame(self, bg="#f4f6fb", height=56)
270
+ foot.pack(fill="x", side="bottom")
271
+ self.btn_cancel = tk.Button(foot, text=self.t("btn_cancel"), command=self.do_cancel, bd=0,
272
+ bg="#f4f6fb", fg="#5b6b82", font=(FONT, 10),
273
+ padx=16, pady=8, cursor="hand2")
274
+ self.btn_cancel.pack(side="left", padx=(16, 0), pady=10)
275
+ self.btn_next = tk.Button(foot, text=self.t("btn_next"), command=self.do_next, bd=0,
276
+ bg=HEAD, fg="#ffffff", activebackground="#2456d6",
277
+ activeforeground="#ffffff", font=(FONT, 10, "bold"),
278
+ padx=24, pady=8, cursor="hand2")
279
+ self.btn_next.pack(side="right", padx=16, pady=10)
280
+
281
+ self.steps = (["license"] if str(self.text.get("license") or "").strip() else []) \
282
+ + ["welcome", "options", "progress", "finish"]
283
+ self.step = self.steps[0]
284
+ self.show_page()
285
+
286
+ # ---------------- 文字
287
+ def t(self, key: str, **extra) -> str:
288
+ """取一条文案,顺便把 {name} / {target} 这类占位符填好"""
289
+ raw = self.text.get(key, "")
290
+ ctx = {
291
+ "name": self.cfg["name"],
292
+ "version": self.cfg["version"],
293
+ "company": self.cfg.get("company") or "独立开发者",
294
+ "description": self.cfg.get("description") or "",
295
+ "target": getattr(self, "target", None).get() if hasattr(self, "target") else "",
296
+ }
297
+ ctx.update(extra)
298
+ try:
299
+ return str(raw).format(**ctx)
300
+ except (KeyError, IndexError, ValueError):
301
+ return str(raw)
302
+
303
+ # ---------------- 页面
304
+ def clear(self):
305
+ for child in self.body.winfo_children():
306
+ child.destroy()
307
+
308
+ def show_page(self):
309
+ self.clear()
310
+ pages = {"license": self.page_license, "welcome": self.page_welcome,
311
+ "options": self.page_options, "progress": self.page_progress,
312
+ "finish": self.page_finish}
313
+ pages[self.step]()
314
+
315
+ def page_license(self):
316
+ tk.Label(self.body, text=self.t("license_title"), bg=BG, fg=TEXT,
317
+ font=(FONT, 12, "bold")).pack(anchor="w")
318
+ box = tk.Frame(self.body, bg=BG)
319
+ box.pack(fill="x", pady=(8, 0))
320
+ text = tk.Text(box, height=7, wrap="word", bd=0, relief="flat",
321
+ bg="#f4f6fb", fg=TEXT, font=(FONT, 9), padx=10, pady=8,
322
+ insertbackground=TEXT)
323
+ bar = tk.Scrollbar(box, command=text.yview)
324
+ text.configure(yscrollcommand=bar.set)
325
+ bar.pack(side="right", fill="y")
326
+ text.pack(side="left", fill="both", expand=True)
327
+ text.insert("1.0", self.t("license"))
328
+ text.configure(state="disabled")
329
+ tk.Checkbutton(self.body, text=self.t("license_accept"), variable=self.opt_license,
330
+ command=self.sync_buttons, bg=BG, fg=TEXT, activebackground=BG,
331
+ selectcolor=BG, font=(FONT, 10)).pack(anchor="w", pady=(8, 0))
332
+ tk.Label(self.body, text=self.t("license_hint"), bg=BG, fg="#9aa8bd",
333
+ font=(FONT, 8)).pack(anchor="w")
334
+ self.btn_cancel.configure(text=self.t("btn_cancel"), state="normal")
335
+ self.btn_next.configure(text=self.t("btn_next"))
336
+ self.sync_buttons()
337
+
338
+ def sync_buttons(self):
339
+ ok = self.opt_license.get()
340
+ self.btn_next.configure(state="normal" if ok else "disabled",
341
+ bg=HEAD if ok else "#c8d3e8")
342
+
343
+ def page_welcome(self):
344
+ tk.Label(self.body, text=self.t("welcome_title"),
345
+ bg=BG, fg=TEXT, font=(FONT, 12, "bold"),
346
+ wraplength=470, justify="left").pack(anchor="w")
347
+ body = "\n".join(x for x in (self.t("welcome_body").strip(), self.t("welcome_hint")) if x)
348
+ tk.Label(self.body, text=body, bg=BG, fg=SUB, font=(FONT, 9),
349
+ wraplength=470, justify="left").pack(anchor="w", pady=(6, 16))
350
+
351
+ row = tk.Frame(self.body, bg=BG)
352
+ row.pack(fill="x")
353
+ tk.Label(row, text=self.t("label_dir"), bg=BG, fg=TEXT, font=(FONT, 9)).pack(side="left")
354
+ self.entry = tk.Entry(row, textvariable=self.target, font=(FONT, 9),
355
+ relief="flat", bg="#f4f6fb", fg=TEXT, insertbackground=TEXT)
356
+ self.entry.pack(side="left", fill="x", expand=True, padx=8, ipady=6)
357
+ tk.Button(row, text=self.t("browse"), command=self.pick_dir, bd=0, bg="#e8eefc",
358
+ fg=HEAD, font=(FONT, 9), padx=12, pady=5, cursor="hand2").pack(side="left")
359
+
360
+ tk.Label(self.body, text=self.t("hint_safe"),
361
+ bg=BG, fg="#9aa8bd", font=(FONT, 8)).pack(anchor="w", pady=(10, 0))
362
+ self.btn_next.configure(text=self.t("btn_next"), state="normal", bg=HEAD)
363
+ self.btn_cancel.configure(text=self.t("btn_cancel"), state="normal")
364
+
365
+ def page_options(self):
366
+ tk.Label(self.body, text=self.t("options_title"), bg=BG, fg=TEXT,
367
+ font=(FONT, 12, "bold")).pack(anchor="w")
368
+ box = tk.Frame(self.body, bg=BG)
369
+ box.pack(anchor="w", pady=(14, 0))
370
+ for key, var in (("option_desktop", self.opt_desktop),
371
+ ("option_startmenu", self.opt_start),
372
+ ("option_run", self.opt_run)):
373
+ tk.Checkbutton(box, text=self.t(key), variable=var, bg=BG, fg=TEXT,
374
+ activebackground=BG, selectcolor=BG, font=(FONT, 10)).pack(anchor="w", pady=4)
375
+ tk.Label(self.body, text=self.t("options_target", target=self.target.get()), bg=BG, fg=SUB,
376
+ font=(FONT, 8), wraplength=470, justify="left").pack(anchor="w", pady=(18, 0))
377
+ self.btn_next.configure(text=self.t("btn_install"))
378
+
379
+ def page_progress(self):
380
+ tk.Label(self.body, text=self.t("progress_title"), bg=BG, fg=TEXT,
381
+ font=(FONT, 12, "bold")).pack(anchor="w")
382
+ self.bar = ttk.Progressbar(self.body, length=470, mode="determinate", maximum=100)
383
+ self.bar.pack(anchor="w", pady=(18, 8))
384
+ self.status = tk.Label(self.body, text="准备中", bg=BG, fg=SUB, font=(FONT, 9))
385
+ self.status.pack(anchor="w")
386
+ self.btn_next.configure(text=self.t("btn_wait"), state="disabled")
387
+ self.btn_cancel.configure(state="disabled")
388
+ self.after(60, self.run_install)
389
+
390
+ def page_finish(self):
391
+ tk.Label(self.body, text=self.t("finish_title"), bg=BG, fg=TEXT,
392
+ font=(FONT, 14, "bold")).pack(anchor="w", pady=(10, 4))
393
+ tk.Label(self.body, text=self.t("finish_body", target=self.target.get()),
394
+ bg=BG, fg=SUB, font=(FONT, 9), justify="left").pack(anchor="w")
395
+ tip = self.t("finish_tip_run") if self.opt_run.get() else self.t("finish_tip")
396
+ tk.Label(self.body, text=tip, bg=BG, fg="#9aa8bd", font=(FONT, 9)).pack(anchor="w", pady=(22, 0))
397
+ self.btn_next.configure(text=self.t("btn_finish"), state="normal")
398
+ self.btn_cancel.configure(text=self.t("btn_close"), state="normal")
399
+
400
+ # ---------------- 动作
401
+ def pick_dir(self):
402
+ chosen = filedialog.askdirectory(title="选择安装位置", initialdir=self.target.get())
403
+ if chosen:
404
+ self.target.set(str(Path(chosen) / self.cfg["name"] if Path(chosen).name != self.cfg["name"] else chosen))
405
+
406
+ def do_next(self):
407
+ if self.step == "license" and not self.opt_license.get():
408
+ return
409
+ if self.step == "welcome" and not self.target.get().strip():
410
+ return
411
+ if self.step == "finish":
412
+ self.launch_if_needed()
413
+ self.finished = True
414
+ self.destroy()
415
+ return
416
+ index = self.steps.index(self.step)
417
+ if index + 1 < len(self.steps):
418
+ self.step = self.steps[index + 1]
419
+ self.show_page()
420
+
421
+ def do_cancel(self):
422
+ self.destroy()
423
+
424
+ def log(self, pct: int, msg: str):
425
+ self.bar["value"] = pct
426
+ self.status.configure(text=msg)
427
+ self.update_idletasks()
428
+
429
+ def run_install(self):
430
+ cfg = self.cfg
431
+ try:
432
+ self.log(10, "正在复制程序…")
433
+ info = install(cfg, Path(self.target.get()), desktop=self.opt_desktop.get(),
434
+ startmenu=self.opt_start.get(), log=lambda m: self.log(60, m))
435
+ self.log(100, "安装完成")
436
+ self.step = "finish"
437
+ # 清空 body 前先记住按钮状态
438
+ self.clear()
439
+ self.page_finish()
440
+ except Exception as exc: # 装失败要让用户看得见
441
+ self.btn_cancel.configure(state="normal", text=self.t("btn_close"))
442
+ self.btn_next.configure(text="重试", state="normal")
443
+ from tkinter import messagebox
444
+ messagebox.showerror("安装失败", f"{type(exc).__name__}: {exc}")
445
+ self.step = "welcome"
446
+ self.show_page()
447
+
448
+ def launch_if_needed(self):
449
+ if self.opt_run.get():
450
+ exe = Path(self.target.get()) / self.cfg["exe"]
451
+ if exe.is_file():
452
+ try:
453
+ subprocess.Popen([str(exe)], cwd=str(exe.parent))
454
+ except OSError:
455
+ pass
456
+
457
+
458
+ def run_auto(argv: list[str]) -> int:
459
+ cfg = load_config()
460
+ wiz = cfg.get("wizard") or {}
461
+ target = Path(argv[1]) if len(argv) > 1 and not argv[1].startswith("-") else default_target(cfg)
462
+ desktop = "--no-desktop" not in argv and _flag(wiz, "desktop_default", True)
463
+ startmenu = "--no-startmenu" not in argv and _flag(wiz, "startmenu_default", True)
464
+ registry = "--no-registry" not in argv
465
+ try:
466
+ info = install(cfg, target, desktop=desktop, startmenu=startmenu, registry=registry)
467
+ except Exception:
468
+ return 1
469
+ return 0 if info["exe"].is_file() else 1
470
+
471
+
472
+ def main() -> int:
473
+ argv = sys.argv[1:]
474
+ if argv and argv[0].lower() == "--auto":
475
+ return run_auto(argv)
476
+ cfg = load_config()
477
+ app = Wizard(cfg)
478
+ app.mainloop()
479
+ return 0
480
+
481
+
482
+ if __name__ == "__main__":
483
+ raise SystemExit(main())