diff --git a/examples/hand_gallery/.gitignore b/examples/hand_gallery/.gitignore new file mode 100644 index 00000000..1da3bddd --- /dev/null +++ b/examples/hand_gallery/.gitignore @@ -0,0 +1,2 @@ +.runtime/ +__pycache__/ diff --git a/examples/hand_gallery/README.md b/examples/hand_gallery/README.md new file mode 100644 index 00000000..2961f232 --- /dev/null +++ b/examples/hand_gallery/README.md @@ -0,0 +1,17 @@ +# 两款灵巧手的本地选择菜单 + +从仓库根目录启动: + +```sh +python3 examples/hand_gallery/launch.py +``` + +- `http://127.0.0.1:8764/`:选择菜单。 +- `http://127.0.0.1:8764/hands/codex`:Codex 的 LH20。 +- `http://127.0.0.1:8764/hands/claude`:Claude 的 20 自由度灵巧手。 + +顶部菜单可随时切换;浏览器前进、后退和直接刷新路由均支持。已经打开的编辑器保留在各自 iframe 中,切换不会触发整手重新构建。右上角可将当前编辑器放到独立窗口。 + +启动器检查现有服务的工作区,复用匹配的 8765 / 8771 编辑器;未启动时使用 `.venv/bin/sca` / `.venv-hand/bin/sca` 启动相应 `hand.py`。遇到无关服务占用端口会报错,不终止其他进程。菜单只绑定本机地址;预览图直接读取两个项目已有的 CAD 渲染结果。 + +`models.py` 管理模型路径与端口,`server.py` 提供只读状态与固定资源路由,`web/` 实现页面;无需新增依赖。日志和 PID 位于忽略提交的 `.runtime/`。本菜单不修改任一 CAD 模型或 SDK 源码。 diff --git a/examples/hand_gallery/launch.py b/examples/hand_gallery/launch.py new file mode 100644 index 00000000..e04966e0 --- /dev/null +++ b/examples/hand_gallery/launch.py @@ -0,0 +1,61 @@ +"""Start missing editors and the menu; reuse already running matching services.""" + +import json +import socket +import subprocess +import sys +from urllib.request import urlopen + +from models import HERE, HOST, MODELS, PORT, ROOT, editor_url +from server import status + + +def port_available(port): + with socket.socket() as sock: + try: + sock.bind((HOST, port)) + except OSError: + return False + return True + + +def spawn(name, args): + runtime = HERE / ".runtime" + runtime.mkdir(exist_ok=True) + with (runtime / f"{name}.log").open("a") as log: + process = subprocess.Popen( + args, cwd=ROOT, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True, + ) + (runtime / f"{name}.pid").write_text(str(process.pid)) + print(f"Started {name}: PID {process.pid}") + + +def main(): + for key, model in MODELS.items(): + state = status(key, model)["state"] + if state in ("online", "loading"): + print(f"Reusing {model['name']}: {editor_url(model)}") + continue + if state == "mismatch" or not port_available(model["port"]): + raise SystemExit(f"Port {model['port']} belongs to another service; left unchanged.") + if not model["executable"].is_file() or not (model["workspace"] / "hand.py").is_file(): + raise SystemExit(f"Missing editor or hand.py for {model['name']}.") + spawn(key, [str(model["executable"]), "edit", str(model["workspace"] / "hand.py"), + "--host", HOST, "--port", str(model["port"]), "--no-browser"]) + if port_available(PORT): + spawn("menu", [sys.executable, str(HERE / "server.py")]) + else: + try: + with urlopen(f"http://{HOST}:{PORT}/api/health", timeout=2) as response: + health = json.load(response) + if health.get("service") != "simplecad-hand-gallery": + raise ValueError("Different service") + except (OSError, ValueError) as error: + raise SystemExit(f"Port {PORT} is occupied; left unchanged: {error}") from error + print("Reusing hand selector") + print(f"Open http://{HOST}:{PORT}/") + + +if __name__ == "__main__": + main() diff --git a/examples/hand_gallery/models.py b/examples/hand_gallery/models.py new file mode 100644 index 00000000..4433ac0a --- /dev/null +++ b/examples/hand_gallery/models.py @@ -0,0 +1,28 @@ +"""The two existing hand workspaces; no CAD source is copied or modified.""" + +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +HOST = "127.0.0.1" +PORT = 8764 +MODELS = { + "codex": { + "name": "LH20 · Codex", + "workspace": ROOT / "examples/lh20_hand", + "executable": ROOT / ".venv/bin/sca", + "port": 8765, + "preview": ROOT / "examples/lh20_hand/out/lh20_right_hand_overview.png", + }, + "claude": { + "name": "20 自由度灵巧手 · Claude", + "workspace": ROOT / "examples/dexterous_hand_20dof", + "executable": ROOT / ".venv-hand/bin/sca", + "port": 8771, + "preview": ROOT / "examples/dexterous_hand_20dof/out/renders/hand_open_iso.png", + }, +} + + +def editor_url(model): + return f"http://{HOST}:{model['port']}" diff --git a/examples/hand_gallery/server.py b/examples/hand_gallery/server.py new file mode 100644 index 00000000..5beb20c0 --- /dev/null +++ b/examples/hand_gallery/server.py @@ -0,0 +1,77 @@ +"""Loopback-only hand selector, with independent editors kept in iframes.""" + +from concurrent.futures import ThreadPoolExecutor +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.error import URLError +from urllib.parse import urlsplit +from urllib.request import urlopen +import json +import mimetypes + +from models import HERE, HOST, MODELS, PORT, editor_url + + +def status(key, model): + row = {"id": key, "name": model["name"], "url": editor_url(model)} + try: + with urlopen(row["url"] + "/api/health", timeout=2) as response: + health = json.load(response) + correct = ( + health.get("ok") is True + and Path(health.get("workspace", "")).resolve() == model["workspace"].resolve() + ) + row.update( + state=("online" if health.get("kernel") else "loading") if correct else "mismatch", + notebook=health.get("notebook") if correct else None, + ) + except (OSError, URLError, ValueError, TypeError): + row["state"] = "offline" + return row + + +class Handler(BaseHTTPRequestHandler): + def send(self, code, data, content_type, head=False): + self.send_response(code) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.send_header("Cache-Control", "no-store") + self.send_header("X-Content-Type-Options", "nosniff") + self.end_headers() + if not head: + self.wfile.write(data) + + def do_HEAD(self): + self.do_GET(head=True) + + def do_GET(self, head=False): + path = urlsplit(self.path).path.rstrip("/") or "/" + if path == "/api/health": + payload = {"ok": True, "service": "simplecad-hand-gallery"} + elif path == "/api/models": + with ThreadPoolExecutor(max_workers=2) as pool: + rows = list(pool.map(lambda item: status(*item), MODELS.items())) + payload = {"models": rows} + else: + payload = None + if payload is not None: + self.send(200, json.dumps(payload, ensure_ascii=False).encode(), "application/json; charset=utf-8", head) + return + routes = { + "/": HERE / "web/index.html", + **{f"/hands/{key}": HERE / "web/index.html" for key in MODELS}, + "/assets/app.js": HERE / "web/app.js", + "/assets/style.css": HERE / "web/style.css", + **{f"/previews/{key}.png": model["preview"] for key, model in MODELS.items()}, + } + file = routes.get(path) + if file is None or not file.is_file(): + self.send(404, b"Not found", "text/plain; charset=utf-8", head) + return + mime = mimetypes.guess_type(file.name)[0] or "application/octet-stream" + self.send(200, file.read_bytes(), mime + ("; charset=utf-8" if mime.startswith("text/") else ""), head) + + +if __name__ == "__main__": + print(f"Hand selector: http://{HOST}:{PORT}", flush=True) + ThreadingHTTPServer((HOST, PORT), Handler).serve_forever() diff --git a/examples/hand_gallery/web/app.js b/examples/hand_gallery/web/app.js new file mode 100644 index 00000000..b065b3f1 --- /dev/null +++ b/examples/hand_gallery/web/app.js @@ -0,0 +1,84 @@ +const models = { + codex: { name: "LH20 · Codex", url: "http://127.0.0.1:8765", state: "checking" }, + claude: { name: "20 自由度灵巧手 · Claude", url: "http://127.0.0.1:8771", state: "checking" }, +}; +const labels = { online: "编辑器已连接", loading: "编辑器启动中", offline: "编辑器未启动", mismatch: "端口对应其他项目", checking: "检查连接中", unavailable: "暂时无法检查连接" }; +const frames = new Map(); +let active = null; + +function updateStatus() { + document.querySelectorAll("[data-status]").forEach((badge) => { + const state = models[badge.dataset.status].state; + badge.textContent = labels[state]; + badge.className = `status ${state}`; + }); + if (!active) return; + const model = models[active]; + const badge = document.querySelector("#workspace-status"); + badge.textContent = labels[model.state]; + badge.className = `status ${model.state}`; + const notice = document.querySelector("#connection-notice"); + notice.hidden = ["online", "checking"].includes(model.state); + notice.textContent = model.state === "mismatch" + ? "这个端口当前对应其他项目,请先检查编辑器服务。" + : model.state === "loading" + ? "编辑器正在启动,首次构建可能需要一些时间。" + : "暂时无法连接此编辑器。重新启动工作台后会自动连接,也可以使用右侧的独立窗口链接。"; + // Create each editor only after verifying its workspace. Keep existing frames + // mounted so switching does not discard camera or in-progress editor state. + if (model.state === "online" && !frames.has(active)) { + const frame = document.createElement("iframe"); + frame.title = `${model.name} 模型编辑器`; + frame.src = model.url; + frame.dataset.model = active; + document.querySelector("#editors").append(frame); + frames.set(active, frame); + } + frames.forEach((frame, id) => { frame.hidden = id !== active; }); +} + +function route() { + const path = location.pathname.replace(/\/$/, "") || "/"; + const key = path.startsWith("/hands/") ? path.slice(7) : null; + active = Object.hasOwn(models, key) ? key : null; + document.querySelector("#gallery").hidden = Boolean(active); + document.querySelector("#workspace").hidden = !active; + document.body.classList.toggle("editing", Boolean(active)); + document.querySelectorAll("nav [data-route]").forEach((link) => { + if (link.dataset.route === path) link.setAttribute("aria-current", "page"); + else link.removeAttribute("aria-current"); + }); + if (active) { + document.querySelector("#workspace-title").textContent = models[active].name; + document.querySelector("#direct-link").href = models[active].url; + } + document.title = active ? `${models[active].name} · 灵巧手工作台` : "灵巧手工作台 · SimpleCAD"; + updateStatus(); +} + +document.addEventListener("click", (event) => { + const link = event.target.closest("a[data-route]"); + if (!link || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + event.preventDefault(); + if (location.pathname !== link.dataset.route) history.pushState({}, "", link.dataset.route); + route(); + window.scrollTo(0, 0); +}); +window.addEventListener("popstate", route); + +async function refreshStatus() { + try { + const response = await fetch("/api/models", { signal: AbortSignal.timeout(6000) }); + if (!response.ok) throw new Error("Status unavailable"); + const data = await response.json(); + data.models.forEach((row) => { + if (Object.hasOwn(models, row.id)) models[row.id].state = row.state; + }); + } catch { + Object.values(models).forEach((model) => { model.state = "unavailable"; }); + } + updateStatus(); + window.setTimeout(refreshStatus, 5000); +} +route(); +refreshStatus(); diff --git a/examples/hand_gallery/web/index.html b/examples/hand_gallery/web/index.html new file mode 100644 index 00000000..24033f97 --- /dev/null +++ b/examples/hand_gallery/web/index.html @@ -0,0 +1,65 @@ + + + + + + 灵巧手工作台 · SimpleCAD + + + + +
+ 灵巧手工作台SIMPLECAD + + 本地工作区 +
+ +
+
+

HAND DESIGN COLLECTION 02

+

选择你的灵巧手。

+

两款方案,一个入口。进入模型后,可随时通过顶部菜单切换。

+
+
+ + +
+ +
+ + + + + diff --git a/examples/hand_gallery/web/style.css b/examples/hand_gallery/web/style.css new file mode 100644 index 00000000..914f1602 --- /dev/null +++ b/examples/hand_gallery/web/style.css @@ -0,0 +1,74 @@ +:root { color-scheme: light; font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Segoe UI", sans-serif; color: #18292b; background: #f5f7f6; } +* { box-sizing: border-box; } +body { margin: 0; } +a { color: inherit; text-decoration: none; } +[hidden] { display: none !important; } +a:focus-visible { outline: 3px solid #0f8275; outline-offset: 5px; } +.topbar { min-height: 82px; padding: 0 5%; background: #fff; border-bottom: 1px solid #e2e8e5; display: flex; align-items: center; gap: 32px; } +.brand { display: flex; gap: 11px; align-items: center; font-size: 16px; font-weight: 650; white-space: nowrap; } +.brand-mark { display: grid; place-items: center; width: 35px; height: 35px; border: 1px solid #244f47; color: #244f47; border-radius: 10px; font: 23px Georgia, serif; } +.brand small { display: block; font-size: 9px; font-weight: 500; letter-spacing: 2.4px; color: #7a8781; margin-top: 4px; } +nav { display: flex; gap: 6px; margin-left: auto; } +.nav-link { padding: 11px 17px; font-size: 13px; border-radius: 7px; color: #69736f; white-space: nowrap; } +.nav-link:hover { background: #f4f6f5; color: #172a25; } +.nav-link[aria-current] { background: #eaf2ef; color: #205c4b; font-weight: 600; } +.local { font-size: 11px; color: #72827b; white-space: nowrap; display: flex; gap: 7px; align-items: center; } +.local i { width: 6px; height: 6px; border-radius: 50%; background: #7b9f8d; } +#gallery { max-width: 1256px; margin: 0 auto; padding: 55px 38px 0; } +.eyebrow { font-size: 10px; color: #668378; letter-spacing: 2px; margin: 0 0 20px; } +.eyebrow span { border: 1px solid #cfdcd5; margin-left: 11px; padding: 3px 5px; border-radius: 3px; } +h1 { font-size: clamp(30px, 3.4vw, 44px); font-weight: 580; letter-spacing: -1.5px; margin: 0 0 15px; } +.intro-copy { font-size: 14px; color: #77817d; line-height: 1.8; margin: 0; } +.cards { display: grid; grid-template-columns: 1fr 1fr; gap: 25px; margin-top: 36px; } +.card { background: #fff; border: 1px solid #dfe6e2; border-radius: 15px; overflow: hidden; transition: border-color .18s, box-shadow .18s; } +.card:hover { border-color: #a6bcb0; box-shadow: 0 9px 35px #183c2510; } +.preview { position: relative; display: flex; align-items: center; justify-content: center; height: 315px; border-bottom: 1px solid #e7ebe9; overflow: hidden; } +.codex .preview { background: #e8edf1; } +.claude .preview { background: #000; } +.claude .preview-label, .claude .preview-caption { color: #9aa9a2; } +.preview svg { height: 100%; width: 100%; } +.preview img { height: 94%; width: 100%; object-fit: contain; } +.preview-label { position: absolute; left: 22px; top: 20px; z-index: 1; font-size: 10px; letter-spacing: 1.8px; color: #596a65; } +.preview-caption { position: absolute; bottom: 15px; right: 18px; font-size: 10px; color: #7b8984; } +.card-body { padding: 24px 25px 23px; } +.card-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 15px; } +h2 { font-size: 22px; font-weight: 600; letter-spacing: -.5px; margin: 0; } +h2 span { display: block; color: #8a948f; font-size: 11px; font-weight: 400; letter-spacing: .6px; margin-top: 7px; } +.status { display: inline-flex; align-items: center; gap: 6px; flex-shrink: 0; font-size: 10px; color: #8a8f88; line-height: 22px; white-space: nowrap; } +.status::before { content: ""; display: inline-block; width: 5px; height: 5px; border-radius: 50%; background: currentColor; } +.status.online { color: #39785e; } +.status.offline, .status.mismatch, .status.unavailable { color: #a67840; } +.card-body > p { font-size: 13px; color: #77817e; line-height: 1.8; min-height: 46px; margin: 20px 0 17px; } +.tags { display: flex; flex-wrap: wrap; gap: 7px; } +.tags span { font-size: 10px; color: #66746e; border: 1px solid #e3e9e5; padding: 5px 8px; border-radius: 4px; } +.enter { margin-top: 24px; padding-top: 18px; border-top: 1px solid #ecf0ed; display: flex; justify-content: space-between; align-items: center; font-size: 13px; font-weight: 550; color: #214f40; } +.enter span { font-size: 20px; font-weight: 400; } +footer { display: flex; justify-content: space-between; gap: 15px; font-size: 11px; color: #8d9892; padding: 24px 0 32px; line-height: 1.8; } +.editing { overflow: hidden; height: 100dvh; display: flex; flex-direction: column; } +.editing .topbar { flex-shrink: 0; } +#workspace { flex: 1; min-height: 0; display: flex; flex-direction: column; } +.workspace-bar { background: #fff; min-height: 44px; padding: 8px 22px; display: flex; align-items: center; justify-content: space-between; gap: 16px; border-bottom: 1px solid #e5eae7; } +.workspace-bar > div { display: flex; gap: 18px; align-items: center; } +.workspace-bar strong { font-size: 12px; font-weight: 550; } +.workspace-bar a { font-size: 11px; color: #52786a; white-space: nowrap; } +#connection-notice { padding: 10px 22px; color: #8c663b; background: #fff5e7; font-size: 12px; } +#editors { flex: 1; min-height: 0; background: #fff; } +iframe { width: 100%; height: 100%; display: block; border: 0; } +.noscript { padding: 22px; } +@media (max-width: 720px) { + .topbar { padding: 15px 19px 11px; flex-wrap: wrap; gap: 14px; min-height: 110px; } + .brand { font-size: 14px; } + .local { margin-left: auto; order: 1; } + nav { width: 100%; margin: 0; order: 2; } + .nav-link { flex: 1; text-align: center; padding: 9px 10px; font-size: 12px; } + #gallery { padding: 31px 19px 0; } + .cards { grid-template-columns: 1fr; margin-top: 26px; gap: 20px; } + .preview { height: 290px; } + .card-body { padding: 22px; } + .card-body > p { min-height: 0; } + footer { flex-direction: column; gap: 6px; } + .workspace-bar { padding: 7px 13px; min-height: 48px; } + .workspace-bar > div { display: block; } + #workspace-status { display: flex; line-height: 16px; } +} +@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }