mirror of
https://git.triforceproject.com/triforce/source
synced 2026-11-19 16:20:01 -04:00
Triforce v0.2.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
6
builder/py/hookshot_builder/__init__.py
Normal file
6
builder/py/hookshot_builder/__init__.py
Normal file
@@ -0,0 +1,6 @@
|
||||
"""Hookshot Builder, in Python: the same window as the WPF builder (builder/HookshotBuilder), run by python.org's own python.exe and
|
||||
Qt's DLLs (both signed by their makers), with no executable of Hookshot's own to download. It also does what the setup exe did
|
||||
(builder/setup/setup.c): it reads a release's hookshot-setup.txt, downloads the parts it names, checks each one's SHA-256 and
|
||||
unpacks them into %LOCALAPPDATA%\\HookshotBuilder\\versions\\<tag>."""
|
||||
APP_ID = "NotRexed.Hookshot.Builder" # (Windows' AppUserModelID: the taskbar groups and shows the window as Hookshot, not Python)
|
||||
REPO = "NotRexed/Hookshot"
|
||||
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-Bold.ttf
Normal file
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-Bold.ttf
Normal file
Binary file not shown.
92
builder/py/hookshot_builder/assets/Fonts/Inter-LICENSE.txt
Normal file
92
builder/py/hookshot_builder/assets/Fonts/Inter-LICENSE.txt
Normal file
@@ -0,0 +1,92 @@
|
||||
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION AND CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-Medium.ttf
Normal file
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-Medium.ttf
Normal file
Binary file not shown.
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-Regular.ttf
Normal file
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-Regular.ttf
Normal file
Binary file not shown.
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-SemiBold.ttf
Normal file
BIN
builder/py/hookshot_builder/assets/Fonts/Inter-SemiBold.ttf
Normal file
Binary file not shown.
BIN
builder/py/hookshot_builder/assets/hookshot.ico
Normal file
BIN
builder/py/hookshot_builder/assets/hookshot.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 71 KiB |
BIN
builder/py/hookshot_builder/assets/hookshot.png
Normal file
BIN
builder/py/hookshot_builder/assets/hookshot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 54 KiB |
557
builder/py/hookshot_builder/core.py
Normal file
557
builder/py/hookshot_builder/core.py
Normal file
@@ -0,0 +1,557 @@
|
||||
"""What the WPF builder's Runner.cs, Storage.cs, Finder.cs and BuildWorkers.cs do, the same rules: the build tools, nx2/make_game.py as a
|
||||
child process, what the builder keeps on the PC, the game files found on it, and the game's shortcuts."""
|
||||
import ctypes
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import string
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from ctypes import wintypes
|
||||
|
||||
from . import paths
|
||||
|
||||
CREATE_NO_WINDOW = 0x08000000
|
||||
BELOW_NORMAL_PRIORITY_CLASS = 0x00004000
|
||||
|
||||
|
||||
# ---------------- the build tools (Runner.cs: Tools) ----------------
|
||||
|
||||
class Tools:
|
||||
"""Where nx2/make_game.py and its Python are: the installed version's tools, or the source tree this app sits in"""
|
||||
|
||||
def __init__(self, root, python, python_args=None):
|
||||
self.root, self.python, self.python_args = root, python, python_args or []
|
||||
|
||||
@property
|
||||
def version(self):
|
||||
"""Which release these tools are (tools/version.txt, written when the release is packed); None from the source tree"""
|
||||
return paths.read_small(os.path.join(self.root, "version.txt")) or None
|
||||
|
||||
@staticmethod
|
||||
def find():
|
||||
from . import setup_parts
|
||||
env = os.environ.get("HOOKSHOT_TOOLS") # (development: these tools)
|
||||
cands = [env] if env else []
|
||||
cur = setup_parts.current()
|
||||
if cur:
|
||||
cands.append(os.path.join(cur, "HookshotBuilder", "tools"))
|
||||
for c in cands:
|
||||
if c and os.path.isfile(os.path.join(c, "nx2", "make_game.py")):
|
||||
py = os.path.join(c, "python", "python.exe")
|
||||
return Tools(c, py if os.path.isfile(py) else "python")
|
||||
d = paths.APP_DIR
|
||||
while True: # (a source checkout: builder/py/hookshot_builder in it)
|
||||
if os.path.isfile(os.path.join(d, "nx2", "make_game.py")):
|
||||
return Tools(d, sys.executable)
|
||||
up = os.path.dirname(d)
|
||||
if up == d:
|
||||
return None
|
||||
d = up
|
||||
|
||||
|
||||
def build_env(tools, workers=None, ngx_sdk=None):
|
||||
env = dict(os.environ)
|
||||
env["PYTHONIOENCODING"] = "utf-8"
|
||||
if workers:
|
||||
env["HOOKSHOT_JOBS"] = str(int(workers))
|
||||
# (written into the game folder's hookshot_version.txt: the game starts this app again to update, host/hos_update.c)
|
||||
exe, args = paths.launcher_command()
|
||||
env["HOOKSHOT_BUILDER_EXE"] = exe
|
||||
env["HOOKSHOT_BUILDER_ARGS"] = subprocess.list2cmdline(args)
|
||||
# (NVIDIA DLSS: only when ticked. Without it, one set on the PC is not passed on either)
|
||||
if ngx_sdk:
|
||||
env["HOOKSHOT_NGX_SDK"] = ngx_sdk
|
||||
else:
|
||||
env.pop("HOOKSHOT_NGX_SDK", None)
|
||||
for name, folder in (("EMSDK", "emsdk"), ("RX_CPM", "cpm"), ("WGPU_NATIVE", "wgpu-native")):
|
||||
p = os.path.join(tools.root, folder)
|
||||
if os.path.isdir(p):
|
||||
env[name] = p
|
||||
return env
|
||||
|
||||
|
||||
def build_command(tools, args):
|
||||
return [tools.python, *tools.python_args, "-I", os.path.join(tools.root, "nx2", "make_game.py"), *args]
|
||||
|
||||
|
||||
class Runner:
|
||||
"""nx2/make_game.py as a child process: its lines as they come (on_line, from a worker thread), and how it ended (on_finished:
|
||||
None, "cancelled", or why it stopped)"""
|
||||
|
||||
def __init__(self, tools, args, workers=None, ngx_sdk=None, on_line=None, on_finished=None):
|
||||
if workers is not None and workers <= 0:
|
||||
raise ValueError("Build workers must be positive.")
|
||||
self.tools, self.args, self.workers, self.ngx_sdk = tools, args, workers, ngx_sdk
|
||||
self.on_line, self.on_finished = on_line or (lambda l: None), on_finished or (lambda f: None)
|
||||
self.process, self.error, self.cancelled = None, None, False
|
||||
|
||||
def start(self):
|
||||
threading.Thread(target=self._run, daemon=True).start()
|
||||
|
||||
def _run(self):
|
||||
try:
|
||||
p = subprocess.Popen(build_command(self.tools, self.args), cwd=self.tools.root,
|
||||
env=build_env(self.tools, self.workers, self.ngx_sdk), stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, stdin=subprocess.DEVNULL,
|
||||
creationflags=CREATE_NO_WINDOW | BELOW_NORMAL_PRIORITY_CLASS)
|
||||
except OSError as e:
|
||||
self.on_finished("The build tools could not start: %s" % e)
|
||||
return
|
||||
self.process = p
|
||||
|
||||
def errs():
|
||||
for raw in p.stderr:
|
||||
self.on_line(raw.decode("utf-8", "replace").rstrip("\r\n"))
|
||||
threading.Thread(target=errs, daemon=True).start()
|
||||
for raw in p.stdout:
|
||||
line = raw.decode("utf-8", "replace").rstrip("\r\n")
|
||||
if line.startswith("@@error "):
|
||||
self.error = line[8:]
|
||||
self.on_line(line)
|
||||
p.wait()
|
||||
self.on_finished("cancelled" if self.cancelled else None if p.returncode == 0 else
|
||||
self.error or "The build tools stopped without saying why. See the details.")
|
||||
|
||||
def cancel(self):
|
||||
self.cancelled = True
|
||||
p = self.process
|
||||
if p and p.poll() is None: # (the whole tree: the compilers it started too)
|
||||
subprocess.run(["taskkill", "/T", "/F", "/PID", str(p.pid)], capture_output=True, creationflags=CREATE_NO_WINDOW)
|
||||
|
||||
|
||||
def check(tools, args):
|
||||
"""Is this the supported game and version? (ok, the answer in plain words)"""
|
||||
try:
|
||||
p = subprocess.run(build_command(tools, args), cwd=tools.root, env=build_env(tools), capture_output=True,
|
||||
stdin=subprocess.DEVNULL, creationflags=CREATE_NO_WINDOW)
|
||||
except OSError:
|
||||
if tools.python == "python" and os.path.isdir(os.path.join(tools.root, "python")):
|
||||
return False, ("The builder's own Python (tools/python/python.exe) is missing. Your antivirus probably removed it: restore "
|
||||
"it from quarantine, then try again.")
|
||||
return False, "Python 3 was not found. Install it from python.org (not the Microsoft Store build)."
|
||||
result, answered = (False, "The game files could not be read."), False
|
||||
for line in p.stdout.decode("utf-8", "replace").splitlines():
|
||||
if line.startswith("@@check ok "):
|
||||
result, answered = (True, line[11:]), True
|
||||
elif line.startswith("@@check bad "):
|
||||
result, answered = (False, line[12:]), True
|
||||
elif line.startswith("@@error "):
|
||||
result, answered = (False, line[8:]), True
|
||||
if not answered:
|
||||
errs = [l for l in p.stderr.decode("utf-8", "replace").splitlines() if l.strip()]
|
||||
last = errs[-1] if errs else None
|
||||
if last and "microsoft store" in last.lower():
|
||||
return False, ("Python 3 was not found: the 'python' command on this PC is the Microsoft Store shortcut, which only opens "
|
||||
"the Store. Install Python 3 from python.org (not the Store version).")
|
||||
return False, last or "The game tools stopped without saying why (exit code %d)." % p.returncode
|
||||
return result
|
||||
|
||||
|
||||
# ---------------- build workers (BuildWorkers.cs) ----------------
|
||||
|
||||
AUTOMATIC = "Automatic"
|
||||
|
||||
|
||||
def worker_choices():
|
||||
return [AUTOMATIC] + list(range(1, max(1, os.cpu_count() or 1) + 1))
|
||||
|
||||
|
||||
# ---------------- what the builder keeps on the PC (Storage.cs) ----------------
|
||||
|
||||
BUILD_FILES_BYTES = 4 << 30
|
||||
|
||||
|
||||
def keep_build_files():
|
||||
v = os.environ.get("HOOKSHOT_KEEP_BUILD_FILES", "")
|
||||
return bool(v) and v != "0"
|
||||
|
||||
|
||||
def _same(a, b):
|
||||
return os.path.normcase(os.path.abspath(a)).rstrip("\\/") == os.path.normcase(os.path.abspath(b)).rstrip("\\/")
|
||||
|
||||
|
||||
def work():
|
||||
"""Where builds keep their files: the folder the player chose (work.txt), else the builder's own"""
|
||||
chosen = paths.read_small(os.path.join(paths.base(), "work.txt"))
|
||||
return chosen if len(chosen) > 2 and os.path.isabs(chosen) else paths.base()
|
||||
|
||||
|
||||
def work_chosen():
|
||||
return not _same(work(), paths.base())
|
||||
|
||||
|
||||
def ngx_sdk():
|
||||
return os.path.join(paths.base(), "ngx-sdk")
|
||||
|
||||
|
||||
WORK_PARTS = ("objcache", "sa", "exefs", "probe", "image", "system_headers.txt", "hot_funcs.txt", "hot_order.txt",
|
||||
"hookshot_pieces.prof", "hookshot.res")
|
||||
|
||||
|
||||
def _delete(p):
|
||||
try:
|
||||
if os.path.isdir(p):
|
||||
shutil.rmtree(p)
|
||||
elif os.path.isfile(p):
|
||||
os.remove(p)
|
||||
except OSError:
|
||||
shutil.rmtree(p, ignore_errors=True) if os.path.isdir(p) else None
|
||||
|
||||
|
||||
def move_work(picked):
|
||||
"""The build files go to a folder of their own in the one the player picked (None: back to the builder's own); what the last
|
||||
builds left at the old place goes"""
|
||||
old = work()
|
||||
to = paths.base() if picked is None else os.path.join(picked, "Hookshot build files")
|
||||
if _same(old, to):
|
||||
return
|
||||
os.makedirs(to, exist_ok=True)
|
||||
os.makedirs(paths.base(), exist_ok=True)
|
||||
if picked is None:
|
||||
try:
|
||||
os.remove(os.path.join(paths.base(), "work.txt"))
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
paths.write_small(os.path.join(paths.base(), "work.txt"), to)
|
||||
for n in WORK_PARTS:
|
||||
_delete(os.path.join(old, n))
|
||||
if not _same(old, paths.base()):
|
||||
try:
|
||||
os.rmdir(old)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _kept_version(d):
|
||||
from . import setup_parts
|
||||
cur = setup_parts.current()
|
||||
return bool(cur) and _same(cur, d)
|
||||
|
||||
|
||||
def freeable(after_build=False):
|
||||
for d in (("sa", "exefs", "probe") if after_build else ("objcache", "sa", "exefs", "probe")):
|
||||
yield os.path.join(work(), d)
|
||||
for d in ("downloads", "update"):
|
||||
yield os.path.join(paths.base(), d)
|
||||
v = paths.versions()
|
||||
if os.path.isdir(v):
|
||||
for name in os.listdir(v):
|
||||
p = os.path.join(v, name)
|
||||
if os.path.isdir(p) and not _kept_version(p):
|
||||
yield p
|
||||
|
||||
|
||||
def _size(d, seen):
|
||||
n = 0
|
||||
for root, _dirs, files in os.walk(d):
|
||||
for f in files:
|
||||
try:
|
||||
st = os.stat(os.path.join(root, f))
|
||||
except OSError:
|
||||
continue
|
||||
if not st.st_size:
|
||||
continue
|
||||
if st.st_nlink > 1: # (an object hard-linked in both sa\build and objcache counted once)
|
||||
key = (st.st_dev, st.st_ino)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
n += st.st_size
|
||||
return n
|
||||
|
||||
|
||||
def measure():
|
||||
"""(bytes in the builder's folder and the build files folder, bytes Free lets go)"""
|
||||
seen = set()
|
||||
free = sum(_size(d, seen) for d in freeable())
|
||||
seen = set()
|
||||
total = _size(paths.base(), seen) + (_size(work(), seen) if work_chosen() else 0)
|
||||
return max(total, free), free
|
||||
|
||||
|
||||
def free(after_build=False):
|
||||
"""Lets go of what measure counts as freeable; returns the bytes it could not delete (a file in use)"""
|
||||
for d in list(freeable(after_build)):
|
||||
_delete(d)
|
||||
if not after_build:
|
||||
_delete(os.path.join(work(), "system_headers.txt"))
|
||||
return measure()[1]
|
||||
seen = set()
|
||||
return sum(_size(d, seen) for d in freeable(True))
|
||||
|
||||
|
||||
def gb(n):
|
||||
return "%.1f GB" % (n / (1 << 30)) if n >= 1 << 30 else "%d MB" % (n >> 20)
|
||||
|
||||
|
||||
def free_space(path):
|
||||
try:
|
||||
root = os.path.splitdrive(os.path.abspath(path))[0] + "\\"
|
||||
return root, shutil.disk_usage(root).free
|
||||
except OSError:
|
||||
return None, None
|
||||
|
||||
|
||||
def spinning(path):
|
||||
"""True on a hard drive, False on an SSD, None when the drive cannot be told (Disk.cs's IOCTL: the volume's seek penalty).
|
||||
A build reads and writes tens of gigabytes, and an SSD makes that much faster: a warning only, never a stop."""
|
||||
try:
|
||||
from ctypes import wintypes
|
||||
root = os.path.splitdrive(os.path.abspath(os.path.expanduser(path)))[0]
|
||||
if not root:
|
||||
return None
|
||||
|
||||
class Query(ctypes.Structure):
|
||||
_fields_ = [("PropertyId", wintypes.DWORD), ("QueryType", wintypes.DWORD), ("Additional", wintypes.DWORD)]
|
||||
|
||||
class SeekPenalty(ctypes.Structure):
|
||||
_fields_ = [("Version", wintypes.DWORD), ("Size", wintypes.DWORD), ("IncursSeekPenalty", ctypes.c_ubyte)]
|
||||
|
||||
k = ctypes.windll.kernel32
|
||||
k.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p,
|
||||
wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
|
||||
k.CreateFileW.restype = wintypes.HANDLE
|
||||
k.DeviceIoControl.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD,
|
||||
ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p]
|
||||
k.DeviceIoControl.restype = wintypes.BOOL
|
||||
k.CloseHandle.argtypes = [wintypes.HANDLE]
|
||||
handle = k.CreateFileW("\\\\.\\" + root, 0, 0x1 | 0x2, None, 3, 0, None) # (read + write share, OPEN_EXISTING)
|
||||
if not handle or handle == wintypes.HANDLE(-1).value:
|
||||
return None
|
||||
try:
|
||||
query, answer, returned = Query(7, 0, 0), SeekPenalty(), wintypes.DWORD()
|
||||
ok = k.DeviceIoControl(handle, 0x002D1400, ctypes.byref(query), ctypes.sizeof(query), ctypes.byref(answer),
|
||||
ctypes.sizeof(answer), ctypes.byref(returned), None)
|
||||
if not ok or returned.value < ctypes.sizeof(answer):
|
||||
return None
|
||||
return bool(answer.IncursSeekPenalty)
|
||||
finally:
|
||||
k.CloseHandle(handle)
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
# ---------------- the player's game files (Finder.cs) ----------------
|
||||
|
||||
class Dump:
|
||||
def __init__(self, path, where, size, modified):
|
||||
self.path, self.where, self.size, self.modified = path, where, size, modified
|
||||
|
||||
|
||||
def _known_folder(fid):
|
||||
buf = ctypes.c_wchar_p()
|
||||
guid = (ctypes.c_byte * 16).from_buffer_copy(fid)
|
||||
if ctypes.windll.shell32.SHGetKnownFolderPath(guid, 0, None, ctypes.byref(buf)) == 0:
|
||||
p = buf.value
|
||||
ctypes.windll.ole32.CoTaskMemFree(buf)
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def _guid(s):
|
||||
import uuid
|
||||
return uuid.UUID(s).bytes_le
|
||||
|
||||
|
||||
FOLDER_DESKTOP = _guid("B4BFCC3A-DB2C-424C-B029-7FE99A87C641")
|
||||
FOLDER_DOCUMENTS = _guid("FDD39AD0-238F-46AF-ADB4-6C85480369C7")
|
||||
FOLDER_DOWNLOADS = _guid("374DE290-123F-4565-9164-39C4925E467B")
|
||||
FOLDER_PROGRAMS = _guid("A77F5D77-2E2B-44C3-A6A2-ABA601054A51")
|
||||
|
||||
|
||||
def find_dumps():
|
||||
""".nup files in Downloads, Desktop, Documents, the home folder and the top of each drive, one folder level down too, newest first"""
|
||||
home = os.path.expanduser("~")
|
||||
places = [(_known_folder(FOLDER_DOWNLOADS) or os.path.join(home, "Downloads"), "Downloads"),
|
||||
(_known_folder(FOLDER_DESKTOP) or os.path.join(home, "Desktop"), "Desktop"),
|
||||
(_known_folder(FOLDER_DOCUMENTS) or os.path.join(home, "Documents"), "Documents"), (home, "Home")]
|
||||
mask = ctypes.windll.kernel32.GetLogicalDrives()
|
||||
for i, letter in enumerate(string.ascii_uppercase):
|
||||
if mask >> i & 1:
|
||||
root = letter + ":\\"
|
||||
if ctypes.windll.kernel32.GetDriveTypeW(root) in (2, 3): # (removable, fixed)
|
||||
places.append((root, letter + ":"))
|
||||
seen, found = set(), []
|
||||
for d, name in places:
|
||||
if not d or not os.path.isdir(d) or os.path.normcase(os.path.abspath(d)) in seen:
|
||||
continue
|
||||
seen.add(os.path.normcase(os.path.abspath(d)))
|
||||
dirs = [d]
|
||||
try:
|
||||
subs = [e.path for e in os.scandir(d) if e.is_dir() and not e.name.startswith((".", "$"))
|
||||
and e.name.lower() != "windows" and not e.name.lower().startswith("program")]
|
||||
dirs += subs[:200]
|
||||
except OSError:
|
||||
pass
|
||||
for sub in dirs:
|
||||
try:
|
||||
for e in os.scandir(sub):
|
||||
if e.is_file() and e.name.lower().endswith(".nup"):
|
||||
full = os.path.abspath(e.path)
|
||||
if os.path.normcase(full) not in seen:
|
||||
seen.add(os.path.normcase(full))
|
||||
st = e.stat()
|
||||
found.append(Dump(full, name, st.st_size, st.st_mtime))
|
||||
except OSError:
|
||||
pass
|
||||
return sorted(found, key=lambda x: -x.modified)
|
||||
|
||||
|
||||
def ago(t):
|
||||
import datetime
|
||||
now, then = datetime.datetime.now(), datetime.datetime.fromtimestamp(t)
|
||||
days = (now - then).total_seconds() / 86400
|
||||
if days < 1 and then.date() == now.date():
|
||||
return "modified today"
|
||||
if days < 2:
|
||||
return "modified yesterday"
|
||||
if days < 14:
|
||||
return "%d days ago" % int(days)
|
||||
if days < 60:
|
||||
return "%d weeks ago" % int(days / 7)
|
||||
return "%d %s" % (then.day, then.strftime("%b %Y"))
|
||||
|
||||
|
||||
def size_text(n):
|
||||
return "%.1f GB" % (n / (1 << 30)) if n >= 1 << 30 else "%d MB" % (n >> 20)
|
||||
|
||||
|
||||
# ---------------- the game folder ----------------
|
||||
|
||||
def _version_line(folder):
|
||||
for line in paths.read_small(os.path.join(folder, "hookshot_version.txt")).splitlines():
|
||||
if line.startswith("version="):
|
||||
return line[8:].strip() or None
|
||||
return None
|
||||
|
||||
|
||||
def game_version(folder):
|
||||
"""The release a game folder was built with, when it keeps its game files for updates"""
|
||||
if not os.path.isdir(os.path.join(folder, ".hookshot_exefs")) or not os.path.isdir(os.path.join(folder, "romfs")):
|
||||
return None
|
||||
return _version_line(folder)
|
||||
|
||||
|
||||
def read_version(folder):
|
||||
"""(a folder built before it kept its game files has a version too: only shown)"""
|
||||
return _version_line(folder)
|
||||
|
||||
|
||||
def game_exe(folder):
|
||||
g = os.path.join(folder, "bin", "hookshot.exe")
|
||||
return g if os.path.isfile(g) else os.path.join(folder, "hookshot.exe")
|
||||
|
||||
|
||||
def start_game(folder):
|
||||
"""(the launcher already checked for updates: the game does not ask again)"""
|
||||
env = dict(os.environ, HOOKSHOT_NO_UPDATE_CHECK="1")
|
||||
subprocess.Popen([game_exe(folder)], cwd=folder, env=env)
|
||||
|
||||
|
||||
def open_folder(folder):
|
||||
subprocess.Popen(["explorer.exe", folder])
|
||||
|
||||
|
||||
# ---------------- shortcuts (Finder.cs: IShellLinkW + IPersistFile, Windows' own shell object writes the .lnk) ----------------
|
||||
|
||||
def desktop_link():
|
||||
return os.path.join(_known_folder(FOLDER_DESKTOP) or os.path.join(os.path.expanduser("~"), "Desktop"), "Hookshot.lnk")
|
||||
|
||||
|
||||
def start_link():
|
||||
return os.path.join(_known_folder(FOLDER_PROGRAMS) or "", "Hookshot.lnk")
|
||||
|
||||
|
||||
def folder_link(game_folder):
|
||||
"""The game folder's own launcher: Play, and Update left of it when a newer release is out (the setup exe's launch mode)"""
|
||||
return os.path.join(game_folder, "Hookshot.lnk")
|
||||
|
||||
|
||||
shortcut_error = None
|
||||
|
||||
|
||||
def _com_call(obj, index, restype, *args):
|
||||
vtbl = ctypes.cast(obj, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents
|
||||
fn = ctypes.WINFUNCTYPE(restype, ctypes.c_void_p, *[type(a) for a in args])(vtbl[index])
|
||||
return fn(obj, *args)
|
||||
|
||||
|
||||
def make_link(link, target, args, workdir, icon, description):
|
||||
ole32 = ctypes.windll.ole32
|
||||
ole32.CoInitialize(None)
|
||||
clsid = (ctypes.c_byte * 16).from_buffer_copy(_guid("00021401-0000-0000-C000-000000000046"))
|
||||
iid_link = (ctypes.c_byte * 16).from_buffer_copy(_guid("000214F9-0000-0000-C000-000000000046"))
|
||||
iid_file = (ctypes.c_byte * 16).from_buffer_copy(_guid("0000010B-0000-0000-C000-000000000046"))
|
||||
sl = ctypes.c_void_p()
|
||||
hr = ole32.CoCreateInstance(clsid, None, 1, iid_link, ctypes.byref(sl))
|
||||
if hr != 0:
|
||||
raise OSError("CoCreateInstance(ShellLink) failed: 0x%08x" % (hr & 0xFFFFFFFF))
|
||||
try:
|
||||
W = ctypes.c_wchar_p
|
||||
_com_call(sl, 20, ctypes.HRESULT, W(target)) # SetPath
|
||||
_com_call(sl, 11, ctypes.HRESULT, W(args)) # SetArguments
|
||||
_com_call(sl, 9, ctypes.HRESULT, W(workdir)) # SetWorkingDirectory
|
||||
_com_call(sl, 17, ctypes.HRESULT, W(icon), ctypes.c_int(0)) # SetIconLocation
|
||||
_com_call(sl, 7, ctypes.HRESULT, W(description)) # SetDescription
|
||||
pf = ctypes.c_void_p()
|
||||
_com_call(sl, 0, ctypes.HRESULT, ctypes.cast(iid_file, ctypes.c_void_p), ctypes.byref(pf)) # QueryInterface
|
||||
try:
|
||||
os.makedirs(os.path.dirname(link), exist_ok=True)
|
||||
_com_call(pf, 6, ctypes.HRESULT, W(link), wintypes.BOOL(True)) # IPersistFile::Save
|
||||
finally:
|
||||
_com_call(pf, 2, ctypes.c_ulong)
|
||||
finally:
|
||||
_com_call(sl, 2, ctypes.c_ulong)
|
||||
|
||||
|
||||
def shortcuts(game_folder, desktop, start, folder=True):
|
||||
"""Made or removed as the ticks say: each starts this app's launcher for the folder (Play, and Update when a newer release is
|
||||
out), with the game's own icon"""
|
||||
global shortcut_error
|
||||
exe, args = paths.launcher_command()
|
||||
args = subprocess.list2cmdline(args + ["--launch", game_folder])
|
||||
icon = os.path.join(game_folder, "bin", "hookshot.exe")
|
||||
if not os.path.isfile(icon):
|
||||
icon = os.path.join(game_folder, "hookshot.exe")
|
||||
for link, want in ((desktop_link(), desktop), (start_link(), start), (folder_link(game_folder), folder)):
|
||||
try:
|
||||
if not want:
|
||||
if os.path.isfile(link):
|
||||
os.remove(link)
|
||||
continue
|
||||
if not os.path.isfile(icon):
|
||||
continue
|
||||
make_link(link, exe, args, game_folder, icon, "The Legend of Zelda: Ocarina of Time, built by Hookshot")
|
||||
except OSError as e:
|
||||
shortcut_error = "%s: %s" % (os.path.basename(link), e)
|
||||
|
||||
|
||||
def refresh_shortcuts(game_folder):
|
||||
shortcuts(game_folder, os.path.isfile(desktop_link()), os.path.isfile(start_link()))
|
||||
|
||||
|
||||
# ---------------- what the player chose last time (builder-settings.json, the WPF builder's) ----------------
|
||||
|
||||
def settings_path():
|
||||
return os.path.join(paths.base(), "builder-settings.json")
|
||||
|
||||
|
||||
def load_settings():
|
||||
try:
|
||||
with open(settings_path(), encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def save_settings(s):
|
||||
try:
|
||||
os.makedirs(paths.base(), exist_ok=True)
|
||||
with open(settings_path(), "w", encoding="utf-8") as f:
|
||||
json.dump(s, f)
|
||||
except OSError:
|
||||
pass
|
||||
45
builder/py/hookshot_builder/paths.py
Normal file
45
builder/py/hookshot_builder/paths.py
Normal file
@@ -0,0 +1,45 @@
|
||||
"""Where things are: the builder's own folder in %LOCALAPPDATA%, and this app's folder."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
APP_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
ASSETS = os.path.join(APP_DIR, "assets")
|
||||
|
||||
|
||||
def base():
|
||||
"""%LOCALAPPDATA%\\HookshotBuilder (HOOKSHOT_SETUP_BASE=<folder>: another, for testing installs and updates)"""
|
||||
b = os.environ.get("HOOKSHOT_SETUP_BASE")
|
||||
if b:
|
||||
return b
|
||||
return os.path.join(os.environ.get("LOCALAPPDATA") or os.path.expanduser("~"), "HookshotBuilder")
|
||||
|
||||
|
||||
def versions():
|
||||
return os.path.join(base(), "versions")
|
||||
|
||||
|
||||
def read_small(path):
|
||||
try:
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
return f.read().strip()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def write_small(path, text):
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(text)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def launcher_command():
|
||||
"""How this app is started again (the game folder's launcher, the game's update offer, a shortcut): the Python that runs it
|
||||
(pythonw.exe beside python.exe when there is one: no console window) and the app's start script"""
|
||||
exe = sys.executable
|
||||
w = os.path.join(os.path.dirname(exe), "pythonw.exe")
|
||||
if os.path.isfile(w):
|
||||
exe = w
|
||||
return exe, ["-I", os.path.join(os.path.dirname(APP_DIR), "hookshot_builder_start.py")]
|
||||
337
builder/py/hookshot_builder/setup_parts.py
Normal file
337
builder/py/hookshot_builder/setup_parts.py
Normal file
@@ -0,0 +1,337 @@
|
||||
"""The setup's work (builder/setup/setup.c, the same rules): a release's hookshot-setup.txt names its tag and its parts (one zip each,
|
||||
with its SHA-256 and size); each part is downloaded (or moved over from the installed version when its checksum did not change),
|
||||
checked and unpacked into versions\\<tag>.part, which becomes versions\\<tag> once complete. The version installed stays, the others
|
||||
and the downloads go.
|
||||
|
||||
hookshot-setup.txt, one item a line:
|
||||
tag <tag>
|
||||
part <sha256> <bytes> <folder under the install> <top folder in the zip to rename, or -> <new name, or -> <url>
|
||||
run <the WPF builder, relative to the install> (not needed here: the tools are what this app uses)"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
|
||||
from . import REPO, paths
|
||||
|
||||
UA = "HookshotBuilder-Setup/2.0"
|
||||
WAITS = (3, 6, 12, 20, 30, 45, 60) # (8 tries over ~3 minutes: GitHub's release downloads answered 504 for hours on 2026-11-08)
|
||||
OWN = ("python", "emsdk", "cpm", "third_party", "wgpu-native")
|
||||
|
||||
|
||||
class SetupError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Part:
|
||||
def __init__(self, sha, size, dest, frm, to, url):
|
||||
self.sha, self.size, self.dest, self.frm, self.to, self.url = sha, int(size), dest, frm, to, url
|
||||
|
||||
|
||||
def retryable(status):
|
||||
"""an answer worth trying again: none, a server error, a download cut off half way (200), a timeout or the API's rate limit"""
|
||||
return not status or status >= 500 or status in (200, 408, 429, 403)
|
||||
|
||||
|
||||
class Http:
|
||||
def __init__(self):
|
||||
self.status = 0
|
||||
|
||||
def get(self, url, sink=None, expect=0, accept=None, progress=None, cancel=None):
|
||||
"""GET following redirects (never to http); the bytes to sink, or returned. Sets self.status; raises on failure"""
|
||||
if not url.startswith("https://"):
|
||||
raise SetupError("Only https downloads are allowed: " + url)
|
||||
req = urllib.request.Request(url, headers={"User-Agent": UA, **({"Accept": accept} if accept else {})})
|
||||
self.status = 0
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
if not r.geturl().startswith("https://"):
|
||||
raise SetupError("A download was redirected away from https")
|
||||
self.status = r.status
|
||||
got, out = 0, []
|
||||
while True:
|
||||
if cancel and cancel():
|
||||
raise SetupError("cancelled")
|
||||
b = r.read(1 << 16)
|
||||
if not b:
|
||||
break
|
||||
got += len(b)
|
||||
if sink:
|
||||
sink(b)
|
||||
else:
|
||||
out.append(b)
|
||||
if progress and expect:
|
||||
progress(min(1.0, got / expect))
|
||||
if expect and got != expect:
|
||||
self.status = 200 # (cut off half way: worth another try)
|
||||
raise SetupError("The download ended early (%d of %d MB)" % (got >> 20, expect >> 20))
|
||||
return None if sink else b"".join(out)
|
||||
except urllib.error.HTTPError as e:
|
||||
self.status = e.code
|
||||
raise SetupError("GitHub returned HTTP %d" % e.code) from None
|
||||
except (urllib.error.URLError, OSError, TimeoutError) as e:
|
||||
if not isinstance(e, SetupError):
|
||||
self.status = self.status if self.status and self.status != 200 else 0
|
||||
raise SetupError("Could not reach GitHub (%s)" % getattr(e, "reason", e)) from None
|
||||
raise
|
||||
|
||||
|
||||
def api_link_for(http, url):
|
||||
"""https://github.com/<owner>/<repo>/releases/download/<tag>/<name> (or .../latest/download/<name>) -> the API's own link to
|
||||
that file, which redirects to a fresh download (GitHub's cached release links answered 504 for hours while its API answered)"""
|
||||
m = re.match(r"https://github\.com/([^/]+/[^/]+)/releases/(?:download/([^/]+)|latest/download)/([^/?]+)$", url)
|
||||
if not m:
|
||||
return None
|
||||
repo, tag, name = m.groups()
|
||||
api = "https://api.github.com/repos/%s/releases/%s" % (repo, ("tags/" + tag) if tag else "latest")
|
||||
try:
|
||||
doc = json.loads(http.get(api, accept="application/vnd.github+json"))
|
||||
for a in doc.get("assets", []):
|
||||
if a.get("name") == name and str(a.get("url", "")).startswith("https://api.github.com/"):
|
||||
return a["url"]
|
||||
except (SetupError, ValueError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def manifest_url(tag=None):
|
||||
"""(an update to a named release reads THAT release's list: the latest/download link can answer with the release before it for
|
||||
a while after a publish. HOOKSHOT_SETUP_LIST=<url>: another list, for testing a release before it is the latest)"""
|
||||
e = os.environ.get("HOOKSHOT_SETUP_LIST")
|
||||
if e:
|
||||
return e
|
||||
if tag:
|
||||
return "https://github.com/%s/releases/download/%s/hookshot-setup.txt" % (REPO, tag)
|
||||
return "https://github.com/%s/releases/latest/download/hookshot-setup.txt" % REPO
|
||||
|
||||
|
||||
def read_manifest(status, tag=None, cancel=None):
|
||||
"""(tag, parts) of the release's list, tried again on a server error or no answer"""
|
||||
http, url = Http(), manifest_url(tag)
|
||||
text, last = None, ""
|
||||
for attempt in range(len(WAITS) + 1):
|
||||
if attempt:
|
||||
status("GitHub didn't answer (%s). Trying again in %d s..." % (http.status or "no answer", WAITS[attempt - 1]))
|
||||
time.sleep(WAITS[attempt - 1])
|
||||
status("Looking for the latest Hookshot Builder...")
|
||||
try:
|
||||
text = http.get(url, cancel=cancel).decode("utf-8", "replace")
|
||||
break
|
||||
except SetupError as e:
|
||||
last = str(e)
|
||||
first = http.status
|
||||
if not first or first >= 500: # (the API's link instead)
|
||||
api = api_link_for(http, url)
|
||||
if api:
|
||||
try:
|
||||
text = http.get(api, accept="application/octet-stream", cancel=cancel).decode("utf-8", "replace")
|
||||
break
|
||||
except SetupError:
|
||||
http.status = first
|
||||
if not retryable(http.status):
|
||||
break
|
||||
if text is None:
|
||||
if http.status == 404:
|
||||
raise SetupError("The latest Hookshot release has no setup files yet. Download it from the releases page for now: "
|
||||
"https://github.com/%s/releases/latest" % REPO)
|
||||
if http.status:
|
||||
raise SetupError("GitHub's download servers are failing right now (an error 500 or above, tried 8 times over 3 minutes). "
|
||||
"This is on GitHub's side: try again in a few minutes, or later today.")
|
||||
raise SetupError("Could not reach GitHub to get the Hookshot Builder (%s). Check your internet connection and try again." % last)
|
||||
got_tag, parts = "", []
|
||||
for line in text.splitlines():
|
||||
p = line.split()
|
||||
if len(p) >= 2 and p[0] == "tag":
|
||||
got_tag = p[1]
|
||||
elif len(p) == 7 and p[0] == "part":
|
||||
parts.append(Part(*p[1:]))
|
||||
if not got_tag or not parts:
|
||||
raise SetupError("The release's setup list could not be read. Try again later.")
|
||||
if tag and tag != got_tag:
|
||||
raise SetupError("GitHub answered with the setup list of %s, not %s (its download links can lag right after a release). "
|
||||
"Try the update again in a few minutes." % (got_tag, tag))
|
||||
return got_tag, parts
|
||||
|
||||
|
||||
def part_folder(p):
|
||||
"""The folder a part unpacks into, relative to a version's folder (None: the part has none of its own)"""
|
||||
if p.to != "-" and p.dest != ".":
|
||||
return os.path.join(p.dest, p.to).replace("/", os.sep)
|
||||
b = p.url.rsplit("/", 1)[-1]
|
||||
for own in OWN:
|
||||
if b.startswith("HookshotBuilder-%s-" % own):
|
||||
return os.path.join("HookshotBuilder", "tools", own)
|
||||
return None
|
||||
|
||||
|
||||
def reuse_part(tag, p, install):
|
||||
"""A part whose checksum the installed version lists in its parts.txt (and whose folder it has) is moved over from it instead of
|
||||
downloaded: that version is deleted after the install anyway"""
|
||||
rel = part_folder(p)
|
||||
was = paths.read_small(os.path.join(paths.versions(), "current.txt"))
|
||||
if not rel or not was or was == tag:
|
||||
return False
|
||||
if p.sha not in paths.read_small(os.path.join(paths.versions(), was, "parts.txt")):
|
||||
return False
|
||||
src, dst = os.path.join(paths.versions(), was, rel), os.path.join(install, rel)
|
||||
if not os.path.exists(src):
|
||||
return False
|
||||
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
try:
|
||||
os.replace(src, dst)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def rmtree(p):
|
||||
shutil.rmtree(p, ignore_errors=True)
|
||||
|
||||
|
||||
def installed(tag):
|
||||
d = os.path.join(paths.versions(), tag)
|
||||
return d if os.path.isfile(os.path.join(d, "installed.txt")) and os.path.isfile(
|
||||
os.path.join(d, "HookshotBuilder", "tools", "nx2", "make_game.py")) else None
|
||||
|
||||
|
||||
def current():
|
||||
"""The version installed last, its folder (None: none yet)"""
|
||||
tag = paths.read_small(os.path.join(paths.versions(), "current.txt"))
|
||||
return installed(tag) if tag else None
|
||||
|
||||
|
||||
def install(status, progress=lambda f: None, tag=None, repair=False, cancel=None):
|
||||
"""Installs the release (the latest, or tag) unless it is there already; returns (tag, its folder)"""
|
||||
tag, parts = read_manifest(status, tag, cancel)
|
||||
versions, downloads = paths.versions(), os.path.join(paths.base(), "downloads")
|
||||
final = os.path.join(versions, tag)
|
||||
if repair or not installed(tag):
|
||||
work = final + ".part"
|
||||
rmtree(work)
|
||||
rmtree(final)
|
||||
os.makedirs(work, exist_ok=True)
|
||||
os.makedirs(downloads, exist_ok=True)
|
||||
n = len(parts)
|
||||
for i, p in enumerate(parts, 1):
|
||||
if cancel and cancel():
|
||||
raise SetupError("cancelled")
|
||||
if reuse_part(tag, p, work):
|
||||
status("Part %d of %d unchanged: kept from the installed version" % (i, n))
|
||||
continue
|
||||
zpath = os.path.join(downloads, p.sha + ".zip")
|
||||
if not (os.path.isfile(zpath) and sha256_file(zpath) == p.sha):
|
||||
download_part(status, progress, p, i, n, zpath, cancel)
|
||||
status("Unpacking part %d of %d..." % (i, n))
|
||||
progress(-1)
|
||||
dest = work if p.dest == "." else os.path.join(work, p.dest.replace("/", os.sep))
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
try:
|
||||
with zipfile.ZipFile(zpath) as z:
|
||||
z.extractall(dest)
|
||||
except (OSError, zipfile.BadZipFile) as e:
|
||||
raise SetupError("Unpacking part %d of %d failed: %s" % (i, n, e)) from None
|
||||
if p.frm != "-" and p.to != "-": # (llvm-mingw-<version>-ucrt-x86_64 -> llvm-mingw)
|
||||
src, dst = os.path.join(dest, p.frm), os.path.join(dest, p.to)
|
||||
if not os.path.exists(dst):
|
||||
try:
|
||||
os.replace(src, dst)
|
||||
except OSError:
|
||||
raise SetupError("Could not set up part %d of %d (renaming %s)." % (i, n, p.frm)) from None
|
||||
if not os.path.isfile(os.path.join(work, "HookshotBuilder", "tools", "nx2", "make_game.py")):
|
||||
raise SetupError("The build tools are missing after unpacking. Your antivirus may have removed them: allow the folder %s "
|
||||
"and try again." % paths.base())
|
||||
try:
|
||||
os.replace(work, final)
|
||||
except OSError:
|
||||
raise SetupError("Could not finish installing into %s." % final) from None
|
||||
paths.write_small(os.path.join(final, "installed.txt"), tag)
|
||||
write_parts(final, parts)
|
||||
elif not os.path.isfile(os.path.join(final, "parts.txt")):
|
||||
write_parts(final, parts)
|
||||
prune(tag, parts)
|
||||
rmtree(downloads) # (installed: its zips are not kept; an update moves unchanged folders over instead)
|
||||
return tag, final
|
||||
|
||||
|
||||
def download_part(status, progress, p, i, n, zpath, cancel):
|
||||
http, part = Http(), zpath + ".part"
|
||||
for attempt in range(len(WAITS) + 1):
|
||||
if attempt:
|
||||
status("Part %d of %d: GitHub didn't answer (%s). Trying again in %d s..." % (i, n, http.status or "no answer",
|
||||
WAITS[attempt - 1]))
|
||||
time.sleep(WAITS[attempt - 1])
|
||||
status("Downloading part %d of %d (%d MB)..." % (i, n, p.size >> 20))
|
||||
h = hashlib.sha256()
|
||||
try:
|
||||
with open(part, "wb") as f:
|
||||
def sink(b):
|
||||
f.write(b)
|
||||
h.update(b)
|
||||
url = api_link_for(http, p.url) if attempt % 2 == 1 else None # (the API's link, every other try)
|
||||
if url:
|
||||
http.get(url, sink, p.size, "application/octet-stream", progress, cancel)
|
||||
else:
|
||||
http.get(p.url, sink, p.size, None, progress, cancel)
|
||||
except SetupError as e:
|
||||
if str(e) == "cancelled":
|
||||
raise
|
||||
if not retryable(http.status):
|
||||
break
|
||||
continue
|
||||
except OSError:
|
||||
raise SetupError("Could not write to %s." % os.path.dirname(zpath)) from None
|
||||
progress(-1)
|
||||
if h.hexdigest() != p.sha:
|
||||
os.remove(part)
|
||||
raise SetupError("Part %d of %d did not download correctly (its checksum differs). Try again." % (i, n))
|
||||
os.replace(part, zpath)
|
||||
return
|
||||
try:
|
||||
os.remove(part)
|
||||
except OSError:
|
||||
pass
|
||||
raise SetupError(("Downloading part %d of %d failed: GitHub's download servers are failing right now (tried 8 times over 3 "
|
||||
"minutes). This is on GitHub's side. The parts already downloaded are kept: try again in a few minutes."
|
||||
if retryable(http.status) else
|
||||
"Downloading part %d of %d failed. Check your connection and free space, then try again.") % (i, n))
|
||||
|
||||
|
||||
def sha256_file(path):
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for b in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(b)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def write_parts(install_dir, parts):
|
||||
"""The checksums of the parts this version holds in folders of their own (reuse_part reads them at the next update)"""
|
||||
paths.write_small(os.path.join(install_dir, "parts.txt"), "".join(p.sha + "\n" for p in parts if part_folder(p)))
|
||||
|
||||
|
||||
def prune(tag, parts):
|
||||
"""Only the version installed stays (a folder still in use cannot be renamed: it goes at a later run), and downloads the list
|
||||
no longer names go"""
|
||||
versions = paths.versions()
|
||||
was = paths.read_small(os.path.join(versions, "current.txt"))
|
||||
if was != tag:
|
||||
if was:
|
||||
paths.write_small(os.path.join(versions, "previous.txt"), was)
|
||||
paths.write_small(os.path.join(versions, "current.txt"), tag)
|
||||
for name in os.listdir(versions):
|
||||
p = os.path.join(versions, name)
|
||||
if not os.path.isdir(p) or name == tag:
|
||||
continue
|
||||
if name.endswith(".gone"):
|
||||
rmtree(p)
|
||||
continue
|
||||
try:
|
||||
os.replace(p, p + ".gone")
|
||||
rmtree(p + ".gone")
|
||||
except OSError:
|
||||
pass
|
||||
71
builder/py/hookshot_builder/strings.py
Normal file
71
builder/py/hookshot_builder/strings.py
Normal file
@@ -0,0 +1,71 @@
|
||||
"""The builder's languages, generated by gen_strings.py from builder/HookshotBuilder/Strings.cs: one of the game's languages
|
||||
is its code in language.txt, its own name, and the app's text in it. Do not edit by hand."""
|
||||
|
||||
KEYS = ['Subtitle', 'GameFiles', 'Nup', 'Folders', 'DropHint', 'SaveTo', 'Build', 'Browse', 'Needs', 'Free', 'Checking', 'VersionOk', 'VersionBad', 'ToolsMissing', 'PythonMissing', 'Building', 'Patience', 'Elapsed', 'Read', 'Lift', 'Compile', 'Finish', 'ShowDetails', 'HideDetails', 'Cancel', 'Back', 'OpenFolder', 'Play', 'Ready', 'BuiltIn', 'Stopped', 'Cancelled', 'CancelledNote', 'CloseQuestion', 'LanguageLabel', 'Download', 'Updating', 'UpdateFailed']
|
||||
|
||||
TEXT = {
|
||||
'En': ["Turns your own copy of Ocarina of Time into a game folder you can start on PC.", "Game files", ".nup file", "romfs and exefs", "You can also drop a file or folder onto this window.", "Save the game to", "Build", "Browse", "Takes about 45 minutes and needs 45 GB.", "{0} has {1} GB free.", "Checking the game version...", "This is the version Hookshot supports.", "This version isn't supported. Hookshot needs build e0f3ccfa.", "The Hookshot tools were not found next to this app.", "Python was not found.", "Building", "This takes a while, and your PC stays usable.", "Elapsed", "Reading your game files", "Translating the game to PC code", "Compiling", "Putting the game folder together", "Show details", "Hide details", "Cancel", "Back", "Open folder", "Play", "Your game is ready", "built in", "The build stopped", "Build cancelled", "You can start again from the same folder.", "Stop the build and close?", "Language", "Downloading the new version", "Updating your game", "The update could not be downloaded"],
|
||||
'Fr': ["Transforme votre copie d'Ocarina of Time en un dossier de jeu à lancer sur PC.", "Fichiers du jeu", "Fichier .nup", "romfs et exefs", "Vous pouvez aussi déposer un fichier ou un dossier sur cette fenêtre.", "Enregistrer le jeu dans", "Créer", "Parcourir", "Prend environ 45 minutes et nécessite 45 Go.", "{0} : {1} Go libres.", "Vérification de la version du jeu...", "Cette version est prise en charge par Hookshot.", "Cette version n'est pas prise en charge. Hookshot a besoin de la version e0f3ccfa.", "Les outils Hookshot sont introuvables à côté de cette application.", "Python est introuvable.", "Création en cours", "Cela prend du temps, et votre PC reste utilisable.", "Temps écoulé", "Lecture de vos fichiers de jeu", "Traduction du jeu en code PC", "Compilation", "Assemblage du dossier du jeu", "Afficher les détails", "Masquer les détails", "Annuler", "Retour", "Ouvrir le dossier", "Jouer", "Votre jeu est prêt", "créé en", "La création s'est arrêtée", "Création annulée", "Vous pouvez recommencer depuis le même dossier.", "Arrêter la création et fermer ?", "Langue"],
|
||||
'De': ["Macht aus deiner eigenen Kopie von Ocarina of Time einen Spielordner für den PC.", "Spieldateien", ".nup-Datei", "romfs und exefs", "Du kannst auch eine Datei oder einen Ordner auf dieses Fenster ziehen.", "Spiel speichern unter", "Erstellen", "Durchsuchen", "Dauert etwa 45 Minuten und benötigt 45 GB.", "{0} hat {1} GB frei.", "Spielversion wird geprüft...", "Diese Version wird von Hookshot unterstützt.", "Diese Version wird nicht unterstützt. Hookshot benötigt Build e0f3ccfa.", "Die Hookshot-Werkzeuge wurden neben dieser App nicht gefunden.", "Python wurde nicht gefunden.", "Wird erstellt", "Das dauert eine Weile, dein PC bleibt nutzbar.", "Vergangen", "Spieldateien werden gelesen", "Spiel wird in PC-Code übersetzt", "Kompilieren", "Spielordner wird zusammengestellt", "Details anzeigen", "Details ausblenden", "Abbrechen", "Zurück", "Ordner öffnen", "Spielen", "Dein Spiel ist fertig", "erstellt in", "Die Erstellung wurde angehalten", "Erstellung abgebrochen", "Du kannst im selben Ordner neu beginnen.", "Erstellung beenden und schließen?", "Sprache"],
|
||||
'It': ["Trasforma la tua copia di Ocarina of Time in una cartella di gioco da avviare su PC.", "File di gioco", "File .nup", "romfs ed exefs", "Puoi anche trascinare un file o una cartella su questa finestra.", "Salva il gioco in", "Crea", "Sfoglia", "Richiede circa 45 minuti e 45 GB.", "{0} ha {1} GB liberi.", "Controllo della versione del gioco...", "Questa versione è supportata da Hookshot.", "Questa versione non è supportata. Hookshot richiede la build e0f3ccfa.", "Gli strumenti di Hookshot non sono stati trovati accanto a questa app.", "Python non è stato trovato.", "Creazione in corso", "Ci vuole un po', e il PC resta utilizzabile.", "Trascorso", "Lettura dei file di gioco", "Traduzione del gioco in codice PC", "Compilazione", "Assemblaggio della cartella di gioco", "Mostra dettagli", "Nascondi dettagli", "Annulla", "Indietro", "Apri cartella", "Gioca", "Il tuo gioco è pronto", "creato in", "La creazione si è interrotta", "Creazione annullata", "Puoi ricominciare dalla stessa cartella.", "Interrompere la creazione e chiudere?", "Lingua"],
|
||||
'Es': ["Convierte tu copia de Ocarina of Time en una carpeta de juego para iniciar en PC.", "Archivos del juego", "Archivo .nup", "romfs y exefs", "También puedes soltar un archivo o una carpeta en esta ventana.", "Guardar el juego en", "Crear", "Examinar", "Tarda unos 45 minutos y necesita 45 GB.", "{0} tiene {1} GB libres.", "Comprobando la versión del juego...", "Hookshot admite esta versión.", "Esta versión no es compatible. Hookshot necesita la build e0f3ccfa.", "No se encontraron las herramientas de Hookshot junto a esta aplicación.", "No se encontró Python.", "Creando", "Tarda un rato, y tu PC sigue siendo utilizable.", "Transcurrido", "Leyendo tus archivos del juego", "Traduciendo el juego a código de PC", "Compilando", "Preparando la carpeta del juego", "Mostrar detalles", "Ocultar detalles", "Cancelar", "Atrás", "Abrir carpeta", "Jugar", "Tu juego está listo", "creado en", "La creación se detuvo", "Creación cancelada", "Puedes empezar de nuevo desde la misma carpeta.", "¿Detener la creación y cerrar?", "Idioma"],
|
||||
'Pt': ["Transforma sua cópia de Ocarina of Time em uma pasta de jogo para iniciar no PC.", "Arquivos do jogo", "Arquivo .nup", "romfs e exefs", "Você também pode soltar um arquivo ou uma pasta nesta janela.", "Salvar o jogo em", "Criar", "Procurar", "Leva cerca de 45 minutos e precisa de 45 GB.", "{0} tem {1} GB livres.", "Verificando a versão do jogo...", "Esta versão é compatível com o Hookshot.", "Esta versão não é compatível. O Hookshot precisa da build e0f3ccfa.", "As ferramentas do Hookshot não foram encontradas ao lado deste aplicativo.", "O Python não foi encontrado.", "Criando", "Isso leva um tempo, e seu PC continua utilizável.", "Decorrido", "Lendo seus arquivos do jogo", "Traduzindo o jogo para código de PC", "Compilando", "Montando a pasta do jogo", "Mostrar detalhes", "Ocultar detalhes", "Cancelar", "Voltar", "Abrir pasta", "Jogar", "Seu jogo está pronto", "criado em", "A criação parou", "Criação cancelada", "Você pode recomeçar a partir da mesma pasta.", "Parar a criação e fechar?", "Idioma"],
|
||||
'Nl': ["Maakt van je eigen exemplaar van Ocarina of Time een spelmap om op pc te starten.", "Spelbestanden", ".nup-bestand", "romfs en exefs", "Je kunt ook een bestand of map op dit venster slepen.", "Spel opslaan in", "Maken", "Bladeren", "Duurt ongeveer 45 minuten en vereist 45 GB.", "{0} heeft {1} GB vrij.", "Spelversie controleren...", "Deze versie wordt door Hookshot ondersteund.", "Deze versie wordt niet ondersteund. Hookshot heeft build e0f3ccfa nodig.", "De Hookshot-tools zijn niet naast deze app gevonden.", "Python is niet gevonden.", "Bezig met maken", "Dit duurt even, en je pc blijft bruikbaar.", "Verstreken", "Je spelbestanden lezen", "Spel vertalen naar pc-code", "Compileren", "Spelmap samenstellen", "Details tonen", "Details verbergen", "Annuleren", "Terug", "Map openen", "Spelen", "Je spel is klaar", "gemaakt in", "Het maken is gestopt", "Maken geannuleerd", "Je kunt opnieuw beginnen vanuit dezelfde map.", "Maken stoppen en sluiten?", "Taal"],
|
||||
'Pl': ["Zamienia Twoją kopię Ocarina of Time w folder gry, który uruchomisz na PC.", "Pliki gry", "Plik .nup", "romfs i exefs", "Możesz też upuścić plik lub folder na to okno.", "Zapisz grę w", "Utwórz", "Przeglądaj", "Trwa około 45 minut i wymaga 45 GB.", "{0}: wolne {1} GB.", "Sprawdzanie wersji gry...", "Ta wersja jest obsługiwana przez Hookshot.", "Ta wersja nie jest obsługiwana. Hookshot wymaga kompilacji e0f3ccfa.", "Nie znaleziono narzędzi Hookshot obok tej aplikacji.", "Nie znaleziono Pythona.", "Tworzenie", "To chwilę potrwa, a komputer pozostanie w użyciu.", "Upłynęło", "Odczytywanie plików gry", "Tłumaczenie gry na kod PC", "Kompilowanie", "Składanie folderu gry", "Pokaż szczegóły", "Ukryj szczegóły", "Anuluj", "Wstecz", "Otwórz folder", "Graj", "Twoja gra jest gotowa", "utworzono w", "Tworzenie zostało przerwane", "Anulowano tworzenie", "Możesz zacząć ponownie z tego samego folderu.", "Przerwać tworzenie i zamknąć?", "Język"],
|
||||
'Ru': ["Превращает вашу копию Ocarina of Time в папку с игрой для запуска на ПК.", "Файлы игры", "Файл .nup", "romfs и exefs", "Также можно перетащить файл или папку в это окно.", "Сохранить игру в", "Собрать", "Обзор", "Занимает около 45 минут и требует 45 ГБ.", "{0}: свободно {1} ГБ.", "Проверка версии игры...", "Эта версия поддерживается Hookshot.", "Эта версия не поддерживается. Hookshot нужна сборка e0f3ccfa.", "Инструменты Hookshot не найдены рядом с этим приложением.", "Python не найден.", "Сборка", "Это займёт время, а компьютером можно пользоваться.", "Прошло", "Чтение файлов игры", "Перевод игры в код для ПК", "Компиляция", "Подготовка папки с игрой", "Показать подробности", "Скрыть подробности", "Отмена", "Назад", "Открыть папку", "Играть", "Ваша игра готова", "собрано за", "Сборка остановлена", "Сборка отменена", "Можно начать заново из той же папки.", "Остановить сборку и закрыть?", "Язык"],
|
||||
'Ja': ["お持ちの Ocarina of Time を、PC で起動できるゲームフォルダーに変換します。", "ゲームファイル", ".nup ファイル", "romfs と exefs", "ファイルやフォルダーをこのウィンドウにドロップすることもできます。", "ゲームの保存先", "ビルド", "参照", "約 45 分かかり、45 GB 必要です。", "{0} の空き容量: {1} GB", "ゲームのバージョンを確認しています...", "このバージョンは Hookshot に対応しています。", "このバージョンには対応していません。Hookshot にはビルド e0f3ccfa が必要です。", "このアプリの横に Hookshot ツールが見つかりません。", "Python が見つかりません。", "ビルド中", "時間がかかりますが、PC はそのまま使えます。", "経過時間", "ゲームファイルを読み込んでいます", "ゲームを PC 用コードに変換しています", "コンパイル中", "ゲームフォルダーを作成しています", "詳細を表示", "詳細を隠す", "キャンセル", "戻る", "フォルダーを開く", "プレイ", "ゲームの準備ができました", "所要時間", "ビルドが停止しました", "ビルドをキャンセルしました", "同じフォルダーからやり直せます。", "ビルドを中止して閉じますか?", "言語"],
|
||||
'Ko': ["가지고 있는 Ocarina of Time을 PC에서 실행할 수 있는 게임 폴더로 만듭니다.", "게임 파일", ".nup 파일", "romfs 및 exefs", "파일이나 폴더를 이 창에 끌어다 놓을 수도 있습니다.", "게임 저장 위치", "빌드", "찾아보기", "약 45분이 걸리며 45GB가 필요합니다.", "{0} 여유 공간: {1}GB", "게임 버전을 확인하는 중...", "Hookshot이 지원하는 버전입니다.", "지원되지 않는 버전입니다. Hookshot에는 빌드 e0f3ccfa가 필요합니다.", "이 앱 옆에서 Hookshot 도구를 찾을 수 없습니다.", "Python을 찾을 수 없습니다.", "빌드 중", "시간이 걸리지만 PC는 계속 사용할 수 있습니다.", "경과 시간", "게임 파일을 읽는 중", "게임을 PC 코드로 변환하는 중", "컴파일 중", "게임 폴더를 만드는 중", "자세히 보기", "자세히 숨기기", "취소", "뒤로", "폴더 열기", "플레이", "게임이 준비되었습니다", "소요 시간", "빌드가 중단되었습니다", "빌드가 취소되었습니다", "같은 폴더에서 다시 시작할 수 있습니다.", "빌드를 중단하고 닫을까요?", "언어"],
|
||||
'ZhHans': ["将你自己的 Ocarina of Time 变成可在电脑上启动的游戏文件夹。", "游戏文件", ".nup 文件", "romfs 和 exefs", "也可以将文件或文件夹拖放到此窗口。", "游戏保存位置", "生成", "浏览", "大约需要 45 分钟和 45 GB 空间。", "{0} 可用空间 {1} GB。", "正在检查游戏版本...", "Hookshot 支持此版本。", "不支持此版本。Hookshot 需要构建版本 e0f3ccfa。", "在此应用旁边找不到 Hookshot 工具。", "找不到 Python。", "正在生成", "这需要一些时间,期间电脑仍可正常使用。", "已用时间", "正在读取游戏文件", "正在将游戏转换为电脑代码", "正在编译", "正在整理游戏文件夹", "显示详细信息", "隐藏详细信息", "取消", "返回", "打开文件夹", "开始游戏", "你的游戏已准备就绪", "用时", "生成已停止", "生成已取消", "你可以从同一文件夹重新开始。", "要停止生成并关闭吗?", "语言"],
|
||||
'ZhHant': ["將你自己的 Ocarina of Time 變成可在電腦上啟動的遊戲資料夾。", "遊戲檔案", ".nup 檔案", "romfs 和 exefs", "也可以將檔案或資料夾拖放到此視窗。", "遊戲儲存位置", "建置", "瀏覽", "大約需要 45 分鐘和 45 GB 空間。", "{0} 可用空間 {1} GB。", "正在檢查遊戲版本...", "Hookshot 支援此版本。", "不支援此版本。Hookshot 需要建置版本 e0f3ccfa。", "在此應用程式旁找不到 Hookshot 工具。", "找不到 Python。", "正在建置", "這需要一些時間,期間電腦仍可正常使用。", "已用時間", "正在讀取遊戲檔案", "正在將遊戲轉換為電腦程式碼", "正在編譯", "正在整理遊戲資料夾", "顯示詳細資訊", "隱藏詳細資訊", "取消", "返回", "開啟資料夾", "開始遊戲", "你的遊戲已準備就緒", "用時", "建置已停止", "建置已取消", "你可以從同一資料夾重新開始。", "要停止建置並關閉嗎?", "語言"],
|
||||
}
|
||||
|
||||
LANGUAGES = [ # (code, its own name, the TEXT it uses)
|
||||
('en-US', 'English (US)', 'En'),
|
||||
('en-GB', 'English (UK)', 'En'),
|
||||
('fr', 'Français', 'Fr'),
|
||||
('fr-CA', 'Français (Canada)', 'Fr'),
|
||||
('de', 'Deutsch', 'De'),
|
||||
('it', 'Italiano', 'It'),
|
||||
('es', 'Español (España)', 'Es'),
|
||||
('es-419', 'Español (Latinoamérica)', 'Es'),
|
||||
('pt-BR', 'Português (Brasil)', 'Pt'),
|
||||
('nl', 'Nederlands', 'Nl'),
|
||||
('pl', 'Polski', 'Pl'),
|
||||
('ru', 'Русский', 'Ru'),
|
||||
('ja', '日本語', 'Ja'),
|
||||
('ko', '한국어', 'Ko'),
|
||||
('zh-Hans', '简体中文', 'ZhHans'),
|
||||
('zh-Hant', '繁體中文', 'ZhHant'),
|
||||
]
|
||||
|
||||
|
||||
|
||||
def text(lang, key):
|
||||
"""A string in the language (a LANGUAGES entry), English where it has none (the update's lines are English only)"""
|
||||
i = KEYS.index(key)
|
||||
arr = TEXT[lang[2]]
|
||||
return arr[i] if i < len(arr) else TEXT["En"][i]
|
||||
|
||||
|
||||
def default_language():
|
||||
"""The language closest to Windows' own: the exact one, then the same family, else English (US)"""
|
||||
name = ""
|
||||
try:
|
||||
import ctypes
|
||||
buf = ctypes.create_unicode_buffer(85)
|
||||
if ctypes.windll.kernel32.GetUserDefaultLocaleName(buf, 85):
|
||||
name = buf.value
|
||||
except Exception:
|
||||
pass
|
||||
for lang in LANGUAGES:
|
||||
if lang[0].lower() == name.lower():
|
||||
return lang
|
||||
if name.startswith("zh"):
|
||||
pick = "zh-Hant" if any(t in name for t in ("TW", "HK", "Hant")) else "zh-Hans"
|
||||
elif name.startswith("es-") and name != "es-ES":
|
||||
pick = "es-419"
|
||||
elif name.startswith("pt"):
|
||||
pick = "pt-BR"
|
||||
else:
|
||||
pick = name.split("-")[0]
|
||||
return next((lang for lang in LANGUAGES if lang[0] == pick), LANGUAGES[0])
|
||||
461
builder/py/hookshot_builder/theme.py
Normal file
461
builder/py/hookshot_builder/theme.py
Normal file
@@ -0,0 +1,461 @@
|
||||
"""The WPF builder's App.xaml in Qt: the Slate palette, the Inter fonts, and the controls drawn as its templates draw them (the same
|
||||
sizes, radii, colours, glows and hover states)."""
|
||||
import math
|
||||
import os
|
||||
|
||||
from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal
|
||||
from PySide6.QtGui import QBrush, QColor, QFont, QFontDatabase, QLinearGradient, QPainter, QPainterPath, QPen
|
||||
from PySide6.QtWidgets import (QAbstractButton, QComboBox, QFrame, QGraphicsDropShadowEffect, QLabel, QLineEdit, QListView,
|
||||
QSizePolicy, QStyledItemDelegate, QWidget)
|
||||
|
||||
from . import paths
|
||||
|
||||
|
||||
def argb(s):
|
||||
"""#AARRGGBB or #RRGGBB, as WPF writes them"""
|
||||
s = s.lstrip("#")
|
||||
if len(s) == 8:
|
||||
return QColor(int(s[2:4], 16), int(s[4:6], 16), int(s[6:8], 16), int(s[0:2], 16))
|
||||
return QColor(int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16))
|
||||
|
||||
|
||||
C = {k: argb(v) for k, v in {
|
||||
"Page": "#14161A", "Raised": "#1C1F24", "RaisedHover": "#23272D", "Line": "#2C3037", "LineStrong": "#3D434C",
|
||||
"Ink": "#EDEFF2", "InkSoft": "#A2A9B3", "InkFaint": "#6E7681", "Brand": "#3D63E6", "BrandHover": "#4B70F0",
|
||||
"BrandInk": "#DFE6FF", "Go": "#5FB08A", "GoHover": "#70C09A", "GoInk": "#06150E", "Warn": "#E2B86B", "Bad": "#E2776B",
|
||||
"Glass": "#0DFFFFFF", "GlassHover": "#17FFFFFF", "GlassLine": "#17FFFFFF", "GlassLineStrong": "#2AFFFFFF",
|
||||
"GoSoft": "#265FB08A", "BadSoft": "#26E2776B", "WarnSoft": "#1FE2B86B", "BrandSoft": "#333D63E6", "White": "#FFFFFF",
|
||||
}.items()}
|
||||
|
||||
UI = "Inter"
|
||||
MONO = "Cascadia Mono"
|
||||
W_MEDIUM, W_SEMIBOLD, W_BOLD = QFont.Weight.Medium, QFont.Weight.DemiBold, QFont.Weight.Bold
|
||||
|
||||
|
||||
def load_fonts():
|
||||
global MONO
|
||||
for f in ("Inter-Regular.ttf", "Inter-Medium.ttf", "Inter-SemiBold.ttf", "Inter-Bold.ttf"):
|
||||
QFontDatabase.addApplicationFont(os.path.join(paths.ASSETS, "Fonts", f))
|
||||
if MONO not in QFontDatabase.families():
|
||||
MONO = "Consolas"
|
||||
|
||||
|
||||
def font(size=14, weight=QFont.Weight.Normal, family=None):
|
||||
f = QFont(family or UI)
|
||||
f.setPixelSize(int(size))
|
||||
f.setWeight(weight)
|
||||
f.setHintingPreference(QFont.HintingPreference.PreferNoHinting) # (WPF's Ideal text formatting)
|
||||
f.setStyleStrategy(QFont.StyleStrategy.PreferAntialias)
|
||||
return f
|
||||
|
||||
|
||||
def css(c):
|
||||
return "rgba(%d,%d,%d,%d)" % (c.red(), c.green(), c.blue(), c.alpha())
|
||||
|
||||
|
||||
def label(text="", size=14, weight=QFont.Weight.Normal, color="Ink", wrap=False, mono=False):
|
||||
l = QLabel(text)
|
||||
l.setFont(font(size, weight, MONO if mono else None))
|
||||
set_color(l, color)
|
||||
l.setWordWrap(wrap)
|
||||
l.setTextInteractionFlags(Qt.TextInteractionFlag.NoTextInteraction)
|
||||
l.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
return l
|
||||
|
||||
|
||||
def set_color(l, color):
|
||||
c = C[color] if isinstance(color, str) else color
|
||||
l.setStyleSheet("color: %s; background: transparent;" % css(c))
|
||||
|
||||
|
||||
# the text styles of App.xaml
|
||||
def heading(text=""):
|
||||
return label(text, 24, W_BOLD)
|
||||
|
||||
|
||||
def sub(text=""):
|
||||
l = label(text, 14, color="InkSoft", wrap=True)
|
||||
l.setContentsMargins(0, 6, 0, 0)
|
||||
return l
|
||||
|
||||
|
||||
def note(text="", size=13):
|
||||
return label(text, size, color="InkSoft", wrap=True)
|
||||
|
||||
|
||||
def faint(text="", size=12):
|
||||
return label(text, size, color="InkFaint")
|
||||
|
||||
|
||||
def section(text):
|
||||
l = label(text, 12, W_SEMIBOLD, "InkSoft")
|
||||
l.setContentsMargins(0, 24, 0, 10)
|
||||
return l
|
||||
|
||||
|
||||
def glow(widget, color, blur, depth, opacity):
|
||||
"""WPF's DropShadowEffect (Direction 270: straight down)"""
|
||||
e = QGraphicsDropShadowEffect(widget)
|
||||
c = QColor(argb(color) if isinstance(color, str) else color)
|
||||
c.setAlphaF(opacity)
|
||||
e.setColor(c)
|
||||
e.setBlurRadius(blur * 1.2)
|
||||
e.setOffset(0, depth)
|
||||
widget.setGraphicsEffect(e)
|
||||
return e
|
||||
|
||||
|
||||
def rounded(rect, r):
|
||||
p = QPainterPath()
|
||||
p.addRoundedRect(rect, r, r)
|
||||
return p
|
||||
|
||||
|
||||
class Card(QFrame):
|
||||
"""Card: Glass background, GlassLine border, corner radius 10"""
|
||||
|
||||
def __init__(self, radius=10, bg="Glass", line="GlassLine"):
|
||||
super().__init__()
|
||||
self.radius, self.bg, self.line = radius, bg, line
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
r = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
p.fillPath(rounded(r, self.radius), C[self.bg] if isinstance(self.bg, str) else self.bg)
|
||||
p.setPen(QPen(C[self.line] if isinstance(self.line, str) else self.line, 1))
|
||||
p.drawPath(rounded(r, self.radius))
|
||||
|
||||
|
||||
class Button(QAbstractButton):
|
||||
"""Quiet / Primary / GoButton / LinkButton / Link / Caption, as App.xaml's templates"""
|
||||
KINDS = {
|
||||
# kind: (height, padding x, radius, font size, weight)
|
||||
"quiet": (40, 18, 8, 14, W_SEMIBOLD), "primary": (40, 20, 8, 14, W_SEMIBOLD), "go": (50, 34, 10, 16, W_BOLD),
|
||||
"link": (None, 0, 0, 13, W_SEMIBOLD), "toggle": (None, 0, 0, 13, QFont.Weight.Normal), "caption": (36, 0, 8, 12, QFont.Weight.Normal),
|
||||
}
|
||||
|
||||
def __init__(self, text="", kind="quiet", icon=None, color=None, size=None):
|
||||
super().__init__()
|
||||
self._glow = None
|
||||
self.kind, self.icon, self.hover, self._color = kind, icon, False, color
|
||||
h, self.padx, self.radius, fs, fw = self.KINDS[kind]
|
||||
self.setFont(font(size or fs, fw))
|
||||
self.setText(text)
|
||||
self.setCursor(Qt.CursorShape.PointingHandCursor if kind != "caption" else Qt.CursorShape.ArrowCursor)
|
||||
self.setFocusPolicy(Qt.FocusPolicy.TabFocus if kind in ("quiet", "primary", "go") else Qt.FocusPolicy.NoFocus)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
self.fixed_h = h
|
||||
if kind == "caption":
|
||||
self.setFixedSize(46, 36)
|
||||
self._glow = None
|
||||
if kind == "primary":
|
||||
self._glow = glow(self, "#3D63E6", 22, 6, 0.55)
|
||||
elif kind == "go":
|
||||
self._glow = glow(self, "#5FB08A", 30, 8, 0.5)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
|
||||
|
||||
def setText(self, t):
|
||||
super().setText(t)
|
||||
self.updateGeometry()
|
||||
self.update()
|
||||
|
||||
def set_color(self, color):
|
||||
self._color = color
|
||||
self.update()
|
||||
|
||||
def sizeHint(self):
|
||||
fm = self.fontMetrics()
|
||||
w = fm.horizontalAdvance(self.text())
|
||||
if self.icon == "play":
|
||||
w += 21
|
||||
if self.kind in ("link", "toggle"):
|
||||
return QSize(w + 1, fm.height() + 2)
|
||||
if self.kind == "caption":
|
||||
return QSize(46, 36)
|
||||
return QSize(w + 2 * self.padx + 2, self.fixed_h)
|
||||
|
||||
def enterEvent(self, e):
|
||||
self.hover = True
|
||||
self.update()
|
||||
|
||||
def leaveEvent(self, e):
|
||||
self.hover = False
|
||||
self.update()
|
||||
|
||||
def changeEvent(self, e):
|
||||
if self._glow is not None:
|
||||
self._glow.setEnabled(self.isEnabled())
|
||||
super().changeEvent(e)
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
p.setRenderHint(QPainter.RenderHint.TextAntialiasing)
|
||||
r = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
k, on, hov, focus = self.kind, self.isEnabled(), self.hover and self.isEnabled(), self.hasFocus()
|
||||
ink = C["Ink"]
|
||||
if k == "quiet":
|
||||
bg = C["GlassHover"] if hov else argb("#08FFFFFF")
|
||||
line = C["BrandHover"] if focus else C["GlassLineStrong"] if hov else argb("#1FFFFFFF")
|
||||
p.fillPath(rounded(r, 8), bg)
|
||||
p.setPen(QPen(line, 1))
|
||||
p.drawPath(rounded(r, 8))
|
||||
ink = C["Ink"] if on else C["InkFaint"]
|
||||
elif k == "primary":
|
||||
bg = (C["BrandHover"] if hov else C["Brand"]) if on else argb("#14FFFFFF")
|
||||
p.fillPath(rounded(r, 8), bg)
|
||||
p.setPen(QPen(argb("#AAFFFFFF") if focus else argb("#33FFFFFF"), 1))
|
||||
p.drawPath(rounded(r, 8))
|
||||
ink = C["White"] if on else C["InkFaint"]
|
||||
elif k == "go":
|
||||
p.fillPath(rounded(r, 10), C["GoHover"] if hov else C["Go"])
|
||||
p.setPen(QPen(argb("#40FFFFFF"), 1))
|
||||
p.drawPath(rounded(r, 10))
|
||||
ink = C["GoInk"]
|
||||
elif k == "link":
|
||||
ink = C["White"] if hov else (self._color or C["BrandInk"])
|
||||
elif k == "toggle":
|
||||
ink = C["Ink"] if hov else (self._color or C["InkSoft"])
|
||||
elif k == "caption":
|
||||
if self.hover:
|
||||
p.fillPath(rounded(r, 8), C["GlassHover"])
|
||||
ink = C["Ink"] if self.hover else argb("#80FFFFFF")
|
||||
p.setPen(QPen(ink, 1.2 if self.icon == "close" else 1))
|
||||
cx, cy = self.width() / 2, self.height() / 2
|
||||
if self.icon == "min":
|
||||
p.fillRect(QRectF(cx - 5, cy, 10, 1), ink)
|
||||
else:
|
||||
p.drawLine(QPointF(cx - 5, cy - 5), QPointF(cx + 5, cy + 5))
|
||||
p.drawLine(QPointF(cx + 5, cy - 5), QPointF(cx - 5, cy + 5))
|
||||
return
|
||||
p.setFont(self.font())
|
||||
p.setPen(ink)
|
||||
fm = self.fontMetrics()
|
||||
tw = fm.horizontalAdvance(self.text())
|
||||
if self.icon == "play": # (the triangle M0,0 L11,7 L0,14, 10 px before the text)
|
||||
total = 11 + 10 + tw
|
||||
x0 = (self.width() - total) / 2
|
||||
tri = QPainterPath()
|
||||
cy = self.height() / 2
|
||||
tri.moveTo(x0, cy - 7)
|
||||
tri.lineTo(x0 + 11, cy)
|
||||
tri.lineTo(x0, cy + 7)
|
||||
tri.closeSubpath()
|
||||
p.fillPath(tri, ink)
|
||||
p.drawText(QRectF(x0 + 21, 0, tw + 2, self.height()), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, self.text())
|
||||
return
|
||||
align = Qt.AlignmentFlag.AlignCenter if k in ("quiet", "primary", "go") else Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
|
||||
p.drawText(QRectF(self.rect()), align, self.text())
|
||||
|
||||
|
||||
class Tick(QAbstractButton):
|
||||
"""CheckBox Tick: an 18x18 box, radius 5, its mark when checked, the text in InkSoft 13"""
|
||||
|
||||
def __init__(self, text, checked=False):
|
||||
super().__init__()
|
||||
self.setCheckable(True)
|
||||
self.setChecked(checked)
|
||||
self.setText(text)
|
||||
self.setFont(font(13))
|
||||
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||
|
||||
def sizeHint(self):
|
||||
return QSize(26 + self.fontMetrics().horizontalAdvance(self.text()) + 2, max(18, self.fontMetrics().height()))
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
y = (self.height() - 18) / 2
|
||||
box = QRectF(0.75, y + 0.75, 16.5, 16.5)
|
||||
if self.isChecked():
|
||||
p.fillPath(rounded(box, 5), C["Brand"])
|
||||
p.setPen(QPen(C["Brand"], 1.5))
|
||||
p.drawPath(rounded(box, 5))
|
||||
p.setPen(QPen(C["White"], 2))
|
||||
path = QPainterPath(QPointF(2, y + 8))
|
||||
path.lineTo(6, y + 12)
|
||||
path.lineTo(14, y + 3)
|
||||
p.drawPath(path)
|
||||
else:
|
||||
p.setPen(QPen(argb("#40FFFFFF"), 1.5))
|
||||
p.drawPath(rounded(box, 5))
|
||||
p.setFont(self.font())
|
||||
p.setPen(C["InkSoft"])
|
||||
p.drawText(QRectF(26, 0, self.width() - 26, self.height()), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
|
||||
self.text())
|
||||
|
||||
|
||||
class Bar(QWidget):
|
||||
"""ProgressBar Bar: 6 high, track #12FFFFFF, the indicator in Foreground, both radius 3"""
|
||||
|
||||
def __init__(self, color="Brand", width=None):
|
||||
super().__init__()
|
||||
self.value, self.color = 0.0, color
|
||||
self.setFixedHeight(6)
|
||||
if width:
|
||||
self.setFixedWidth(width)
|
||||
|
||||
def set(self, v, color=None):
|
||||
self.value = max(0.0, min(1.0, v))
|
||||
if color:
|
||||
self.color = color
|
||||
self.update()
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
r = QRectF(self.rect())
|
||||
p.fillPath(rounded(r, 3), argb("#12FFFFFF"))
|
||||
if self.value > 0:
|
||||
p.fillPath(rounded(QRectF(0, 0, r.width() * self.value, r.height()), 3), C[self.color])
|
||||
|
||||
|
||||
class Chip(QLabel):
|
||||
"""Border Chip: 26 high, radius 13, #0DFFFFFF with #14FFFFFF, 10 px each side"""
|
||||
|
||||
def __init__(self, text, color, soft=None):
|
||||
super().__init__(text)
|
||||
self.setFont(font(12))
|
||||
self.soft = soft
|
||||
self.setStyleSheet("color: %s; background: transparent; padding: 0 10px;" % css(C[color]))
|
||||
self.setFixedHeight(26)
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
r = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
p.fillPath(rounded(r, 13), C[self.soft] if self.soft else argb("#0DFFFFFF"))
|
||||
p.setPen(QPen(argb("#14FFFFFF"), 1))
|
||||
p.drawPath(rounded(r, 13))
|
||||
p.end()
|
||||
super().paintEvent(e)
|
||||
|
||||
|
||||
class PathEdit(QLineEdit):
|
||||
"""TextBox Path: mono 12 in InkSoft, Glass with GlassLine (Brand when focused), radius 8, 40 high"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.setFont(font(12, family=MONO))
|
||||
self.setFixedHeight(40)
|
||||
self.setStyleSheet(
|
||||
"QLineEdit { color: %s; background: %s; border: 1px solid %s; border-radius: 8px; padding: 0 11px;"
|
||||
" selection-background-color: %s; }"
|
||||
"QLineEdit:focus { border-color: %s; }" % (css(C["InkSoft"]), css(C["Glass"]), css(C["GlassLine"]), css(C["Brand"]),
|
||||
css(C["Brand"])))
|
||||
|
||||
|
||||
class _ItemDelegate(QStyledItemDelegate):
|
||||
"""ComboBoxItem ChoiceItem: radius 6, 10/7 padding, RaisedHover under the mouse, BrandInk when chosen"""
|
||||
|
||||
def __init__(self, combo):
|
||||
super().__init__(combo)
|
||||
self.combo = combo
|
||||
|
||||
def sizeHint(self, opt, idx):
|
||||
return QSize(opt.rect.width(), 7 + 7 + opt.fontMetrics.height())
|
||||
|
||||
def paint(self, p, opt, idx):
|
||||
from PySide6.QtWidgets import QStyle
|
||||
p.save()
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
if opt.state & QStyle.StateFlag.State_MouseOver or opt.state & QStyle.StateFlag.State_Selected:
|
||||
p.fillPath(rounded(QRectF(opt.rect), 6), C["RaisedHover"])
|
||||
p.setFont(font(13))
|
||||
p.setPen(C["BrandInk"] if idx.row() == self.combo.currentIndex() else C["Ink"])
|
||||
p.drawText(QRectF(opt.rect).adjusted(10, 0, -10, 0), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
|
||||
idx.data())
|
||||
p.restore()
|
||||
|
||||
|
||||
class Choice(QComboBox):
|
||||
"""ComboBox Choice: 40 high, #08FFFFFF with #1FFFFFFF (GlassHover under the mouse), radius 8, its chevron; the list in Raised
|
||||
with LineStrong, radius 8, padding 4"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.setFixedHeight(40)
|
||||
self.setFont(font(13))
|
||||
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.hover = False
|
||||
v = QListView()
|
||||
v.setItemDelegate(_ItemDelegate(self))
|
||||
v.setMouseTracking(True)
|
||||
self.setView(v)
|
||||
self.setStyleSheet(
|
||||
"QComboBox { background: transparent; border: none; color: %s; }"
|
||||
"QComboBox::drop-down { width: 0; border: none; } QComboBox::down-arrow { image: none; }"
|
||||
"QComboBox QAbstractItemView { background: %s; border: 1px solid %s; border-radius: 8px; padding: 4px; outline: none;"
|
||||
" color: %s; }" % (css(C["Ink"]), css(C["Raised"]), css(C["LineStrong"]), css(C["Ink"])))
|
||||
self.view().window().setWindowFlags(Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint |
|
||||
Qt.WindowType.NoDropShadowWindowHint)
|
||||
self.view().window().setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
|
||||
def enterEvent(self, e):
|
||||
self.hover = True
|
||||
self.update()
|
||||
|
||||
def leaveEvent(self, e):
|
||||
self.hover = False
|
||||
self.update()
|
||||
|
||||
def showPopup(self):
|
||||
super().showPopup()
|
||||
w = self.view().window() # (4 px below the box, as WPF's Popup margin)
|
||||
w.move(w.x(), self.mapToGlobal(self.rect().bottomLeft()).y() + 4)
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
r = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
p.fillPath(rounded(r, 8), C["GlassHover"] if self.hover else argb("#08FFFFFF"))
|
||||
p.setPen(QPen(C["Brand"], 2) if self.hasFocus() and self.property("focus_ring") else QPen(argb("#1FFFFFFF"), 1))
|
||||
p.drawPath(rounded(r, 8))
|
||||
p.setPen(QPen(C["InkSoft"], 1.3))
|
||||
x, y = self.width() - 12 - 8, self.height() / 2 - 2
|
||||
path = QPainterPath(QPointF(x, y))
|
||||
path.lineTo(x + 4, y + 4)
|
||||
path.lineTo(x + 8, y)
|
||||
p.drawPath(path)
|
||||
p.setFont(self.font())
|
||||
p.setPen(C["Ink"])
|
||||
p.drawText(QRectF(12, 0, self.width() - 40, self.height()), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
|
||||
self.currentText())
|
||||
|
||||
|
||||
class Ring(QWidget):
|
||||
"""The build's ring: a #14FFFFFF circle of 10, the Brand arc over it (round caps), the percent in the middle"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.setFixedSize(120, 120)
|
||||
self.f = 0.0
|
||||
|
||||
def set(self, f):
|
||||
self.f = max(0.0, min(1.0, f))
|
||||
self.update()
|
||||
|
||||
def paintEvent(self, e):
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
p.setPen(QPen(argb("#14FFFFFF"), 10))
|
||||
p.drawEllipse(QRectF(5, 5, 110, 110))
|
||||
if self.f >= 0.002:
|
||||
pen = QPen(C["Brand"], 10)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
p.setPen(pen)
|
||||
p.drawArc(QRectF(5, 5, 110, 110), 90 * 16, -int(self.f * 360 * 16))
|
||||
p.setPen(C["Ink"])
|
||||
p.setFont(font(24, W_BOLD))
|
||||
p.drawText(QRectF(self.rect()), Qt.AlignmentFlag.AlignCenter, "%d%%" % int(self.f * 100))
|
||||
|
||||
|
||||
def tick_path(cx, cy):
|
||||
"""M0,4 L3.5,7.5 L10,0, centred on (cx, cy)"""
|
||||
path = QPainterPath(QPointF(cx - 5, cy))
|
||||
path.lineTo(cx - 1.5, cy + 3.5)
|
||||
path.lineTo(cx + 5, cy - 4)
|
||||
return path
|
||||
111
builder/py/hookshot_builder/updater.py
Normal file
111
builder/py/hookshot_builder/updater.py
Normal file
@@ -0,0 +1,111 @@
|
||||
"""The game's update offer and the builder's own (Updater.cs, the same rules). The game (host/hos_update.c) starts this app with
|
||||
--update <game folder> --tag <release>. When these tools are not that release, the release is installed (setup_parts: only the
|
||||
parts that changed are downloaded) and this app starts again on it with --fetched to build the folder; when they are, the folder is
|
||||
built again here (nx2/make_game.py --update: from the game files the folder keeps)."""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
from . import REPO, paths, setup_parts
|
||||
from .core import Tools
|
||||
|
||||
LATEST = "https://api.github.com/repos/%s/releases/latest" % REPO
|
||||
|
||||
|
||||
def latest_tag():
|
||||
"""The latest release's tag, quietly (None: GitHub did not answer); a few tries, 20 s at most"""
|
||||
if os.environ.get("HOOKSHOT_LATEST_TAG"): # (development: a made-up latest release, "none" for no answer)
|
||||
t = os.environ["HOOKSHOT_LATEST_TAG"]
|
||||
return None if t == "none" else t
|
||||
for attempt in range(3):
|
||||
try:
|
||||
req = urllib.request.Request(LATEST, headers={"User-Agent": "HookshotBuilder", "Accept": "application/vnd.github+json"})
|
||||
with urllib.request.urlopen(req, timeout=8) as r:
|
||||
return json.loads(r.read()).get("tag_name")
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code < 500: # (the API's limit, 60 an hour a PC: the list below instead)
|
||||
break
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
time.sleep(2 << attempt)
|
||||
# (v2.0.0: when the API did not answer, the builder said a game was up to date. The release's setup list names its tag in its
|
||||
# first line, from GitHub's download service, not the API)
|
||||
for _ in range(2):
|
||||
try:
|
||||
req = urllib.request.Request(setup_parts.manifest_url(), headers={"User-Agent": "HookshotBuilder"})
|
||||
with urllib.request.urlopen(req, timeout=8) as r:
|
||||
for line in r.read().decode("utf-8", "replace").splitlines():
|
||||
if line.startswith("tag "):
|
||||
return line[4:].strip()
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(2)
|
||||
return None
|
||||
|
||||
|
||||
def restart(args):
|
||||
"""This app started again (on the version just installed: hookshot_builder_start.py picks it) with args, and this one closes"""
|
||||
exe, base_args = paths.launcher_command()
|
||||
subprocess.Popen([exe, *base_args, *args], cwd=os.path.dirname(exe))
|
||||
|
||||
|
||||
class Install:
|
||||
"""The release installed on a worker thread; ui is the window (note, download_progress, download_failed, and done(tag) called
|
||||
on the window's thread through ui.post)"""
|
||||
|
||||
def __init__(self, ui, tag=None, then=None):
|
||||
self.ui, self.tag, self.then, self.cancelled = ui, tag, then, False
|
||||
|
||||
def start(self):
|
||||
threading.Thread(target=self._run, daemon=True).start()
|
||||
return self
|
||||
|
||||
def cancel(self):
|
||||
self.cancelled = True
|
||||
|
||||
def _run(self):
|
||||
post = self.ui.post
|
||||
try:
|
||||
tag, _ = setup_parts.install(lambda s: post(self.ui.note, s), lambda f: post(self.ui.download_progress, f) if f >= 0 else None,
|
||||
tag=self.tag, cancel=lambda: self.cancelled)
|
||||
post(self.then, tag)
|
||||
except setup_parts.SetupError as e:
|
||||
msg = str(e)
|
||||
post(self.ui.download_failed, "The download was cancelled. Your game folder is unchanged." if msg == "cancelled" else
|
||||
msg + " Your game folder is unchanged.")
|
||||
except Exception as e: # (anything else: said, not a silent window)
|
||||
post(self.ui.download_failed, "%s. Your game folder is unchanged." % e)
|
||||
|
||||
|
||||
def update_folder(ui, folder, tag, fetched):
|
||||
"""The game in folder built again with the latest release: here when these tools are it (or fetched), else after installing it
|
||||
(this app then starts again on it with --update folder --tag t --fetched)"""
|
||||
ui.begin_update(folder, tag)
|
||||
tools = Tools.find()
|
||||
# (just installed, but another release than asked for: GitHub's latest link lags right after a publish)
|
||||
if fetched and tag and tools and tools.version and tools.version != tag:
|
||||
ui.download_failed("The update installed %s, not %s: GitHub's download links can lag right after a release. Try Update again "
|
||||
"in a few minutes." % (tools.version, tag))
|
||||
return
|
||||
if tools and (fetched or (tag and tools.version == tag)):
|
||||
ui.update_build(tools, folder)
|
||||
return
|
||||
ui.note("Asking GitHub for the latest release")
|
||||
|
||||
def installed(new_tag):
|
||||
restart(["--update", folder, "--tag", new_tag, "--fetched"])
|
||||
ui.quit_app()
|
||||
ui.download = Install(ui, tag, installed).start()
|
||||
|
||||
|
||||
def run_latest_setup(ui):
|
||||
"""The latest release installed, then this app started again on it (the builder's own update)"""
|
||||
ui.note("Asking GitHub for the latest release")
|
||||
|
||||
def installed(_tag):
|
||||
restart([])
|
||||
ui.quit_app()
|
||||
ui.download = Install(ui, None, installed).start()
|
||||
1812
builder/py/hookshot_builder/window.py
Normal file
1812
builder/py/hookshot_builder/window.py
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user