""" Single-file launcher: extracts the app into LocalAppData on first run (or when the version changes), then starts the real GUI EXE from there. Distribute only this launcher EXE — no _internal folder for end users. """ from __future__ import annotations import os import shutil import subprocess import sys import zipfile from pathlib import Path # Keep in sync with app.__version__ APP_VERSION = "1.5.0" APP_NAME = "PDF_to_DXF" PAYLOAD_NAME = "app_payload.zip" def _local_app_data() -> Path: base = os.environ.get("LOCALAPPDATA") if base: return Path(base) return Path.home() / "AppData" / "Local" def _install_root() -> Path: return _local_app_data() / APP_NAME def _app_dir() -> Path: return _install_root() / "app" def _version_file() -> Path: return _install_root() / "version.txt" def _payload_zip() -> Path: if getattr(sys, "frozen", False): return Path(sys._MEIPASS) / PAYLOAD_NAME # type: ignore[attr-defined] # Dev fallback: look next to this file / in build/ here = Path(__file__).resolve().parent for candidate in ( here / "build" / PAYLOAD_NAME, here / PAYLOAD_NAME, here / "dist" / PAYLOAD_NAME, ): if candidate.is_file(): return candidate return here / "build" / PAYLOAD_NAME def _needs_install(app_dir: Path) -> bool: exe = app_dir / f"{APP_NAME}.exe" if not exe.is_file(): return True vf = _version_file() if not vf.is_file(): return True try: return vf.read_text(encoding="utf-8").strip() != APP_VERSION except OSError: return True def _show_setup_window(): """Minimal first-run progress window (std tkinter only).""" import tkinter as tk root = tk.Tk() root.title(f"{APP_NAME} Setup") root.resizable(False, False) root.attributes("-topmost", True) frame = tk.Frame(root, padx=36, pady=28) frame.pack() tk.Label( frame, text=f"{APP_NAME}", font=("Segoe UI", 14, "bold"), ).pack(anchor="w") status = tk.Label( frame, text="First run setup — copying files to AppData…\nThis only happens once per version.", font=("Segoe UI", 10), justify="left", ) status.pack(anchor="w", pady=(10, 0)) root.update_idletasks() # Center on screen w, h = root.winfo_reqwidth(), root.winfo_reqheight() x = max(0, (root.winfo_screenwidth() - w) // 2) y = max(0, (root.winfo_screenheight() - h) // 2) root.geometry(f"+{x}+{y}") root.update() return root, status def _install(app_dir: Path, status_cb=None) -> None: zip_path = _payload_zip() if not zip_path.is_file(): raise FileNotFoundError( f"Missing app payload ({PAYLOAD_NAME}). Rebuild with build_exe.ps1." ) root = _install_root() root.mkdir(parents=True, exist_ok=True) # Replace previous app files for this install if app_dir.exists(): if status_cb: status_cb("Updating previous install…") shutil.rmtree(app_dir, ignore_errors=True) app_dir.mkdir(parents=True, exist_ok=True) if status_cb: status_cb("Extracting application files…\nPlease wait.") with zipfile.ZipFile(zip_path, "r") as zf: zf.extractall(app_dir) exe = app_dir / f"{APP_NAME}.exe" if not exe.is_file(): raise FileNotFoundError(f"Extracted payload is missing {APP_NAME}.exe") _version_file().write_text(APP_VERSION, encoding="utf-8") def _launch(app_dir: Path) -> None: exe = app_dir / f"{APP_NAME}.exe" # Detach so this launcher can exit and clean its temp unpack subprocess.Popen( [str(exe)], cwd=str(app_dir), close_fds=True, ) def main() -> int: app_dir = _app_dir() setup_root = None try: if _needs_install(app_dir): setup_root, status = _show_setup_window() def set_status(text: str) -> None: status.configure(text=text) setup_root.update() _install(app_dir, status_cb=set_status) set_status("Starting…") setup_root.update() _launch(app_dir) return 0 except Exception as exc: try: import tkinter as tk from tkinter import messagebox tmp = tk.Tk() tmp.withdraw() messagebox.showerror(APP_NAME, f"Could not start the application:\n\n{exc}") tmp.destroy() except Exception: print(f"ERROR: {exc}", file=sys.stderr) return 1 finally: if setup_root is not None: try: setup_root.destroy() except Exception: pass if __name__ == "__main__": raise SystemExit(main())