Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
FreeVideo for Linux desktops, an image editor in Media, and faster Windows generation when memory is tight (0.3.21) (#150)
Bowen Xue502bcd6054c0
diff --git a/.github/workflows/install.yml b/.github/workflows/install.ymlindex f1655dc..b201873 100644--- a/.github/workflows/install.yml+++ b/.github/workflows/install.yml@@ -1,5 +1,5 @@name: Installation and launchers-# Every merge to main publishes the rolling nightly (Windows unsigned, Mac not notarized).+# Every merge to main publishes the rolling nightly (Windows unsigned, Mac not notarized, Linux AppImage).# Users get an update only from a stable vX.Y.Z release, published by running this# workflow with "release" checked; Windows signing then waits for the release environment.on:@@ -249,10 +249,70 @@ jobs:${{ runner.temp }}/freevideo-smoke/smoke.jsonif-no-files-found: ignoreretention-days: 1+ linux:+ if: github.event_name != 'pull_request'+ needs: [installation]+ runs-on: ubuntu-24.04+ timeout-minutes: 40+ permissions:+ contents: read+ # glibc 2.34, the oldest PySide6 6.11 supports: Ubuntu 22.04, Debian 12, Fedora 36, RHEL 9 and newer.+ container: quay.io/pypa/manylinux_2_34_x86_64:2026.10.03-1@sha256:e4ca528d41ab66b3654110295d7a2c7bfa599ddbb6efb269ec21f7f73b88f1b6+ env:+ FREEVIDEO_RELEASE_TRACK: ${{ github.event_name == 'workflow_dispatch' && inputs.release && 'stable' || 'nightly' }}+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ - name: Install the libraries Qt loads, and those bundled for desktops that lack them+ run: |+ dnf install -y epel-release+ dnf install -y xcb-util-cursor xcb-util-image xcb-util-keysyms xcb-util-renderutil xcb-util-wm xcb-util \+ libxkbcommon-x11 libxkbcommon mesa-libGL mesa-libEGL fontconfig freetype dbus-libs xorg-x11-server-Xvfb+ - name: Prepare Python 3.12 with a shared libpython+ run: |+ /opt/python/cp312-cp312/bin/python -m pip install uv==0.9.0+ /opt/python/cp312-cp312/bin/uv python install 3.12+ /opt/python/cp312-cp312/bin/uv venv /opt/launcher --python 3.12+ /opt/python/cp312-cp312/bin/uv pip install --python /opt/launcher/bin/python -r constraints/linux-launcher.txt+ - name: Check installation and build the Linux launcher+ run: |+ git config --global --add safe.directory "$GITHUB_WORKSPACE"+ /opt/launcher/bin/python scripts/check_installation.py+ /opt/launcher/bin/python scripts/build_linux.py --out build/linux+ - name: Start the AppImage on a virtual display+ env:+ FREEVIDEO_LAUNCHER_HOME: ${{ runner.temp }}/freevideo-launcher-state+ APPIMAGE_EXTRACT_AND_RUN: '1'+ run: |+ Xvfb :99 -screen 0 1280x800x24 &+ export DISPLAY=:99+ sleep 2+ build/linux/release/FreeVideo-Linux-x86_64.AppImage --smoke-test "$RUNNER_TEMP/freevideo-smoke"+ /opt/launcher/bin/python -c "import json, os; from pathlib import Path; value=json.loads((Path(os.environ['RUNNER_TEMP'])/'freevideo-smoke/smoke.json').read_text()); assert value['success'] and not value['model_modules_imported'], value"+ - name: Stage the Linux launcher for publishing+ run: |+ mkdir -p build/linux-publish+ cp build/linux/release/FreeVideo-Linux-x86_64.AppImage build/linux/release/launcher-build.json build/linux-publish/+ - name: Keep the Linux launcher for publishing+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: linux-launcher+ path: build/linux-publish/+ if-no-files-found: error+ retention-days: 1+ - name: Keep failure diagnostics+ if: failure()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: linux-build-failure+ path: |+ ${{ runner.temp }}/freevideo-smoke/smoke.json+ ${{ runner.temp }}/freevideo-smoke/launcher.png+ if-no-files-found: ignore+ retention-days: 1publish:# Release assets use Releases storage, not the Actions artifact quota.if: github.event_name != 'pull_request' && github.repository == 'FlashML-org/FreeVideo' && github.ref == 'refs/heads/main'- needs: [windows, macos]+ needs: [windows, macos, linux]runs-on: ubuntu-24.04timeout-minutes: 30permissions:@@ -270,10 +330,14 @@ jobs:with:name: macos-launcherpath: build/macos+ - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0+ with:+ name: linux-launcher+ path: build/linux- name: Publish the releaseenv:GH_TOKEN: ${{ github.token }}GH_REPO: ${{ github.repository }}run: >-python scripts/publish_release.py --track ${{ github.event_name == 'workflow_dispatch' && inputs.release && 'stable' || 'nightly' }}- --windows build/windows --macos build/macos --sha ${{ github.sha }}+ --windows build/windows --macos build/macos --linux build/linux --sha ${{ github.sha }}diff --git a/.gitignore b/.gitignoreindex 83019f5..c09426e 100644--- a/.gitignore+++ b/.gitignore@@ -52,6 +52,10 @@ engine-gpu-*.lock/tuning//input-cache//comfyui.json+# ComfyUI that ./setup.sh installs beside the engine, and the service that runs it.+/ComfyUI/+/ComfyUI.freevideo-download/+/launcher//optimization-runs/# Optional local prompt models, runtime binaries and private rewrite caches.diff --git a/README.md b/README.mdindex c3aa36c..d03cd91 100644--- a/README.md+++ b/README.md@@ -6,7 +6,7 @@</div><p align="center">-| <a href="https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo.exe"><b>Download for Windows</b></a> | <a href="https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo-Mac-arm64.dmg"><b>Download for macOS</b></a> | <a href="https://freevideo-community.pages.dev/#gallery"><b>Gallery</b></a> | <a href="https://discord.gg/MsA277cJzZ"><b>Discord</b></a> | <a href="https://freevideo-community.pages.dev/qq"><b>QQ Group</b></a> | <a href="https://freevideo-community.pages.dev/wechat"><b>WeChat Group</b></a> |+| <a href="https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo.exe"><b>Download for Windows</b></a> | <a href="https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo-Mac-arm64.dmg"><b>Download for macOS</b></a> | <a href="https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo-Linux-x86_64.AppImage"><b>Download for Linux</b></a> | <a href="https://freevideo-community.pages.dev/#gallery"><b>Gallery</b></a> | <a href="https://discord.gg/MsA277cJzZ"><b>Discord</b></a> | <a href="https://freevideo-community.pages.dev/qq"><b>QQ Group</b></a> | <a href="https://freevideo-community.pages.dev/wechat"><b>WeChat Group</b></a> |</p><p align="center">English · <a href="README.zh-CN.md">中文</a></p>@@ -32,14 +32,14 @@ https://github.com/user-attachments/assets/ecda7d0d-7fbe-4e0c-8c29-8f3315bafc15FreeVideo is a local inference engine for MiniMax H3 on consumer GPUs, built on [OpenVDN](https://github.com/OpenVDN)'s 8-step [VDN-H3](https://huggingface.co/OpenVDN/vdn-minimax-h3) model with [Video DeltaNet](https://openvdn.github.io/)'s hybrid attention.-It coordinates VRAM, system memory and disk, adapting weight placement, compute precision and attention kernels to the available hardware. FreeVideo runs as a ComfyUI plugin, with a Windows launcher for setup and command-line support on Linux. Its core features include:+It coordinates VRAM, system memory and disk, adapting weight placement, compute precision and attention kernels to the available hardware. FreeVideo runs as a ComfyUI plugin, with launchers for Windows, macOS and Linux and a server mode for remote GPUs. Its core features include:- **Hardware-adaptive execution**: Chooses the weight format for each GPU, int8 on GeForce and RTX 30-series cards and FP8 on workstation and datacenter cards, and automatically probes the available attention kernels.- **Low-memory inference**: Weight streaming, asynchronous prefetching and chunked computation keep peak memory low, enabling inference with as little as 8 GB of VRAM and 16 GB of RAM.- **Multimodal inputs**: Text prompts, first and last frames, and image, video and audio references.- **Community LoRAs**: Use MiniMax H3 LoRAs in your workflow. See [examples](docs/LoRA.md).- **ComfyUI integration**: A dedicated creative workspace inside ComfyUI that supports two-pass sampling and batch generation and keeps a history of past creations. For finer control, switch to the node view to add LoRAs or customize the workflow.-- **One-click deployment**: The Windows and Mac launchers set up ComfyUI, the runtime environment and the models, reuse existing models, and support offline installation.+- **One-click deployment**: The Windows, Mac and Linux launchers set up ComfyUI, the runtime environment and the models, reuse existing models, and support offline installation. On Linux, `./setup.sh` does the same from a terminal.## Getting Started@@ -78,23 +78,20 @@ Restart ComfyUI, open **Workflow → Browse Templates → FreeVideo → FreeVide### Linux-Install:+**Desktop:** [Download FreeVideo-Linux-x86_64.AppImage](https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo-Linux-x86_64.AppImage), make it executable and open it, then follow the same steps as on Windows.++**Terminal or server:**```bashgit clone https://github.com/FlashML-org/FreeVideo.git && cd FreeVideo./setup.sh```-Generate a video from a prompt file:--```bash-./freevideo generate --prompt-file prompt.txt --out video.mp4-```+Setup installs FreeVideo, ComfyUI and the models, then opens FreeVideo in the browser. Afterwards, type `freevideo` to open it again. On a server, connect from your own computer through SSH, or run `freevideo server --listen 0.0.0.0` for an access link on your local network. See the [Linux guide](docs/Linux.md).### More details- [FreeVideo Adaptive Execution Planner](docs/execution-planning.md)-- [Community results](docs/community-results.md)### Supportdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex a9822e2..fd15e27 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -6,7 +6,7 @@</div><p align="center">-| <a href="https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo.exe"><b>Windows 下载</b></a> | <a href="https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo-Mac-arm64.dmg"><b>macOS 下载</b></a> | <a href="https://freevideo-community.pages.dev/#gallery"><b>作品展示</b></a> | <a href="https://discord.gg/MsA277cJzZ"><b>Discord</b></a> | <a href="https://freevideo-community.pages.dev/qq"><b>QQ 群</b></a> | <a href="https://freevideo-community.pages.dev/wechat"><b>微信群</b></a> |+| <a href="https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo.exe"><b>Windows 下载</b></a> | <a href="https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo-Mac-arm64.dmg"><b>macOS 下载</b></a> | <a href="https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo-Linux-x86_64.AppImage"><b>Linux 下载</b></a> | <a href="https://freevideo-community.pages.dev/#gallery"><b>作品展示</b></a> | <a href="https://discord.gg/MsA277cJzZ"><b>Discord</b></a> | <a href="https://freevideo-community.pages.dev/qq"><b>QQ 群</b></a> | <a href="https://freevideo-community.pages.dev/wechat"><b>微信群</b></a> |</p><p align="center"><a href="README.md">English</a> · 中文</p>@@ -32,14 +32,14 @@ https://github.com/user-attachments/assets/ecda7d0d-7fbe-4e0c-8c29-8f3315bafc15FreeVideo 是面向消费级显卡的 MiniMax H3 本地推理引擎,基于 [OpenVDN](https://github.com/OpenVDN) 的 8 步模型 [VDN-H3](https://huggingface.co/OpenVDN/vdn-minimax-h3) 和 [Video DeltaNet](https://openvdn.github.io/) 的混合注意力。-它统一调度显存、内存与磁盘,并根据硬件条件调整权重放置、计算精度和注意力内核。FreeVideo 以 ComfyUI 插件形式提供,配备 Windows 启动器,也支持 Linux 命令行。主要特性包括:+它统一调度显存、内存与磁盘,并根据硬件条件调整权重放置、计算精度和注意力内核。FreeVideo 以 ComfyUI 插件形式提供,配备 Windows、macOS 和 Linux 启动器,并支持在远程 GPU 服务器上以服务器模式运行。主要特性包括:- **硬件自适应**:针对不同显卡选择权重格式(GeForce 和 RTX 30 系用 int8,专业卡和数据中心卡用 FP8),并自动探测可用的注意力内核,无需手动配置。- **低显存推理**:通过权重流式加载、异步预取与分块计算降低峰值显存,最低只需 8GB 显存和 16GB 内存。- **多模态输入**:支持文本、首帧、尾帧,以及图像、视频、音频参考输入。- **社区 LoRA**:支持在工作流中使用 MiniMax H3 社区 LoRA。[查看效果对比](docs/LoRA.zh-CN.md)。- **ComfyUI 集成**:在 ComfyUI 中提供专门的创作面板,支持二次采样和批量生成,并可浏览历史作品;需要更精细的控制时,可切换到节点视图,接入 LoRA 或自定义工作流。-- **一键部署**:Windows 和 Mac 启动器自动完成 ComfyUI、运行环境与模型的部署,可复用已有模型,并支持离线安装。+- **一键部署**:Windows、Mac 和 Linux 启动器自动完成 ComfyUI、运行环境与模型的部署,可复用已有模型,并支持离线安装。Linux 上也可以在终端运行 `./setup.sh` 一次装好。## 开始使用@@ -78,23 +78,20 @@ git clone https://github.com/FlashML-org/FreeVideo.git### Linux-安装:+**桌面:** [下载 FreeVideo-Linux-x86_64.AppImage](https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo-Linux-x86_64.AppImage),加上可执行权限后打开,之后的步骤与 Windows 相同。++**终端或服务器:**```bashgit clone https://github.com/FlashML-org/FreeVideo.git && cd FreeVideo./setup.sh```-从提示词文件生成视频:--```bash-./freevideo generate --prompt-file prompt.txt --out video.mp4-```+安装程序会装好 FreeVideo、ComfyUI 和模型,然后在浏览器中打开 FreeVideo。之后输入 `freevideo` 即可再次打开。在服务器上,可以通过 SSH 从自己的电脑访问,或运行 `freevideo server --listen 0.0.0.0` 获取局域网访问链接。详见 [Linux 说明](docs/Linux.zh-CN.md)。### 更多文档- [FreeVideo Adaptive Execution Planner](docs/zh-CN/execution-planning.md)-- [社区实测](docs/zh-CN/community-results.md)### 问题反馈diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 1cd37ba..fe905cc 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -12,9 +12,15 @@ FreeVideo code uses [Apache-2.0](LICENSE). Its dependencies and models retain th| [VDN-H3 and H3 model weights](https://huggingface.co/OpenVDN/vdn-minimax-h3-edge/blob/main/LICENSE) | MiniMax H3 Community License || [MiniMax H3 latent upscaler](https://huggingface.co/LBH-123-AI/Minimax_h3_latent_Upscaler) | [MIT](freevideo_engine/licenses/latent-upscaler-MIT.txt) || [FreeToken](https://github.com/FlashML-org/FreeToken) prompt VLM operators, [Qwen3-VL-4B-Instruct](https://huggingface.co/Qwen/Qwen3-VL-4B-Instruct) optional weights | [Apache-2.0](freevideo_engine/licenses/FreeToken-Apache-2.0.txt) |+| [Lucide](https://lucide.dev) icons (image editor: eyedropper, hand, crop) | [ISC](freevideo_engine/licenses/Lucide-ISC.txt) |+| [Noto Sans CJK SC and Noto Sans Mono CJK SC](https://github.com/notofonts/noto-cjk) 2.004, © 2014-2021 Adobe: subsets renamed FreeVideo Sans SC and FreeVideo Mono SC (image editor text, share card, Linux launcher) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-CJK-Sans-OFL.txt) |+| [Noto Serif CJK SC](https://github.com/notofonts/noto-cjk) 2.003, © 2017-2024 Adobe: subset renamed FreeVideo Serif SC (image editor text) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-CJK-Serif-OFL.txt) |+| [LXGW WenKai](https://github.com/lxgw/LxgwWenKai) v1.522, © 2021-2026 LXGW, © 2020 The Klee Project Authors: subset renamed FreeVideo Kai SC (image editor text) | [SIL OFL 1.1](freevideo_engine/licenses/LXGW-WenKai-OFL.txt) |Original launcher license texts are included in Windows packages. Other runtime dependencies are listed in [constraints](constraints), with their license information in the installed packages.+The fonts in `web/fonts/` are built by `scripts/build_web_fonts.py` from the pinned sources above; each file keeps its original copyright notice and licence in its name table. `FreeVideoBox.woff2` is FreeVideo's own.+`decode_stream.py`, `lora_cache.py` and `reference_sampler.py` include adaptations of upstream code; their source headers retain the attribution.`prompt_vlm/core.py` adapts FreeToken's merged MLP/QKV and bounded vision operators from revisiondiff --git a/constraints/linux-launcher.txt b/constraints/linux-launcher.txtnew file mode 100644index 0000000..89e83af--- /dev/null+++ b/constraints/linux-launcher.txt@@ -0,0 +1,6 @@+# Native launcher build dependencies; inference runs in its managed environment.+pyinstaller==6.22.3+psutil==7.2.2+# Build only: cuts the bundled Chinese font down to the launcher's characters.+fonttools==4.66.1+PySide6-Essentials==6.11.2diff --git a/docs/Linux.md b/docs/Linux.mdnew file mode 100644index 0000000..d98840e--- /dev/null+++ b/docs/Linux.md@@ -0,0 +1,70 @@+# Linux++English · [中文](Linux.zh-CN.md)++FreeVideo runs on x86_64 Linux with an NVIDIA GPU and driver 580 or newer. On a desktop, the AppImage works like the Windows launcher. From a terminal or on a server, `./setup.sh` installs everything in one go, and the `freevideo` command opens it afterwards.++## Desktop: the AppImage++1. [Download FreeVideo-Linux-x86_64.AppImage](https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo-Linux-x86_64.AppImage).+2. Make it executable, either in the file's properties (**Allow executing file as program**) or with `chmod +x FreeVideo-Linux-x86_64.AppImage`, then open it.+3. Choose a folder for a new installation, or an existing ComfyUI, and click **Install & launch**. ComfyUI opens in the browser with the FreeVideo workspace.++FreeVideo then appears in the application menu and on the desktop, and later versions update the launcher by themselves, as on Windows. The AppImage needs a distribution from 2022 or newer (Ubuntu 22.04, Debian 12, Fedora 36, RHEL 9 or later); on older systems, use the terminal installation below. If the computer lacks the compiler FreeVideo builds its GPU acceleration with, the installation plan shows the command that installs it.++## Terminal: one command++```bash+git clone https://github.com/FlashML-org/FreeVideo.git && cd FreeVideo+./setup.sh+```++Setup checks the GPU, memory and disk, shows the plan, and after you confirm it installs the runtime, the models and ComfyUI. It then starts ComfyUI and opens FreeVideo in the browser. Everything stays in the FreeVideo folder.++Afterwards, type `freevideo` in any terminal to open FreeVideo again. ComfyUI keeps running in the background until you stop it:++| Command | What it does |+| --- | --- |+| `freevideo` | Open FreeVideo; starts ComfyUI first if it is not running |+| `freevideo status` | Show whether it runs, and its address |+| `freevideo stop` | Stop ComfyUI; while a video is generating, only with `--force` |+| `freevideo restart` | Restart ComfyUI |++After `git pull`, `freevideo` restarts ComfyUI with the update; while a video is generating it leaves ComfyUI running and asks you to restart later. ComfyUI uses port 8188, or the next free one if another program has it; `freevideo open --port 8190` chooses another.++## Server: use FreeVideo from another computer++On a server without a desktop, setup ends by printing the address and an SSH command. ComfyUI only accepts connections from the server itself, so other computers reach it through an SSH tunnel. On your own computer, run:++```bash+ssh -N -L 8188:127.0.0.1:8188 you@server+```++Then open http://127.0.0.1:8188/?freevideo=launch in your browser.++To connect from computers on your local network without SSH:++```bash+freevideo server --listen 0.0.0.0+```++This prints an access link with a token. Anyone with the link can use FreeVideo on the server; `freevideo server --listen 0.0.0.0 --new-token` replaces it, and `freevideo status` shows it again. ComfyUI itself still listens only on the server; a small proxy in front of it turns away every request without the token. The connection is not encrypted, so use it on a network you trust, or add `--tls-cert cert.pem --tls-key key.pem` for HTTPS.++To start FreeVideo with the server, add `--enable`; it becomes a systemd user service. To keep it running after you log out and start it at boot, also run `sudo loginctl enable-linger $USER` once. `freevideo server --disable` removes the service.++## Command-line generation++The engine also runs without ComfyUI:++```bash+./freevideo generate --prompt-file prompt.txt --out video.mp4+./test.sh+```++`./freevideo --help` lists every command.++## Troubleshooting++- **The AppImage does not start.** Some systems lack FUSE. Run it with `--appimage-extract-and-run`, or install the `fuse3` package.+- **ComfyUI does not start.** `freevideo status` names the last error. The logs are in the `launcher` folder of the installation (`service.log`, and `comfy-runs` for ComfyUI itself).+- **The address is in use.** Another program uses the port; start FreeVideo on another one with `freevideo open --port 8190`.diff --git a/docs/Linux.zh-CN.md b/docs/Linux.zh-CN.mdnew file mode 100644index 0000000..6023d78--- /dev/null+++ b/docs/Linux.zh-CN.md@@ -0,0 +1,70 @@+# Linux++[English](Linux.md) · 中文++FreeVideo 支持 x86_64 Linux,需要 NVIDIA 显卡和 580 及以上版本的驱动。桌面环境下,AppImage 的用法与 Windows 启动器相同;在终端或服务器上,运行 `./setup.sh` 即可一次装好,之后用 `freevideo` 命令打开。++## 桌面:AppImage++1. [下载 FreeVideo-Linux-x86_64.AppImage](https://github.com/FlashML-org/FreeVideo/releases/latest/download/FreeVideo-Linux-x86_64.AppImage)。+2. 在文件属性中勾选**允许作为程序执行**,或运行 `chmod +x FreeVideo-Linux-x86_64.AppImage`,然后打开它。+3. 选择新安装的文件夹或已有的 ComfyUI,点击**安装并启动**。ComfyUI 会在浏览器中打开,并进入 FreeVideo 创作面板。++安装完成后,应用菜单和桌面上会出现 FreeVideo,启动器也会像 Windows 版一样自动更新。AppImage 需要 2022 年以后的发行版(Ubuntu 22.04、Debian 12、Fedora 36、RHEL 9 或更新版本);更老的系统请使用下面的终端安装方式。如果系统缺少编译 GPU 加速所需的编译器,安装计划会给出安装它的命令。++## 终端:一条命令++```bash+git clone https://github.com/FlashML-org/FreeVideo.git && cd FreeVideo+./setup.sh+```++安装程序会检查显卡、内存和硬盘,显示安装计划,确认后安装运行环境、模型和 ComfyUI,然后启动 ComfyUI,并在浏览器中打开 FreeVideo。所有文件都在 FreeVideo 文件夹内。++之后在任意终端输入 `freevideo` 即可再次打开。ComfyUI 会在后台持续运行,直到手动停止:++| 命令 | 作用 |+| --- | --- |+| `freevideo` | 打开 FreeVideo;ComfyUI 没有运行时先启动它 |+| `freevideo status` | 查看是否在运行,以及访问地址 |+| `freevideo stop` | 停止 ComfyUI;有视频正在生成时需加 `--force` |+| `freevideo restart` | 重启 ComfyUI |++执行 `git pull` 后,再运行 `freevideo` 会重启 ComfyUI 加载新版本;如果有视频正在生成,则保持运行,并提示稍后重启。ComfyUI 默认使用 8188 端口,被其他程序占用时自动改用下一个空闲端口;也可以用 `freevideo open --port 8190` 指定端口。++## 服务器:从其他电脑使用++在没有桌面的服务器上,安装结束时会打印访问地址和一条 SSH 命令。ComfyUI 只接受服务器本机的连接,其他电脑通过 SSH 隧道访问。在自己的电脑上运行:++```bash+ssh -N -L 8188:127.0.0.1:8188 用户名@服务器+```++然后在浏览器中打开 http://127.0.0.1:8188/?freevideo=launch 。++如果希望局域网内的电脑不经过 SSH 直接访问:++```bash+freevideo server --listen 0.0.0.0+```++这会打印一个带访问令牌的链接,持有链接的人都可以使用这台服务器上的 FreeVideo;用 `freevideo server --listen 0.0.0.0 --new-token` 可以换一个新链接,`freevideo status` 可以再次查看。ComfyUI 本身仍然只监听服务器本机,前面的访问代理会拒绝所有不带令牌的请求。连接没有加密,请只在可信的网络中使用,或加上 `--tls-cert cert.pem --tls-key key.pem` 使用 HTTPS。++如需随服务器启动,加上 `--enable`,FreeVideo 会注册为 systemd 用户服务;若要在注销后保持运行、开机自动启动,还需运行一次 `sudo loginctl enable-linger $USER`。`freevideo server --disable` 会移除这个服务。++## 命令行生成++引擎也可以不经过 ComfyUI 直接运行:++```bash+./freevideo generate --prompt-file prompt.txt --out video.mp4+./test.sh+```++`./freevideo --help` 列出全部命令。++## 常见问题++- **AppImage 打不开**:部分系统缺少 FUSE。可以加上 `--appimage-extract-and-run` 运行,或安装 `fuse3`。+- **ComfyUI 没有启动**:运行 `freevideo status` 查看上次的错误。日志在安装目录的 `launcher` 文件夹中(`service.log`,ComfyUI 本身的日志在 `comfy-runs`)。+- **端口被占用**:有其他程序在使用该端口,可以用 `freevideo open --port 8190` 换一个端口。diff --git a/docs/assets/capacity-blocks.en.svg b/docs/assets/capacity-blocks.en.svgindex 3f0d2b5..9da2720 100644--- a/docs/assets/capacity-blocks.en.svg+++ b/docs/assets/capacity-blocks.en.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="988" height="620" viewBox="0 0 988 620">-<style>text{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Noto Sans','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',Helvetica,Arial,sans-serif}.v{font-size:10.5px;text-anchor:middle}.t{font-size:11px;fill:#57606a}.a{font-size:12.5px;fill:#24292f;text-anchor:middle}</style>+<style>text{font-family:'Noto Sans','Noto Sans CJK SC','Source Han Sans SC',sans-serif}.v{font-size:10.5px;text-anchor:middle}.t{font-size:11px;fill:#57606a}.a{font-size:12.5px;fill:#24292f;text-anchor:middle}</style><rect width="988" height="620" fill="#ffffff"/><text class="t" x="68" y="27.0" text-anchor="end">32</text><rect x="76" y="12" width="35" height="21" fill="#f7fbff"/>diff --git a/docs/assets/capacity-blocks.zh.svg b/docs/assets/capacity-blocks.zh.svgindex 2f94f2b..1e1a0a0 100644--- a/docs/assets/capacity-blocks.zh.svg+++ b/docs/assets/capacity-blocks.zh.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="988" height="620" viewBox="0 0 988 620">-<style>text{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Noto Sans','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',Helvetica,Arial,sans-serif}.v{font-size:10.5px;text-anchor:middle}.t{font-size:11px;fill:#57606a}.a{font-size:12.5px;fill:#24292f;text-anchor:middle}</style>+<style>text{font-family:'Noto Sans','Noto Sans CJK SC','Source Han Sans SC',sans-serif}.v{font-size:10.5px;text-anchor:middle}.t{font-size:11px;fill:#57606a}.a{font-size:12.5px;fill:#24292f;text-anchor:middle}</style><rect width="988" height="620" fill="#ffffff"/><text class="t" x="68" y="27.0" text-anchor="end">32</text><rect x="76" y="12" width="35" height="21" fill="#f7fbff"/>diff --git a/docs/assets/capacity-speed.en.svg b/docs/assets/capacity-speed.en.svgindex c435310..c2008aa 100644--- a/docs/assets/capacity-speed.en.svg+++ b/docs/assets/capacity-speed.en.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="988" height="620" viewBox="0 0 988 620">-<style>text{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Noto Sans','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',Helvetica,Arial,sans-serif}.v{font-size:10.5px;text-anchor:middle}.t{font-size:11px;fill:#57606a}.a{font-size:12.5px;fill:#24292f;text-anchor:middle}</style>+<style>text{font-family:'Noto Sans','Noto Sans CJK SC','Source Han Sans SC',sans-serif}.v{font-size:10.5px;text-anchor:middle}.t{font-size:11px;fill:#57606a}.a{font-size:12.5px;fill:#24292f;text-anchor:middle}</style><rect width="988" height="620" fill="#ffffff"/><text class="t" x="68" y="27.0" text-anchor="end">32</text><rect x="76" y="12" width="35" height="21" fill="#ec7014"/>diff --git a/docs/assets/capacity-speed.zh.svg b/docs/assets/capacity-speed.zh.svgindex 964d72c..400c7bc 100644--- a/docs/assets/capacity-speed.zh.svg+++ b/docs/assets/capacity-speed.zh.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="988" height="620" viewBox="0 0 988 620">-<style>text{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Noto Sans','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',Helvetica,Arial,sans-serif}.v{font-size:10.5px;text-anchor:middle}.t{font-size:11px;fill:#57606a}.a{font-size:12.5px;fill:#24292f;text-anchor:middle}</style>+<style>text{font-family:'Noto Sans','Noto Sans CJK SC','Source Han Sans SC',sans-serif}.v{font-size:10.5px;text-anchor:middle}.t{font-size:11px;fill:#57606a}.a{font-size:12.5px;fill:#24292f;text-anchor:middle}</style><rect width="988" height="620" fill="#ffffff"/><text class="t" x="68" y="27.0" text-anchor="end">32</text><rect x="76" y="12" width="35" height="21" fill="#ec7014"/>diff --git a/freevideo_engine/access_proxy.py b/freevideo_engine/access_proxy.pynew file mode 100644index 0000000..6aacf43--- /dev/null+++ b/freevideo_engine/access_proxy.py@@ -0,0 +1,173 @@+"""Token-protected access to a ComfyUI that listens on this computer only.++`freevideo server --listen ADDRESS` runs this in front of ComfyUI. The access+link carries the token once; the page then keeps it in a cookie, and API+clients send it as a bearer token. Everything else gets 401, so ComfyUI is+never reachable from other computers without it, and not at all when this+proxy is not running. Runs with ComfyUI's Python, which brings aiohttp.+"""+import argparse+import asyncio+import hmac+from pathlib import Path+import ssl+from urllib.parse import urlencode++from aiohttp import ClientSession, ClientTimeout, DummyCookieJar, TCPConnector, WSMsgType, client_exceptions, web+from yarl import URL++COOKIE = 'freevideo_access'+DAYS = 30+# Hop-by-hop headers belong to one connection; Content-Length follows the body actually sent.+HOP_BY_HOP = frozenset(('connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'proxy-connection',+ 'te', 'trailer', 'transfer-encoding', 'upgrade', 'content-length'))+DENIED = """<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">+<title>FreeVideo</title></head><body style="margin:0;min-height:100vh;display:grid;place-items:center;background:#10151e;+color:#e7edf7;font:15px/1.6 'Segoe UI','Noto Sans CJK SC','Noto Sans SC',system-ui,sans-serif"><main style="max-width:520px;+padding:28px 32px;border:1px solid #2a3443;border-radius:12px;background:#1a222e"><h1 style="margin:0 0 10px;font-size:19px">+This FreeVideo server opens from its access link</h1><p style="margin:0 0 18px;color:#a5b3c6">To show the link, run+<code>freevideo status</code> on the server.</p><h1 style="margin:0 0 10px;font-size:19px">请使用访问链接打开这台 FreeVideo 服务器</h1>+<p style="margin:0;color:#a5b3c6">在服务器上运行 <code>freevideo status</code> 即可查看链接。</p></main></body></html>"""+++def matches(value, token):+ return bool(value) and hmac.compare_digest(value.encode(), token.encode())+++def supplied(request):+ header = request.headers.get('Authorization', '')+ return request.cookies.get(COOKIE) or (header[7:].strip() if header[:7].lower() == 'bearer ' else '')+++def denied(request):+ if 'text/html' in request.headers.get('Accept', ''):+ return web.Response(status=401, text=DENIED, content_type='text/html')+ return web.json_response(dict(error='This FreeVideo server needs its access token.'), status=401)+++def forwarded(request):+ """The browser's headers for ComfyUI, minus this connection's and our cookie.++ Host and Origin pass through unchanged: ComfyUI compares them only for a+ loopback Host, as a guard against other websites, and they match here.+ """+ headers = []+ for name, value in request.headers.items():+ lower = name.lower()+ if lower in HOP_BY_HOP or lower == 'authorization':+ continue+ if lower == 'cookie':+ value = '; '.join(part for part in value.split(';') if part.strip() and+ part.split('=', 1)[0].strip() != COOKIE)+ if not value:+ continue+ headers.append((name, value))+ return headers+++def create(upstream, token):+ upstream = upstream.rstrip('/')+ sockets = 'ws' + upstream[len('http'):]+ client = []++ async def startup(app):+ # No total timeout: downloads and the progress socket last as long as they need.+ client.append(ClientSession(auto_decompress=False, cookie_jar=DummyCookieJar(),+ timeout=ClientTimeout(total=None, sock_connect=10), connector=TCPConnector(limit=0)))++ async def cleanup(app):+ await client[0].close()++ async def forward(request):+ body = request.content if request.body_exists else None+ try:+ async with client[0].request(request.method, URL(upstream + request.raw_path, encoded=True),+ headers=forwarded(request), data=body, allow_redirects=False) as reply:+ response = web.StreamResponse(status=reply.status, reason=reply.reason)+ for name, value in reply.headers.items():+ if name.lower() not in HOP_BY_HOP:+ response.headers.add(name, value)+ if reply.content_length is not None and request.method != 'HEAD':+ response.content_length = reply.content_length+ await response.prepare(request)+ async for chunk in reply.content.iter_chunked(1 << 16):+ await response.write(chunk)+ await response.write_eof()+ return response+ except client_exceptions.ClientConnectorError:+ return web.json_response(dict(error='ComfyUI is not answering yet.'), status=502)++ async def websocket(request):+ browser = web.WebSocketResponse(max_msg_size=0)+ await browser.prepare(request)+ headers = [(k, v) for k, v in forwarded(request) if k.lower() not in (+ 'sec-websocket-key', 'sec-websocket-version', 'sec-websocket-extensions', 'sec-websocket-protocol')]+ try:+ async with client[0].ws_connect(URL(sockets + request.raw_path, encoded=True), headers=headers,+ max_msg_size=0, autoping=True) as comfy:+ async def pump(source, target):+ async for message in source:+ if message.type == WSMsgType.TEXT:+ await target.send_str(message.data)+ elif message.type == WSMsgType.BINARY:+ await target.send_bytes(message.data)+ else:+ break+ tasks = [asyncio.ensure_future(pump(browser, comfy)), asyncio.ensure_future(pump(comfy, browser))]+ _, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)+ for task in pending:+ task.cancel()+ except (client_exceptions.ClientError, ConnectionError):+ pass+ finally:+ await browser.close()+ return browser++ async def handle(request):+ offered = request.rel_url.query.get('token')+ if offered is not None:+ if not matches(offered, token):+ return denied(request)+ # The access link: keep the token in a cookie and show the address without it.+ rest = [(k, v) for k, v in request.rel_url.query.items() if k != 'token']+ response = web.Response(status=303, headers={'Location': request.rel_url.path + ('?' + urlencode(rest) if rest else '')})+ response.set_cookie(COOKIE, token, max_age=DAYS * 86400, httponly=True, samesite='Lax',+ secure=request.secure, path='/')+ return response+ if not matches(supplied(request), token):+ return denied(request)+ if request.headers.get('Upgrade', '').lower() == 'websocket':+ return await websocket(request)+ return await forward(request)++ app = web.Application(client_max_size=0)+ app.on_startup.append(startup)+ app.on_cleanup.append(cleanup)+ app.router.add_route('*', '/{path:.*}', handle)+ return app+++def main(argv=None):+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--listen', required=True)+ parser.add_argument('--port', type=int, required=True)+ parser.add_argument('--upstream', required=True, help='The local ComfyUI, http://127.0.0.1:PORT')+ parser.add_argument('--token-file', type=Path, required=True)+ parser.add_argument('--tls-cert', type=Path)+ parser.add_argument('--tls-key', type=Path)+ args = parser.parse_args(argv)+ token = args.token_file.read_text(encoding='utf-8').strip()+ if len(token) < 32:+ raise SystemExit('The access token is missing or too short: ' + str(args.token_file))+ if not args.upstream.startswith('http://127.0.0.1:'):+ raise SystemExit('The upstream must be the ComfyUI on this computer')+ context = None+ if args.tls_cert:+ context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)+ context.load_cert_chain(args.tls_cert, args.tls_key)+ web.run_app(create(args.upstream, token), host=args.listen, port=args.port, ssl_context=context,+ access_log=None, print=None)+++if __name__ == '__main__':+ main()diff --git a/freevideo_engine/adaln.py b/freevideo_engine/adaln.pyindex 89a2865..33e9954 100644--- a/freevideo_engine/adaln.py+++ b/freevideo_engine/adaln.py@@ -38,11 +38,21 @@ class CachedModulation(torch.nn.Module):self.steps = len(values)for index, values_at_step in enumerate(values):self.register_buffer(f'step_{index}', torch.cat(values_at_step, dim=-1))+ # Steps differ in how many distinct timesteps they carry: the first H3+ # step has video and audio at the same t, so its rows are fewer. The+ # fused pre/post kernels compile for static shapes and recompiled in the+ # second step, mid-request and beside a full step's activations. Rows+ # past a step's own timesteps are never indexed, so the narrower steps+ # repeat their last row up to the widest step; stored tables are unchanged.+ self.rows = max(len(getattr(self, f'step_{index}')) for index in range(self.steps))def forward(self, temb):if self.cursor.index < 0:raise RuntimeError('AdaLN schedule has not started')- return getattr(self, f'step_{self.cursor.index}').chunk(6, dim=-1)+ values = getattr(self, f'step_{self.cursor.index}')+ if len(values) < self.rows:+ values = torch.cat((values, values[-1:].expand(self.rows - len(values), -1)))+ return values.chunk(6, dim=-1)class TableCache:diff --git a/freevideo_engine/adaln_assets.py b/freevideo_engine/adaln_assets.pyindex ddd5a37..cbf047e 100644--- a/freevideo_engine/adaln_assets.py+++ b/freevideo_engine/adaln_assets.py@@ -11,6 +11,7 @@ from pathlib import Path, PurePosixPathimport reimport shutilimport struct+from . import disk_spaceCONTRACT = 'minimax-h3-adaln-silu-linear-3x6-v1'FORMAT = 'freevideo-adaln-v2'@@ -208,7 +209,7 @@ def download_table(root, table, index):raise ValueError('Missing locally computed AdaLN table; original receipt retained: ' + str(path))remaining = sum(r['bytes'] for r in table['files'] ifnot asset_path(root, '%02d.safetensors' % r['index']).is_file())- if shutil.disk_usage(root).free < remaining + 64 * 1024**2:+ if disk_space.free_bytes(root) < remaining + 64 * 1024**2:raise ValueError('Not enough disk space to prepare this sampling preset. Existing files retained.')plan = _download_plan()remote = table['download']@@ -257,7 +258,7 @@ def restore_projections(cache, manifest):raise ValueError('This schedule/LoRA needs original AdaLN weights. Reuse a full prepared cache; ''the slim package has no pinned recovery source.')needed = sum(r['bytes'] for r in missing)- if shutil.disk_usage(cache).free < needed + 1024**3:+ if disk_space.free_bytes(cache) < needed + 1024**3:raise ValueError('This schedule/LoRA needs %.2f GiB of optional AdaLN weights; ''insufficient disk space. Existing model and request retained.' % (needed / 1024**3))print(json.dumps({'event': 'adaln_sources_required', 'bytes': needed,diff --git a/freevideo_engine/backends/mps_int8.py b/freevideo_engine/backends/mps_int8.pyindex 39cd22f..1bddfd2 100644--- a/freevideo_engine/backends/mps_int8.py+++ b/freevideo_engine/backends/mps_int8.py@@ -462,4 +462,3 @@ def install(model, *, stats=None, storage=None, int8_linears=None):stats['modules'] += 1return dict(implementation='mps-int8-tensorops-v1', storage=storage or 'quantize-on-load',modules=stats['modules'])-diff --git a/freevideo_engine/blocks.py b/freevideo_engine/blocks.pyindex 08368de..387f853 100644--- a/freevideo_engine/blocks.py+++ b/freevideo_engine/blocks.py@@ -29,12 +29,14 @@ def chunked_ff(original, chunk):def install_bounded_blocks(model, residual_offload=False):from src.models.ops.fused_block import _compiled, _pre_ref+ from .row_kernels import POST_ROWS, dynamic_rowspre = _compiled('pre', _pre_ref)# Autotuning a mutating kernel clones its full branch input. That extra# ~758 MiB copy defeats reuse under small memory limits. This elementwise# kernel needs no shape search or reduction; use the fixed launch policy.- post = torch.compile(_post_into_branch, dynamic=False,- options={'triton.autotune_pointwise': False})+ # One graph for every row count, like the kernels in row_kernels.+ post = dynamic_rows(torch.compile(_post_into_branch, dynamic=False,+ options={'triton.autotune_pointwise': False}), POST_ROWS)def forward(self, hidden_states, temb, adaln_indices, rotary_emb, attention_mask=None):if torch.is_grad_enabled():diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.pyindex 22bf2f3..3c0625d 100644--- a/freevideo_engine/bootstrap.py+++ b/freevideo_engine/bootstrap.py@@ -28,6 +28,7 @@ from .terminal_ui import TerminalUI, LogProgressfrom .locking import runtime_lock, LOCK_ENVfrom .environments import (ENVIRONMENTS, environment_names, select_layout, role_pythons, constraints_file,bootstrap_versions, uv_file_arguments)+from . import disk_spacefrom . import networkfrom . import processesfrom .system import install_root, venv_python, system_memory, nvidia_smi, memory_sample, curl_executable, missing_curl_message@@ -206,6 +207,7 @@ def inventory(gpu=None):'cpu_threads': os.cpu_count(), 'swap_total_bytes': ram.get('swap_total_bytes'),'swap_free_bytes': ram.get('swap_free_bytes'), 'system_memory': ram,'compiler': shutil.which('cl' if platform.system() == 'Windows' else 'g++'), 'git': usable_git(),+ **({} if platform.system() == 'Windows' else {'make': shutil.which('make')}),'git_found': shutil.which('git')}@@ -335,9 +337,15 @@ def plan(args, *, local_progress=None):errors.append(compatibility['error'])snapshot['cuda_compatibility'] = compatibility# A missing or too old Git is replaced by FreeVideo's own.- for name in () if windows_target else ('compiler',):- if not snapshot.get(name):- errors.append('Missing %s. Run ./setup.sh interactively to install basic tools, then review the engine plan.' % name)+ if not windows_target:+ # ./setup.sh installs these before planning; the desktop launcher names the command instead.+ missing = ([] if snapshot.get('compiler') else ['g++']) + ([] if snapshot.get('make', True) else ['make'])+ if missing:+ from .system import linux_tools_command+ command = linux_tools_command(missing)+ errors.append('Missing %s, needed to build GPU acceleration for this GPU. %s, then check again.' % (+ ' and '.join(missing), 'In a terminal, run: ' + command if command else+ 'Ask your administrator to install them'))if offline_installation(root):# Its sources carry no Git history and its Python is the package's.errors.append('This folder holds an installation from offline packages; automatic installation does not change it. '@@ -441,7 +449,7 @@ def plan(args, *, local_progress=None):present += row['bytes'] if size_matches else 0device = existing_parent(path.parent)entry = groups.setdefault(str(device), {'path': str(device), 'needed_bytes': 0,- 'free_bytes': shutil.disk_usage(device).free})+ 'free_bytes': disk_space.free_bytes(device)})local = (local_reuse or {}).get('matches', {}).get(row['repo'] + '/' + row['file'])model_entries.append((row, 'found' if size_matches else 'verified' if local else 'download'))entry['needed_bytes'] += 0 if size_matches or local and local['method'] == 'hardlink' else row['bytes']@@ -455,7 +463,11 @@ def plan(args, *, local_progress=None):# future source deletion toward the space needed to complete conversion.dependencies = dependency_status(root, layout, system)environments_ready = all(r['exists'] and not r['missing'] and not r['mismatched'] for r in dependencies.values())- extra = (0 if reuse_cache or prepared else 52) + (5 if environments_ready else 30 if layout == 'unified' else 45) + 10+ # A Mac environment has no CUDA packages: a fresh one measured 4.3 GB+ # including the package cache, against 30 GiB allowed for CUDA ones.+ environment_gib = ((1 if environments_ready else 6) if mac_target else+ 5 if environments_ready else 30 if layout == 'unified' else 45)+ extra = (0 if reuse_cache or prepared else 52) + environment_gib + 10frontend = Noneif getattr(args, 'frontend_root', None):frontend = dict(root=str(args.frontend_root.expanduser().resolve()),@@ -467,9 +479,11 @@ def plan(args, *, local_progress=None):eligible=bool(windows_target and layout == 'unified' and (reuse_cache or prepared)and getattr(args, 'model_downloader', 'auto') != 'xet'),environments_ready=environments_ready, frontend=frontend,- keep_extreme=reviewed.get('disk_mode') == 'extreme')+ keep_extreme=reviewed.get('disk_mode') == 'extreme', frontend_gib=disk_space.frontend_gib(mac_target))extra = disk_plan['environment_cache_safety_gib']errors.extend(disk_plan['errors'])+ if mac_target:+ errors.extend(disk_space.problem_messages([root, model_dir, encoder_dir] + ([frontend['root']] if frontend else [])))if reuse_cache and not cache_compatible(reuse_cache, **cache_format):errors.append('--cache must contain a prepared FP8 cache compatible with this GPU scale format.')from .download_settings import read as download_preferences@@ -1080,10 +1094,13 @@ class Installer:self.ui.begin(key, title, detail=str(log) if self.ui.verbose else detail)progress = LogProgress(log)parallel_tasks = set()+ models_step = label == 'models'def update_progress(*, final=False):self.ui.update(key, **progress.read(final=final))if progress.model_groups is not None:self.ui.event('models', groups=progress.model_groups)+ if models_step and getattr(self, 'model_bytes_callback', None):+ self.model_bytes_callback(progress.model_groups)progress.model_groups = Nonefor name, details in progress.take_tasks().items():subkey = key + '-' + name@@ -1576,12 +1593,27 @@ class Installer:tasks, pythons, comfy = self.component_tasks(uv)total = len(tasks) + 4 # Bootstrap, preparation, checks and final readiness.phase = 'Install with space saver' if self.plan.get('disk_mode') == 'extreme' else 'Install components in parallel'+ weighted = dict(finished=set(), fetched=0, shown=1.)+ def publish():+ with self.state_lock:+ units = install_phase_units(len(tasks), weighted['finished'], self.plan.get('model_download_bytes') or 0,+ weighted['fetched'])+ # Never step back: a restarted file may report fewer bytes for a moment.+ weighted['shown'] = done = max(weighted['shown'], 1 + units)+ self.ui.phase(phase, done, total)def scheduling(name, status, completed, count):with self.state_lock:self.state.setdefault('schedule', {})[name] = dict(status=status, after=tasks[name]['after'],exclusive_writers=tasks[name]['writes'], epoch=time.time())save(self.run_dir / 'status.json', self.state)- self.ui.phase(phase, 1 + completed, total)+ if status in ('complete', 'skipped'):+ weighted['finished'].add(name)+ publish()+ def model_bytes(groups):+ weighted['fetched'] = sum(min(group.get('download_bytes') or 0, group.get('downloaded_bytes') or 0)+ for group in groups or ())+ publish()+ self.model_bytes_callback = model_bytesself.ui.phase(phase, 1, total)results = run(tasks, self.cancel, progress=scheduling,workers=1 if self.plan.get('disk_mode') == 'extreme' else 3)@@ -1613,6 +1645,26 @@ class Installer:return configuration+# What the rest of an installation weighs against the model download in the+# overall bar: PyTorch wheels, packages, sources and checks, as bytes.+INSTALL_PHASE_OTHER_BYTES = 6 * 2**30+++def install_phase_units(tasks, finished, download_bytes, fetched_bytes):+ """Units of the parallel install phase completed, out of ``tasks``.++ Counting finished tasks left the overall bar still for the whole model+ download (one task, most of the time). That task now takes a share of the+ phase in proportion to its bytes and advances with the bytes fetched.+ """+ if download_bytes <= 0:+ return len(finished)+ share = download_bytes / (download_bytes + INSTALL_PHASE_OTHER_BYTES)+ others = len(finished - {'models'})+ models = 1. if 'models' in finished else min(1., max(0, fetched_bytes) / download_bytes)+ return tasks * ((1 - share) * others / max(1, tasks - 1) + share * models)++class Prefetcher:"""Download the prepared model an installation is switching to, beside the one in use.@@ -1728,6 +1780,8 @@ def main(argv=None):parser.add_argument('--hardware-json', type=Path, help='Offline inventory fixture, only with --plan')parser.add_argument('--yes', action='store_true')parser.add_argument('--accept-model-license', action='store_true')+ parser.add_argument('--no-launch', action='store_true',+ help='Linux: finish after the engine instead of installing ComfyUI and opening FreeVideo')parser.add_argument('--approved-plan', type=Path, help='GUI confirmation receipt; changed paths, models or larger disk/download requirements require a new review')args = parser.parse_args(argv)if not 1 <= args.network_timeout <= 30:@@ -1813,10 +1867,14 @@ def main(argv=None):installer.locks.close()ui.close()if installer.state['status'] == 'complete':- entry = '.\\test.ps1' if platform.system() == 'Windows' else './test.sh'- print('\nSetup complete. Next: %s --root "%s"' % (entry, installer.root))if args.verbose:print('Configuration: %s' % (installer.root / 'machine.json'))+ from .comfy_service import after_setup, continues_after_setup+ if continues_after_setup(no_launch=args.no_launch, approved_plan=args.approved_plan):+ print('\nSetup complete.')+ return after_setup(installer.root)+ entry = '.\\test.ps1' if platform.system() == 'Windows' else './test.sh'+ print('\nSetup complete. Next: %s --root "%s"' % (entry, installer.root))return 0ui.event('failure', error=installer.state.get('resource_guard') or installer.state['error'])print('\nSetup failed: %s\nAll files retained. Logs: %s\nRerun the same setup command to resume.' %diff --git a/freevideo_engine/comfy_assets.py b/freevideo_engine/comfy_assets.pyindex a6e230b..2b9cf7d 100644--- a/freevideo_engine/comfy_assets.py+++ b/freevideo_engine/comfy_assets.py@@ -18,6 +18,10 @@ def saved_video(output, output_directory):if getattr(args, 'enable_assets', False):# ComfyUI enriches output entries itself when global assets are on.return entry+ from app.database.db import can_create_session+ if not can_create_session():+ # Newer ComfyUI opens its database only with assets on; without it there is no library to add to.+ return entryfrom app.assets.services.ingest import register_file_in_placeregistered = register_file_in_place(abs_path=str(output), name=output.name, tags=['output'])entry['id'] = registered.ref.iddiff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.pyindex 12b6564..c5d338f 100644--- a/freevideo_engine/comfy_launcher_runtime.py+++ b/freevideo_engine/comfy_launcher_runtime.py@@ -20,6 +20,7 @@ from urllib.parse import urlsplit, urlunsplitfrom urllib.request import ProxyHandler, Request, build_openerfrom .comfy_bridge import installation+from . import disk_spacefrom .comfy_environment import isolated_environmentfrom .comfy_setup import Setup, SetupRunnerfrom .comfy_source import SOURCE_DISK_BYTES, new_layout, validate_target@@ -35,27 +36,21 @@ def disk_review(plan, engine, comfy, *, separate, new_comfy):"""Add frontend costs to the right volume, including cross-drive installs."""frontend = plan.get('frontend')if frontend and frontend['root'] == str(Path(comfy).resolve()) and frontend['separate'] == separate:- from .install_disk import existing, errors- disks = [dict(disk, paths=list(disk['paths']),- free_bytes=shutil.disk_usage(existing(disk['paths'][0])).free)+ from .install_disk import errors+ disks = [dict(disk, paths=list(disk['paths']), free_bytes=disk_space.free_bytes(disk['paths'][0]))for disk in plan.get('disks', [])]return 0, disks, errors(disks) # Already included before automatic mode selection.- def existing(path):- path = Path(path)- while not path.exists() and path != path.parent:- path = path.parent- return pathdisks = {}for disk in plan.get('disks', []):- parent = existing(disk['paths'][0])- disks[parent.stat().st_dev] = dict(disk, paths=list(disk['paths']))+ disks[disk_space.disk_key(disk['paths'][0])] = dict(disk, paths=list(disk['paths']))extra = 0- for path, amount in ((engine, 12 * 2**30 if separate else 0), (comfy, SOURCE_DISK_BYTES if new_comfy else 0)):+ frontend_bytes = disk_space.frontend_gib(sys.platform == 'darwin') * 2**30+ for path, amount in ((engine, frontend_bytes if separate else 0), (comfy, SOURCE_DISK_BYTES if new_comfy else 0)):if not amount:continue- parent = existing(path)- disk = disks.setdefault(parent.stat().st_dev, dict(paths=[str(parent)], needed_bytes=0))- disk['free_bytes'] = shutil.disk_usage(parent).free+ parent = disk_space.existing(path)+ disk = disks.setdefault(disk_space.disk_key(parent), dict(paths=[str(parent)], needed_bytes=0))+ disk['free_bytes'] = disk_space.free_bytes(parent)disk['needed_bytes'] += amountextra += amountfrom .install_disk import errors@@ -137,7 +132,8 @@ def probe_host(descriptor, python=None):if not python:return dict(ready=False, python=None, libraries=[str(Path(descriptor['root']) / 'models')],reason='No ComfyUI Python found; prepare a separate environment.')- env = dict(os.environ, PYTHONUTF8='1', PYTHONDONTWRITEBYTECODE='1')+ from .linux_bundle import child_environment+ env = dict(child_environment(), PYTHONUTF8='1', PYTHONDONTWRITEBYTECODE='1')# SystemRoot and Windows crypto variables must survive even an isolated test.for name in ('PYTHONPATH', 'PYTHONHOME', 'VIRTUAL_ENV', 'CONDA_PREFIX'):env.pop(name, None)@@ -252,6 +248,13 @@ def shield_engine(engine):return True+def checkout_entry(data, folder):+ """A FreeVideo checkout's own entry point, put back by git, a node updater or a copied repository."""+ text = data.decode('utf-8', 'replace')+ return ('async def comfy_entrypoint' in text and 'from .freevideo_engine.' in text+ and (Path(folder) / 'freevideo_engine' / 'comfy_nodes.py').is_file())++def deploy(root, source, engine):"""Update only our entry point; preserve source edits, libraries and templates."""root, source, engine = map(lambda p: Path(p).resolve(), (root, source, engine))@@ -262,8 +265,10 @@ def deploy(root, source, engine):previous = json.loads(receipt.read_text(encoding='utf-8')) if receipt.is_file() else {}entry = target / '__init__.py'old = entry.read_bytes() if entry.is_file() else None- if old and previous.get('entry_sha256') and hashlib.sha256(old).hexdigest() != previous['entry_sha256']:- raise ValueError('The managed FreeVideo entry point was edited. Changes are retained; restore it before updating.')+ if (old and previous.get('entry_sha256') and hashlib.sha256(old).hexdigest() != previous['entry_sha256']+ and not checkout_entry(old, target)):+ raise ValueError(f'The managed FreeVideo entry point ({entry}) was edited. Changes are retained; '+ 'undo them or delete that file before updating.')# The small loader may be replaced; all original checkout files remain intact.code = ("# Installed by FreeVideo launcher. Original entry points are retained in the engine launcher/backups folder.\n""import importlib.util as _util\nimport json as _json\nfrom pathlib import Path as _Path\nimport sys as _sys\n"@@ -324,7 +329,7 @@ class Controller:self.update_bridge = None# Earlier FreeVideo copies removed in the background once ComfyUI runs# this version; kept out of `state`, which the task thread replaces.- self.old_versions = dict(released_bytes=0)+ self.old_versions = dict(released_bytes=0, download_bytes=0)self._old_versions_thread = Nonedef retire_old_versions(self, selected):@@ -342,7 +347,8 @@ class Controller:engine_source=selected['source'], server_source=server_info(selected['url']).get('source'))except Exception as error: # Cleanup never affects using ComfyUI.result = dict(released_bytes=0, error=type(error).__name__ + ': ' + str(error))- self.old_versions = dict(result, released_bytes=self.old_versions['released_bytes'] + result['released_bytes'])+ self.old_versions = dict(result, released_bytes=self.old_versions['released_bytes'] + result['released_bytes'],+ download_bytes=self.old_versions.get('download_bytes', 0) + result.get('download_bytes', 0))self._old_versions_thread = threading.Thread(target=work, name='freevideo-old-versions', daemon=True)self._old_versions_thread.start()@@ -452,8 +458,9 @@ class Controller:self.state = dict(status='ready', engine_update_available=not matching_source(self.source, source),selection=dict(self.selection))self.restore_terminal(engine)+ from .linux_bundle import appimagefrom .system import windows- if windows() and getattr(sys, 'frozen', False):+ if getattr(sys, 'frozen', False) and (windows() or appimage() is not None):# Opening the launcher repairs a missing, broken or stale shortcut# even when no launch follows, such as one that failed to start.self.ensure_shortcut()@@ -697,8 +704,11 @@ class Controller:deadline = time.monotonic() + 10while True:with socket.socket(socket.AF_INET6 if parsed.hostname == '::1' else socket.AF_INET, socket.SOCK_STREAM) as check:- if sys.platform == 'darwin':- # Reopening our own server must tolerate TIME_WAIT on macOS.+ if sys.platform != 'win32':+ # Reopening a server that just stopped must tolerate its+ # connections in TIME_WAIT, as ComfyUI's own bind does. A+ # listening socket still refuses the bind. (On Windows the+ # option would let two servers share the port.)check.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)try:check.bind((parsed.hostname, parsed.port or 80))diff --git a/freevideo_engine/comfy_metadata.py b/freevideo_engine/comfy_metadata.pyindex 745a8e4..1a87aa2 100644--- a/freevideo_engine/comfy_metadata.py+++ b/freevideo_engine/comfy_metadata.py@@ -13,6 +13,7 @@ import shutilimport threadingimport timeimport uuid+from . import disk_spaceBACKFILL_MARKER = '.workflow-backfill.json'BACKUP_NAME = 'video.before-workflow.mp4'@@ -37,7 +38,7 @@ def embed_comfy_metadata(path, *, prompt=None, workflow=None, backup=None):if backup is not None and backup.exists():logging.info('FreeVideo left %s unchanged: %s already exists.', path, backup.name)return False- if shutil.disk_usage(path.parent).free < 2 * size + 512 * 1024 * 1024:+ if disk_space.free_bytes(path.parent) < 2 * size + 512 * 1024 * 1024:logging.info('FreeVideo left %s unchanged: not enough free disk space.', path)return False# faststart puts moov, and with it the metadata, before the media data.diff --git a/freevideo_engine/comfy_service.py b/freevideo_engine/comfy_service.pynew file mode 100644index 0000000..8200174--- /dev/null+++ b/freevideo_engine/comfy_service.py@@ -0,0 +1,851 @@+"""FreeVideo in ComfyUI from a Linux terminal: install once, then open, serve and stop.++The graphical launcher's control plane does the work: the same ComfyUI+application and environment, the same node installation and the same startup+checks. ComfyUI keeps running in a background service after the command+returns, and `freevideo stop` ends it. ComfyUI itself listens on this computer+only. Other computers reach it through an SSH tunnel, or through the+token-protected proxy that `freevideo server --listen ADDRESS` puts in front of+it; nothing is reachable from outside when that proxy is not running.+"""+import argparse+import getpass+import hashlib+import ipaddress+import json+import os+from pathlib import Path+import secrets+import shlex+import shutil+import signal+import socket+import subprocess+import sys+import threading+import time++from .monitoring import save++DEFAULT_PORT = 8188+RECORD = 'comfyui-cli.json'+STATE = 'service.json'+TOKEN = 'access-token'+UNIT = 'freevideo.service'+WRAPPER_MARK = '# FreeVideo command, written by FreeVideo setup.'+DESKTOP_ID = 'freevideo.desktop'+LOOPBACK = ('127.0.0.1', 'localhost', '::1')+COMMANDS = ('open', 'stop', 'status', 'restart', 'server')+++def say(*args):+ print(*args, flush=True)+++def source_root():+ return Path(__file__).resolve().parents[1]+++def folder(root):+ return Path(root) / 'launcher'+++def read_json(path):+ try:+ value = json.loads(Path(path).read_text(encoding='utf-8'))+ return value if isinstance(value, dict) else None+ except (OSError, ValueError):+ return None+++def source_stamp(source):+ """What the running node loaded, to restart it after `git pull`."""+ from .desktop_runtime import source_files+ source = Path(source)+ digest = hashlib.sha256()+ for path in source_files(source):+ digest.update(path.relative_to(source).as_posix().encode() + b'\0' + hashlib.sha256(path.read_bytes()).digest())+ return digest.hexdigest()[:16]+++def ready_machine(root):+ machine = read_json(Path(root) / 'machine.json')+ return machine if machine and machine.get('ready') else None+++def installed(root):+ """The ComfyUI this command installed for the engine at root."""+ record = read_json(folder(root) / RECORD)+ keys = ('root', 'engine', 'source', 'python', 'url')+ if not record or not all(isinstance(record.get(k), str) and record[k] for k in keys):+ return None+ return dict(record, separate=True)+++def port_of(url):+ from urllib.parse import urlsplit+ return urlsplit(url).port or 80+++def loopback(address):+ if address in LOOPBACK:+ return True+ try:+ return ipaddress.ip_address(address).is_loopback+ except ValueError:+ return False+++def install(root, source, machine, port, out=say):+ """The pinned ComfyUI in <root>/ComfyUI with its own environment, and our node in it."""+ from .comfy_launcher_runtime import deploy, managed_python+ from .comfy_source import new_layout+ layout = new_layout(str(root))+ comfy = Path(layout['root'])+ python = managed_python(Path(root), comfy) if (comfy / 'main.py').is_file() else None+ if python is None:+ out('Installing ComfyUI for FreeVideo. This happens once; the next start takes seconds.')+ # The engine's Python reads the CUDA packages the ComfyUI environment must match.+ code = ("import runpy,sys;sys.path.insert(0,sys.argv.pop(1));"+ "runpy.run_module('freevideo_engine.comfy_host',run_name='__main__')")+ command = [machine['python'], '-B', '-c', code, str(source), '--root', str(root), '--comfy', str(comfy)]+ if not (comfy / 'main.py').is_file():+ command.append('--download-comfy')+ env = dict(os.environ, FREEVIDEO_HOME=str(root), PYTHONUTF8='1', PYTHONIOENCODING='utf-8')+ for name in ('PYTHONPATH', 'PYTHONHOME', 'VIRTUAL_ENV', 'FREEVIDEO_UI_EVENTS'):+ env.pop(name, None)+ if subprocess.run(command, cwd=str(root), env=env, stdin=subprocess.DEVNULL).returncode:+ raise RuntimeError('ComfyUI could not be installed. Run the same command again to continue; '+ 'downloaded files are kept.')+ python = managed_python(Path(root), comfy)+ if python is None:+ raise RuntimeError('ComfyUI was installed, but its environment is incomplete. Run the same command again.')+ deploy(comfy, source, root)+ record = dict(root=str(comfy), engine=str(Path(root)), source=str(source), python=python,+ url='http://127.0.0.1:%d' % port)+ save(folder(root) / RECORD, record)+ return dict(record, separate=True)+++# --- the background service -------------------------------------------------++def lock_path(root):+ return folder(root) / 'service.lock'+++def acquire(path, *, wait=0.):+ """Hold the service lock for this process's life. A probe from `status` may hold it for a moment."""+ import fcntl+ path.parent.mkdir(parents=True, exist_ok=True)+ stream = open(path, 'a+b')+ deadline = time.monotonic() + wait+ while True:+ try:+ fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)+ return stream+ except BlockingIOError:+ if time.monotonic() >= deadline:+ stream.close()+ raise+ time.sleep(.1)+++def running(root):+ """The service's state while its process holds the service lock, else None."""+ import fcntl+ path = lock_path(root)+ try:+ stream = open(path, 'rb')+ except OSError:+ return None+ with stream:+ try:+ fcntl.flock(stream, fcntl.LOCK_SH | fcntl.LOCK_NB)+ return None+ except BlockingIOError:+ pass+ state = read_json(folder(root) / STATE) or {}+ return state if state.get('status') in ('starting', 'open') else dict(state, status='starting')+++def service_pids(root):+ from .locking import lock_holders+ pids = []+ for pid in lock_holders([lock_path(root)]):+ try:+ if b'freevideo_engine.comfy_service' in Path('/proc/%d/cmdline' % pid).read_bytes():+ pids.append(pid)+ except OSError:+ pass+ return pids+++def first_free_port(start=DEFAULT_PORT, count=12):+ """The first installation takes 8188, or the next free port when another ComfyUI already has it."""+ for port in range(start, start + count):+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:+ probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # As ComfyUI binds.+ try:+ probe.bind(('127.0.0.1', port))+ return port+ except OSError:+ continue+ return start+++def free_port():+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:+ probe.bind(('127.0.0.1', 0))+ return probe.getsockname()[1]+++def token(root, renew=False):+ """The access token, readable by this account only, kept across restarts."""+ path = folder(root) / TOKEN+ if not renew:+ try:+ value = path.read_text(encoding='utf-8').strip()+ if len(value) >= 32:+ return value+ except OSError:+ pass+ path.parent.mkdir(parents=True, exist_ok=True)+ value = secrets.token_urlsafe(32)+ temporary = path.with_name(TOKEN + '.' + secrets.token_hex(4))+ descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ with os.fdopen(descriptor, 'w', encoding='utf-8') as stream:+ stream.write(value + '\n')+ os.replace(temporary, path)+ return value+++def request(url, *, headers=None, timeout=3):+ """Status of a GET without following redirects; loopback requests skip any proxy."""+ import ssl+ import urllib.error+ from urllib.request import HTTPRedirectHandler, HTTPSHandler, ProxyHandler, Request, build_opener++ class Stay(HTTPRedirectHandler):+ def redirect_request(self, *args, **kwargs):+ return None+ context = ssl.create_default_context()+ context.check_hostname, context.verify_mode = False, ssl.CERT_NONE # Our own certificate, possibly self-signed.+ opener = build_opener(ProxyHandler({}), Stay(), HTTPSHandler(context=context))+ try:+ with opener.open(Request(url, headers=headers or {}), timeout=timeout) as reply:+ return reply.status+ except urllib.error.HTTPError as error:+ return error.code+++def start_proxy(record, *, listen, port, upstream, token_file, tls):+ """Run the access proxy with ComfyUI's Python, which brings aiohttp."""+ from . import processes+ code = ("import runpy,sys;sys.path.insert(0,sys.argv.pop(1));"+ "runpy.run_module('freevideo_engine.access_proxy',run_name='__main__')")+ command = [record['python'], '-B', '-c', code, record['source'], '--listen', listen, '--port', str(port),+ '--upstream', upstream, '--token-file', str(token_file)]+ if tls:+ command += ['--tls-cert', str(tls[0]), '--tls-key', str(tls[1])]+ env = dict(os.environ, PYTHONUTF8='1', PYTHONNOUSERSITE='1')+ for name in ('PYTHONPATH', 'PYTHONHOME', 'VIRTUAL_ENV'):+ env.pop(name, None)+ log = folder(record['engine']) / 'access-proxy.log'+ with log.open('ab') as output:+ return processes.popen(command, cwd=record['engine'], env=env, stdin=subprocess.DEVNULL,+ stdout=output, stderr=subprocess.STDOUT, start_new_session=True, supervise=True)+++def check_proxy(proxy, *, scheme, port, secret, timeout=30):+ """Refuse to serve unless requests without the token are turned away."""+ base = '%s://127.0.0.1:%d' % (scheme, port)+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if proxy.poll() is not None:+ raise RuntimeError('The access proxy stopped while starting; see %s.' % 'launcher/access-proxy.log')+ try:+ refused = request(base + '/system_stats')+ allowed = request(base + '/system_stats', headers={'Authorization': 'Bearer ' + secret})+ except OSError:+ time.sleep(.3)+ continue+ if refused == 401 and allowed == 200:+ return+ raise RuntimeError('The access proxy did not protect ComfyUI (status %s without the token, %s with it).' % (refused, allowed))+ raise RuntimeError('The access proxy did not start within %d s.' % timeout)+++def serve(root, *, port=DEFAULT_PORT, listen='127.0.0.1', tls=None):+ """Run ComfyUI until stopped. Exactly one service per installation."""+ from .comfy_launcher_runtime import Controller+ root = Path(root).resolve()+ state_file = folder(root) / STATE+ stopping = threading.Event()+ try:+ lease = acquire(lock_path(root), wait=3)+ except BlockingIOError:+ print('FreeVideo is already running for %s.' % root, file=sys.stderr)+ return 1+ with lease:+ state = dict(status='starting', pid=os.getpid(), port=port, listen=listen, started=time.time(),+ tls=[str(p) for p in tls] if tls else None)+ save(state_file, state)+ controller = proxy = None+ previous = {}+ try:+ record = installed(root)+ if record is None:+ raise RuntimeError('ComfyUI is not installed for this installation yet. Run freevideo once to install it.')+ proxied = not loopback(listen)+ internal = free_port() if proxied else port+ controller = Controller(Path(record['source']))+ for name in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):+ previous[name] = signal.signal(name, lambda *_: (stopping.set(), controller.cancelled.set()))+ if not controller.restore({'installation': dict(record, url='http://127.0.0.1:%d' % internal)}):+ raise RuntimeError('This installation is incomplete. Run ./setup.sh again; downloaded files are reused.')+ stamp = source_stamp(record['source'])+ try:+ controller._connect()+ except ValueError as error:+ if 'port is in use' not in str(error):+ raise+ raise RuntimeError('Port %d is in use by another program. Start FreeVideo on another port, for '+ 'example: freevideo open --port %d' % (internal, internal + 2)) from None+ if controller.state.get('status') == 'restart-required':+ raise RuntimeError('Another ComfyUI already uses port %d. Stop it, or start FreeVideo on another port, '+ 'for example: freevideo open --port %d' % (internal, internal + 2))+ if controller.state.get('status') != 'open':+ raise RuntimeError(controller.state.get('error') or 'ComfyUI did not open')+ local = 'http://127.0.0.1:%d' % internal+ state.update(url=local, source_stamp=stamp, comfy_log=str(controller.server_log or ''),+ owned=controller.owns_server())+ if not controller.owns_server():+ # Our nodes already run in a ComfyUI started elsewhere, such as the desktop launcher.+ save(state_file, dict(state, status='external'))+ return 0+ if proxied:+ secret = token(root)+ scheme = 'https' if tls else 'http'+ proxy = start_proxy(record, listen=listen, port=port, upstream=local,+ token_file=folder(root) / TOKEN, tls=tls)+ check_proxy(proxy, scheme=scheme, port=port, secret=secret)+ state.update(access=dict(scheme=scheme, port=port))+ save(state_file, dict(state, status='open'))+ while not stopping.wait(1):+ if controller.server is None or controller.server.poll() is not None:+ from .failure_details import startup_failure+ raise RuntimeError(startup_failure('ComfyUI stopped.', Path(controller.server_log),+ exit_code=getattr(controller.server, 'returncode', None)))+ if proxy is not None and proxy.poll() is not None:+ raise RuntimeError('The access proxy stopped; ComfyUI was stopped with it. See launcher/access-proxy.log.')+ save(state_file, dict(state, status='stopped', stopped=time.time()))+ return 0+ except BaseException as error:+ if stopping.is_set():+ save(state_file, dict(state, status='stopped', stopped=time.time()))+ return 0+ save(state_file, dict(state, status='failed', error=str(error), stopped=time.time()))+ print('FreeVideo service failed: %s' % error, file=sys.stderr, flush=True)+ return 1+ finally:+ if proxy is not None:+ from . import processes+ processes.stop(proxy, grace=3)+ if controller is not None:+ controller.close()+ for name, handler in previous.items():+ signal.signal(name, handler)+++def spawn(root, *, port, listen='127.0.0.1', tls=None):+ """Start the service so that it outlives this command and its terminal."""+ root = Path(root).resolve()+ folder(root).mkdir(parents=True, exist_ok=True)+ python = (ready_machine(root) or {}).get('python') or sys.executable+ command = [python, '-B', '-X', 'utf8', '-m', 'freevideo_engine.comfy_service', '--root', str(root),+ 'run', '--port', str(port), '--listen', listen]+ if tls:+ command += ['--tls-cert', str(tls[0]), '--tls-key', str(tls[1])]+ env = dict(os.environ, PYTHONPATH=str(source_root()), PYTHONNOUSERSITE='1')+ for name in ('FREEVIDEO_RUNTIME_LOCK_FD', 'FREEVIDEO_LOCK_PATH', 'PYTHONHOME', 'VIRTUAL_ENV'):+ env.pop(name, None)+ with (folder(root) / 'service.log').open('ab') as output:+ output.write(('\n[%s] freevideo service starting\n' % time.strftime('%Y-%m-%d %H:%M:%S')).encode())+ output.flush()+ return subprocess.Popen(command, cwd=str(root), env=env, stdin=subprocess.DEVNULL, stdout=output,+ stderr=subprocess.STDOUT, start_new_session=True, close_fds=True)+++def wait_until_open(root, process, *, timeout=300, out=say):+ state_file = folder(root) / STATE+ deadline = time.monotonic() + timeout+ shown = time.monotonic()+ interactive = sys.stdout.isatty()+ out('Starting ComfyUI ...')+ while time.monotonic() < deadline:+ state = read_json(state_file) or {}+ mine = state.get('pid') == process.pid+ if mine and state.get('status') in ('open', 'external'):+ return state+ if mine and state.get('status') == 'failed':+ raise RuntimeError(state.get('error') or 'ComfyUI could not start.')+ if process.poll() is not None:+ raise RuntimeError(state.get('error') if mine and state.get('error') else+ 'The FreeVideo service stopped while starting. See %s.' % (folder(root) / 'service.log'))+ if interactive and time.monotonic() - shown >= 15:+ shown = time.monotonic()+ out(' still starting (%d s) ...' % (timeout - (deadline - time.monotonic())))+ time.sleep(.3)+ raise RuntimeError('ComfyUI is still starting after %d s. See %s.' % (timeout, folder(root) / 'service.log'))+++def respawn(root, state, *, port=None):+ """Start again as the service last ran: same address, port and certificate."""+ tls = tuple(Path(p) for p in state['tls']) if isinstance(state.get('tls'), list) else None+ listen = state.get('listen') or '127.0.0.1'+ return spawn(root, port=port or state.get('port') or DEFAULT_PORT, listen=listen, tls=tls)+++def stop(root, *, force=False, out=say):+ from .comfy_launcher_runtime import queue_busy+ state = running(root)+ if state is None:+ out('FreeVideo is not running.')+ return 0+ if not force and state.get('url') and queue_busy(state['url']):+ out('ComfyUI is running a job. Run freevideo stop again after it finishes, or freevideo stop --force to stop it now.')+ return 1+ pids = service_pids(root)+ for pid in pids:+ try:+ os.kill(pid, signal.SIGTERM)+ except ProcessLookupError:+ pass+ deadline = time.monotonic() + 30+ while time.monotonic() < deadline and running(root) is not None:+ time.sleep(.2)+ if running(root) is not None:+ for pid in service_pids(root):+ try:+ os.kill(pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ time.sleep(1)+ out('FreeVideo stopped.' if running(root) is None else 'FreeVideo is still stopping; check freevideo status.')+ return 0 if running(root) is None else 1+++# --- what the person sees ------------------------------------------------------++def desktop_session():+ return bool(os.environ.get('DISPLAY') or os.environ.get('WAYLAND_DISPLAY'))+++def browser_allowed():+ """A local desktop gets a browser window; an SSH session gets the address instead."""+ if os.environ.get('FREEVIDEO_NO_BROWSER') == '1' or not desktop_session():+ return False+ return not os.environ.get('SSH_CONNECTION')+++def open_browser(url):+ import webbrowser+ try:+ return webbrowser.open(url, new=2)+ except (OSError, webbrowser.Error):+ return False+++def ssh_target():+ """How this computer was reached over SSH, for a tunnel command the person can paste."""+ user = getpass.getuser()+ parts = os.environ.get('SSH_CONNECTION', '').split()+ if len(parts) == 4:+ host, port = parts[2], parts[3]+ host = '[%s]' % host if ':' in host else host+ return ('-p %s ' % port if port != '22' else '') + '%s@%s' % (user, host)+ return '%s@%s' % (user, socket.getfqdn())+++def addresses(listen):+ """Addresses other computers can use for a proxy that listens on all interfaces."""+ if listen not in ('0.0.0.0', '::', ''):+ return [listen]+ found = []+ parts = os.environ.get('SSH_CONNECTION', '').split()+ if len(parts) == 4:+ found.append(parts[2])+ for family, target in ((socket.AF_INET, '192.0.2.1'), (socket.AF_INET6, '2001:db8::1')):+ try:+ # connect() on UDP only selects a route; no packet is sent.+ with socket.socket(family, socket.SOCK_DGRAM) as probe:+ probe.connect((target, 9))+ found.append(probe.getsockname()[0])+ except OSError:+ pass+ found = [a for a in dict.fromkeys(found) if not loopback(a)]+ return found or [socket.getfqdn()]+++def host_url(scheme, address, port):+ return '%s://%s:%d' % (scheme, '[%s]' % address if ':' in address else address, port)+++def describe(root, state, *, browser_opened=False, out=say):+ url = state['url'] + '/?freevideo=launch'+ access = state.get('access')+ if access:+ secret = token(root)+ out('FreeVideo is running. Open it from another computer with:')+ for address in addresses(state.get('listen', '')):+ out(' %s/?freevideo=launch&token=%s' % (host_url(access['scheme'], address, access['port']), secret))+ out('Anyone with this link can use FreeVideo on this computer; freevideo server --new-token replaces it.')+ if access['scheme'] == 'http':+ out('The connection is not encrypted. Use it on a network you trust, add --tls-cert/--tls-key, or use an SSH tunnel.')+ out('On this computer: %s' % url)+ elif browser_opened:+ out('FreeVideo is open in your browser: %s' % url)+ else:+ out('FreeVideo is running: %s' % url)+ if os.environ.get('SSH_CONNECTION') or not desktop_session():+ port = port_of(state['url'])+ out('Only this computer can connect. From your own computer, run:')+ out(' ssh -N -L %d:127.0.0.1:%d %s' % (port, port, ssh_target()))+ out('then open http://127.0.0.1:%d/?freevideo=launch in your browser.' % port)+ out('To connect from your local network instead: freevideo server --listen 0.0.0.0')+ if unit_path().exists():+ out('It starts with your user session; to stop that: freevideo server --disable')+ else:+ out('Stop it with: freevideo stop')+++# --- the freevideo command and the menu entry -----------------------------------++def command_line(root, source):+ return [str(Path(source) / 'freevideo'), '--root', str(Path(root).resolve())]+++def write_wrapper(root, source, *, home=None):+ """~/.local/bin/freevideo, so typing freevideo opens this installation from any folder."""+ home = Path(home or Path.home())+ path = home / '.local' / 'bin' / 'freevideo'+ content = '#!/bin/sh\n%s\nexec %s "$@"\n' % (WRAPPER_MARK, ' '.join(shlex.quote(p) for p in command_line(root, source)))+ try:+ if path.is_symlink() or (path.exists() and WRAPPER_MARK not in path.read_text(encoding='utf-8', errors='replace')):+ return dict(status='kept', path=str(path)) # Someone else's freevideo command.+ if path.is_file() and path.read_text(encoding='utf-8') == content:+ return dict(status='present', path=str(path))+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary = path.with_name('.freevideo.' + secrets.token_hex(4))+ temporary.write_text(content, encoding='utf-8')+ temporary.chmod(0o755)+ os.replace(temporary, path)+ except OSError as error:+ return dict(status='failed', path=str(path), error=str(error))+ on_path = any(Path(p).expanduser().resolve() == path.parent.resolve()+ for p in os.environ.get('PATH', '').split(os.pathsep) if p)+ return dict(status='created', path=str(path), on_path=on_path)+++def write_desktop_entry(root, source, *, home=None):+ """An application-menu entry on Linux desktops; servers have no menu to add it to."""+ data = Path(os.environ.get('XDG_DATA_HOME') or Path(home or Path.home()) / '.local' / 'share')+ path = data / 'applications' / DESKTOP_ID+ icon = Path(source) / 'freevideo_engine' / 'assets' / 'icon.png'+ from .desktop_shortcut import desktop_quote+ entry = ' '.join(desktop_quote(p) for p in command_line(root, source) + ['open'])+ content = ('[Desktop Entry]\nType=Application\nName=FreeVideo\nComment=Create videos with FreeVideo in ComfyUI\n'+ 'Comment[zh_CN]=在 ComfyUI 中用 FreeVideo 生成视频\nExec=%s\nIcon=%s\nTerminal=false\n'+ 'Categories=AudioVideo;Video;Graphics;\nStartupNotify=false\n' % (entry, icon))+ try:+ if path.is_file() and path.read_text(encoding='utf-8') == content:+ return dict(status='present', path=str(path))+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content, encoding='utf-8')+ except OSError as error:+ return dict(status='failed', path=str(path), error=str(error))+ return dict(status='created', path=str(path))+++def shortcuts(root, source, out=say):+ wrapper = write_wrapper(root, source)+ if wrapper['status'] == 'created':+ out('Added the freevideo command: %s' % wrapper['path'])+ if not wrapper.get('on_path'):+ out(' It works in new terminals. In this one, run: export PATH="$HOME/.local/bin:$PATH"')+ elif wrapper['status'] == 'kept':+ out('Kept the existing %s; run %s to open FreeVideo.' % (wrapper['path'], ' '.join(command_line(root, source))))+ if desktop_session() and os.environ.get('XDG_CURRENT_DESKTOP'):+ write_desktop_entry(root, source)+++# --- commands ----------------------------------------------------------------------++def ensure_installed(root, port, out=say):+ root = Path(root).expanduser().resolve()+ source = source_root()+ machine = ready_machine(root)+ if machine is None:+ # ./setup.sh also installs the system tools it needs, then continues here.+ raise RuntimeError('FreeVideo is not set up in %s yet. Run ./setup.sh: it installs FreeVideo and ComfyUI, '+ 'then opens FreeVideo.' % root)+ record = installed(root)+ if record is None or Path(record['source']).resolve() != source or not Path(record['python']).is_file():+ record = install(root, source, machine, port or (port_of(record['url']) if record else first_free_port()), out=out)+ else:+ from .comfy_launcher_runtime import deploy+ deploy(record['root'], source, root)+ if port and port_of(record['url']) != port:+ record = dict(record, url='http://127.0.0.1:%d' % port)+ save(folder(root) / RECORD, {k: record[k] for k in ('root', 'engine', 'source', 'python', 'url')})+ return root, source, record+++def open_command(root, *, port=None, browser=True, restart=False, out=say):+ root, source, record = ensure_installed(root, port, out=out)+ shortcuts(root, source, out=out)+ state = running(root)+ if state and state.get('status') == 'starting':+ state = wait_for_running(root, out=out)+ moved = bool(port and state and state.get('port') != port and not state.get('access'))+ if state and (restart or moved or state.get('source_stamp') != source_stamp(source)):+ from .comfy_launcher_runtime import queue_busy+ if queue_busy(state['url']) and not restart:+ out('FreeVideo was updated; it loads the update when ComfyUI restarts after the current job '+ '(freevideo restart).')+ else:+ out('Restarting ComfyUI ...' if restart or moved else 'Restarting ComfyUI to load the updated FreeVideo ...')+ previous = state+ if stop(root, force=restart, out=lambda *_: None):+ raise RuntimeError('ComfyUI did not stop; check freevideo status.')+ state = wait_until_open(root, respawn(root, previous, port=port if moved else None), out=out)+ if state is None:+ state = wait_until_open(root, spawn(root, port=port_of(record['url'])), out=out)+ opened = False+ if browser and browser_allowed():+ opened = open_browser(state['url'] + '/?freevideo=launch')+ describe(root, state, browser_opened=opened, out=out)+ return 0+++def wait_for_running(root, timeout=300, absent=0., out=say):+ """Wait while the service starts; `absent` allows for one that a service manager starts shortly."""+ started = time.monotonic()+ while time.monotonic() - started < timeout:+ state = running(root)+ if state is not None and state.get('status') == 'open':+ return state+ if state is None and time.monotonic() - started >= absent:+ previous = read_json(folder(root) / STATE) or {}+ if previous.get('status') == 'failed':+ raise RuntimeError(previous.get('error') or 'ComfyUI could not start.')+ return None+ time.sleep(.3)+ raise RuntimeError('ComfyUI is still starting. Check freevideo status.')+++def status_command(root, out=say):+ root = Path(root).expanduser().resolve()+ record = installed(root)+ if ready_machine(root) is None:+ out('FreeVideo is not set up in %s. Run ./setup.sh.' % root)+ return 1+ if record is None:+ out('FreeVideo is set up; ComfyUI is not installed yet. Run freevideo to install and open it.')+ return 0+ state = running(root)+ if state is None:+ previous = read_json(folder(root) / STATE) or {}+ out('FreeVideo is not running. Start it with: freevideo')+ reason = (previous.get('error') or '').strip().splitlines()+ if previous.get('status') == 'failed' and reason:+ out('The last start failed: %s' % reason[0][:300])+ out('ComfyUI: %s' % record['root'])+ return 0+ describe(root, state, out=out)+ out('Service: process %s, started %s; logs in %s' % (+ state.get('pid'), time.strftime('%Y-%m-%d %H:%M', time.localtime(state.get('started', 0))), folder(root)))+ return 0+++def tls_pair(cert, key):+ if not cert and not key:+ return None+ if not (cert and key):+ raise ValueError('--tls-cert and --tls-key go together')+ cert, key = Path(cert).expanduser().resolve(), Path(key).expanduser().resolve()+ for path in (cert, key):+ if not path.is_file():+ raise ValueError('File not found: %s' % path)+ return cert, key+++def unit_text(root, source, listen, port, tls):+ command = command_line(root, source) + ['server', '--foreground', '--listen', listen, '--port', str(port)]+ if tls:+ command += ['--tls-cert', str(tls[0]), '--tls-key', str(tls[1])]+ return ('[Unit]\nDescription=FreeVideo (ComfyUI with FreeVideo)\nAfter=network-online.target\n\n'+ '[Service]\nType=simple\nExecStart=%s\nRestart=on-failure\nRestartSec=10\nTimeoutStopSec=60\n\n'+ '[Install]\nWantedBy=default.target\n') % ' '.join(shlex.quote(p) for p in command)+++def unit_path():+ return Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config') / 'systemd' / 'user' / UNIT+++def systemctl(*arguments):+ return subprocess.run(['systemctl', '--user', *arguments], capture_output=True, text=True)+++def enable_unit(root, source, listen, port, tls, out=say):+ if not shutil.which('systemctl') or systemctl('show-environment').returncode:+ raise RuntimeError('systemd user services are not available here. Run freevideo server --foreground '+ 'from your own service manager instead.')+ path = unit_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(unit_text(root, source, listen, port, tls), encoding='utf-8')+ if running(root) is not None:+ stop(root, out=lambda *_: None)+ for arguments in (('daemon-reload',), ('enable', '--now', UNIT)):+ result = systemctl(*arguments)+ if result.returncode:+ raise RuntimeError('systemctl --user %s failed: %s' % (' '.join(arguments), (result.stderr or result.stdout).strip()))+ out('FreeVideo now starts with your user session (%s).' % path)+ linger = subprocess.run(['loginctl', 'show-user', getpass.getuser(), '-P', 'Linger'], capture_output=True, text=True)+ if linger.stdout.strip() != 'yes':+ out('To keep it running after you log out and start it at boot, run once: sudo loginctl enable-linger %s'+ % getpass.getuser())+++def disable_unit(out=say):+ path = unit_path()+ if shutil.which('systemctl'):+ systemctl('disable', '--now', UNIT)+ if path.exists():+ path.unlink()+ systemctl('daemon-reload')+ out('FreeVideo no longer starts with your user session.')+++def server_command(root, *, listen='127.0.0.1', port=None, tls=None, renew=False, foreground=False,+ enable=False, disable=False, force=False, out=say):+ if disable:+ disable_unit(out=out)+ return 0+ root, source, record = ensure_installed(root, port, out=out)+ port = port or port_of(record['url'])+ if not loopback(listen):+ token(root, renew=renew)+ if enable:+ enable_unit(root, source, listen, port, tls, out=out)+ state = wait_for_running(root, absent=20, out=out)+ if state is None:+ out('The service did not start. Check: systemctl --user status %s' % UNIT)+ return 1+ describe(root, state, out=out)+ return 0+ if foreground:+ if running(root) is not None:+ raise RuntimeError('FreeVideo is already running; stop it first (freevideo stop).')+ return serve(root, port=port, listen=listen, tls=tls)+ state = running(root)+ if state and state.get('status') == 'starting':+ state = wait_for_running(root, out=out)+ wanted = dict(listen=listen, port=port, tls=[str(p) for p in tls] if tls else None)+ if state and (any(state.get(k) != v for k, v in wanted.items()) or renew+ or state.get('source_stamp') != source_stamp(source)):+ from .comfy_launcher_runtime import queue_busy+ if queue_busy(state['url']) and not force:+ out('ComfyUI is running a job. Run this again after it finishes, or add --force to restart now.')+ return 1+ stop(root, force=True, out=lambda *_: None)+ state = None+ if state is None:+ state = wait_until_open(root, spawn(root, port=port, listen=listen, tls=tls), out=out)+ describe(root, state, out=out)+ return 0+++def cli(command, root, arguments, out=say):+ """`./freevideo open|stop|status|restart|server` on Linux."""+ if not sys.platform.startswith('linux'):+ out('This command is for Linux. On Windows and macOS, open the FreeVideo app.')+ return 1+ parser = argparse.ArgumentParser(prog='freevideo ' + command)+ if command in ('open', 'restart', 'server'):+ parser.add_argument('--port', type=int, help='Port for ComfyUI (default: the last one used, first %d)' % DEFAULT_PORT)+ if command in ('open', 'restart'):+ parser.add_argument('--no-browser', action='store_true', help='Only start ComfyUI and print its address')+ if command == 'stop':+ parser.add_argument('--force', action='store_true', help='Stop even while ComfyUI is running a job')+ if command == 'server':+ parser.add_argument('--listen', default='127.0.0.1', help='Address to accept connections on. The default '+ 'accepts this computer only (use an SSH tunnel); 0.0.0.0 accepts other computers with the access link.')+ parser.add_argument('--tls-cert', type=Path, help='Certificate for HTTPS on --listen')+ parser.add_argument('--tls-key', type=Path, help='Private key for --tls-cert')+ parser.add_argument('--new-token', action='store_true', help='Replace the access link')+ parser.add_argument('--foreground', action='store_true', help='Run in this terminal or under a service manager')+ parser.add_argument('--enable', action='store_true', help='Start with your user session (systemd)')+ parser.add_argument('--disable', action='store_true', help='Remove the systemd user service')+ parser.add_argument('--force', action='store_true', help='Restart even while ComfyUI is running a job')+ args = parser.parse_args(arguments)+ if getattr(args, 'port', None) is not None and not 1024 <= args.port <= 65535:+ parser.error('--port must be between 1024 and 65535')+ try:+ if command == 'open':+ return open_command(root, port=args.port, browser=not args.no_browser, out=out)+ if command == 'restart':+ return open_command(root, port=args.port, browser=not args.no_browser, restart=True, out=out)+ if command == 'stop':+ return stop(root, force=args.force, out=out)+ if command == 'status':+ return status_command(root, out=out)+ if args.enable and args.disable:+ parser.error('--enable and --disable cannot be combined')+ if (args.tls_cert or args.tls_key) and loopback(args.listen):+ parser.error('--tls-cert/--tls-key need --listen with an address other computers use')+ return server_command(root, listen=args.listen, port=args.port, tls=tls_pair(args.tls_cert, args.tls_key),+ renew=args.new_token, foreground=args.foreground, enable=args.enable,+ disable=args.disable, force=args.force, out=out)+ except (RuntimeError, ValueError, OSError) as error:+ print('FreeVideo could not %s: %s' % ('start' if command != 'stop' else 'stop', error), file=sys.stderr)+ return 1+++def continues_after_setup(*, no_launch=False, approved_plan=None, environ=None, system=None):+ """Whether ./setup.sh goes on to open FreeVideo: a terminal setup on Linux does.++ The desktop launcher and the ComfyUI settings panel run setup with UI events+ and an approved plan, and continue on their own.+ """+ import platform+ environ = os.environ if environ is None else environ+ return ((system or platform.system()) == 'Linux' and not no_launch and not approved_plan+ and environ.get('FREEVIDEO_UI_EVENTS') != '1')+++def after_setup(root, out=say):+ """The end of ./setup.sh: install ComfyUI, start it and open FreeVideo."""+ out('')+ try:+ return open_command(root, out=out)+ except (RuntimeError, ValueError, OSError) as error:+ print('\nThe engine is set up, but FreeVideo could not open: %s\nRun freevideo to try again.' % error, file=sys.stderr)+ return 1+++def main(argv=None):+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--root', type=Path, required=True)+ sub = parser.add_subparsers(dest='action', required=True)+ run = sub.add_parser('run', help='Run the service in this process')+ run.add_argument('--port', type=int, default=DEFAULT_PORT)+ run.add_argument('--listen', default='127.0.0.1')+ run.add_argument('--tls-cert', type=Path)+ run.add_argument('--tls-key', type=Path)+ args = parser.parse_args(argv)+ return serve(args.root, port=args.port, listen=args.listen, tls=tls_pair(args.tls_cert, args.tls_key))+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/freevideo_engine/comfy_setup.py b/freevideo_engine/comfy_setup.pyindex c439874..1643a3a 100644--- a/freevideo_engine/comfy_setup.py+++ b/freevideo_engine/comfy_setup.py@@ -123,6 +123,15 @@ class Events:return rows+def owned_comfy(root, host):+ """./setup.sh puts the ComfyUI it installs in <engine>/ComfyUI; that one is the engine's own."""+ from .comfy_source import RECEIPT, specification+ try:+ return host == root / 'ComfyUI' and json.loads((host / RECEIPT).read_text(encoding='utf-8')) == specification()+ except (OSError, ValueError):+ return False++class Setup:def __init__(self, source, folder_paths, runner_factory=SetupRunner):self.source = Path(source).resolve()@@ -209,7 +218,7 @@ class Setup:raise ValueError('Choose an engine installation folder')root = Path(value).expanduser().resolve()host = Path(self.folder_paths.base_path).resolve()- if root == Path(root.anchor) or root == host or root in host.parents:+ if root == Path(root.anchor) or root == host or (root in host.parents and not owned_comfy(root, host)):raise ValueError('Use a dedicated FreeVideo folder, not the ComfyUI root or its parent')prefix = Path(sys.prefix).resolve()# Refuse to pip into the interpreter that is running, and nothing more.diff --git a/freevideo_engine/comfy_updates.py b/freevideo_engine/comfy_updates.pyindex d009ca3..e092c87 100644--- a/freevideo_engine/comfy_updates.py+++ b/freevideo_engine/comfy_updates.py@@ -84,7 +84,7 @@ class UpdateStatus:# Pages that reload themselves after an update polled recently.state['clients'] = int(now - self.client_seen < 20)if launcher is not None:- if launcher.get('channel') in (launcher_update.CHANNEL, launcher_update.MAC_CHANNEL):+ if launcher.get('channel') in launcher_update.CHANNELS:state['channel'] = launcher['channel']if launcher.get('track') in launcher_update.TRACKS:state['track'] = launcher['track']diff --git a/freevideo_engine/decode_prefetch.py b/freevideo_engine/decode_prefetch.pyindex 56dcc83..8880752 100644--- a/freevideo_engine/decode_prefetch.py+++ b/freevideo_engine/decode_prefetch.py@@ -4,7 +4,9 @@ No Torch imports, CUDA allocations, model objects, pinned copies or encoderweights. Only reclaimable OS file cache retains the read data. Native decodingstill validates and loads the original checkpoint after sampling releases VRAM.The sampler starts this reader before its last two steps; the reader can still-stop immediately when the live RAM/Commit allowance is insufficient.+stop immediately when the live RAM/Commit allowance is insufficient. When the+allowance covers only part of the decoder, that part is read and the loader+reads the rest itself."""import jsonimport os@@ -76,17 +78,28 @@ class DecoderReadAhead:used = memory_sample(sample)complete = complete and type(used) is int and used >= 0allowance = min(allowance, max(0, self.ram_budget_bytes - (used or 0) - 2 * GiB))- self.result.update(total_bytes=total, allowance_bytes=allowance)- if not complete or not 0 < total <= allowance:+ # The allowance bounds how much the cache may hold for the decoder,+ # not whether reading is worth it. Short of the whole decoder, read+ # the part that fits: every page read here is one the loader does+ # not wait for after sampling. Pinning a few more transformer layers+ # can leave the allowance just under the decoder's size, and+ # skipping the whole read then costs the entire cold load.+ target = min(total, allowance)+ self.result.update(total_bytes=total, allowance_bytes=allowance, target_bytes=target)+ if not complete or total <= 0 or target < min(total, CHUNK):self.result.update(state='skipped', reason='Live RAM cannot retain decoder pages alongside sampling')returnself.result.update(state='reading', reason='Final denoising steps can overlap decoder disk reads')scratch = bytearray(CHUNK)for path, spans, stamp in plans:+ if self.result['read_bytes'] >= target:+ breakwith path.open('rb', buffering=0) as file:for lo, hi in spans:+ if self.result['read_bytes'] >= target:+ breakfile.seek(lo)- remaining = hi - lo+ remaining = min(hi - lo, target - self.result['read_bytes'])while remaining:available, complete = available_memory()if self.cancelled.is_set() or not complete or available < 2 * GiB + CHUNK:@@ -100,7 +113,10 @@ class DecoderReadAhead:current = path.stat()if (current.st_size, current.st_mtime_ns) != stamp:raise ValueError('VAE checkpoint changed during read-ahead')- self.result.update(state='ready', reason='Decoder pages read while sampling; normal loader reuses surviving OS cache')+ if self.result['read_bytes'] < total:+ self.result.update(state='partial', reason='Decoder pages within the live RAM allowance read while sampling; the loader reads the rest')+ else:+ self.result.update(state='ready', reason='Decoder pages read while sampling; normal loader reuses surviving OS cache')except Exception as error:# Speculative I/O must not replace the normal loader's validation.self.result.update(state='failed', reason=type(error).__name__ + ': ' + str(error))diff --git a/freevideo_engine/desktop_runtime.py b/freevideo_engine/desktop_runtime.pyindex 71805da..37b8958 100644--- a/freevideo_engine/desktop_runtime.py+++ b/freevideo_engine/desktop_runtime.py@@ -240,7 +240,8 @@ class Runner:str(self.source / 'freevideo.ps1'), '--root', str(root), *arguments]def environment(self, root):- return dict(os.environ, PYTHONUTF8='1', PYTHONIOENCODING='utf-8', NO_COLOR='1', FREEVIDEO_UI_EVENTS='1')+ from .linux_bundle import child_environment+ return dict(child_environment(), PYTHONUTF8='1', PYTHONIOENCODING='utf-8', NO_COLOR='1', FREEVIDEO_UI_EVENTS='1')def prepare(self, action, root, env, progress):return envdiff --git a/freevideo_engine/desktop_shortcut.py b/freevideo_engine/desktop_shortcut.pyindex 7cdd0c9..28e28bd 100644--- a/freevideo_engine/desktop_shortcut.py+++ b/freevideo_engine/desktop_shortcut.py@@ -1,4 +1,7 @@-"""A durable, per-user Windows shortcut; no shell scripts or registry writes."""+"""A durable, per-user shortcut: a Windows link, or a Linux desktop entry for the AppImage.++No shell scripts or registry writes.+"""import hashlibimport jsonimport os@@ -297,11 +300,132 @@ def _failure(error, menu_ready):return ' '.join(en), ''.join(zh)+# --- Linux: the AppImage in the application menu and on the desktop ---------------++APP_ID = 'org.flashml.FreeVideo'+APPIMAGE_NAME = 'FreeVideo-Linux-x86_64.AppImage'+++def desktop_quote(value):+ """Desktop Entry quoting: double quotes, with a backslash before \\, ", ` and $."""+ value = str(value).replace('%', '%%')+ if not any(c in value for c in ' \t\n"\'\\><~|&;$*?#()`'):+ return value+ return '"' + ''.join('\\' + c if c in '"`$\\' else c for c in value) + '"'+++def _xdg(variable, fallback):+ value = os.environ.get(variable, '')+ return Path(value) if os.path.isabs(value) else fallback+++def linux_desktop_directory():+ """The desktop folder the file manager shows (XDG_DESKTOP_DIR), which may be localized."""+ config = _xdg('XDG_CONFIG_HOME', Path.home() / '.config') / 'user-dirs.dirs'+ try:+ for line in config.read_text(encoding='utf-8').splitlines():+ if line.startswith('XDG_DESKTOP_DIR='):+ return Path(line.split('=', 1)[1].strip().strip('"').replace('$HOME', str(Path.home())))+ except OSError:+ pass+ return Path.home() / 'Desktop'+++def appimage_target(engine, appimage):+ """A copy of the AppImage for the menu entry, wherever the download itself later goes."""+ fingerprint = digest(appimage)+ parent = copies_folder(engine, fingerprint)+ for root in [parent / fingerprint, *sorted(parent.glob(fingerprint + '-*'))]:+ try:+ if digest(root / APPIMAGE_NAME) == fingerprint and os.access(root / APPIMAGE_NAME, os.X_OK):+ return root / APPIMAGE_NAME+ except OSError:+ continue+ parent.mkdir(parents=True, exist_ok=True)+ stage = parent / ('launcher-' + uuid.uuid4().hex)+ stage.mkdir()+ try:+ shutil.copy2(appimage, stage / APPIMAGE_NAME)+ (stage / APPIMAGE_NAME).chmod(0o755)+ if digest(stage / APPIMAGE_NAME) != fingerprint:+ raise OSError('Launcher changed while preparing the desktop shortcut; retry installation')+ root = parent / fingerprint+ if os.path.lexists(root):+ root = root.with_name(fingerprint + '-' + uuid.uuid4().hex[:8])+ stage.rename(root)+ finally:+ if stage.exists():+ shutil.rmtree(stage, ignore_errors=True)+ return root / APPIMAGE_NAME+++def desktop_entry(target, icon):+ return ('[Desktop Entry]\nType=Application\nName=FreeVideo\nComment=Install and open FreeVideo in ComfyUI\n'+ 'Comment[zh_CN]=安装并在 ComfyUI 中打开 FreeVideo\nExec=%s\nIcon=%s\nTerminal=false\n'+ 'Categories=AudioVideo;Video;Graphics;\nStartupWMClass=FreeVideo\n' % (desktop_quote(target), icon))+++def _write_entry(path, content, *, trusted=False):+ """Write or repair our entry; a file of the same name that starts something else stays."""+ try:+ current = path.read_text(encoding='utf-8', errors='replace')+ except FileNotFoundError:+ current = None+ if current == content:+ return dict(status='present', path=str(path))+ if current is not None and not any(line.startswith('Exec=') and 'FreeVideo' in line for line in current.splitlines()):+ return dict(status='kept', path=str(path))+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary = path.with_name('.' + path.name + '.' + uuid.uuid4().hex[:8])+ temporary.write_text(content, encoding='utf-8')+ temporary.chmod(0o755)+ os.replace(temporary, path)+ if trusted and shutil.which('gio'):+ # GNOME asks before running a desktop launcher it has not been told to trust.+ subprocess.run(['gio', 'set', str(path), 'metadata::trusted', 'true'],+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ return dict(status='created', path=str(path))+++def create_linux(engine):+ from .linux_bundle import appimage+ image = appimage()+ if image is None:+ return dict(status='not-applicable') # Started from a checkout: ./setup.sh adds the freevideo command.+ engine = Path(engine)+ target = appimage_target(engine, image)+ data = _xdg('XDG_DATA_HOME', Path.home() / '.local/share')+ icon = data / 'icons/hicolor/512x512/apps' / (APP_ID + '.png')+ source_icon = Path(__file__).parent / 'assets/icon.png'+ if not icon.is_file() or digest(icon) != digest(source_icon):+ icon.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(source_icon, icon)+ content = desktop_entry(target, icon)+ menu = _write_entry(data / 'applications' / (APP_ID + '.desktop'), content)+ desktop = linux_desktop_directory()+ # A server has no desktop folder; never create one for it.+ result = (_write_entry(desktop / 'FreeVideo.desktop', content, trusted=True) if desktop.is_dir()+ else dict(status='not-applicable', path=str(desktop / 'FreeVideo.desktop')))+ result = dict(result, target=str(target), start_menu=menu)+ if result['status'] == 'not-applicable':+ result['status'] = menu['status']+ receipt = engine / 'launcher/desktop-shortcut.json'+ try:+ previous = json.loads(receipt.read_text(encoding='utf-8'))+ except (OSError, ValueError):+ previous = None+ if result != previous:+ save(receipt, result)+ return result++def create(engine, source, portable_root=None):if not windows():if sys.platform == 'darwin':from .macos_shortcut import create as create_macreturn create_mac(engine)+ if sys.platform.startswith('linux'):+ return create_linux(engine)return dict(status='not-applicable')engine = Path(engine)receipt = engine / 'launcher/desktop-shortcut.json'diff --git a/freevideo_engine/diagnostic_resources.py b/freevideo_engine/diagnostic_resources.pyindex 95ed627..883f5a5 100644--- a/freevideo_engine/diagnostic_resources.py+++ b/freevideo_engine/diagnostic_resources.py@@ -248,11 +248,11 @@ def failure_cleanup(value):def decoder_read_ahead(value):"""Keep bounded decoder overlap evidence without paths or free-form text."""value = mapping(value)- result = numbers(value, ('read_bytes', 'total_bytes', 'allowance_bytes',+ result = numbers(value, ('read_bytes', 'total_bytes', 'allowance_bytes', 'target_bytes','elapsed_seconds', 'private_buffer_bytes','gpu_allocation_bytes'))state = value.get('state')- if state in ('not-started', 'reading', 'ready', 'skipped', 'stopped', 'failed'):+ if state in ('not-started', 'reading', 'ready', 'partial', 'skipped', 'stopped', 'failed'):result['state'] = statesampling = mapping(value.get('sampling'))if sampling:@@ -298,9 +298,9 @@ def weight_placement(value):result = numbers(value, WEIGHT_PLACEMENT)if type(value.get('host_prefetch')) is bool:result['host_prefetch'] = value['host_prefetch']- reason = value.get('host_prefetch_disabled_reason')- if reason in ('host_headroom', 'host_allocation_refused', 'live_host_pressure'):- result['host_prefetch_disabled_reason'] = reason+ for key in ('host_prefetch_disabled_reason', 'host_prefetch_shared_reason'):+ if value.get(key) in ('host_headroom', 'host_allocation_refused', 'live_host_pressure'):+ result[key] = value[key]return result@@ -444,6 +444,9 @@ def resources(value):WINDOWS_BUDGET = ('peak_usage_bytes', 'minimum_budget_bytes', 'maximum_budget_bytes','first_budget_bytes', 'last_budget_bytes', 'budget_changes', 'over_budget_samples', 'samples')+# Whole-device NVML samples inside one sampling step (monitoring.step_activity).+STEP_ACTIVITY = ('samples', 'busy_samples', 'gpu_util_mean_percent', 'sm_clock_mean_mhz', 'power_mean_mw',+ 'device_used_peak_bytes', 'device_used_minimum_bytes', 'device_total_bytes')def dynamic_budget(value):@@ -455,9 +458,10 @@ def dynamic_budget(value):def clean(row):row = mapping(row)item = numbers(row, ('elapsed_seconds', 'previous_limit_bytes', 'candidate_limit_bytes',- 'allocator_limit_bytes', 'live_free_bytes', 'reserved_bytes', 'non_torch_local_bytes', 'driver_budget_bytes'))+ 'allocator_limit_bytes', 'live_free_bytes', 'reserved_bytes', 'non_torch_local_bytes', 'driver_budget_bytes',+ 'device_used_bytes', 'workspace_bytes', 'settle_seconds', 'settle_samples', 'settled_candidate_bytes'))for key, allowed in (('stage', ('load', 'sample', 'upscale', 'decode')),- ('action', ('hold', 'pending', 'shrink', 'grow'))):+ ('action', ('hold', 'pending', 'shrink', 'settled', 'grow'))):if row.get(key) in allowed:item[key] = row[key]if type(row.get('driver_available')) is bool:@@ -504,6 +508,9 @@ def sampling(value):for segment in ('local', 'nonlocal'):item[segment] = numbers(observed.get(segment),WINDOWS_BUDGET)+ device = numbers(row.get('device_activity'), STEP_ACTIVITY)+ if device:+ item['device'] = deviceresult['steps'].append(item)observed = mapping(value.get('incomplete_step_windows'))result['incomplete_step'] = {segment: numbers(observed.get(segment),@@ -526,7 +533,7 @@ def sampling_passes(value):config=numbers(config, ENGINE_KNOBS), offload=weight_placement(row.get('offload')),cache_admission=numbers(row.get('pass_cache_admission'), ('gpu_budget_bytes', 'admitted_bytes','measured_peak_reserved_bytes', 'live_free_bytes', 'commit_available_bytes',- 'requested_resident_blocks', 'workspace_peak_bytes', 'peak_cache_bytes')),+ 'requested_resident_blocks', 'workspace_peak_bytes', 'peak_cache_bytes', 'device_headroom_bytes')),kernels=kernel_receipt(row))item['config'].update({key: config[key] for key in ENGINE_KNOBS if type(config.get(key)) is bool})refinement = mapping(row.get('refinement'))diff --git a/freevideo_engine/diagnostic_summary.py b/freevideo_engine/diagnostic_summary.pyindex 659b360..ff64a4c 100644--- a/freevideo_engine/diagnostic_summary.py+++ b/freevideo_engine/diagnostic_summary.py@@ -117,6 +117,9 @@ def summary_report(report):for segment in ('local','nonlocal'):item[segment] = _measurements((row.get('windows') or {}).get(segment),diagnostic.WINDOWS_BUDGET)+ device = diagnostic.numbers(row.get('device_activity'), diagnostic.STEP_ACTIVITY)+ if device:+ item['device'] = deviceresult['steps'].append(item)sampling = summary.get('sampling_memory') or {}if sampling.get('windows_status') in ('observing','unavailable','not-applicable','reader-still-stopping'):diff --git a/freevideo_engine/disk_space.py b/freevideo_engine/disk_space.pynew file mode 100644index 0000000..0e9ad9b--- /dev/null+++ b/freevideo_engine/disk_space.py@@ -0,0 +1,362 @@+"""Free space as the system's file manager reports it, and the disks a user can pick.++On macOS, statfs (shutil.disk_usage) leaves out purgeable space: APFS local+snapshots, iCloud files kept in the cloud and caches the system removes on+demand. Finder adds it, and so does the volume's capacity for important+usage, which Apple recommends for downloads the user asked for. Volumes of+one APFS container share their space, so they are counted as one disk.+Other systems keep shutil.disk_usage, which matches Explorer and df.+"""+import os+from pathlib import Path+import re+import shutil+import sys+import threading+import time++_HIDDEN_MOUNTS = ('/System/Volumes/', '/private/var/vm', '/Library/Developer/CoreSimulator', '/Volumes/.timemachine')+++def existing(path):+ path = Path(path).expanduser()+ while not path.exists() and path != path.parent:+ path = path.parent+ return path+++if sys.platform == 'darwin':+ import ctypes+ import ctypes.util++ MNT_RDONLY, MNT_LOCAL, MNT_DONTBROWSE = 0x1, 0x1000, 0x00100000++ class _StatFS(ctypes.Structure):+ # struct statfs with 64-bit inodes, the only layout on Apple Silicon.+ _fields_ = [('f_bsize', ctypes.c_uint32), ('f_iosize', ctypes.c_int32),+ ('f_blocks', ctypes.c_uint64), ('f_bfree', ctypes.c_uint64),+ ('f_bavail', ctypes.c_uint64), ('f_files', ctypes.c_uint64),+ ('f_ffree', ctypes.c_uint64), ('f_fsid', ctypes.c_int32 * 2),+ ('f_owner', ctypes.c_uint32), ('f_type', ctypes.c_uint32),+ ('f_flags', ctypes.c_uint32), ('f_fssubtype', ctypes.c_uint32),+ ('f_fstypename', ctypes.c_char * 16), ('f_mntonname', ctypes.c_char * 1024),+ ('f_mntfromname', ctypes.c_char * 1024), ('f_flags_ext', ctypes.c_uint32),+ ('f_reserved', ctypes.c_uint32 * 7)]++ _libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)+ _statfs = getattr(_libc, 'statfs$INODE64' if hasattr(_libc, 'statfs$INODE64') else 'statfs')+ _statfs.argtypes = (ctypes.c_char_p, ctypes.POINTER(_StatFS))+ _getfsstat = getattr(_libc, 'getfsstat$INODE64' if hasattr(_libc, 'getfsstat$INODE64') else 'getfsstat')+ _getfsstat.argtypes = (ctypes.POINTER(_StatFS), ctypes.c_int, ctypes.c_int)++ _cf = None++ def _corefoundation():+ global _cf+ if _cf is None:+ cf = ctypes.CDLL('/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation')+ void = ctypes.c_void_p+ cf.CFURLCreateFromFileSystemRepresentation.restype = void+ cf.CFURLCreateFromFileSystemRepresentation.argtypes = (void, ctypes.c_char_p, ctypes.c_long, ctypes.c_bool)+ cf.CFURLCopyResourcePropertyForKey.restype = ctypes.c_bool+ cf.CFURLCopyResourcePropertyForKey.argtypes = (void, void, ctypes.POINTER(void), ctypes.POINTER(void))+ cf.CFNumberGetValue.restype = ctypes.c_bool+ cf.CFNumberGetValue.argtypes = (void, ctypes.c_int, void)+ cf.CFStringGetCString.restype = ctypes.c_bool+ cf.CFStringGetCString.argtypes = (void, ctypes.c_char_p, ctypes.c_long, ctypes.c_uint32)+ cf.CFGetTypeID.restype = ctypes.c_ulong+ cf.CFGetTypeID.argtypes = (void,)+ cf.CFNumberGetTypeID.restype = ctypes.c_ulong+ cf.CFStringGetTypeID.restype = ctypes.c_ulong+ cf.CFBooleanGetValue.restype = ctypes.c_bool+ cf.CFBooleanGetValue.argtypes = (void,)+ cf.CFBooleanGetTypeID.restype = ctypes.c_ulong+ cf.CFRelease.argtypes = (void,)+ _cf = cf+ return _cf++ def _resource(path, key):+ """One NSURL resource value of the volume holding path (number, string or bool)."""+ cf = _corefoundation()+ name = ctypes.c_void_p.in_dll(cf, key).value+ raw = os.fsencode(str(path))+ url = cf.CFURLCreateFromFileSystemRepresentation(None, raw, len(raw), True)+ if not url or not name:+ return None+ value, error = ctypes.c_void_p(), ctypes.c_void_p()+ try:+ if not cf.CFURLCopyResourcePropertyForKey(url, name, ctypes.byref(value), ctypes.byref(error)):+ if error.value:+ cf.CFRelease(error)+ return None+ if not value.value:+ return None+ try:+ kind = cf.CFGetTypeID(value)+ if kind == cf.CFNumberGetTypeID():+ number = ctypes.c_int64()+ return number.value if cf.CFNumberGetValue(value, 4, ctypes.byref(number)) else None+ if kind == cf.CFStringGetTypeID():+ buffer = ctypes.create_string_buffer(1024)+ return buffer.value.decode('utf-8') if cf.CFStringGetCString(value, buffer, 1024, 0x08000100) else None+ if kind == cf.CFBooleanGetTypeID():+ return bool(cf.CFBooleanGetValue(value))+ return None+ finally:+ cf.CFRelease(value)+ finally:+ cf.CFRelease(url)++ def _stat(path):+ record = _StatFS()+ if _statfs(os.fsencode(str(path)), ctypes.byref(record)) != 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error), str(path))+ return record++ def _describe(record, path=None, *, details=True):+ filesystem = record.f_fstypename.decode('utf-8', 'replace')+ mount = os.fsdecode(record.f_mntonname)+ device = os.fsdecode(record.f_mntfromname)+ free = record.f_bavail * record.f_bsize+ # APFS volumes named diskNsM (and their snapshots, diskNsMsK) share+ # the space of container diskN.+ container = re.match(r'/dev/(disk\d+)s\d+', device) if filesystem == 'apfs' else None+ key = 'apfs:' + container.group(1) if container else 'fs:%d:%d' % tuple(record.f_fsid)+ probe = path or mount+ important = None+ name = None+ if details:+ try:+ important = _resource(probe, 'kCFURLVolumeAvailableCapacityForImportantUsageKey')+ # The Data volume holds the home folder; Finder names it after the system volume.+ name = _resource('/' if mount == '/System/Volumes/Data' else probe, 'kCFURLVolumeLocalizedNameKey')+ except (OSError, ValueError, AttributeError):+ pass+ return dict(key=key, mount=mount, name=name or Path(mount).name or mount, filesystem=filesystem,+ total_bytes=record.f_blocks * record.f_bsize, statfs_free_bytes=free,+ important_free_bytes=important, free_bytes=max(free, important or 0),+ read_only=bool(record.f_flags & MNT_RDONLY), local=bool(record.f_flags & MNT_LOCAL),+ hidden=bool(record.f_flags & MNT_DONTBROWSE))++ def _volume(path):+ return _describe(_stat(path), path)++ def _mounts():+ count = _getfsstat(None, 0, 2)+ if count <= 0:+ return []+ records = (_StatFS * (count + 8))()+ count = _getfsstat(records, ctypes.sizeof(records), 2) # MNT_NOWAIT+ return list(records[:max(0, count)])+else:+ def _volume(path):+ usage = shutil.disk_usage(path)+ return dict(key='fs:%d' % os.stat(path).st_dev, mount=None, name=None, filesystem=None,+ total_bytes=usage.total, statfs_free_bytes=usage.free, important_free_bytes=None,+ free_bytes=usage.free, read_only=False, local=True, hidden=False)++ def _mounts():+ return []+++def _disconnected(path):+ """The name of the external disk path points to when that disk is not mounted, or ''.++ Writing there would create /Volumes/<name> on the startup disk instead.+ """+ parts = Path(path).expanduser().parts+ if sys.platform != 'darwin' or len(parts) < 3 or parts[:2] != ('/', 'Volumes'):+ return ''+ return '' if os.path.ismount(os.path.realpath(os.path.join('/Volumes', parts[2]))) else parts[2]+++def volume(path):+ """The disk holding path (or its nearest existing folder)."""+ folder = existing(path)+ value = dict(_volume(folder), path=str(folder))+ missing = _disconnected(path)+ if missing:+ value.update(name=missing, disconnected=True)+ return value+++def free_bytes(path):+ """Bytes that can be written at path, counting space the system frees on demand."""+ if sys.platform != 'darwin':+ return shutil.disk_usage(existing(path)).free+ try:+ return volume(path)['free_bytes']+ except (OSError, ValueError):+ return shutil.disk_usage(existing(path)).free+++def disk_key(path):+ """Paths with the same key draw on the same free space."""+ path = existing(path)+ if sys.platform != 'darwin':+ return path.stat().st_dev+ try:+ return _describe(_stat(path), str(path), details=False)['key']+ except (OSError, ValueError):+ return path.stat().st_dev+++def install_problem(disk):+ """Why this disk cannot hold an installation ('disconnected', 'read-only', 'fat32' or 'exfat'), or ''."""+ if disk.get('disconnected'):+ return 'disconnected'+ if disk['read_only']:+ return 'read-only'+ # FAT32 stores files up to 4 GB; the text encoder alone is a 15.7 GB file.+ if disk['filesystem'] == 'msdos':+ return 'fat32'+ # exFAT keeps no extended attributes, so macOS writes a "._" file beside every+ # file that has one; uv cannot install Python there, and the "._" twins of+ # package metadata break importlib.metadata in the environment.+ if disk['filesystem'] == 'exfat':+ return 'exfat'+ return ''+++def problem(path):+ try:+ return install_problem(volume(path))+ except (OSError, ValueError):+ return ''+++def problem_messages(paths):+ """Plan errors for installation folders on disks that cannot hold one (filesystems are read on macOS)."""+ messages, seen = [], set()+ if sys.platform != 'darwin':+ return messages+ for path in paths:+ try:+ disk = volume(path)+ except (OSError, ValueError):+ continue+ issue = install_problem(disk)+ if not issue or disk['key'] in seen:+ continue+ seen.add(disk['key'])+ messages.append({+ 'fat32': 'The installation folder is on a FAT32 disk, which stores files up to 4 GB; the text encoder '+ 'alone is 15.7 GB. Choose a folder on an APFS or Mac OS Extended disk: %s',+ 'exfat': 'The installation folder is on an exFAT disk, where the Python environment cannot work '+ '(macOS adds a hidden "._" copy of every file). Choose a folder on an APFS or Mac OS Extended disk: %s',+ 'read-only': 'The installation folder is on a read-only disk. Choose a folder on another disk: %s',+ 'disconnected': 'The installation folder is on a disk that is not connected. '+ 'Connect it, or choose another folder: %s'}[issue] % path)+ return messages+++def frontend_gib(mac):+ """Space for a separate ComfyUI environment: 1.4 GB measured on a Mac, CUDA ones need far more."""+ return 2 if mac else 12+++def disks():+ """Writable local disks a user could install to, one per shared space."""+ found = {}+ for record in _mounts():+ try:+ disk = _describe(record)+ except (OSError, ValueError):+ continue+ mount = disk['mount']+ system = mount == '/'+ if not system and (disk['read_only'] or not disk['local'] or disk['hidden']+ or any(mount.startswith(prefix) for prefix in _HIDDEN_MOUNTS)):+ continue+ if system:+ # Folders in the home folder live on the Data volume of this container.+ try:+ data = volume(Path.home())+ disk = dict(disk, free_bytes=max(disk['free_bytes'], data['free_bytes']),+ statfs_free_bytes=data['statfs_free_bytes'],+ important_free_bytes=data['important_free_bytes'], read_only=False)+ except (OSError, ValueError):+ pass+ previous = found.get(disk['key'])+ if previous is None or system:+ found[disk['key']] = dict(disk, system=system)+ return sorted(found.values(), key=lambda d: (not d['system'], d['name'].lower()))+++def size_text(n):+ """Sizes as the system's file manager shows them: decimal GB on macOS, GiB elsewhere."""+ n = max(0, int(n or 0))+ if sys.platform != 'darwin':+ return '%.1f GiB' % (n / 2**30)+ for unit, scale, digits in (('TB', 1e12, 2), ('GB', 1e9, 2), ('MB', 1e6, 1)):+ if n >= scale:+ # Finder rounds to two decimals and drops trailing zeros: 1.26 TB, 64.4 GB.+ return ('%.*f' % (digits, n / scale)).rstrip('0').rstrip('.') + ' ' + unit+ return '%d KB' % round(n / 1e3)+++class Cache:+ """Look up disks off the interface thread; the important-usage query can take a second."""++ def __init__(self, ttl=15.):+ self.ttl = ttl+ self.lock = threading.Lock()+ self.values = {}+ self.pending = set()++ def get(self, key, compute):+ now = time.monotonic()+ with self.lock:+ value = self.values.get(key)+ if value and now - value[0] < self.ttl or key in self.pending:+ return value[1] if value else None+ self.pending.add(key)++ def work():+ try:+ result = compute()+ except Exception:+ result = None+ with self.lock:+ self.values[key] = (time.monotonic(), result)+ self.pending.discard(key)+ threading.Thread(target=work, daemon=True, name='freevideo-disk-space').start()+ return value[1] if value else None+++_cache = Cache()+++def location(destination, *, need_bytes=0, suggest=True):+ """The disk under an installation folder and the other disks, for the launcher.++ Only macOS lists disks; elsewhere this returns None and the page is unchanged.+ The values come from a background lookup, so the first call can return None.+ """+ if sys.platform != 'darwin' or not str(destination or '').strip():+ return None+ try:+ folder = Path(destination).expanduser().resolve()+ except (OSError, RuntimeError, ValueError):+ return None+ here = _cache.get(('volume', str(folder)), lambda: volume(folder))+ if not here:+ return None+ others = (_cache.get(('disks',), disks) or []) if suggest else []+ need = max(0, int(need_bytes or 0))+ choices = []+ for disk in others:+ if disk['key'] == here['key'] and not here.get('disconnected'):+ continue+ # A disk in a format FreeVideo cannot use is listed, unavailable, so its absence is not a puzzle.+ unusable = install_problem(disk)+ target = Path.home() / 'FreeVideo' if disk.get('system') else Path(disk['mount']) / 'FreeVideo'+ choices.append(dict(name=disk['name'], free_bytes=disk['free_bytes'], free=size_text(disk['free_bytes']),+ path=str(target), problem=unusable,+ enough=not unusable and (not need or disk['free_bytes'] >= need)))+ choices.sort(key=lambda d: (bool(d['problem']), -d['free_bytes']))+ issue = install_problem(here)+ return dict(name=here['name'], free_bytes=here['free_bytes'], free=size_text(here['free_bytes']),+ need_bytes=need, need=size_text(need) if need else '', short=bool(need and here['free_bytes'] < need),+ problem=issue, others=choices[:8])diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.pyindex adde6f2..087eb1f 100644--- a/freevideo_engine/failure_details.py+++ b/freevideo_engine/failure_details.py@@ -2,6 +2,7 @@import jsonfrom pathlib import Pathimport re+import sysfrom .diagnostics import Redactor@@ -67,18 +68,63 @@ def setup_command_failure(label, log, exit_code):return '\n'.join(lines) + STEP_OUTPUT + output-def launcher_failure(value, *, zh=False):- """Short guidance for known failures; callers retain the full error separately."""+# Checked before free space: freeing space cannot fix a disk that cannot hold the installation.+PLACE_RULES = (+ (r'The installation folder is on a FAT32 disk', 'disk-format',+ ('This disk cannot hold the models', '这块硬盘放不下模型'),+ ('It is formatted as FAT32, which stores files up to 4 GB; the text encoder alone is 15.7 GB. '+ 'Choose a folder on an APFS or Mac OS Extended disk.',+ '它是 FAT32 格式,单个文件最大 4 GB,而文本编码器一个文件就有 15.7 GB。'+ '请选择 APFS 或 Mac OS 扩展格式硬盘上的文件夹。')),+ (r'The installation folder is on an exFAT disk', 'disk-format',+ ('This disk cannot hold the FreeVideo environment', '这块硬盘装不了 FreeVideo 的运行环境'),+ ("It is formatted as exFAT, where FreeVideo's Python environment does not work. "+ 'Choose a folder on an APFS or Mac OS Extended disk.',+ '它是 exFAT 格式,FreeVideo 的 Python 运行环境在这种格式上无法正常工作。'+ '请选择 APFS 或 Mac OS 扩展格式硬盘上的文件夹。')),+ (r'The installation folder is on a disk that is not connected', 'disk-missing',+ ('The disk is not connected', '这块硬盘没有连接'),+ ('Connect the disk that holds the installation folder, then check again, or choose another folder.',+ '请接上安装位置所在的硬盘后重新检查,或者换一个位置。')),+ (r'The installation folder is on a read-only disk', 'disk-read-only',+ ('This disk is read-only', '这块硬盘是只读的'),+ ('This Mac can read the disk but not write to it, as with NTFS disks. Choose a folder on another disk.',+ '这台 Mac 只能读取这块硬盘,不能写入(例如 NTFS 格式的硬盘)。请选择其他硬盘上的文件夹。')),+)+++def launcher_failure(value, *, zh=False, other_disk=False, disk_name=''):+ """Short guidance for known failures; callers retain the full error separately.++ other_disk: the launcher can offer another disk with enough room (macOS).+ disk_name: the disconnected disk the launcher found; the error's paths are redacted.+ """if not value:return dict(title='', detail='', action='', kind='')text = str(value)summary = text.partition(STEP_OUTPUT)[0]+ if disk_name and 'on a disk that is not connected' in summary:+ return dict(title='这块硬盘没有连接' if zh else 'The disk is not connected', kind='disk-missing', detail='',+ action=('请接上“%s”后点击“重新检查”' % disk_name + (',或者改装到其他硬盘。' if other_disk else '。') if zh else+ 'Connect "%s" and click Check again' % disk_name + (', or install on another disk.' if other_disk else '.')))+ for pattern, kind, title, action in PLACE_RULES:+ if re.search(pattern, summary):+ return dict(title=title[zh], detail='', action=action[zh], kind=kind)disk = re.search(r'Insufficient disk space: need ([\d.]+) GiB, available ([\d.]+) GiB, short ([\d.]+) GiB', summary, re.I)if disk:- needed, available, short = disk.groups()- return dict(title='磁盘空间不足' if zh else 'Not enough disk space', kind='disk',- detail=('需要 %s GiB,可用 %s GiB。再释放 %s GiB 后点击“重新检查”。' % (needed, available, short)- if zh else 'Need %s GiB; %s GiB available. Free another %s GiB, then click “Check again”.' % (needed, available, short)),+ if sys.platform == 'darwin':+ # In Finder's units, so the numbers match what it shows for the disk.+ from .disk_space import size_text+ sizes = tuple(size_text(float(value) * 2**30) for value in disk.groups())+ # The figures and what to do go on their own lines, so a narrow window breaks between them.+ detail = (('需要约 %s,可用 %s。\n再释放 %s 后点击“重新检查”' % sizes) + (',或者改装到其他硬盘。' if other_disk else '。')+ if zh else ('Needs about %s; %s available.\nFree up %s and click Check again' % sizes)+ + (', or install on another disk.' if other_disk else '.'))+ else:+ sizes = tuple('%s GiB' % value for value in disk.groups())+ detail = ('需要 %s,可用 %s。再释放 %s 后点击“重新检查”。' % sizes+ if zh else 'Need %s; %s available. Free another %s, then click “Check again”.' % sizes)+ return dict(title='磁盘空间不足' if zh else 'Not enough disk space', kind='disk', detail=detail,action='重新检查' if zh else 'Check again')if text.startswith('ComfyUI could not start.'):return dict(title='ComfyUI 启动失败' if zh else 'ComfyUI could not start',diff --git a/freevideo_engine/gpu_budget.py b/freevideo_engine/gpu_budget.pyindex 41ac94c..d487c63 100644--- a/freevideo_engine/gpu_budget.py+++ b/freevideo_engine/gpu_budget.py@@ -136,15 +136,26 @@ def configure(torch, budget_bytes, explicit_limit=None, *, reserve_bytes=0, systreturn report+# A falling driver budget can be Windows answering a full device: once this+# process frees its optional cache planes the budget returns within seconds.+# Before lowering the cap below the next step's measured workspace (a certain+# OOM and a full restart), wait this long for it to come back.+SETTLE_SECONDS = 15.+SETTLE_INTERVAL = .5++class LiveGPUBudget:"""Refresh a Windows allocator ceiling at idle CUDA stage/step boundaries.The 256 MiB reserve is growth headroom, in addition to observed allocationsoutside Torch. A larger driver budget must survive two observations before- use. Pressure takes effect immediately, reclaiming optional weights first.- No background thread changes CUDA limits or frees tensors in active kernels.+ use. Pressure takes effect immediately, reclaiming optional weights first;+ a cap that would fall below the next step's workspace first waits briefly+ for the budget to recover. No background thread changes CUDA limits or+ frees tensors in active kernels."""- def __init__(self, torch, report, maximum_bytes, reserve_bytes, *, reader_factory=None):+ def __init__(self, torch, report, maximum_bytes, reserve_bytes, *, reader_factory=None,+ device_factory=None, settle_seconds=SETTLE_SECONDS, sleep=time.sleep, clock=time.monotonic):self.torch, self.report = torch, reportself.total = report['device_total_bytes']self.limit = report['effective_allocator_limit_bytes']@@ -152,8 +163,11 @@ class LiveGPUBudget:report.get('benchmark_allocator_limit_bytes') or self.total)self.reserve = reserve_bytesself.pending = None- self.started = time.monotonic()+ self.settle_seconds, self.sleep, self.clock = settle_seconds, sleep, clock+ self.started = clock()self.reader = None+ self.device = None+ self.device_memory = Noneself.receipt = report['dynamic_budget'] = dict(enabled=True,base_reserve_bytes=reserve_bytes, maximum_allocator_bytes=self.maximum,minimum_limit_bytes=self.limit, maximum_limit_bytes=self.limit,@@ -165,13 +179,24 @@ class LiveGPUBudget:self.reader = reader_factory()except (OSError, RuntimeError, AttributeError, ValueError) as error:self._error(error)+ try:+ if device_factory is None and windows():+ from .monitoring import DeviceMemory+ uuid = str(getattr(torch.cuda.get_device_properties(torch.cuda.current_device()), 'uuid', ''))+ if uuid and not uuid.startswith(('GPU-', 'MIG-')):+ uuid = 'GPU-' + uuid+ device_factory = lambda: DeviceMemory(uuid or None)+ if device_factory is not None:+ self.device = device_factory()+ except (OSError, RuntimeError, AttributeError, ValueError) as error:+ self._error(error)def _error(self, error):errors = self.receipt['errors']if len(errors) < 8 and str(error) not in errors:errors.append(str(error))- def refresh(self, stage, reclaim=None):+ def _observe(self):cuda = self.torch.cudafree, _ = cuda.mem_get_info()reserved = cuda.memory_reserved()@@ -188,6 +213,38 @@ class LiveGPUBudget:known = 'wddm_pool_capacity_bytes' in decision['bounds']if not known:candidate = min(candidate, self.limit)+ self.device_memory = None+ if self.device is not None:+ try:+ self.device_memory = self.device.sample()+ except (OSError, RuntimeError, AttributeError, ValueError) as error:+ self._error(error)+ return free, reserved, local, decision, known, candidate++ def device_headroom(self):+ """Physical device memory no process holds at the last observation, or None if unread."""+ memory = self.device_memory or {}+ used, total = memory.get('used_bytes'), memory.get('total_bytes')+ if type(used) is not int or type(total) is not int:+ return None+ return max(0, total - used)++ def _settle(self, workspace):+ """Wait for a driver budget that again covers `workspace` twice in a row."""+ deadline = self.clock() + self.settle_seconds+ seen, samples = [], 0+ while self.clock() < deadline:+ self.sleep(SETTLE_INTERVAL)+ *_, known, candidate = self._observe()+ samples += 1+ seen = seen + [candidate] if known and candidate >= workspace else []+ if len(seen) == 2:+ return min(seen), samples+ return None, samples++ def refresh(self, stage, reclaim=None, workspace=None):+ cuda = self.torch.cuda+ free, reserved, local, decision, known, candidate = self._observe()target, action = self.limit, 'hold'if candidate < self.limit:target, action, self.pending = candidate, 'shrink', None@@ -199,12 +256,13 @@ class LiveGPUBudget:self.pending, action = candidate, 'pending'else:self.pending = None- row = dict(stage=stage, elapsed_seconds=time.monotonic()-self.started,+ row = dict(stage=stage, elapsed_seconds=self.clock()-self.started,previous_limit_bytes=self.limit, candidate_limit_bytes=candidate,allocator_limit_bytes=target, action=action, driver_available=known,live_free_bytes=free, reserved_bytes=reserved,non_torch_local_bytes=decision['observed_non_torch_local_bytes'],- driver_budget_bytes=local.get('budget_bytes') if known else None)+ driver_budget_bytes=local.get('budget_bytes') if known else None,+ device_used_bytes=(self.device_memory or {}).get('used_bytes'))self.receipt['observations'] += 1self.receipt['last'] = rowif action in ('shrink', 'grow'):@@ -215,6 +273,14 @@ class LiveGPUBudget:reclaim(target)if cuda.memory_reserved() > target:cuda.empty_cache()+ if known and workspace is not None and target < workspace:+ started = self.clock()+ settled, samples = self._settle(workspace)+ row.update(settle_seconds=self.clock() - started, settle_samples=samples,+ workspace_bytes=int(workspace))+ if settled is not None:+ target = min(settled, self.limit)+ row.update(action='settled', allocator_limit_bytes=target, settled_candidate_bytes=settled)# The setter only governs future allocations. If active tensors# cannot fit after reclamation, use the existing controlled OOM# recovery rather than assume that setting a fraction evicts them.@@ -234,3 +300,9 @@ class LiveGPUBudget:reader.close()except (OSError, RuntimeError) as error:self._error(error)+ device, self.device = self.device, None+ if device is not None:+ try:+ device.close()+ except (OSError, RuntimeError) as error:+ self._error(error)diff --git a/freevideo_engine/head_chunk.py b/freevideo_engine/head_chunk.pyindex 7b9c4fb..8cda14e 100644--- a/freevideo_engine/head_chunk.py+++ b/freevideo_engine/head_chunk.py@@ -49,6 +49,31 @@ def project_rows(planes, out, project, size=TAIL_ROWS):out[rows] = project(part)+def release_readouts(policy):+ """Return a previous canvas's page-locked attention readouts before allocating new ones.++ The first pass's readouts stayed referenced while the refine pass allocated+ its larger ones, and the host allocator kept the freed blocks. Windows+ page-locks both against a non-local budget of about half of physical RAM:+ a 16 GiB machine failed cudaHostAlloc at the refine pass's first layer.+ """+ held = [getattr(policy, name, None) for name in ('group_readouts', 'host_outputs')]+ for name in ('group_readouts', 'host_outputs', 'host_output_key'):+ if hasattr(policy, name):+ delattr(policy, name)+ if any(value is not None for value in held):+ del held+ gc.collect()+ # Copies into blocks the host allocator is about to free can still be+ # in flight at a pass's first layer (residual staging, the previous+ # pass's last tiles). Returning them then broke the next copy on+ # Windows with cudaErrorInvalidValue; wait for the device first.+ if torch.cuda.is_initialized():+ torch.cuda.synchronize()+ from .torch_compat import empty_host_cache+ empty_host_cache(torch)++def install_head_chunks(transformer, policy, chunk, cpu_outputs=False, projection_chunk=1024, grouped_outputs=False,parallelism=1):if chunk < 1 or projection_chunk < 1:@@ -103,12 +128,15 @@ def install_head_chunks(transformer, policy, chunk, cpu_outputs=False, projectiostores = getattr(policy, 'group_readouts', None)if stores is None or any(not store.supports(rows, widths, x.dtype, projection_chunk)for store, rows in zip(stores, (len(x), linear_shape[0]))):+ stores = None # the old tuple must be unreferenced when it is returned+ release_readouts(policy)policy.group_readouts = tuple(HeadReadouts(rows, widths, x.dtype, projection_chunk)for rows in (len(x), linear_shape[0]))soft, linear = policy.group_readoutselif cpu_outputs:key = (soft_shape, linear_shape, x.dtype)if getattr(policy, 'host_output_key', None) != key:+ release_readouts(policy)policy.host_outputs = (torch.empty(soft_shape, dtype=x.dtype, pin_memory=True),torch.empty(linear_shape, dtype=x.dtype, pin_memory=True))policy.host_output_key = keydiff --git a/freevideo_engine/input_cache.py b/freevideo_engine/input_cache.pyindex 8878075..833c393 100644--- a/freevideo_engine/input_cache.py+++ b/freevideo_engine/input_cache.py@@ -13,6 +13,7 @@ import uuidfrom .monitoring import savefrom .paths import data_root+from . import disk_spacedef digest(path):@@ -96,7 +97,7 @@ class InputCache:self.note = 'Input exceeds the small-input cache limit; original artifact retained'return Falseself.root.mkdir(parents=True, exist_ok=True)- if shutil.disk_usage(self.root).free < size + 2**30:+ if disk_space.free_bytes(self.root) < size + 2**30:self.note = 'Low disk space; existing caches retained, new input not cached'return Falsechecksum = digest(source)diff --git a/freevideo_engine/install_disk.py b/freevideo_engine/install_disk.pyindex cedbf97..ee3a751 100644--- a/freevideo_engine/install_disk.py+++ b/freevideo_engine/install_disk.py@@ -1,9 +1,10 @@"""Disk estimates and live guards for the automatic Windows space saver."""from pathlib import Path-import shutilimport hashlibimport json+from . import disk_space+GiB = 1 << 30SPACE_FLOOR = 2 * GiB@@ -17,8 +18,11 @@ def existing(path):def add(disks, path, amount):parent = existing(path)- disk = disks.setdefault(parent.stat().st_dev,- dict(paths=[], needed_bytes=0, free_bytes=shutil.disk_usage(parent).free))+ # Volumes of one APFS container share their free space.+ key = disk_space.disk_key(parent)+ if key not in disks:+ disks[key] = dict(paths=[], needed_bytes=0, free_bytes=disk_space.free_bytes(parent))+ disk = disks[key]if str(parent) not in disk['paths']:disk['paths'].append(str(parent))disk['needed_bytes'] += amount@@ -49,7 +53,8 @@ def frontend_ready(root, frontend):return False-def budget(groups, root, normal_extra, *, eligible, environments_ready, frontend=None, keep_extreme=False):+def budget(groups, root, normal_extra, *, eligible, environments_ready, frontend=None, keep_extreme=False,+ frontend_gib=12):"""Estimate each volume for the selected installation strategy."""frontend = frontend or {}def estimate(extreme):@@ -59,7 +64,7 @@ def budget(groups, root, normal_extra, *, eligible, environments_ready, frontendextra = (1 if environments_ready else 6) if extreme else normal_extraadd(disks, root, extra * GiB)if frontend.get('separate') and not (extreme and frontend_ready(root, frontend)):- add(disks, root, (3 if extreme else 12) * GiB)+ add(disks, root, (3 if extreme else frontend_gib) * GiB)if frontend.get('download') and not Path(frontend['root']).exists():add(disks, frontend['root'], GiB)if extreme:@@ -88,11 +93,11 @@ def check_floor(paths):seen = set()for path in paths:parent = existing(path)- device = parent.stat().st_dev+ device = disk_space.disk_key(parent)if device in seen:continueseen.add(device)- free = shutil.disk_usage(parent).free+ free = disk_space.free_bytes(parent)if free < SPACE_FLOOR:raise RuntimeError('Space-saving installation paused: less than 2 GiB free on %s ''(%.2f GiB available). Free space and resume; downloaded files are retained.' %diff --git a/freevideo_engine/latent_upscale.py b/freevideo_engine/latent_upscale.pyindex 1e2d2fa..7a71d34 100644--- a/freevideo_engine/latent_upscale.py+++ b/freevideo_engine/latent_upscale.py@@ -59,8 +59,10 @@ def upscale(video, checkpoint, width, height, *, memory_saving=False):model = LatentResizer3D(reuse_buffers=memory_saving)# Keep the same bounded Windows reader as the main engine; do not# create a new copy-on-write mapping/Commit charge for optional weights.+ # Move each tensor to the device as it is read: host RAM then holds one+ # tensor (at most 13.5 MiB) instead of the whole 0.66 GiB checkpoint.with _open_safetensors(checkpoint, framework='pt', device='cpu') as handle:- state = {name: handle.get_tensor(name) for name in handle.keys()}+ state = {name: handle.get_tensor(name).to(video.device) for name in handle.keys()}model.load_state_dict({key.removeprefix('upscaler.'):value for key,value in state.items()},strict=True,assign=True)del statediff --git a/freevideo_engine/launcher/FIcon.qml b/freevideo_engine/launcher/FIcon.qmlindex f1a8fb7..a110e54 100644--- a/freevideo_engine/launcher/FIcon.qml+++ b/freevideo_engine/launcher/FIcon.qml@@ -17,6 +17,7 @@ Canvas {else if (kind === "download") { c.moveTo(12,3); c.lineTo(12,15); c.moveTo(7,10); c.lineTo(12,15); c.lineTo(17,10); c.moveTo(4,16); c.lineTo(4,21); c.lineTo(20,21); c.lineTo(20,16) }else if (kind === "settings") { c.moveTo(5,3); c.lineTo(5,21); c.moveTo(12,3); c.lineTo(12,21); c.moveTo(19,3); c.lineTo(19,21); c.stroke(); c.beginPath(); c.fillStyle=knockout; c.rect(2,7,6,4); c.rect(9,14,6,4); c.rect(16,6,6,4); c.fill() }else if (kind === "text") { c.moveTo(5,5); c.lineTo(19,5); c.moveTo(12,5); c.lineTo(12,20); c.moveTo(8,20); c.lineTo(16,20) }+ else if (kind === "disk") { c.rect(3,7,18,10); c.moveTo(3,13); c.lineTo(21,13); c.moveTo(16.5,15.2); c.lineTo(17.5,15.2) }else if (kind === "decoder") { c.rect(3,5,18,14); c.moveTo(8,9); c.lineTo(5,12); c.lineTo(8,15); c.moveTo(16,9); c.lineTo(19,12); c.lineTo(16,15) }else { c.rect(3,4,18,16); c.moveTo(9,8); c.lineTo(16,12); c.lineTo(9,16); c.closePath() }c.stroke()diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qmlindex 4d30581..e7f8f2d 100644--- a/freevideo_engine/launcher/Main.qml+++ b/freevideo_engine/launcher/Main.qml@@ -12,6 +12,7 @@ ApplicationWindow {Connections { target: backend; function onChanged() { win.s = backend.state } }property bool settingsOpen: falseproperty bool terminalOpen: false+ property bool confirmArchives: false // the in-place "delete the imported ZIPs?" stepproperty string settingsTab: "downloads"property string modelInfo: "video"property bool modelInfoOpen: false@@ -45,7 +46,37 @@ ApplicationWindow {function sourceName(value) { return ({"auto": t("Automatic", "自动选择"), "official": "Hugging Face", "hf-mirror": t("HF Mirror", "HF 镜像"), "modelscope": t("ModelScope", "魔搭")})[value] || value }function number(n) { return typeof n === "number" && isFinite(n) }function fraction(row) { return row && number(row.total) && row.total > 0 && number(row.done) && row.done <= row.total ? row.done / row.total : -1 }- function bytes(n) { return n >= 1073741824 ? (n/1073741824).toFixed(1)+" GiB" : (n/1048576).toFixed(1)+" MiB" }+ function bytes(n) {+ // macOS counts in decimal units like Finder: 1.26 TB, 64.4 GB.+ if (s.decimal_sizes) {+ var units = [[1e12, " TB", 2], [1e9, " GB", 2], [1e6, " MB", 1]]+ for (var i = 0; i < units.length; i++)+ if (n >= units[i][0]) return parseFloat((n/units[i][0]).toFixed(units[i][2])) + units[i][1]+ return Math.round(n/1e3) + " KB"+ }+ return n >= 1073741824 ? (n/1073741824).toFixed(1)+" GiB" : (n/1048576).toFixed(1)+" MiB"+ }+ readonly property var disk: s.disk || null+ readonly property var diskChoices: disk ? disk.others : []+ readonly property var bestDisk: diskChoices.filter(function(d) { return d.enough })[0] || null+ property bool diskDialogOpen: false+ function diskLine() {+ var d = disk+ if (!d) return ""+ var en = "\"" + d.name + "\"", zh = "“" + d.name + "”"+ if (d.problem === "fat32") return t(en + " uses FAT32, which limits each file to 4 GB, too small for the model files.", zh + "是 FAT32 格式,单个文件最大 4 GB,放不下模型。")+ if (d.problem === "exfat") return t(en + " uses exFAT, where the FreeVideo environment cannot run.", zh + "是 exFAT 格式,装不了 FreeVideo 的运行环境。")+ if (d.problem === "disconnected") return t(en + " is not connected. Connect it to continue.", zh + "没有连接,请接上这块硬盘。")+ if (d.problem === "read-only") return t(en + " is read-only on this Mac.", zh + "在这台 Mac 上是只读的。")+ if (d.short) return t(en + " has " + d.free + " available; this installation needs about " + d.need + ".",+ zh + "可用 " + d.free + ",这次安装需要约 " + d.need + "。")+ return t(d.name + " · " + d.free + " available", d.name + " · 可用 " + d.free)+ + (d.need ? t(" · about " + d.need + " needed", " · 需要约 " + d.need) : "")+ }+ // The label before diskLine() when the line states the disk rather than a problem.+ function diskLabel() { return disk && !disk.problem && !disk.short ? t("Disk:", "所在硬盘:") : "" }+ // On a Mac, a disk problem is fixed by choosing another disk, not by reporting a fault.+ readonly property bool diskFailure: !!disk && (s.failure.kind || "").indexOf("disk") === 0readonly property bool updateOffered: s.update.engine || (!!s.update.candidate && ["available", "downloading", "ready", "error", "cancelled"].indexOf(s.update.status) >= 0)// An engine update needs no download; offer it as the way to launch.readonly property bool updateFirst: s.page === "launcher" && s.update.engine && !s.update.phase && !s.busy && s.status !== "open" && s.status !== "restart-required" && !s.needs_consent@@ -331,11 +362,16 @@ ApplicationWindow {FText { visible: !!(s.failure.detail || s.failure.action); text: s.failure.detail || s.failure.action; color: theme.text; Layout.fillWidth: true }Flow {Layout.fillWidth: true; spacing: 8+ FButton { objectName: "moveToDisk"; visible: diskFailure && s.form.new_comfy && !!bestDisk; enabled: !s.busy; primary: true+ text: bestDisk ? t("Install on \"" + bestDisk.name + "\"", "改装到“" + bestDisk.name + "”") : ""+ onClicked: backend.useDisk(bestDisk.path) }+ FButton { objectName: "chooseDisk"; visible: diskFailure && s.form.new_comfy && diskChoices.length > (bestDisk ? 1 : 0); enabled: !s.busy+ text: t("Other disks…", "其他硬盘…"); onClicked: diskDialogOpen = true }FButton { objectName: "diskCleanupButton"; visible: s.failure.kind === "disk"; enabled: s.can_cleanup; text: t("Clean download cache", "清理下载缓存"); onClicked: { settingsTab = "general"; settingsOpen = true; backend.cleanupDownloads(false) } }FButton { visible: s.failure.kind === "download"; text: t("Change source", "切换下载源"); onClicked: { settingsTab = "downloads"; settingsOpen = true } }- FButton { objectName: "copyError"; text: t("Copy full details", "复制完整详情"); onClicked: backend.copy(s.error) }+ FButton { objectName: "copyError"; visible: !diskFailure; text: t("Copy full details", "复制完整详情"); onClicked: backend.copy(s.error) }FButton { objectName: "showError"; text: errorDetailsOpen ? t("Hide details", "收起详情") : t("Show details", "查看详情"); flat: true; onClicked: errorDetailsOpen = !errorDetailsOpen }- FButton { objectName: "exportError"; text: t("Export report", "导出报告"); enabled: s.report.status !== "running"; onClicked: backend.exportReport() }+ FButton { objectName: "exportError"; visible: !diskFailure; text: t("Export report", "导出报告"); enabled: s.report.status !== "running"; onClicked: backend.exportReport() }}ScrollView {visible: errorDetailsOpen; Layout.fillWidth: true; Layout.preferredHeight: Math.min(160, errorText.implicitHeight+10); clip: true@@ -394,6 +430,18 @@ ApplicationWindow {FButton { text: t("Browse…", "浏览…"); implicitHeight: theme.height + 4; onClicked: backend.browse(s.form.new_comfy ? "destination" : "comfy") }}FText { visible: !s.form.new_comfy; text: t("Uses your existing Python when available. A separate environment loads only FreeVideo.", "优先使用已有 Python;独立环境仅加载 FreeVideo。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }+ RowLayout {+ objectName: "installDisk"; visible: !!disk; Layout.fillWidth: true; spacing: 8+ FIcon { kind: "disk"; ink: disk && (disk.problem || disk.short) ? theme.danger : theme.muted; Layout.preferredWidth: 16; Layout.preferredHeight: 16; Layout.alignment: Qt.AlignVCenter }+ // A full-width colon carries its own space; pull the value up to it.+ FText { id: diskLabelText; objectName: "installDiskLabel"; visible: !!diskLabel(); text: diskLabel(); color: theme.muted; font.pixelSize: theme.micro + 1; wrapMode: Text.NoWrap+ Layout.alignment: Qt.AlignBaseline; Layout.rightMargin: s.zh ? -(8 + Math.round(font.pixelSize / 2) - 2) : -4 }+ FText { objectName: "installDiskText"; text: diskLine(); color: disk && (disk.problem || disk.short) ? theme.danger : theme.muted; font.pixelSize: theme.micro + 1; Layout.fillWidth: true; Layout.alignment: Qt.AlignBaseline }+ // The label's right edge lines up with Browse; the hover fill reaches into the card's padding.+ FButton { objectName: "changeDisk"; visible: s.form.new_comfy && diskChoices.length > 0; enabled: !s.busy; flat: true; implicitHeight: theme.heightSm; font.pixelSize: theme.micro + 1+ leftPadding: 10; rightPadding: 10; Layout.rightMargin: -10; Layout.alignment: Qt.AlignBaseline+ text: t("Choose another disk", "换一块硬盘"); onClicked: diskDialogOpen = true }+ }}FCard {objectName: "runtimeImportCard"; visible: manualEnvironment; Layout.fillWidth: true; padding: shortWindow ? 16 : 20; spacing: 10@@ -735,6 +783,21 @@ ApplicationWindow {FText { text: ["created","present"].indexOf(s.shortcut.status) >= 0 ? "✓ " + t("Shortcut ready", "快捷方式已就绪") : ""; color: theme.success; font.pixelSize: theme.micro }}FText { objectName: "oldVersions"; visible: !!s.old_versions; text: "✓ " + s.old_versions; color: theme.success; font.pixelSize: theme.micro; Layout.fillWidth: true }+ FText { objectName: "copiedModels"; visible: !!s.copied_models; text: s.copied_models || ""; color: theme.muted; font.pixelSize: theme.micro; wrapMode: Text.WordWrap; Layout.fillWidth: true }+ RowLayout {+ visible: !!s.archives && !confirmArchives; spacing: 12; Layout.fillWidth: true+ FText { objectName: "archivesOffer"; text: s.archives || ""; color: theme.muted; font.pixelSize: theme.micro; wrapMode: Text.WordWrap; Layout.fillWidth: true }+ FButton { objectName: "deleteArchives"; implicitWidth: contentItem.implicitWidth + leftPadding + rightPadding; Layout.rightMargin: -rightPadding; text: t("Delete ZIP files", "删除压缩包"); flat: true; implicitHeight: theme.heightSm - 2; font.pixelSize: theme.micro + 1; enabled: !s.busy; onClicked: confirmArchives = true }+ }+ // The user's own files, and not recoverable: confirm in place, no dialog.+ RowLayout {+ visible: !!s.archives && confirmArchives; spacing: 8; Layout.fillWidth: true+ FText { objectName: "archivesConfirm"; text: s.archives_confirm || ""; color: theme.text; font.pixelSize: theme.micro; wrapMode: Text.WordWrap; Layout.fillWidth: true }+ FButton { objectName: "confirmDeleteArchives"; text: t("Delete", "删除"); danger: true; implicitHeight: theme.heightSm - 2; font.pixelSize: theme.micro + 1; enabled: !s.busy; onClicked: { confirmArchives = false; backend.action("delete_archives", false) } }+ FButton { objectName: "cancelDeleteArchives"; implicitWidth: contentItem.implicitWidth + leftPadding + rightPadding; Layout.rightMargin: -rightPadding; text: t("Cancel", "取消"); flat: true; implicitHeight: theme.heightSm - 2; font.pixelSize: theme.micro + 1; onClicked: confirmArchives = false }+ }+ FText { objectName: "archivesDone"; visible: !!s.archives_done; text: "✓ " + (s.archives_done || ""); color: theme.success; font.pixelSize: theme.micro; Layout.fillWidth: true }+ FText { objectName: "archivesFailed"; visible: !!s.archives_failed; text: s.archives_failed || ""; color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }FCheck { visible: s.needs_consent; text: s.consent; checked: accepted; onToggled: accepted = checked; Layout.fillWidth: true }FButton { visible: s.needs_consent; text: t("Read licenses ↗", "查看许可证 ↗"); flat: true; implicitHeight: theme.heightSm - 2; leftPadding: 32; font.pixelSize: theme.micro + 1; onClicked: backend.link("https://huggingface.co/OpenVDN/vdn-minimax-h3-edge/blob/main/LICENSE") }}@@ -1012,6 +1075,55 @@ ApplicationWindow {}}+ FPopup {+ objectName: "diskDialog"; visible: diskDialogOpen && !!disk; onClosed: diskDialogOpen = false+ width: Math.min(480, win.width - 40); closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside+ height: Math.min(diskContents.implicitHeight + padding * 2, win.height - 48)+ contentItem: ColumnLayout {+ id: diskContents; spacing: 12+ FText { text: t("Choose a disk", "选择安装硬盘"); font.pixelSize: theme.section + 2; font.weight: Font.DemiBold; Layout.fillWidth: true }+ FText { objectName: "diskDialogText"; Layout.fillWidth: true; color: theme.muted; font.pixelSize: theme.micro + 1+ text: (disk && disk.need ? t("This installation needs about " + disk.need + ".\n", "这次安装需要约 " + disk.need + "。\n") : "")+ + t("FreeVideo is installed in a FreeVideo folder on the disk you choose.", "FreeVideo 会装在所选硬盘的 FreeVideo 文件夹里。") }+ Repeater {+ model: diskChoices+ delegate: Rectangle {+ required property var modelData+ objectName: "diskRow-" + modelData.name+ Layout.fillWidth: true; implicitHeight: Math.max(52, diskRowText.implicitHeight + 20); radius: theme.radiusSm+ color: diskArea.containsMouse && modelData.enough ? theme.hover : theme.bg+ border.color: diskArea.containsMouse && modelData.enough ? theme.sheen : theme.border+ opacity: modelData.enough ? 1 : 0.55+ RowLayout {+ anchors.fill: parent; anchors.leftMargin: 14; anchors.rightMargin: 14; spacing: 12+ FIcon { kind: "disk"; ink: modelData.enough ? theme.accent : theme.muted; Layout.preferredWidth: 18; Layout.preferredHeight: 18 }+ ColumnLayout {+ id: diskRowText; Layout.fillWidth: true; spacing: 2+ FText { text: modelData.name; font.weight: Font.DemiBold; Layout.fillWidth: true }+ FText { visible: !modelData.enough; Layout.fillWidth: true; color: theme.danger; font.pixelSize: theme.micro+ text: modelData.problem === "exfat" ? t("exFAT not supported", "不支持 exFAT")+ : modelData.problem === "fat32" ? t("FAT32 not supported", "不支持 FAT32")+ : t("Not enough space", "空间不够") }+ }+ FText { text: t(modelData.free + " available", "可用 " + modelData.free); color: theme.muted; font.pixelSize: theme.micro + 1; font.features: { "tnum": 1 }; wrapMode: Text.NoWrap; Layout.alignment: Qt.AlignVCenter }+ }+ MouseArea {+ id: diskArea; anchors.fill: parent; hoverEnabled: true; enabled: modelData.enough && !s.busy+ cursorShape: enabled ? Qt.PointingHandCursor : Qt.ArrowCursor+ onClicked: { diskDialogOpen = false; backend.useDisk(modelData.path) }+ }+ Accessible.role: Accessible.Button; Accessible.name: modelData.name+ }+ }+ RowLayout {+ Layout.fillWidth: true; Layout.topMargin: 4; spacing: 8+ FButton { text: t("Choose a folder…", "选择文件夹…"); flat: true; onClicked: { diskDialogOpen = false; backend.browse("destination") } }+ Item { Layout.fillWidth: true }+ FButton { text: t("Cancel", "取消"); onClicked: diskDialogOpen = false }+ }+ }+ }+FPopup {id: modelDialog; objectName: "modelDialog"visible: modelInfoOpen; onClosed: modelInfoOpen = falsediff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.pyindex 8efa8d0..4fb0e78 100644--- a/freevideo_engine/launcher_session.py+++ b/freevideo_engine/launcher_session.py@@ -2,11 +2,13 @@import jsonimport osfrom pathlib import Path+import sysimport threadingimport timefrom urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplitfrom . import __version__+from . import disk_spacefrom .comfy_launcher_runtime import Controller, layout, local_url, new_layoutfrom .desktop_runtime import launcher_root, materialize_sourcefrom .download_settings import Probe, read as download_preferences, speed_text@@ -26,6 +28,10 @@ QUEUE_POLL_SECONDS = 3RECEIPT_POLL_SECONDS = 5+def size_text(value):+ return '%.1f GiB' % (value / 2**30) if value >= 2**30 else '%d MiB' % (value // 2**20)++class Session:# Update flow defaults; __init__ starts each launcher session from these.update_snoozed = {}@@ -63,7 +69,7 @@ class Session:self.form = dict(comfy='', destination=str(home / 'FreeVideo'), engine='', python='',url='http://127.0.0.1:8188', models='', model_dirs=[], model_method='auto', environment_method='auto',separate=False, repair=False, new_comfy=True, offline_runtime='', offline_models=[],- sampling_caches=not saved.get('installation'))+ imported_archives=[], sampling_caches=not saved.get('installation'))self.form.update({k: v for k, v in saved.items() if k in self.form})if 'environment_method' not in saved and self.form['offline_runtime']:self.form['environment_method'] = 'manual'@@ -173,8 +179,9 @@ class Session:if key == 'environment_method' and value not in ('auto', 'manual'):raise ValueError('Unknown environment installation method')if key == 'environment_method' and value == 'manual' and not runtime_packages_supported():- raise ValueError(self.t('The Mac environment is prepared automatically. Import model packages in the next step.',- 'Mac 运行环境由安装器自动准备,请在下一步导入模型包。'))+ system = 'Mac' if sys.platform == 'darwin' else 'Linux'+ raise ValueError(self.t('The %s environment is prepared automatically. Import model packages in the next step.' % system,+ '%s 运行环境由安装器自动准备,请在下一步导入模型包。' % system))if key == 'model_method' and value not in ('auto', 'manual', 'reuse'):raise ValueError('Unknown model download method')if self.form[key] == value:@@ -193,6 +200,21 @@ class Session:self.browser_error = self.error = ''self.persist()+ def use_disk(self, folder):+ """Move a new installation to another disk, then show the location page to confirm it."""+ if not self.form['new_comfy'] or self.controller.busy or self.importer.busy or self.cleaner.busy:+ return+ self.edit('destination', str(folder))+ self.page = 'comfy'++ def disk_view(self, row, failure):+ """The disk under the chosen location, with other disks to move to (macOS only)."""+ if self.page != 'comfy' and not str(failure.get('kind', '')).startswith('disk'):+ return None+ need = sum(d.get('needed_bytes', 0) for d in row.get('disks', [])) if row.get('status') == 'review' else 0+ folder = self.form['destination'] if self.form['new_comfy'] else self.form['comfy']+ return disk_space.location(folder, need_bytes=need, suggest=self.form['new_comfy'])+def add_folder(self, folder):from .local_models import library_roots# Saved folders that were deleted since are dropped instead of blocking the new one.@@ -305,6 +327,8 @@ class Session:returnif name == 'browser':self.open_browser(); return+ if name == 'delete_archives':+ self.delete_archives(); returnif name == 'shortcut':self.controller.run('shortcut', self.controller.state.get('status')); returnif name not in ('primary', 'launch'):@@ -923,6 +947,13 @@ class Session:self.imported_batch = importedretry = self.import_retryfor package in imported.get('packages', []):+ if package.get('archive'):+ # The user's own ZIP: offered for deletion once the installation holds its contents.+ record = dict(path=package['archive'], bytes=package['archive_bytes'],+ mtime_ns=package['archive_mtime_ns'], kind=package['kind'], root=package['root'])+ self.form['imported_archives'] = [r for r in self.form['imported_archives']+ if r.get('path') != record['path']] + [record]+ self.archive_view = Noneif package['kind'] == 'runtime':self.edit('offline_runtime', package['root'])self.edit('environment_method', 'manual')@@ -1022,10 +1053,89 @@ class Session:"""What the background removal of earlier FreeVideo copies freed this session."""value = getattr(self.controller, 'old_versions', None)released = value.get('released_bytes') if isinstance(value, dict) else None+ if isinstance(released, int):+ # PyTorch wheels a fresh installation downloaded are not an earlier version.+ downloads = value.get('download_bytes')+ released -= downloads if isinstance(downloads, int) else 0if not isinstance(released, int) or released < 2**20:return ''- size = '%.1f GiB' % (released / 2**30) if released >= 2**30 else '%d MiB' % (released // 2**20)- return self.t('Old versions removed · %s freed', '已清理旧版本 · 释放 %s') % size+ kinds = {row.get('kind') for row in value.get('removed', []) if isinstance(row, dict)}+ if kinds and kinds <= {'offline-package', 'download-leftover', 'torch-wheel'}:+ # Only this installation's own extractions and download leftovers: not an earlier version.+ return self.t('Temporary setup files removed · %s freed', '已清理安装时的临时文件 · 释放 %s') % size_text(released)+ return self.t('Old versions removed · %s freed', '已清理旧版本 · 释放 %s') % size_text(released)++ def copied_models_text(self):+ """Models copied from a library the installation could not link to, with what would save the space."""+ value = getattr(self.controller, 'old_versions', None)+ copied = value.get('copied_model_bytes') if isinstance(value, dict) else None+ if not isinstance(copied, int) or copied < 2**30:+ return ''+ if value.get('copied_model_reason') == 'exfat':+ return self.t('This disk uses exFAT, so %s of models had to be copied instead of shared with your model library.',+ '这块硬盘是 exFAT 格式,有 %s 的模型只能复制,不能和模型库共用。') % size_text(copied)+ return self.t('%s of models were copied from another disk. Keep your model library on the same disk as FreeVideo '+ 'to avoid this.',+ '有 %s 的模型是从另一块硬盘复制来的。把模型库和 FreeVideo 放在同一块硬盘上,就不会多占这部分空间。') % size_text(copied)++ def archive_offer(self):+ """The imported ZIPs whose contents the running installation holds, verified."""+ if self.controller.state.get('status') != 'open' or not self.form.get('imported_archives'):+ return None+ engine = (self.controller.selection or {}).get('engine')+ if not engine:+ return None+ def identity(path):+ try:+ info = os.stat(path)+ return path, info.st_size, info.st_mtime_ns+ except OSError:+ return path, None, None+ # A ZIP moved, changed or deleted while the launcher is open is noticed on the next view.+ key = (engine, tuple(identity(r['path']) for r in self.form['imported_archives']))+ if getattr(self, 'archive_view', None) is None or self.archive_view[0] != key:+ from .package_cleanup import archives+ self.archive_view = (key, archives(self.form['imported_archives'], engine))+ return self.archive_view[1]++ def delete_archives(self):+ from .package_cleanup import delete_archives+ engine = (self.controller.selection or {}).get('engine')+ if self.controller.state.get('status') != 'open' or not engine:+ return+ offered = len((self.archive_offer() or {}).get('paths', []))+ freed, removed = delete_archives(self.form['imported_archives'], engine)+ self.archives_failed = max(0, offered - len(removed))+ self.form['imported_archives'] = [r for r in self.form['imported_archives'] if r['path'] not in removed]+ self.archive_view = None+ self.archives_freed = (getattr(self, 'archives_freed', 0) or 0) + freed+ self.persist()++ def archives_text(self):+ offer = self.archive_offer()+ if offer and offer['bytes'] >= 2**20:+ return self.t('The offline package ZIP files you imported still take %s. FreeVideo no longer needs them.',+ '导入用过的离线包压缩包还占着 %s,FreeVideo 已经用不到它们。') % size_text(offer['bytes'])+ return ''++ def archives_confirm_text(self):+ offer = self.archive_offer()+ if not offer or offer['bytes'] < 2**20:+ return ''+ count = len(offer['paths'])+ english = 'Delete 1 ZIP file (%s)? This cannot be undone.' if count == 1 else 'Delete %d ZIP files (%%s)? This cannot be undone.' % count+ return self.t(english % size_text(offer['bytes']), '删除 %d 个压缩包(%s)?删除后不能恢复。' % (count, size_text(offer['bytes'])))++ def archives_done_text(self):+ freed = getattr(self, 'archives_freed', 0) or 0+ return self.t('ZIP files deleted · %s freed', '已删除压缩包 · 释放 %s') % size_text(freed) if freed >= 2**20 else ''++ def archives_failed_text(self):+ failed = getattr(self, 'archives_failed', 0) or 0+ if not failed:+ return ''+ return self.t('1 ZIP file could not be deleted.' if failed == 1 else '%d ZIP files could not be deleted.' % failed,+ '%d 个压缩包没能删除。' % failed)def snapshot(self):from .failure_details import launcher_failure, redacted_launcher_error@@ -1059,7 +1169,8 @@ class Session:ready = bool(row.get('selection', {}).get('ready') or row.get('status') == 'open')models = []states = {'ready': ('Ready locally', '本地已就绪'), 'waiting': ('Waiting for scan', '等待检查'),- 'pending': ('Download needed', '需要下载'), 'downloading': ('Downloading', '正在下载'),+ 'pending': ('Download needed', '需要下载'), 'remaining': ('Waiting for remaining files', '等待补齐剩余文件'),+ 'downloading': ('Downloading', '正在下载'),'verifying': ('Transfer complete · verifying (no re-download)', '传输完成 · 正在校验(不会重复下载)'),'paused': ('Paused', '已暂停')}for name in FAMILIES:@@ -1067,7 +1178,10 @@ class Session:continueitem = dict(by_id.get(name, {}))state = 'ready' if ready else item.get('state', 'waiting')- if state == 'waiting' and item.get('download_bytes'):+ if state == 'pending':+ # Part of the group is ready; the rest (often small config files) waits for a download slot.+ state = 'remaining'+ elif state == 'waiting' and item.get('download_bytes'):state = 'pending'total = item.get('total_bytes', 0)done = total if state == 'ready' else min(total,@@ -1089,9 +1203,9 @@ class Session:if gpu:estimate.append(gpu)if 'model_download_bytes' in plan:- estimate.append(self.t('Download ', '需下载 ')+'%.1f GiB' % (plan['model_download_bytes']/2**30))+ estimate.append(self.t('Download ', '需下载 ')+disk_space.size_text(plan['model_download_bytes']))if row.get('disks'):- estimate.append(self.t('Peak disk ~', '磁盘峰值约 ')+'%.1f GiB' % (sum(d.get('needed_bytes', 0) for d in row['disks'])/2**30))+ estimate.append(self.t('Peak disk ~', '磁盘峰值约 ')+disk_space.size_text(sum(d.get('needed_bytes', 0) for d in row['disks'])))update = self.update_view()probe = self.probe.snapshot()speeds = []@@ -1106,7 +1220,14 @@ class Session:speeds.append(dict(source=source_name(entry['id'], zh)+' · '+route, group=self.t(*names.get(group, (group, group))),ok=entry.get('ok', False), rate=speed_text(entry, self.language.startswith('zh'))))from .sampling_assets import total_bytes- return dict(sampling_cache_bytes=total_bytes(), version=__version__, zh=self.language.startswith('zh'), form=dict(self.form),+ failure = launcher_failure(error, zh=self.language.startswith('zh'))+ disk = self.disk_view(row, failure)+ if disk and str(failure.get('kind', '')).startswith('disk'):+ failure = launcher_failure(error, zh=self.language.startswith('zh'),+ other_disk=self.form['new_comfy'] and any(d['enough'] for d in disk['others']),+ disk_name=disk['name'] if disk['problem'] == 'disconnected' else '')+ return dict(sampling_cache_bytes=total_bytes(), version=__version__,+ disk=disk, decimal_sizes=sys.platform == 'darwin', zh=self.language.startswith('zh'), form=dict(self.form),page=self.page, status=row.get('status', 'idle'), busy=self.controller.busy or self.importer.busy or self.cleaner.busy,cleanup=dict(self.cleaner.state, busy=self.cleaner.busy),can_cleanup=not (self.controller.busy or self.importer.busy or self.cleaner.busy or self.closing@@ -1123,12 +1244,14 @@ class Session:models=models, overall=overall, progress=progress, detail=clean(progress.get('detail', '')),progress_text=progress_text(progress, self.language.startswith('zh')),elapsed=duration(time.monotonic()-self.started) if self.started else '', summary=' · '.join(estimate),- failure=launcher_failure(error, zh=self.language.startswith('zh')),+ failure=failure,source=source, source_name=source_name(source, zh), proxy_mode=preferences['proxy_mode'],probe=probe, speeds=speeds, token_set=bool(self.token),log=self.tail.text, logs=[dict(label=display(n, zh), path=str(p)) for n, p in self.controller.terminal_sources()],url=(self._browser_url(row.get('url', '')) if row.get('status') == 'open' else ''), shortcut=shortcut,- old_versions=self.old_versions_text(),+ old_versions=self.old_versions_text(), copied_models=self.copied_models_text(),+ archives=self.archives_text(), archives_confirm=self.archives_confirm_text(),+ archives_done=self.archives_done_text(), archives_failed=self.archives_failed_text(),can_shortcut=bool(self.controller.selection and self.controller.selection.get('ready')),update=update, engine_update_available=bool(row.get('engine_update_available')),settings_path=str(self.store.primary),diff --git a/freevideo_engine/launcher_settings.py b/freevideo_engine/launcher_settings.pyindex 706f79b..bb314ce 100644--- a/freevideo_engine/launcher_settings.py+++ b/freevideo_engine/launcher_settings.py@@ -9,6 +9,7 @@ from .monitoring import saveTEXT = ('comfy', 'destination', 'engine', 'models', 'python', 'url', 'language', 'offline_runtime')SELECTION = ('root', 'engine', 'source', 'python', 'url')+ARCHIVE = ('path', 'bytes', 'mtime_ns', 'kind', 'root')def default_language():@@ -40,6 +41,12 @@ def sanitize(value):offline = value.get('offline_models')if isinstance(offline, list) and all(isinstance(p, str) for p in offline):result['offline_models'] = list(dict.fromkeys(offline))+ archives = value.get('imported_archives')+ if isinstance(archives, list):+ result['imported_archives'] = [+ {k: row[k] for k in ARCHIVE} for row in archives+ if isinstance(row, dict) and all(isinstance(row.get(k), str) for k in ('path', 'root', 'kind'))+ and all(type(row.get(k)) is int for k in ('bytes', 'mtime_ns'))][-64:]record = value.get('installation')if isinstance(record, dict) and all(isinstance(record.get(k), str) and record[k] for k in SELECTION):result['installation'] = {k: record[k] for k in SELECTION}diff --git a/freevideo_engine/launcher_update.py b/freevideo_engine/launcher_update.pyindex dbee798..86a42c4 100644--- a/freevideo_engine/launcher_update.py+++ b/freevideo_engine/launcher_update.py@@ -18,6 +18,7 @@ import urllib.requestfrom .diagnostics import Redactorfrom .monitoring import save+from . import disk_spaceREPOSITORY = 'FlashML-org/FreeVideo'# The channel names the platform; launchers from before combined releases read@@ -27,12 +28,16 @@ API = 'https://api.github.com/repos/' + REPOSITORYRELEASE_PAGE = 'https://github.com/' + REPOSITORY + '/releases/latest'MAX_EXE_BYTES = 512 * 2**20MAC_CHANNEL = 'macos-preview'+# Linux has no release before combined releases, so no platform tag to fall back on.+LINUX_CHANNEL = 'linux-preview'# Stable builds follow the latest vX.Y.Z release; nightly builds follow the# rolling `nightly` prerelease. Both carry every platform in one release.TRACKS = ('stable', 'nightly')NIGHTLY_TAG = 'nightly'RELEASE_ASSETS = {CHANNEL: ('FreeVideo.exe', 'update-windows.json'),- MAC_CHANNEL: ('FreeVideo-Mac-arm64.dmg', 'update-macos.json')}+ MAC_CHANNEL: ('FreeVideo-Mac-arm64.dmg', 'update-macos.json'),+ LINUX_CHANNEL: ('FreeVideo-Linux-x86_64.AppImage', 'update-linux.json')}+CHANNELS = tuple(RELEASE_ASSETS)def build_target(value):@@ -52,7 +57,7 @@ def release_page(current):def build_identity(value):if (not isinstance(value, dict) or value.get('repository') != REPOSITORY- or value.get('channel') not in (CHANNEL, MAC_CHANNEL) or value.get('schema') != 1+ or value.get('channel') not in CHANNELS or value.get('schema') != 1or not re.fullmatch(r'[0-9a-f]{40,64}', str(value.get('revision', '')))or type(value.get('built_at')) is not int or value['built_at'] <= 0or not isinstance(value.get('version'), str) or len(value['version']) > 64):@@ -60,6 +65,9 @@ def build_identity(value):if value['channel'] == MAC_CHANNEL:if value.get('target') != 'macos-arm64' or value.get('packaging') != 'app':raise ValueError('Invalid Mac launcher build identity')+ elif value['channel'] == LINUX_CHANNEL:+ if value.get('target') != 'linux-x86_64' or value.get('packaging') != 'appimage':+ raise ValueError('Invalid Linux launcher build identity')elif build_target(value) != 'windows-x86_64':raise ValueError('Launcher update channel does not match its target')if build_track(value) not in TRACKS:@@ -71,6 +79,8 @@ def build_identity(value):result['packaging'] = 'onedir'if value['channel'] == MAC_CHANNEL:result.update(target='macos-arm64', packaging='app')+ if value['channel'] == LINUX_CHANNEL:+ result.update(target='linux-x86_64', packaging='appimage')from .release_notes import optional_fieldsresult.update(optional_fields(value))return result@@ -176,6 +186,8 @@ def _release(token, channel, track):names = {a.get('name') for a in (release or {}).get('assets', []) if isinstance(a, dict)}if isinstance(release, dict) and not release.get('draft') and not release.get('prerelease') and metadata in names:return release, executable, metadata+ if channel == LINUX_CHANNEL:+ raise ValueError('No published update is available for this platform')# Until the first combined release, updates come from the platform tag.release = _json(API + '/releases/tags/' + channel, token)if not isinstance(release, dict) or release.get('draft') or release.get('tag_name') != channel:@@ -185,7 +197,7 @@ def _release(token, channel, track):def latest_release(token='', *, channel=CHANNEL, track='stable'):"""Read and validate the published build without downloading an executable."""- if channel not in (CHANNEL, MAC_CHANNEL):+ if channel not in CHANNELS:raise ValueError('Unknown launcher update channel')if track not in TRACKS:raise ValueError('Unknown launcher release track')@@ -227,7 +239,7 @@ def verified(path, asset):def executable_path(root, candidate):- filename = 'FreeVideo-Mac-arm64.dmg' if build_target(candidate) == 'macos-arm64' else 'FreeVideo.exe'+ filename = RELEASE_ASSETS[candidate['channel']][0]return Path(root).absolute().resolve() / 'updates' / candidate['asset']['sha256'] / filename@@ -242,7 +254,7 @@ def download(candidate, root, token='', *, progress=None, cancel=None):# only ours; never touch another attempt, the original launcher or models.import tempfileimport shutil- if shutil.disk_usage(target.parent).free < asset['bytes'] + 16*2**20:+ if disk_space.free_bytes(target.parent) < asset['bytes'] + 16*2**20:raise OSError('Not enough disk space to download the launcher update')start, done = time.monotonic(), 0stage = None@@ -263,6 +275,8 @@ def download(candidate, root, token='', *, progress=None, cancel=None):raise ValueError('Launcher update failed size/content verification; original EXE retained')if cancel is not None and cancel.is_set():raise InterruptedError('Update stopped before activation')+ if build_target(candidate) == 'linux-x86_64':+ stage.chmod(0o755) # An AppImage runs itself.stage.replace(target)return targetfinally:@@ -284,7 +298,8 @@ def launch_download(candidate, root, *, token='', popen=None):path = executable_path(root, candidate)if not verified(path, candidate['asset']):raise DownloadedLauncherUnavailable('Downloaded launcher is missing or changed; download again')- env = dict(os.environ, FREEVIDEO_LAUNCHER_HOME=str(Path(root).absolute().resolve()))+ from .linux_bundle import child_environment+ env = dict(child_environment(), FREEVIDEO_LAUNCHER_HOME=str(Path(root).absolute().resolve()))if token:env['GITHUB_TOKEN'] = token # Session only; never stored in a receipt or command.kwargs = dict(cwd=path.parent, env=env, close_fds=True)diff --git a/freevideo_engine/licenses/LXGW-WenKai-OFL.txt b/freevideo_engine/licenses/LXGW-WenKai-OFL.txtnew file mode 100644index 0000000..f170b5c--- /dev/null+++ b/freevideo_engine/licenses/LXGW-WenKai-OFL.txt@@ -0,0 +1,94 @@+Copyright 2021-2026 LXGW (https://github.com/lxgw/LxgwWenKai)+Copyright 2020 The Klee Project Authors (https://github.com/fontworks-fonts/Klee)++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:+https://openfontlicense.org+++-----------------------------------------------------------+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 & 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.diff --git a/freevideo_engine/licenses/Lucide-ISC.txt b/freevideo_engine/licenses/Lucide-ISC.txtnew file mode 100644index 0000000..b70071e--- /dev/null+++ b/freevideo_engine/licenses/Lucide-ISC.txt@@ -0,0 +1,15 @@+ISC License++Copyright (c) 2026 Lucide Icons and Contributors++Permission to use, copy, modify, and/or distribute this software for any+purpose with or without fee is hereby granted, provided that the above+copyright notice and this permission notice appear in all copies.++THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.diff --git a/freevideo_engine/licenses/Noto-CJK-Sans-OFL.txt b/freevideo_engine/licenses/Noto-CJK-Sans-OFL.txtnew file mode 100644index 0000000..8b764c5--- /dev/null+++ b/freevideo_engine/licenses/Noto-CJK-Sans-OFL.txt@@ -0,0 +1,94 @@+© 2014-2021 Adobe (http://www.adobe.com/).++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 & 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.diff --git a/freevideo_engine/licenses/Noto-CJK-Serif-OFL.txt b/freevideo_engine/licenses/Noto-CJK-Serif-OFL.txtnew file mode 100644index 0000000..5b99095--- /dev/null+++ b/freevideo_engine/licenses/Noto-CJK-Serif-OFL.txt@@ -0,0 +1,94 @@+© 2017-2024 Adobe (http://www.adobe.com/).++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 & 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.diff --git a/freevideo_engine/linux_bundle.py b/freevideo_engine/linux_bundle.pynew file mode 100644index 0000000..b08037c--- /dev/null+++ b/freevideo_engine/linux_bundle.py@@ -0,0 +1,93 @@+"""The Linux launcher as an AppImage: its own file, and a clean environment for everything it starts.++PyInstaller points LD_LIBRARY_PATH at the libraries it bundles, and the AppImage+runtime adds APPIMAGE, APPDIR, ARGV0 and OWD. Inherited by bash, git, curl, the+ComfyUI Python or the browser, the bundled libraries replace the system's and+those programs fail in ways that look unrelated (an OpenSSL symbol missing in+git, a browser that will not start). The dynamic linker reads LD_LIBRARY_PATH+once, when a process starts, so the launcher restores the original value for+itself as soon as it runs, and every child inherits a clean environment.+"""+import os+from pathlib import Path+import sys++APPIMAGE_VARIABLES = ('APPIMAGE', 'APPDIR', 'ARGV0', 'OWD', 'APPIMAGE_UUID')+# Set by PyInstaller's bootloader and its Qt runtime hook for the bundle only.+BUNDLE_PREFIXES = ('_PYI_', '_MEI')+QT_VARIABLES = ('QT_PLUGIN_PATH', 'QML2_IMPORT_PATH', 'QML_IMPORT_PATH', 'QT_QPA_PLATFORM_PLUGIN_PATH')+_captured = {}+++def frozen_linux():+ return getattr(sys, 'frozen', False) and sys.platform.startswith('linux')+++def bundle_directory():+ return Path(getattr(sys, '_MEIPASS', Path(sys.executable).parent)).resolve()+++def inside_bundle(value):+ """Whether a path-list variable points into this launcher's own files."""+ roots = [bundle_directory()]+ if _captured.get('APPDIR'):+ roots.append(Path(_captured['APPDIR']).resolve())+ for entry in str(value).split(os.pathsep):+ if not entry:+ continue+ try:+ path = Path(entry).resolve()+ except (OSError, RuntimeError):+ continue+ if any(path == root or root in path.parents for root in roots):+ return True+ return False+++def child_environment(environ=None):+ """The environment for a program this launcher starts, as if started from the desktop."""+ env = dict(os.environ if environ is None else environ)+ if not frozen_linux():+ return env+ original = env.pop('LD_LIBRARY_PATH_ORIG', None)+ if original is not None:+ env['LD_LIBRARY_PATH'] = original+ elif 'LD_LIBRARY_PATH' in env and inside_bundle(env['LD_LIBRARY_PATH']):+ env.pop('LD_LIBRARY_PATH')+ if not env.get('LD_LIBRARY_PATH', 'x'):+ env.pop('LD_LIBRARY_PATH')+ for name in list(env):+ if name in APPIMAGE_VARIABLES or name.startswith(BUNDLE_PREFIXES):+ env.pop(name)+ elif name in QT_VARIABLES and inside_bundle(env[name]):+ env.pop(name)+ return env+++def prepare():+ """At start: remember the AppImage, then give this process the environment its children need.++ Qt's own paths stay until the window exists; child_environment() leaves them+ out for children in the meantime.+ """+ if not frozen_linux():+ return+ for name in APPIMAGE_VARIABLES:+ if os.environ.get(name):+ _captured[name] = os.environ[name]+ original = os.environ.pop('LD_LIBRARY_PATH_ORIG', None)+ if original is not None:+ os.environ['LD_LIBRARY_PATH'] = original+ if not original:+ os.environ.pop('LD_LIBRARY_PATH')+ for name in APPIMAGE_VARIABLES:+ os.environ.pop(name, None)+++def appimage():+ """The AppImage file this launcher runs from, or None outside an AppImage."""+ value = _captured.get('APPIMAGE') or (os.environ.get('APPIMAGE') if frozen_linux() else None)+ if not value:+ return None+ path = Path(value)+ return path if path.is_file() else Nonediff --git a/freevideo_engine/local_models.py b/freevideo_engine/local_models.pyindex 00ffca9..65f8c05 100644--- a/freevideo_engine/local_models.py+++ b/freevideo_engine/local_models.py@@ -76,6 +76,13 @@ def can_link(source, destination_parent):return Falseif os.name != 'nt':return True+ return volume_filesystem(destination_parent) == 'NTFS'+++def volume_filesystem(path):+ """The file system of path's Windows volume (NTFS, exFAT, FAT32...), or None elsewhere or when unknown."""+ if os.name != 'nt':+ return Noneimport ctypesfrom ctypes import wintypeskernel = ctypes.WinDLL('kernel32', use_last_error=True)@@ -84,11 +91,11 @@ def can_link(source, destination_parent):ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD),wintypes.LPWSTR, wintypes.DWORD]volume, filesystem = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(64)- if not kernel.GetVolumePathNameW(str(destination_parent), volume, len(volume)):- return False+ if not kernel.GetVolumePathNameW(str(path), volume, len(volume)):+ return Noneif not kernel.GetVolumeInformationW(volume.value, None, 0, None, None, None, filesystem, len(filesystem)):- return False- return filesystem.value.upper() == 'NTFS'+ return None+ return filesystem.value.upper()def progress_output(value):diff --git a/freevideo_engine/lora_cache.py b/freevideo_engine/lora_cache.pyindex c71fef0..e20ff58 100644--- a/freevideo_engine/lora_cache.py+++ b/freevideo_engine/lora_cache.py@@ -24,6 +24,7 @@ from .tensor_io import open_tensorsfrom .media_request import digest, verify_filesfrom .monitoring import savefrom .storage import fingerprint+from . import disk_spacedef _targets(name):@@ -247,7 +248,7 @@ def prepare(cache, adapters, output_root=None):patches.setdefault(targets[patch['target']]['group'], []).append(patch)output.mkdir(parents=True, exist_ok=True)required = sum(row['bytes'] for row in manifest['groups'] if row['file'] in patches)- if shutil.disk_usage(output).free < required + 1024**3:+ if disk_space.free_bytes(output) < required + 1024**3:raise ValueError('Insufficient disk for the separate LoRA variant; original model retained')records = []started = time.perf_counter()diff --git a/freevideo_engine/macos_reference.py b/freevideo_engine/macos_reference.pyindex 60d0c0c..9bd7226 100644--- a/freevideo_engine/macos_reference.py+++ b/freevideo_engine/macos_reference.py@@ -13,6 +13,7 @@ import shutilfrom . import adaln_assets as assetsfrom . import networkfrom .monitoring import save+from . import disk_spaceCATALOG_FILE = Path(__file__).with_name('macos_reference_catalog.json')@@ -139,7 +140,7 @@ def ensure(cache, identity, count, *, catalog, networking=None, env=None):# Rejected partial bytes are retained by the shared downloader. Reserve a# full replacement even when an existing prefix looks complete.needed = sum(row['bytes'] for _, _, row in missing)- if missing and shutil.disk_usage(root).free < needed + 256 * 2**20:+ if missing and disk_space.free_bytes(root) < needed + 256 * 2**20:raise ValueError('Insufficient disk space for Mac reference constants; existing files retained')for sidecar, row in recovered:if not sidecar.exists():diff --git a/freevideo_engine/managed.py b/freevideo_engine/managed.pyindex 4a8af78..1ce0c27 100644--- a/freevideo_engine/managed.py+++ b/freevideo_engine/managed.py@@ -44,8 +44,16 @@ def _main(argv=None):parser.add_argument('--root', type=Path, default=Path(os.environ.get('FREEVIDEO_HOME', DEFAULT_ROOT)))parser.add_argument('--config', type=Path)args, rest = parser.parse_known_args(argv)- if not rest or rest[0] in ('-h', '--help'):- print('FreeVideo Engine ' + __version__ + '\n\nUsage: ./freevideo [--root PATH] COMMAND [OPTIONS]\n\n'+ # On Linux the bare command opens FreeVideo; elsewhere the desktop app does.+ if (rest and rest[0] in ('-h', '--help')) or (not rest and not sys.platform.startswith('linux')):+ print('FreeVideo Engine ' + __version__ + '\n\nUsage: ./freevideo [--root PATH] [COMMAND] [OPTIONS]\n\n'+ ' (none) Linux: open FreeVideo in ComfyUI, installing and starting it as needed\n'+ ' open The same; --port N, --no-browser\n'+ ' server Linux: keep FreeVideo running for other computers (SSH tunnel, or\n'+ ' --listen 0.0.0.0 with an access link); --enable starts it with your session\n'+ ' status Show whether FreeVideo is running and its address\n'+ ' stop Stop ComfyUI (not while a job runs, unless --force)\n'+ ' restart Restart ComfyUI, for example after updating FreeVideo\n'' setup Detect hardware, review and install from scratch\n'' test Run full video/audio tests with a live dashboard\n'' optimize Reuse test results and validate lightweight local tuning\n'@@ -57,14 +65,19 @@ def _main(argv=None):' doctor Check dependencies and GPU kernels\n'' diagnose Collect a small local report, including failed installs\n'' bench Compare attention backends\n\n'- 'Examples:\n ./freevideo setup --plan\n ./freevideo test --suite quick\n'- ' ./freevideo generate --prompt-file prompt.txt --out video.mp4\n\n'+ 'Examples:\n ./freevideo\n ./freevideo server --listen 0.0.0.0\n ./freevideo setup --plan\n'+ ' ./freevideo test --suite quick\n ./freevideo generate --prompt-file prompt.txt --out video.mp4\n\n''Use COMMAND --help for options. Windows: .\\setup.ps1 / .\\test.ps1 / .\\freevideo.ps1; Linux: ./setup.sh / ./test.sh / ./freevideo.')return 0+ if not rest:+ rest = ['open']command, tail = rest[0], rest[1:]if command == 'setup':from .bootstrap import main as setupreturn setup(['--root', str(args.root), *tail])+ if command in ('open', 'stop', 'status', 'restart', 'server'):+ from .comfy_service import cli+ return cli(command, args.root, tail)if command == 'diagnose':from .diagnostics import main as diagnosereturn diagnose(['--root', str(args.root), *(['--config', str(args.config)] if args.config else []), *tail])diff --git a/freevideo_engine/model_guidance.py b/freevideo_engine/model_guidance.pyindex 0fe173d..8457971 100644--- a/freevideo_engine/model_guidance.py+++ b/freevideo_engine/model_guidance.py@@ -6,7 +6,8 @@ from urllib.parse import quote, urlsplitdef runtime_packages_supported():- return sys.platform != 'darwin'+ """The offline Environment package carries a Windows runtime."""+ return sys.platform == 'win32'def package_instructions(runtime_needed, zh=False):@@ -22,6 +23,12 @@ def package_instructions(runtime_needed, zh=False):'The installer downloads the Mac environment automatically. Do not download the Windows Environment package.','下载「视频模型」「文本编码器」「视频与音频解码器」「采样缓存」四个模型包,Mac 同样适用。''Mac 运行环境由安装器自动下载,无需下载 Windows「运行环境」包。')[bool(zh)]+ if sys.platform.startswith('linux'):+ return (+ 'Get the four model packs (video model, text encoder, video & audio decoder, sampling caches); they also work on Linux. '+ 'The installer downloads the Linux environment automatically. Do not download the Windows Environment package.',+ '下载「视频模型」「文本编码器」「视频与音频解码器」「采样缓存」四个模型包,Linux 同样适用。'+ 'Linux 运行环境由安装器自动下载,无需下载 Windows「运行环境」包。')[bool(zh)]text = ('Get the four model packs: video model, text encoder, video & audio decoder, and sampling caches. ''The reference audio pack is optional, for audio references.','下载「视频模型」「文本编码器」「视频与音频解码器」「采样缓存」四个模型包;'diff --git a/freevideo_engine/model_upgrade.py b/freevideo_engine/model_upgrade.pyindex 9670b46..0df413d 100644--- a/freevideo_engine/model_upgrade.py+++ b/freevideo_engine/model_upgrade.py@@ -23,6 +23,7 @@ from pathlib import Pathimport shutilimport threadingimport time+from . import disk_spaceGiB = 1 << 30MARGIN = 2 * GiB@@ -73,7 +74,7 @@ def offer(root):download = setup_download(root, machine, selection)fused = variant_cleanup.fused_lora_variants(root, catalog, current)release = 0 if fused else variant_cleanup.retire(root, catalog, current)['bytes']- free = shutil.disk_usage(root).free+ free = disk_space.free_bytes(root)return dict(status='available' if free >= download + MARGIN else 'low-disk',architecture=hardware.architecture, gpu=hardware.gpu_name, current=current,download_bytes=download, release_bytes=release, free_bytes=free,@@ -234,7 +235,7 @@ class ModelUpgrade:# larger plan is shown on the card and confirmed again first.planned_bytes = value['model_download_bytes']if planned_bytes > offered['download_bytes'] + 64 * (1 << 20):- free = shutil.disk_usage(root).free+ free = disk_space.free_bytes(root)self.state = dict(offered, status='available' if free >= planned_bytes + MARGIN else 'low-disk',download_bytes=planned_bytes, required_bytes=planned_bytes + MARGIN,free_bytes=free, resized=True)diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.pyindex 79b2220..63a031b 100644--- a/freevideo_engine/modern_launcher.py+++ b/freevideo_engine/modern_launcher.py@@ -59,7 +59,15 @@ def create_ui(session, *, show=True):app.setOrganizationName('FreeVideo')app.styleHints().setColorScheme(Qt.ColorScheme.Dark)font = QFont()- font.setFamilies(['Segoe UI', 'Microsoft YaHei UI', 'Noto Sans', 'Noto Sans CJK SC', 'sans-serif'])+ families = ['Segoe UI', 'Microsoft YaHei UI', 'Noto Sans', 'Noto Sans CJK SC']+ # The Linux AppImage carries the launcher's Chinese characters for desktops+ # without a Chinese font; a complete system font still comes first.+ from PySide6.QtGui import QFontDatabase+ for path in sorted((Path(__file__).parent / 'assets/fonts').glob('*.otf')):+ for family in QFontDatabase.applicationFontFamilies(QFontDatabase.addApplicationFont(str(path))):+ if family not in families:+ families.append(family)+ font.setFamilies(families + ['sans-serif'])font.setPointSize(10)app.setFont(font)icon = launcher_icon()@@ -120,6 +128,10 @@ def create_ui(session, *, show=True):def action(self, name, accepted=False):self.invoke(session.action, name, accepted)+ @Slot(str)+ def useDisk(self, folder):+ self.invoke(session.use_disk, folder)+@Slot(bool)def cleanupDownloads(self, remove=False):self.invoke(session.cleanup_downloads, remove)@@ -321,6 +333,9 @@ def smoke_test(app, engine, window, bridge, destination):primary = window.findChild(QQuickItem, 'primaryButton')if primary is None or not primary.isVisible() or primary.width() < 40:raise RuntimeError('Packaged launcher action is not visible: ' + page)+ if page == 'progress':+ # The last setup step shows the finished ones with a check mark; keep it for the font check.+ window.grabWindow().save(str(destination / 'launcher-steps.png'))window.setProperty('settingsOpen', True)app.processEvents()window.setProperty('settingsOpen', False)@@ -360,6 +375,43 @@ def smoke_test(app, engine, window, bridge, destination):timer.start(100)+def smoke_connect(app, engine, window, bridge, destination, values):+ """Connect the packaged launcher to an existing installation, as a person would, and open ComfyUI.++ Exercises what only a packaged launcher does on a real installation: its+ helper processes, the environment of the programs it starts, its source copy.+ """+ from PySide6.QtCore import QTimer+ from .comfy_launcher_runtime import server_info+ from .monitoring import save+ destination = Path(destination)+ destination.mkdir(parents=True, exist_ok=True)+ session = engine.session+ for key, value in values.items():+ session.edit(key, value)+ session.action('primary')+ session.action('primary')+ deadline = time.monotonic() + 900+ timer = QTimer(bridge)+ def step():+ state = session.controller.state+ status = state.get('status')+ if session.controller.busy:+ return+ if status == 'review' and time.monotonic() < deadline:+ session.action('primary', True)+ return+ if status in ('open', 'failed', 'cancelled', 'restart-required') or time.monotonic() > deadline:+ info = server_info(state['url'].split('/?')[0]) if status == 'open' else {}+ save(destination / 'connect.json', dict(success=status == 'open' and info.get('status') == 'freevideo',+ status=status, error=state.get('error'), url=state.get('url'), server=info))+ window.grabWindow().save(str(destination / 'connected.png'))+ timer.stop()+ app.quit()+ timer.timeout.connect(step)+ timer.start(250)++def main(session=None):if (getattr(sys, 'frozen', False) and sys.platform == 'darwin'and sys.argv[1:2] == ['--macos-process-host']):@@ -378,14 +430,27 @@ def main(session=None):freevideo_engine.__path__.insert(0, str(source / 'freevideo_engine'))from .managed import main as managedraise SystemExit(managed(sys.argv[3:]))- # Linux process supervision reexecutes sys.executable. A frozen GUI must- # dispatch this helper before creating another application window.- if (getattr(sys, 'frozen', False) and sys.platform == 'linux'- and sys.argv[1:4] == ['-B', '-m', 'freevideo_engine.linux_process_host']):- from .linux_process_host import main as supervise- sys.argv = [sys.argv[3], *sys.argv[4:]]- raise SystemExit(supervise())+ if getattr(sys, 'frozen', False) and sys.platform.startswith('linux'):+ from .linux_bundle import prepare+ prepare()+ # Helpers such as Linux process supervision run this executable again+ # (processes.module_command); dispatch them before any window exists.+ if sys.argv[1:2] == ['--freevideo-module'] and len(sys.argv) >= 3:+ import runpy+ module = sys.argv[2]+ if module not in ('freevideo_engine.linux_process_host',):+ raise SystemExit('Unknown launcher helper: ' + module)+ # A helper has no window: what PyInstaller set for Qt and for its own+ # bootloader must not reach the programs it supervises.+ from .linux_bundle import child_environment+ clean = child_environment()+ os.environ.clear()+ os.environ.update(clean)+ sys.argv = [module, *sys.argv[3:]]+ runpy.run_module(module, run_name='__main__', alter_sys=True)+ raise SystemExit(0)smoke = '--smoke-test' in sys.argv+ connect = json.loads(sys.argv[sys.argv.index('--smoke-connect') + 1]) if smoke and '--smoke-connect' in sys.argv else Nonefrom .desktop_runtime import launcher_rootportable_root = Path(sys.executable).parentif session is None and getattr(sys, 'frozen', False) and (portable_root / 'portable.json').is_file() and not smoke:@@ -412,8 +477,11 @@ def main(session=None):app, engine, window, bridge = create_ui(session)if smoke:from PySide6.QtCore import QTimer- QTimer.singleShot(0, lambda: smoke_test(app, engine, window, bridge,- sys.argv[sys.argv.index('--smoke-test')+1]))+ destination = sys.argv[sys.argv.index('--smoke-test')+1]+ if connect is not None:+ QTimer.singleShot(0, lambda: smoke_connect(app, engine, window, bridge, destination, connect))+ else:+ QTimer.singleShot(0, lambda: smoke_test(app, engine, window, bridge, destination))try:app.exec()finally:diff --git a/freevideo_engine/monitoring.py b/freevideo_engine/monitoring.pyindex 4abf920..229db12 100644--- a/freevideo_engine/monitoring.py+++ b/freevideo_engine/monitoring.py@@ -1,4 +1,5 @@"""Whole-device NVML sampling; values include driver reservations."""+import bisectimport csvimport ctypesimport json@@ -102,29 +103,59 @@ def thermal_slowdown(measured, *, share=.5, clock_ratio=.7, minimum_samples=200)temperature_mean_c=round(temperature, 1) if isinstance(temperature, (int, float)) else None)+def nvml_device(device=None):+ """Initialize NVML and select one GPU by UUID or index; returns (library, handle, device)."""+ if windows():+ candidates = [Path(os.environ.get('SystemRoot', r'C:\Windows')) / 'System32/nvml.dll',+ Path(os.environ.get('ProgramFiles', r'C:\Program Files')) / 'NVIDIA Corporation/NVSMI/nvml.dll']+ library = next((p for p in candidates if p.is_file()), None)+ if library is None:+ raise RuntimeError('NVML DLL is missing from the NVIDIA driver installation; repair the driver and rerun test.')+ lib = ctypes.CDLL(str(library))+ else:+ lib = ctypes.CDLL('libnvidia-ml.so.1')+ rc = lib.nvmlInit_v2()+ if rc:+ raise RuntimeError(f'NVML initialization returned {rc}')+ handle = ctypes.c_void_p()+ device = str(device if device is not None else os.environ.get('CUDA_VISIBLE_DEVICES', '0').split(',')[0])+ if device.startswith('GPU-'):+ rc = lib.nvmlDeviceGetHandleByUUID(device.encode(), ctypes.byref(handle))+ else:+ rc = lib.nvmlDeviceGetHandleByIndex_v2(int(device), ctypes.byref(handle))+ if rc:+ lib.nvmlShutdown()+ raise RuntimeError(f'NVML could not select {device}: {rc}')+ return lib, handle, device+++class DeviceMemory:+ """Whole-device memory in use by every process, read on demand.++ Windows' per-process budget and CUDA's free memory leave out what other+ applications hold until the device is already full; NVML counts them.+ """+ def __init__(self, device=None):+ self.lib, self.handle, self.device = nvml_device(device)++ def sample(self):+ m = Memory()+ rc = self.lib.nvmlDeviceGetMemoryInfo(self.handle, ctypes.byref(m))+ if rc:+ raise RuntimeError(f'NVML memory read returned {rc}')+ if m.used > m.total or not m.total:+ raise RuntimeError('Driver returned unavailable NVML device memory')+ return dict(used_bytes=m.used, total_bytes=m.total)++ def close(self):+ lib, self.lib = self.lib, None+ if lib is not None:+ lib.nvmlShutdown()++class Monitor:def __init__(self, path, interval=0.05, device=None):- if windows():- candidates = [Path(os.environ.get('SystemRoot', r'C:\Windows')) / 'System32/nvml.dll',- Path(os.environ.get('ProgramFiles', r'C:\Program Files')) / 'NVIDIA Corporation/NVSMI/nvml.dll']- library = next((p for p in candidates if p.is_file()), None)- if library is None:- raise RuntimeError('NVML DLL is missing from the NVIDIA driver installation; repair the driver and rerun test.')- self.lib = ctypes.CDLL(str(library))- else:- self.lib = ctypes.CDLL('libnvidia-ml.so.1')- rc = self.lib.nvmlInit_v2()- if rc:- raise RuntimeError(f'NVML initialization returned {rc}')- self.handle = ctypes.c_void_p()- device = str(device if device is not None else os.environ.get('CUDA_VISIBLE_DEVICES', '0').split(',')[0])- if device.startswith('GPU-'):- rc = self.lib.nvmlDeviceGetHandleByUUID(device.encode(), ctypes.byref(self.handle))- else:- rc = self.lib.nvmlDeviceGetHandleByIndex_v2(int(device), ctypes.byref(self.handle))- if rc:- self.lib.nvmlShutdown()- raise RuntimeError(f'NVML could not select {device}: {rc}')+ self.lib, self.handle, device = nvml_device(device)self.device = deviceself.path, self.interval = Path(path), intervalself.stop_event = threading.Event()@@ -219,3 +250,64 @@ class Monitor:'clock reasons are driver observations, not attribution of elapsed time.','sampling_interval_seconds': self.interval, 'samples': self.count,'sampling_errors': self.errors, 'sample_csv': str(self.path)}++++def step_activity(csv_path, steps, *, limit_bytes=64 * 2**20):+ """Add each sampling step's whole-device NVML samples to it as `device_activity`.++ A request-wide mean cannot show one slow step: whether the device was full,+ another process kept it busy or clocks fell during that step. Steps carry+ the monotonic time they ended; the monitor's CSV, written by the parent+ process, carries the same clock. Returns how many steps were annotated.+ Missing, oversized or partial files add nothing.+ """+ windows = sorted((row['monotonic_seconds'] - row['seconds'], row['monotonic_seconds'], index)+ for index, row in enumerate(steps if isinstance(steps, list) else [])+ if isinstance(row, dict) and all(type(row.get(key)) in (int, float) and row[key] >= 0+ for key in ('monotonic_seconds', 'seconds')))+ if not windows:+ return 0+ try:+ if Path(csv_path).stat().st_size > limit_bytes:+ return 0+ with open(csv_path, newline='', encoding='utf-8') as handle:+ samples = list(csv.DictReader(handle))+ except (OSError, ValueError, csv.Error):+ return 0+ def number(sample, key):+ try:+ value = float(sample.get(key) or 'nan')+ except ValueError:+ return None+ return value if 0 <= value < float('inf') else None+ starts = [start for start, _, _ in windows]+ found = {}+ for sample in samples:+ moment = number(sample, 'monotonic_seconds')+ if moment is None:+ continue+ position = bisect.bisect_right(starts, moment) - 1+ if position < 0 or moment > windows[position][1]:+ continue+ item = found.setdefault(windows[position][2], dict(samples=0, busy_samples=0, sums={}))+ item['samples'] += 1+ util = number(sample, 'gpu_util_percent')+ item['busy_samples'] += util is not None and util >= 50+ for key, value in (('gpu_util_mean_percent', util), ('sm_clock_mean_mhz', number(sample, 'sm_clock_mhz')),+ ('power_mean_mw', number(sample, 'power_mw'))):+ if value is not None:+ total = item['sums'].setdefault(key, [0., 0])+ total[0] += value+ total[1] += 1+ used, size = number(sample, 'used_bytes'), number(sample, 'total_bytes')+ if used is not None:+ item['device_used_peak_bytes'] = max(item.get('device_used_peak_bytes', 0), int(used))+ item['device_used_minimum_bytes'] = min(item.get('device_used_minimum_bytes', int(used)), int(used))+ if size is not None:+ item['device_total_bytes'] = int(size)+ for index, item in found.items():+ for key, (total, count) in item.pop('sums').items():+ item[key] = total / count+ steps[index]['device_activity'] = item+ return len(found)diff --git a/freevideo_engine/offline_packages.py b/freevideo_engine/offline_packages.pyindex ad5bf23..6bd4f73 100644--- a/freevideo_engine/offline_packages.py+++ b/freevideo_engine/offline_packages.py@@ -11,6 +11,7 @@ import zipfilefrom .monitoring import savefrom .portable import ENCODER_LIBRARY, bundle_name, inside, listing+from . import disk_spacePREFIX = 'FreeVideo-Windows/'# Optional packs (reference-audio tables) carry sampling tables outside the@@ -203,6 +204,9 @@ def import_archive(path, destination, progress=lambda **kw: None, cancelled=lamb"""path = Path(path).resolve()progress(done=0, total=None, detail=path.name)+ archive = path.stat()+ # Which ZIP this was, so the launcher can later offer to delete it once installed.+ origin = dict(archive=str(path), archive_bytes=archive.st_size, archive_mtime_ns=archive.st_mtime_ns)value = inspect_archive(path)root = Path(destination).resolve() / '.freevideo-packages' / value['id'] / 'FreeVideo-Windows'total = sum(r['bytes'] for r in value['files'])@@ -212,7 +216,7 @@ def import_archive(path, destination, progress=lambda **kw: None, cancelled=lambparent = rootwhile not parent.exists():parent = parent.parent- if shutil.disk_usage(parent).free < missing + 64 * 2**20:+ if disk_space.free_bytes(parent) < missing + 64 * 2**20:raise ValueError('磁盘空间不足,导入此包还需约 %.1f GiB。' % (missing / 2**30))known, verified = stamps(root), {}for row in value['files']:@@ -227,7 +231,7 @@ def import_archive(path, destination, progress=lambda **kw: None, cancelled=lamb# Imported before and complete: nothing to read again.save(root / VERIFIED, verified)progress(done=total, total=total, detail=path.name)- return dict(root=str(root), kind=value['kind'], variant=value['variant'], name=path.name)+ return dict(root=str(root), kind=value['kind'], variant=value['variant'], name=path.name, **origin)done = sum(r['bytes'] for r in value['files'] if r['path'] in verified)root.mkdir(parents=True, exist_ok=True)progress(done=done, total=total, detail=path.name)@@ -261,7 +265,7 @@ def import_archive(path, destination, progress=lambda **kw: None, cancelled=lambverified[row['path']] = stamp(target)save(root / VERIFIED, verified)marker.write_bytes(value['raw'])- return dict(root=str(root), kind=value['kind'], variant=value['variant'], name=path.name)+ return dict(root=str(root), kind=value['kind'], variant=value['variant'], name=path.name, **origin)ENCODER_COPY = 'engine/vendor/h3-text-encoder'diff --git a/freevideo_engine/offload.py b/freevideo_engine/offload.pyindex 46293e1..6b850f9 100644--- a/freevideo_engine/offload.py+++ b/freevideo_engine/offload.py@@ -194,8 +194,8 @@ class Slot:# process on a 56 GiB RTX 3090 machine (about 2 GiB available while sampling),# 1344x768x124 went from 15.5-15.9 to 10.7-10.9 s per first-pass step and# 29.8-30.0 to 26.0-26.1 per second-pass step at 1 GiB, twice each (327-332 s-# to 283-294 s for the request). The runtime check in _queue_host stops-# read-ahead again under live pressure.+# to 283-294 s for the request). The runtime check in _queue_host returns the+# extra block under live pressure; read-ahead then shares the staging buffer.HOST_PREFETCH_HEADROOM = 1 * 2**30@@ -432,7 +432,10 @@ class LayerOffloader:from .system import windowsrequested = windows() if host_prefetch is None else host_prefetchself.host_prefetch = False+ # Memory pressure no longer switches read-ahead off (see the shared+ # reason below); reports keep this field for earlier versions.self.host_prefetch_disabled_reason = None+ self.host_prefetch_shared_reason = Noneself.host_slots = []self.host_executor = Noneself.host_pending = {}@@ -444,6 +447,17 @@ class LayerOffloader:and getattr(weight_source, 'direct_read', False)and getattr(weight_source, 'intermediate_dtype', None) is Noneand self.pinned_staging):+ # Without room for a second block of locked pages, read ahead into+ # the staging buffer every streamed layer already passes through:+ # the next read starts once the current layer's upload completes,+ # while that layer computes. Reading on the inference thread instead+ # waits until it has queued the current layer, and with a full+ # launch queue the GPU then idles through most of the read. With 18+ # of 50 layers reread from the file every step, each read about as+ # long as a layer's compute, 1344x768x362 steps went from 41.1 to+ # 32.0 s at head groups of 2 and from 34.5 to 27.6 s at 4 on an RTX+ # PRO 6000 (latents identical); the second block saves 0.4 s more.+ self.host_slots = [Slot(host=self.slots[0].host, device={})]extra = _pin_reservation([plane.numel() * plane.element_size()for plane in self.slots[0].host.values()])if _host_prefetch_fits(extra):@@ -453,16 +467,15 @@ class LayerOffloader:host[dtype] = torch.empty(count, dtype=dtype, pin_memory=True)except (RuntimeError, MemoryError):host.clear()- self.host_prefetch_disabled_reason = 'host_allocation_refused'+ self.host_prefetch_shared_reason = 'host_allocation_refused'from .torch_compat import empty_host_cacheempty_host_cache(torch)else:- self.host_slots = [Slot(host=self.slots[0].host, device={}), Slot(host=host, device={})]- self.host_executor = ThreadPoolExecutor(max_workers=1,- thread_name_prefix='freevideo-host-stage')- self.host_prefetch = True+ self.host_slots.append(Slot(host=host, device={}))else:- self.host_prefetch_disabled_reason = 'host_headroom'+ self.host_prefetch_shared_reason = 'host_headroom'+ self.host_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='freevideo-host-stage')+ self.host_prefetch = Truefor index, layer in enumerate(self.layers if manage_hooks else []):self.hooks.append(layer.register_forward_pre_hook(lambda module, args, index=index: self._before(index)))@@ -565,18 +578,24 @@ class LayerOffloader:if not self.host_prefetch or self.host_pending:returnnow = time.monotonic()- if now - self.host_memory_checked >= 1.:+ if len(self.host_slots) > 1 and now - self.host_memory_checked >= 1.:self.host_memory_checked = nowif not _host_prefetch_fits(0):- self.host_prefetch_disabled_reason = 'live_host_pressure'- self._stop_host_prefetch()+ # Return only the extra block of locked pages. Reading ahead+ # through the shared staging buffer holds no more memory than+ # reading on demand does.+ self.host_prefetch_shared_reason = 'live_host_pressure'+ extra = self.host_slots.pop()+ if extra.copy_done is not None:+ extra.copy_done.synchronize()+ del extra+ self.host_cursor = 0from .torch_compat import empty_host_cacheempty_host_cache(torch)- returnfor index in range(start, len(self.layers)):if self.pinned_layers[index] or index in self.cached:continue- slot = self.host_slots[self.host_cursor % 2]+ slot = self.host_slots[self.host_cursor % len(self.host_slots)]self.host_cursor += 1self.host_pending[index] = (slot, self.host_executor.submit(self._fill_host, index, slot))self.host_prefetch_reads += 1@@ -612,7 +631,7 @@ class LayerOffloader:host_slot, counts, host_seconds = future.result()self.host_prefetch_wait_seconds += time.monotonic() - tickelse:- host_slot = self.host_slots[self.host_cursor % 2]+ host_slot = self.host_slots[self.host_cursor % len(self.host_slots)]self.host_cursor += 1host_slot, counts, host_seconds = self._fill_host(index, host_slot)elif direct:@@ -727,6 +746,7 @@ class LayerOffloader:'host_prefetch_buffer_bytes': sum(t.numel() * t.element_size()for slot in self.host_slots[1:] for t in slot.host.values()),'host_prefetch_disabled_reason': self.host_prefetch_disabled_reason,+ 'host_prefetch_shared_reason': self.host_prefetch_shared_reason,'disk_read_ahead': self.read_ahead.stats() if self.read_ahead is not None else {'enabled': False},'disk_read_ahead_before_cache': self.read_ahead_before_cache,'timing_note': 'Host staging, buffer waits and H2D may overlap compute. Prefetch wait can include 'diff --git a/freevideo_engine/optimize_worker.py b/freevideo_engine/optimize_worker.pyindex f91622b..de98bd2 100644--- a/freevideo_engine/optimize_worker.py+++ b/freevideo_engine/optimize_worker.py@@ -52,7 +52,10 @@ def configure(engine, base, patch):elif options['ff_chunk'] != base['ff_chunk']:raise ValueError('This bounded search keeps Ampere FF chunking fixed')from .packing import install_streamed_forward- install_streamed_forward(engine.transformer, options['projection_chunk'])+ # The engine keeps its staged blocks, which take the residual stream as a+ # ResidualState; the packing forward must hand them one.+ install_streamed_forward(engine.transformer, options['projection_chunk'],+ residual_offload=bool(engine.config.get('residual_offload')))engine.config.update({name: options[name] for name in PATCH_KEYS})return enginediff --git a/freevideo_engine/package_cleanup.py b/freevideo_engine/package_cleanup.pynew file mode 100644index 0000000..cb8608b--- /dev/null+++ b/freevideo_engine/package_cleanup.py@@ -0,0 +1,349 @@+"""Remove FreeVideo's own copies of model files the installation already holds, verified.++Two kinds of leftovers duplicate an installed model file:++* an offline package's extraction under ``.freevideo-packages``: every imported+ ZIP is unpacked there in full, and the installation then links or copies the+ files it needs;+* download leftovers: a file's staging folder under ``.freevideo-downloads`` and+ the partial copies that a failed download or local import kept beside it.++They go only once the installation holds and has verified what they could+provide: each file recorded in the installation's ledger with its hash, and+unchanged since. A model package qualifies when every file it holds is+installed that way, or when it was imported before the current installation+was set up and is therefore not waiting to be used. An environment package is+never removed: it is the offline installation itself and holds its ComfyUI,+outputs and workflows. The user's own ZIP files are not touched here+(``archives`` reports them, and ``delete_archives`` removes them on request).+Released bytes count only data no other name still links to.+"""+import json+import os+from pathlib import Path+import re+import shutil+import stat+import uuid++from .installation_cleanup import local_path++PACKAGES = '.freevideo-packages'+STAGES = '.freevideo-downloads'+INNER = 'FreeVideo-Windows'+MODELS_MARKER = 'offline-package.json'+# A model package's own inventory: read to assemble the installation, never installed itself.+PACK_INVENTORY = 'models/model-pack.json'+RUNTIME_MARKER = 'runtime.json'+# network.retain_partial and local_models.import_file: <name>[.partial].<reason>-<time_ns>+RETAINED = re.compile(r'(?P<name>.+?)(?:\.partial)?\.(?:hash-rejected|oversized-response|oversized|resume-unavailable|'+ r'restart-approved|rejected|switch-retained|local-import)-\d{6,}')+STAGE = re.compile(r'(?P<sha>[0-9a-f]{16})-[A-Za-z0-9_-]+(?:\.(?:restart-approved|switch-retained|rejected)-\d{6,})?')+++def unique_bytes(path):+ """Bytes that deleting path frees: regular files no other name links to."""+ path, total = Path(path), 0+ entries = [(path.parent, [], [path.name])] if path.is_file() else os.walk(path, followlinks=False)+ for directory, _, files in entries:+ for name in files:+ try:+ info = os.lstat(os.path.join(directory, name))+ except OSError:+ continue+ if stat.S_ISREG(info.st_mode) and info.st_nlink == 1:+ total += info.st_size+ return total+++def runtime_root(engine):+ """The offline installation's root, when this engine belongs to one."""+ root = Path(engine).parent+ return root if (root / 'portable.json').is_file() else None+++def verified_files(engine):+ """sha256 -> installed files recorded with that hash and unchanged since."""+ engine, found = Path(engine), {}++ def add(path, record):+ if not isinstance(record, dict) or not isinstance(record.get('sha256'), str):+ return+ try:+ info = os.stat(path)+ except OSError:+ return+ if not stat.S_ISREG(info.st_mode) or info.st_size != record.get('bytes'):+ return+ if record.get('mtime_ns') is not None and info.st_mtime_ns != record['mtime_ns']:+ return+ if record.get('inode') and info.st_ino != record['inode']:+ return+ found.setdefault(record['sha256'], []).append(Path(path).absolute())++ ledger = engine / 'verified-models.json'+ rows = load(ledger)+ for path, record in (rows.items() if isinstance(rows, dict) else ()):+ add(path, record)+ root = runtime_root(engine)+ if root is not None:+ rows = load(engine / 'portable-verified.json')+ for path, record in (rows.items() if isinstance(rows, dict) else ()):+ if not Path(path).is_absolute() and '..' not in Path(path).parts:+ add(root / path, record)+ return found+++def load(path):+ try:+ return json.loads(Path(path).read_text(encoding='utf-8'))+ except (OSError, ValueError):+ return None+++def installed_at(engine):+ """When the current installation was last set up; packages imported later may be waiting for it."""+ engine, times = Path(engine), []+ for path in (engine / 'machine.json', engine.parent / 'portable.json'):+ try:+ times.append(path.stat().st_mtime)+ except OSError:+ pass+ return max(times) if times else None+++def package_roots(engine, comfy_root=None):+ """Folders an import may have unpacked into: the destination beside the engine, the ComfyUI folder,+ and, for an offline installation, the destination holding its own package folder."""+ engine = Path(engine).absolute()+ roots = [engine.parent]+ if comfy_root:+ roots += [Path(comfy_root).absolute(), Path(comfy_root).absolute().parent]+ roots += [parent.parent for parent in engine.parents if parent.name == PACKAGES]+ found = []+ for root in roots:+ folder = root / PACKAGES+ if folder.is_dir() and folder not in found:+ found.append(folder)+ return found+++def inside(path, folder):+ try:+ Path(path).absolute().relative_to(Path(folder).absolute())+ return True+ except ValueError:+ return False+++def discard(path, root, running=None, dry_run=False):+ """Rename, then delete; returns the bytes freed, or None when the path was kept.++ A dry run applies every check and reports what would be freed, deleting nothing.+ """+ from .version_cleanup import started_from, plain_tree+ path, root = Path(path), Path(root)+ if not local_path(root, path) or started_from(path, running) or (path.is_dir() and not plain_tree(path)):+ return None+ freed = unique_bytes(path)+ if dry_run:+ return freed+ retired = path.with_name(path.name + '.retired-' + uuid.uuid4().hex[:8])+ try:+ os.rename(path, retired)+ except OSError:+ return None+ if retired.is_dir():+ shutil.rmtree(retired, ignore_errors=True)+ else:+ try:+ retired.unlink()+ except OSError:+ pass+ return freed if not retired.exists() else max(0, freed - unique_bytes(retired))+++def packages(folder):+ for pack in sorted(Path(folder).iterdir()) if Path(folder).is_dir() else ():+ if not pack.is_dir() or '.retired-' in pack.name:+ continue+ inner = pack / INNER+ if (inner / RUNTIME_MARKER).is_file() or (inner / 'portable.json').is_file():+ yield pack, 'runtime', None+ else:+ value = load(inner / MODELS_MARKER)+ yield pack, 'models', value if isinstance(value, dict) else None+++def prune_packages(engine, comfy_root=None, index=None, running=None, dry_run=False):+ """Model package extractions the installation no longer needs."""+ result = dict(released_bytes=0, removed=[], kept=[])+ index = verified_files(engine) if index is None else index+ installed = installed_at(engine)+ holders = [path for paths in index.values() for path in paths]+ for folder in package_roots(engine, comfy_root):+ for pack, kind, value in packages(folder):+ if kind == 'runtime' or inside(engine, pack):+ result['kept'].append(dict(kind='offline-package', path=str(pack), reason='environment package'))+ continue+ if any(inside(path, pack) for path in holders):+ result['kept'].append(dict(kind='offline-package', path=str(pack), reason='installed files live here'))+ continue+ rows = [row for row in (value or {}).get('files', [])+ if isinstance(row, dict) and row.get('path') != PACK_INVENTORY+ and (pack / INNER / str(row.get('path', ''))).is_file()]+ covered = bool(rows) and all(row.get('sha256') in index for row in rows)+ try:+ stale = installed is not None and max((pack / INNER).stat().st_mtime, pack.stat().st_mtime) < installed+ except OSError:+ stale = installed is not None+ if not covered and not stale:+ result['kept'].append(dict(kind='offline-package', path=str(pack), reason='imported after this installation'))+ continue+ freed = discard(pack, folder, running, dry_run)+ if freed is None:+ result['kept'].append(dict(kind='offline-package', path=str(pack), reason='in use'))+ continue+ result['released_bytes'] += freed+ result['removed'].append(dict(kind='offline-package', path=str(pack), bytes=freed,+ reason='installed and verified' if covered else 'not used by this installation'))+ return result+++def prune_downloads(engine, index=None, running=None, dry_run=False):+ """Staging folders and kept partial copies of model files that are installed and verified."""+ result = dict(released_bytes=0, removed=[], kept=[])+ index = verified_files(engine) if index is None else index+ engine = Path(engine).absolute()+ top = runtime_root(engine) or engine+ prefixes = {sha[:16] for sha in index}+ stages, siblings = set(), {}+ for sha, paths in index.items():+ for path in paths:+ siblings.setdefault(path.parent, set()).add(path.name)+ for parent in path.parents:+ if not inside(parent, top):+ break+ if (parent / STAGES).is_dir():+ stages.add(parent / STAGES)+ for folder in sorted(stages):+ for stage in sorted(folder.iterdir()):+ match = STAGE.fullmatch(stage.name)+ if not match or match['sha'] not in prefixes:+ continue+ freed = discard(stage, folder, running, dry_run)+ if freed is None:+ result['kept'].append(dict(kind='download-leftover', path=str(stage), reason='in use'))+ else:+ result['released_bytes'] += freed+ result['removed'].append(dict(kind='download-leftover', path=str(stage), bytes=freed))+ for directory, names in siblings.items():+ try:+ entries = sorted(directory.iterdir())+ except OSError:+ continue+ for entry in entries:+ match = RETAINED.fullmatch(entry.name)+ if not match or match['name'] not in names:+ continue+ freed = discard(entry, directory, running, dry_run)+ if freed is None:+ result['kept'].append(dict(kind='download-leftover', path=str(entry), reason='in use'))+ else:+ result['released_bytes'] += freed+ result['removed'].append(dict(kind='download-leftover', path=str(entry), bytes=freed))+ return result+++def copied_models(engine):+ """Model files imported from a library the installation could not link to, as (bytes, files)."""+ rows = load(Path(engine) / 'verified-models.json')+ copied = [record for record in (rows.values() if isinstance(rows, dict) else ())+ if isinstance(record, dict) and record.get('method') == 'verified_local_copy']+ return sum(int(record.get('bytes') or 0) for record in copied), len(copied)+++def copy_reason(engine):+ """Why imports were copied: 'exfat' when the installation's own disk cannot hold links, else 'other-disk'."""+ from .local_models import volume_filesystem+ filesystem = volume_filesystem(engine)+ return 'exfat' if filesystem and filesystem != 'NTFS' else 'other-disk'+++def run(engine, comfy_root=None, running=None, dry_run=False):+ index = verified_files(engine)+ result = dict(released_bytes=0, removed=[], kept=[], dry_run=dry_run)+ for part in (prune_packages(engine, comfy_root, index, running, dry_run),+ prune_downloads(engine, index, running, dry_run)):+ result['released_bytes'] += part['released_bytes']+ result['removed'] += part['removed']+ result['kept'] += part['kept']+ result['copied_model_bytes'], result['copied_model_files'] = copied_models(engine)+ result['copied_model_reason'] = copy_reason(engine) if result['copied_model_bytes'] else None+ return result+++OPTIONAL_PREFIX = 'models/base/sampling-cache/'+++def archive_unchanged(record):+ try:+ info = os.stat(record['path'])+ except (OSError, KeyError, TypeError):+ return False+ return stat.S_ISREG(info.st_mode) and info.st_size == record.get('bytes') and info.st_mtime_ns == record.get('mtime_ns')+++def archive_rows(record):+ """The files a recorded ZIP provides: from its extraction, or else from the ZIP's own record."""+ value = load(Path(record['root']) / MODELS_MARKER)+ if not isinstance(value, dict):+ try:+ from .offline_packages import inspect_archive+ value = inspect_archive(record['path'])+ except Exception: # A ZIP that cannot be read is never offered.+ return None+ return [row for row in value.get('files', []) if isinstance(row, dict) and row.get('path') != PACK_INVENTORY]+++def archives(records, engine, index=None):+ """The recorded ZIPs whose contents this installation holds, verified: dict(bytes, paths)."""+ index = verified_files(engine) if index is None else index+ runtime = runtime_root(engine)+ paths, total = [], 0+ for record in records:+ if not archive_unchanged(record):+ continue+ if record.get('kind') == 'runtime':+ # The environment package was unpacked into this very installation.+ held = runtime is not None and Path(record['root']).resolve() == runtime.resolve()+ else:+ rows = archive_rows(record)++ def installed(row):+ if row.get('sha256') in index:+ return True+ # Optional sampling tables an offline installation placed itself: present at full size.+ placed = runtime / str(row.get('path', '')) if runtime is not None else None+ return (placed is not None and str(row.get('path', '')).startswith(OPTIONAL_PREFIX)+ and placed.is_file() and placed.stat().st_size == row.get('bytes'))+ held = bool(rows) and all(installed(row) for row in rows)+ if held:+ paths.append(record['path'])+ total += record['bytes']+ return dict(bytes=total, paths=paths)+++def delete_archives(records, engine):+ """Delete the user's imported ZIPs this installation holds; returns (bytes freed, paths removed)."""+ offer = archives(records, engine)+ freed, removed = 0, []+ for path in offer['paths']:+ try:+ info = os.lstat(path)+ os.unlink(path)+ except OSError:+ continue # In use or read-only: kept, offered again next time.+ removed.append(path)+ freed += info.st_size if info.st_nlink == 1 else 0+ return freed, removeddiff --git a/freevideo_engine/policy.py b/freevideo_engine/policy.pyindex 441d1c9..6190b44 100644--- a/freevideo_engine/policy.py+++ b/freevideo_engine/policy.py@@ -98,6 +98,41 @@ SMALL_ACTIVATION_RESERVES = ((8, int(8.2 * GiB)), (4, int(7.6 * GiB)))# allocator retry and no sample over the local budget.WINDOWS_SMALL_HEAD8_TOKENS = 18144 + 4 * 1008WINDOWS_SMALL_HEAD8_FRAMES = 243+# Int8 without LoRA reaches full resolution at the same frame count. With the+# Windows allocator (no expandable segments; its four-head workspace measured+# 6.15 GiB against 6.18 natively on Windows at the same placement),+# 1344x768x243 with two resident blocks over 16 steps:+#+# head 4 17.59 s/step 6.96 GiB reserved+# head 4, second slot 16.84 7.38+# head 8 15.33 8.11+# head 8, second slot 14.97 8.53+#+# Eight heads hold 1.15 GiB more than four at this length, not the 0.34 the+# token table gives, so the group is charged that much over the four-head+# reserve, in proportion to the rows, and residency pays for it. The second+# transfer slot is one block of the same weights and takes one resident+# block's place. Blocks buy under 1%; both changes together take 16% off the+# step at the four-head footprint. At an 8 GiB laptop's 6.65 GiB budget,+# 960x544x243 went from head 4 with one block (10.37 s/step, 4.68 GiB) to+# head 8 with none (8.43 s, 4.18 GiB).+WINDOWS_INT8_HEAD8_TOKENS = 72576+WINDOWS_INT8_HEAD8_EXTRA = int(1.15 * GiB)+# Below that band an 8 GiB card stages the residual stream, and the staged+# pass kept four heads. With the Windows allocator (no expandable segments)+# capped at an 8 GiB laptop's 6.65 GiB budget, 1344x768x243 staged with its+# outputs on the GPU and no resident block, steps 2-8 of two alternating pairs:+#+# head 4 144.2-146.5 s 4.16 GiB allocated 4.32 reserved+# head 8 129.3-131.5 5.10 5.35+#+# and 78624 rows peaked at 5.79 GiB reserved with eight. Natively on Windows,+# an RTX 5060 Ti held to that budget took 78.75 s per second-pass step with+# eight heads against 81.8 with four, at 5.95 GB reserved. Eight heads are+# charged the same extra over the Windows staged measurement and its margin,+# not over the lower FP8-derived estimate, which leaves about 0.5 GiB over+# both peaks. Ampere has no Windows measurement with eight heads and keeps four.+WINDOWS_INT8_STAGED_HEAD8_TOKENS = 72576 + 4 * 1008# Keeping the attention outputs on the GPU instead of in host memory costs this# much extra peak. See benchmarks/2026-09-15-consumer-capacity-grid.json. Measured at four corners of the band that uses the host# buffer: 0.15 GiB at 8 GiB/1344x768x243, 0.23 at 8 GiB/1024x1024x243, 0.22 at@@ -157,27 +192,28 @@ RESIDENT_VRAM_CEILING = 44PREFETCH_GPU_BUDGET = int(13.5 * GiB)-def prefetch_for_budget(gpu_budget, *, ram_budget=None, twelve=False, ampere=False,- system='Linux', architecture=None):+def prefetch_for_budget(gpu_budget, *, twelve=False, ampere=False, system='Linux'):"""Whether a second weight transfer slot fits the selected GPU budget.- Native Windows Blackwell also benefits at 13.5--14 GiB with partial host- retention. Residency below includes the second device slot in its complete- token-scaled workspace; this never spends an unaccounted extra block.+ Windows also takes it at 13.5--14 GiB. Residency below includes the second+ device slot in its complete token-scaled workspace; this never spends an+ unaccounted extra block."""# This extra lower-16-GiB rule was measured on Windows WDDM. Linux has# different page-cache and allocator behaviour, so do not silently apply# a Windows-only transfer overlap threshold there. The established# high-capacity and Ampere paths below remain cross-platform.- low_host = (system == 'Windows' and ram_budget is not None- and ram_budget < 8 * GiB)- # Preserve the established high-capacity path. The new lower-band rule- # is an additional case for the 16 GiB tier; it must not turn prefetch off- # for the already-validated 20/24/32 GiB profiles.+ #+ # The band was first opened for low-RAM hosts and then for the Windows+ # Blackwell card it was measured on. Nothing in it depends on either: the+ # slot is one block of the same weights, charged to the same workspace,+ # and every architecture takes it from 14 GiB, so a 16 GB card whose+ # desktop held 0.2 GiB more lost it. Without the slot each streamed layer+ # is copied between two layers' compute, adding its transfer to the step.+ # The checks in choose() still give the slot up before it displaces a+ # layer the host would otherwise retain or the workspace itself.return (gpu_budget >= 14 * GiB- or (gpu_budget >= PREFETCH_GPU_BUDGET and low_host)- or (gpu_budget >= PREFETCH_GPU_BUDGET and system == 'Windows'- and architecture == 'blackwell-rtx')+ or (gpu_budget >= PREFETCH_GPU_BUDGET and system == 'Windows')or (twelve and ampere))# The transformer's attention heads; a group this wide is unchunked.@@ -232,6 +268,11 @@ ACTIVATION_BY_TOKENS = {}+# Windows takes groups wider than sixteen only up to this many rows: the+# largest token count at which they were measured there (see choose()).+WINDOWS_WIDE_GROUP_TOKENS = 18144++def activation_bytes(head, tokens):"""Measured GPU bytes a head group needs beside the resident blocks.@@ -785,9 +826,7 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',# which made residency drop as the budget grew: three blocks at 10.1 GiB# against one at 10.3 GiB.twelve = not small and gpu_budget < 14 * GiB- prefetch = prefetch_for_budget(gpu_budget, ram_budget=ram_budget,- twelve=twelve, ampere=ampere,- system=hardware.system, architecture=hardware.architecture)+ prefetch = prefetch_for_budget(gpu_budget, twelve=twelve, ampere=ampere, system=hardware.system)# The larger head group is worth about 10% at no extra peak at all. Paying# for its wider activation allowance out of residency, measured on an H200# at 1344x768x243 with the card as the ceiling:@@ -851,11 +890,38 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',+ activation_bytes(head, effective_tokens)- activation_bytes(8, effective_tokens)) > gpu_budget:head //= 2+ def held(group):+ workspace = (windows_gpu_output_workspace(effective_tokens, prefetch=prefetch, ff_stash=not int8)+ + activation_bytes(group, effective_tokens) - activation_bytes(8, effective_tokens))+ return max(0, min(RESIDENT_VRAM_CEILING, int((gpu_budget - workspace) / block_bytes)))+ # Groups wider than sixteen where the head-8 workspace, the wider+ # group's surcharge and the blocks the card holds anyway all fit:+ # in practice a two-pass request's first pass, whose spare memory+ # otherwise only caches layers that the second transfer slot+ # already hides. Same rule as the Linux branch below, against the+ # larger Windows workspace: keep the eight blocks every larger card+ # keeps, or more where RAM cannot take the rest, so a wider group+ # never moves weights to disk. Measured under Windows on an RTX 5060+ # Ti 16 GB, int8, 1344x768x243 two-pass with a 13.77 GiB budget, two+ # runs each: the first pass (18144 tokens) took 28 heads at 13.29+ # s/step against 13.60 with sixteen, peaking 12.57-12.96 GiB against+ # 12.50-12.79 as the pass cache gave up two or three layers; the+ # second pass was unchanged. All 56, forced, ran 13.09 at a 12.87+ # GiB peak; the workspace estimate keeps it to 28 there.+ #+ # RAM here is the request's budget, the figure the eight-head check+ # below uses, not the remembered peak: with a history credit the two+ # disagreed, and a group this rule took was then sent to eight,+ # below the sixteen allowed before. Only up to the token count+ # measured on Windows; a group's requirement at a given token count+ # does not depend on the card, so the bound is in tokens, not in+ # budget.+ if (int8 and not lora and head == 16 and effective_tokens is not None+ and effective_tokens <= WINDOWS_WIDE_GROUP_TOKENS):+ keep = max(RESIDENT_TARGET, 50 - max(0, int((ram_budget - 2.5 * GiB) // block_bytes)))+ head = next((group for group in (ALL_HEADS, 28)+ if held(group) >= max(RESIDENT_TARGET, min(keep, held(16)))), 16)if widened and head > 8:- def held(group):- workspace = (windows_gpu_output_workspace(effective_tokens, prefetch=prefetch, ff_stash=not int8)- + activation_bytes(group, effective_tokens) - activation_bytes(8, effective_tokens))- return max(0, min(RESIDENT_VRAM_CEILING, int((gpu_budget - workspace) / block_bytes)))if ((50 - held(head)) * block_bytes + int(2.5 * GiB) > ram_budget>= (50 - held(8)) * block_bytes + int(2.5 * GiB)):head = 8@@ -887,6 +953,20 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',and effective_tokens is not Noneand canvas['frames'] <= WINDOWS_SMALL_HEAD8_FRAMESand effective_tokens <= WINDOWS_SMALL_HEAD8_TOKENS)+ windows_int8_full = (desktop and int8 and not lora and legs == ['sage2', 'sage2']+ and effective_tokens is not None+ and canvas['frames'] <= WINDOWS_SMALL_HEAD8_FRAMES+ and WINDOWS_SMALL_HEAD8_TOKENS < effective_tokens <= WINDOWS_INT8_HEAD8_TOKENS)+ windows_int8_staged_head8 = (desktop and int8 and not lora and legs == ['sage2', 'sage2']+ and hardware.architecture != 'ampere'+ and effective_tokens is not None+ and canvas['frames'] <= WINDOWS_SMALL_HEAD8_FRAMES+ and effective_tokens <= WINDOWS_INT8_STAGED_HEAD8_TOKENS)+ reserves = SMALL_ACTIVATION_RESERVES+ if windows_int8_full:+ four = dict(SMALL_ACTIVATION_RESERVES)[4]+ extra = int(WINDOWS_INT8_HEAD8_EXTRA * effective_tokens / WINDOWS_INT8_HEAD8_TOKENS)+ reserves = tuple((heads, max(need, four + extra) if heads == 8 else need) for heads, need in reserves)if not desktop and head >= 8:# The measured requirement for the group this request can afford,# already scaled by its token count, so the band's own reference@@ -898,8 +978,8 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',# slower.selected = (head, activation_bytes(head, effective_tokens) - GPU_ATTENTION_OUTPUT_BYTES)else:- available = [(heads, need) for heads, need in SMALL_ACTIVATION_RESERVES- if heads <= 4 or not desktop or (windows_small_head8+ available = [(heads, need) for heads, need in reserves+ if heads <= 4 or not desktop or ((windows_small_head8 or windows_int8_full)and gpu_budget >= need + small_adjustment + GPU_ATTENTION_OUTPUT_BYTES)]selected = next(((heads, need + small_adjustment) for heads, need in availableif gpu_budget >= need + small_adjustment), None)@@ -1035,6 +1115,15 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',cpu_outputs = gpu_budget < needif not cpu_outputs:reserve = max(reserve, need)+ if windows_int8_staged_head8 and head == 4:+ # Charged over the Windows measurement itself, not the+ # lower FP8-derived estimate kept below its first token+ # count. Never with the outputs in host memory: eight+ # heads there measured eight times slower.+ wider = (max(reserve, int8_gpu_output_need(effective_tokens, windows=True))+ + int(WINDOWS_INT8_HEAD8_EXTRA * effective_tokens / WINDOWS_INT8_HEAD8_TOKENS))+ if gpu_budget >= wider:+ head, reserve = 8, widerelse:cpu_outputs = not no_weights and gpu_budget < reserve + GPU_ATTENTION_OUTPUT_BYTESif not cpu_outputs:@@ -1065,6 +1154,9 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',# after two allocator retries; 1344x768x243 without blocks, 3.88 and# 4.52 with none. Every 0.3.2 Windows staging plan held no blocks.resident = 0+ if windows_int8_full and not residual_offload and not prefetch and resident >= 1:+ # The second transfer slot in place of one resident block.+ prefetch, resident = True, resident - 1pinned_like = Noneif not small:# One measured requirement for the group in use, so the block count is@@ -1103,8 +1195,7 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',# Budget the current execution path before host placement is planned.windows_workspace = windows_gpu_output_workspace(effective_tokens, prefetch=prefetch, ff_stash=not int8)windows_workspace += max(0, activation_bytes(head, effective_tokens) - activation_bytes(8, effective_tokens))- if (prefetch and gpu_budget < 14 * GiB- and hardware.architecture == 'blackwell-rtx'):+ if prefetch and gpu_budget < 14 * GiB:# Saving a transfer slot must not turn fully retained host weights# into per-step disk reads. Compare both placements, including the# full FF workspace, before spending that slot.diff --git a/freevideo_engine/processes.py b/freevideo_engine/processes.pyindex 8c0f87e..e3675fb 100644--- a/freevideo_engine/processes.py+++ b/freevideo_engine/processes.py@@ -35,6 +35,9 @@ def descriptors():def module_command(module, *arguments):"""Also works with portable Windows Python, whose ._pth ignores PYTHONPATH."""+ if getattr(sys, 'frozen', False) and sys.platform.startswith('linux'):+ # The Linux launcher (AppImage) runs its own helpers; see modern_launcher.main.+ return [sys.executable, '--freevideo-module', module, *map(str, arguments)]code = ("import runpy,sys;sys.path.insert(0,sys.argv.pop(1));""runpy.run_module(sys.argv.pop(1),run_name='__main__',alter_sys=True)")return [sys.executable, '-B', '-X', 'utf8', '-c', code,diff --git a/freevideo_engine/prompt_vlm/assets.py b/freevideo_engine/prompt_vlm/assets.pyindex 1395016..0c7c60e 100644--- a/freevideo_engine/prompt_vlm/assets.py+++ b/freevideo_engine/prompt_vlm/assets.py@@ -2,6 +2,7 @@import jsonfrom pathlib import Pathimport shutil+from .. import disk_spacedef catalog():@@ -48,7 +49,7 @@ def install(root, progress, check):size = partial.stat().st_sizeif size < row['bytes']:retained += size- if shutil.disk_usage(folder).free < total - retained + 256 * 2**20:+ if disk_space.free_bytes(folder) < total - retained + 256 * 2**20:raise ValueError('disk_space')plan = _download_plan(root)# This catalog has no verified ModelScope mirror yet. Preserve configureddiff --git a/freevideo_engine/prompt_vlm/rules.py b/freevideo_engine/prompt_vlm/rules.pyindex d29f594..ffb8d86 100644--- a/freevideo_engine/prompt_vlm/rules.py+++ b/freevideo_engine/prompt_vlm/rules.py@@ -44,10 +44,16 @@ def instruction(value):actions and camera movement exactly. Image references describe appearance, not whether anobject moves. Keep dialogue, lyrics and visible writing verbatim in their original language.Add concrete motion, framing, lighting and sounds without changing the intended scene.-Do not invent dialogue, captions or music. Return only the sections listed below as plain-headings followed by colons. No preface, commentary, markdown fences or JSON.+Do not invent dialogue, captions or music. Return only the sections listed below, each starting+on its own line with its heading and a colon, separated by one blank line. No preface,+commentary, markdown fences or JSON.Use [Shot 1] for the opening; if the user wants cuts, add [Shot 2] At MM:SS.mmm, etc.-Keep unbroken shots unbroken. Literal dialogue uses (S1) <d>[Language] speech</d>.+Keep unbroken shots unbroken.+Spoken words never go in quotation marks (quotes mean text visible on screen). Write each spoken+line as a speaker ID, then the exact words with their punctuation inside <d>[Language] ...</d>,+untranslated; each speaker keeps one ID and different speakers get different IDs, e.g.+The young woman (S1) says softly: <d>[Chinese] 再见了。</d> The man (S2) replies: <d>[English] Wait.</d>+Dialogue belongs only in the first section, not in the sound sections."""if value['mode'] == 'ref2va':rule += """subject_definitions: Name each visible subject literally <Subject 1>, <Subject 2>, etc.,@@ -72,14 +78,28 @@ Use only supplied media labels; do not invent audio or video references.+ ', '.join(fields) + f'. Begin with "{fields[0]}:".')+def sections(text, fields):+ """Each expected heading on its own paragraph, as H3 expects.++ The model sometimes runs every section into one line ("... overall_soundscape: N/A+ non_diegetic_music: N/A"), mostly when pictures are attached; only the expected+ heading names are split out, so prose is never cut.+ """+ names = '|'.join(fields)+ text = re.sub(r'(?m)^(?:#{1,3} +)?\*{0,2}(%s)\*{0,2}:\*{0,2}' % names, r'\1:', text)+ text = re.sub(r'(?<=\S)[ \t]+(%s):' % '|'.join(fields[1:]), r'\n\n\1:', text)+ text = re.sub(r'[ \t]+\n', '\n', text)+ return re.sub(r'\n+(?=(?:%s):)' % names, '\n\n', text).strip()++def validate_output(text, value):if not isinstance(text, str) or not 100 <= len(text.strip()) <= 20000:raise ValueError('invalid_output')text = text.strip()if text.startswith('```') and text.endswith('```'):text = '\n'.join(text.splitlines()[1:-1]).strip()- text = re.sub(r'(?m)^#{1,3} +([a-z_]+):', r'\1:', text)fields = REF_FIELDS if value['mode'] == 'ref2va' else BASE_FIELDS+ text = sections(text, fields)found = re.findall(r'(?m)^([a-z_]+):', text)if found != list(fields) or not text.startswith(fields[0] + ':'):raise ValueError('invalid_output')@@ -103,4 +123,170 @@ def validate_output(text, value):for i in range(1, len(value['media']) + 1):if f'<Picture {i}>' not in text:raise ValueError('invalid_output')+ return dialogue(text, value['text'])+++# Spoken lines -------------------------------------------------------------------------------------------+# H3 reads double-quoted text as writing visible on screen; speech must be (S1) <d>[Language] ...</d>.+QUOTES = {'\u201c': '\u201d', '\u300c': '\u300d', '\u300e': '\u300f', '"': '"', '\uff02': '\uff02'}+QUOTED = re.compile('|'.join('%s([^%s\n]{1,400})%s' % (re.escape(a), re.escape(b), re.escape(b))+ for a, b in QUOTES.items()))+# Verbs that end the words right before a spoken quote. Bare 叫/道/喝 also mean "named",+# "road" or "drink", so only their speech compounds count; the strong verbs may be followed+# by a few characters (说了一句:).+CJK_SPEECH = ('说道', '喊道', '叫道', '问道', '答道', '笑道', '叹道', '骂道', '吼道', '念道', '喝道', '唤道', '回道',+ '大叫', '尖叫', '叫喊', '吆喝', '呼喊', '惊呼', '高呼', '呼唤', '念叨', '嘀咕', '嘟囔', '低语', '耳语',+ '回应', '回复', '告诉', '宣布', '感叹', '自语', '叮嘱', '嘱咐', '曰',+ '言う', '言っ', '叫ぶ', '叫ん', '囁', 'つぶや', '呟', '答え', '尋ね', '歌う', '話す',+ '말하', '외치', '묻', '대답', '속삭')+CJK_STRONG = ('说', '喊', '问', '答', '吼', '嚷', '唱', '讲', '骂')+EN_SPEECH = re.compile(r"\b(?:says?|said|saying|asks?|asked|asking|repl(?:y|ies|ied|ying)|answers?|answered|"+ r"shouts?|shouted|shouting|yells?|yelled|yelling|whispers?|whispered|whispering|"+ r"calls? out|called out|cries|cried|crying out|screams?|screamed|mutters?|"+ r"muttered|murmurs?|murmured|adds?|added|exclaims?|exclaimed|sings?|sang|singing|"+ r"tells?|told|announces?|announced|begs?|begged|pleads?|pleaded|laughs?|sighs?|sighed|"+ r"speaks?|spoke|speaking|goes)\b[^\n.!?]{0,24}$", re.I)+NOUNS = (r'写着|写有|写的|印着|刻着|标着|显示|字样|字幕|招牌|牌子|标语|横幅|海报|屏幕|标题|文字|书名|名叫|叫做|叫作|'+ r'名为|名字|称为|号称|看板|書かれ|表示|간판|\bsigns?|\bbanners?|\bcaptions?|\btitles?|\bposters?|'+ r'\bscreens?|\blabels?|\bboards?|\bneon|\btext|\bplacards?|\bgraffiti|\bheadlines?|\bsubtitles?|'+ r'\blettering|\bnamed|\bcalled|\btitled|\bnicknamed|\bbrand\w*|\breads?|\breading|\bwritten|'+ r'\bprinted|\bpainted|\bspelled')+# Writing, not speech: a sign "OPEN", 写着“老街馄饨”, a sign that says "OPEN", a shop called "Kiko".+WRITING = re.compile(NOUNS, re.I)+SIGN_SAYS = re.compile(r'(?:%s)\w*\s+(?:that\s+|which\s+)?(?:says|said|reads|shows|displays)$' % NOUNS, re.I)+++def language(words):+ if re.search('[\u3040-\u30ff]', words):+ return 'Japanese'+ if re.search('[\uac00-\ud7af]', words):+ return 'Korean'+ if re.search('[\u4e00-\u9fff]', words):+ return 'Chinese'+ if re.search('[\u0400-\u04ff]', words):+ return 'Russian'+ return 'English'+++def plain(words):+ """Comparable form: no tags, speaker IDs, quotes, punctuation, spacing or case."""+ words = re.sub(r'<[^>]{1,24}>|\(S\d+(?:,S\d+)*\)|\[[A-Za-z]+\]', '', words)+ return re.sub(r'[\W_]+', '', words).lower()+++def spoken_lines(scene):+ """Quoted spans the user introduced as speech (not signs or captions), in order."""+ lines = []+ for match in QUOTED.finditer(scene):+ words = next(group for group in match.groups() if group is not None).strip()+ before = scene[max(0, match.start() - 40):match.start()]+ after = scene[match.end():match.end() + 12]+ if not plain(words):+ continue+ lead = before.rstrip(' ::,,\u3000')+ if SIGN_SAYS.search(lead):+ continue+ writing = max((m.end() for m in WRITING.finditer(lead)), default=-1)+ cues = [len(lead) for verb in CJK_SPEECH if lead.endswith(verb)]+ cues += [lead.rfind(verb) + len(verb) for verb in CJK_STRONG if verb in lead[-6:]]+ cues += [m.start() + 1 for m in EN_SPEECH.finditer(lead)]+ if cues:+ # Whichever cue is nearer the quote decides: 招牌亮着,老板说:“…” is speech.+ speech = max(cues) > writing+ else:+ speech = (writing < 0 or writing < len(lead) - 8) and bool(+ re.match(r'[\s,,。.!?!?]*(?:と|って)?\s*(?:[^\s,,。.!?!?]{0,6}?)(?:%s)'+ % '|'.join(CJK_SPEECH + CJK_STRONG), after)+ or re.match(r'[\s,]*(?:\w+\s+){0,3}(?:says|said|asks|asked|replies|replied|shouts|shouted|'+ r'whispers|whispered|calls|called|cries|cried)\b', after, re.I))+ if speech:+ lines.append(words)+ return lines+++def dialogue(text, scene):+ """Turn the user's spoken lines that came back quoted into H3 dialogue, verbatim.++ Matching is by words only, so a changed full stop or added <en> tag still matches;+ the user's own words and punctuation are restored. On-screen text stays quoted.+ """+ lines = spoken_lines(scene) if isinstance(scene, str) else []+ by_words = {plain(line): line for line in lines}+ single = len(set(by_words)) == 1+ def tag(match):+ body = match.group(1).strip()+ return '<d>[%s] %s</d>' % (language(body), body)+ # <d>speech</d> without a language, or <en>speech</en>-style tags.+ text = re.sub(r'<d>(?!\s*\[)\s*([^<\n]{1,400}?)\s*</d>', tag, text)+ text = re.sub(r'<(?:en|zh|ja|ko|cn)>\s*([^<\n]{1,400}?)\s*</(?:en|zh|ja|ko|cn)>', tag, text)+ if not by_words:+ return text+ # Speech belongs in the description; the sound sections (last in every mode) only summarise.+ found = re.search(r'(?m)^overall_soundscape:', text)+ body_end = found.start() if found else len(text)+ def match_line(words):+ key = plain(words)+ if key in by_words:+ return by_words[key]+ for other, line in by_words.items():+ if len(key) >= 2 and (key in other or other in key) and min(len(key), len(other)) >= .8 * max(+ len(key), len(other)):+ return line+ return None+ pieces, position = [], 0+ for match in QUOTED.finditer(text):+ words = next(group for group in match.groups() if group is not None)+ line = match_line(words)+ if line is None:+ continue+ pieces.append(text[position:match.start()])+ if match.start() >= body_end:+ # Sound sections only summarise; keep the words without on-screen quotes.+ pieces.append(line)+ else:+ lead = ''.join(pieces)[-24:]+ speaker = '' if re.search(r'\(S\d+(?:,S\d+)*\)[^()<]{0,16}$', lead) else '(S1) ' if single else ''+ replacement = '%s<d>[%s] %s</d>' % (speaker, language(line), line)+ gloss = re.match(r'\s*\([A-Za-z][^()\n]{0,80}\)', text[match.end():])+ if gloss and language(line) != 'English':+ # A translation gloss after the line would be read as more speech.+ pieces.append(replacement)+ position = match.end() + gloss.end()+ continue+ pieces.append(replacement)+ position = match.end()+ pieces.append(text[position:])+ text = ''.join(pieces)+ if len(by_words) == 1 and not re.search(r'\(S\d+', text):+ # One speaker in the scene: give the line its stable ID.+ text = re.sub(r'(?<!\) )<d>\[', '(S1) <d>[', text)+ missing = missing_lines(text, scene)+ if missing:+ # Last resort after the worker's retry: never drop the user's dialogue silently.+ ids = [int(n) for n in re.findall(r'\(S(\d+)', text)]+ speaker = 'S%d' % (max(ids) + 1 if ids else 1)+ said = ' '.join('The speaker (%s) says: <d>[%s] %s</d>' % (speaker, language(line), line) for line in missing)+ found = re.search(r'(?m)^overall_soundscape:', text)+ end = found.start() if found else len(text)+ text = text[:end].rstrip() + ' ' + said + ('\n\n' + text[end:] if end < len(text) else '')+ return text+++def missing_lines(text, scene):+ """The user's spoken lines that the rewrite does not contain at all."""+ have = plain(text)+ return [line for line in dict.fromkeys(spoken_lines(scene)) if plain(line) not in have]+++DIALOGUE_RETRY = ('Your rewrite left out these spoken lines. Rewrite the whole prompt again in the same format and '+ 'include each line once, verbatim, at the moment it is spoken, as (S1) <d>[Language] ...</d>:\n')+++def user_text(value):+ """The user's scene, plus the spoken lines the rewrite must keep verbatim."""+ text = f'User scene to rewrite (preserve every requested action):\n{value["text"]}'+ lines = spoken_lines(value['text'])+ if lines:+ text += '\n\nSpoken lines to keep verbatim inside <d>[Language] ...</d>:\n' + '\n'.join(+ '- [%s] %s' % (language(line), line) for line in lines)return textdiff --git a/freevideo_engine/prompt_vlm/service.py b/freevideo_engine/prompt_vlm/service.pyindex e95c1e7..2652670 100644--- a/freevideo_engine/prompt_vlm/service.py+++ b/freevideo_engine/prompt_vlm/service.py@@ -167,7 +167,11 @@ class Service:if owner.process is not None and owner.process.poll() is None and owner.endpoint:env[resident_process.ENV] = str(owner.endpoint)if env.get(resident_process.ENV) and Path(env[resident_process.ENV]).is_file():- resident_process.release_idle_cache(env, descriptor)+ try:+ resident_process.release_idle_cache(env, descriptor)+ except resident_process.SessionRestarted:+ pass # That worker already exited, which is the release we need.+ env.pop(resident_process.ENV, None)command = processes.module_command('freevideo_engine.prompt_vlm.worker', assets.directory(root))command[0] = machine['comfy_python']child = processes.popen(command, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,diff --git a/freevideo_engine/prompt_vlm/worker.py b/freevideo_engine/prompt_vlm/worker.pyindex 862033d..9252a51 100644--- a/freevideo_engine/prompt_vlm/worker.py+++ b/freevideo_engine/prompt_vlm/worker.py@@ -1,4 +1,4 @@-"""One rewrite per process: model, CUDA context and private commit die together."""+"""One rewrite job per process: model, CUDA context and private commit die together."""import jsonimport osfrom pathlib import Path@@ -32,7 +32,7 @@ def gpu_snapshot(stats):stats['gpu_sample_unavailable'] = True-def failure(error):+def failure(error, mode='rewrite'):"""Keep stack locations and typed causes, never arbitrary exception text.Tokenizers may quote only a fragment of either draft: replacing the full@@ -46,57 +46,51 @@ def failure(error):return dict(error=code, exception=type(error).__name__, error_details=frames)-def run(folder, value, *, stats=None):- stats = {} if stats is None else stats+def begin(stats):+ """Imports and the RAM check shared by every mode; returns checkpoint()."""started = time.monotonic()- stats.update(stage='imports', pid=os.getpid(), image_count=len(value['media']),- mode=value['mode'], dtype='bfloat16', attention='sdpa', kv_cache='dynamic',- backend='transformers', accelerations=[],- persistent_model=False)import hashlibstats['code_sha256'] = {name: hashlib.sha256(Path(__file__).with_name(name).read_bytes()).hexdigest()for name in ('core.py', 'worker.py', 'rules.py')}emit(phase='loading', diagnostics=dict(stats))os.environ.update(HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', HF_HUB_DISABLE_TELEMETRY='1')- import psutilimport torchimport transformers- from PIL import Image, ImageOps- from transformers import AutoProcessor, Qwen3VLForConditionalGeneration, StoppingCriteria, StoppingCriteriaList- from .core import prepare- from .rules import instruction, validate_outputstats.update(import_seconds=time.monotonic() - started, torch_version=torch.__version__,transformers_version=transformers.__version__, cuda_version=torch.version.cuda,platform=sys.platform, python_version=sys.version.split()[0])- def checkpoint(stage, phase='loading'):+ def checkpoint(stage, phase='loading', **extra):stats['stage'] = stagestats['worker_seconds'] = time.monotonic() - startedgpu_snapshot(stats)- emit(phase=phase, diagnostics=dict(stats))+ emit(phase=phase, diagnostics=dict(stats), **extra)stats['available_memory_before_load_bytes'] = available_memory()if stats['available_memory_before_load_bytes'] < 11 * 2**30:raise ValueError('ram_space')torch.set_num_threads(min(8, os.cpu_count() or 1))- checkpoint('preprocess')- preparing = time.monotonic()- processor = AutoProcessor.from_pretrained(folder, local_files_only=True, trust_remote_code=False)- messages = [{'role': 'system', 'content': instruction(value)}]- content = []- for index, row in enumerate(value['media'], 1):- with Image.open(row['path']) as source:- if source.width * source.height > 50_000_000:- raise ValueError('image_size')- image = ImageOps.exif_transpose(source).convert('RGB')- image.thumbnail((768, 768))- content.extend([{'type': 'text', 'text': f'<Picture {index}> ({row["role"]})'},- {'type': 'image', 'image': image}])- content.append({'type': 'text', 'text': f'User scene to rewrite (preserve every requested action):\n{value["text"]}'})- messages.append({'role': 'user', 'content': content})- inputs = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True,- return_dict=True, return_tensors='pt', processor_kwargs={'images_kwargs': {'max_pixels': 512 * 32 * 32}})- if inputs.input_ids.shape[-1] > 6500:- raise ValueError('context_length')- stats.update(input_tokens=int(inputs.input_ids.shape[-1]), preprocess_seconds=time.monotonic() - preparing)+ return torch, checkpoint+++def open_image(path):+ from PIL import Image, ImageOps+ with Image.open(path) as source:+ if source.width * source.height > 50_000_000:+ raise ValueError('image_size')+ image = ImageOps.exif_transpose(source).convert('RGB')+ image.thumbnail((768, 768))+ return image+++def tokenize(processor, messages, max_pixels=512 * 32 * 32):+ return processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True,+ return_dict=True, return_tensors='pt', processor_kwargs={'images_kwargs': {'max_pixels': max_pixels}})+++def load_model(folder, torch, stats, checkpoint):+ """Weights, FreeToken operators and GPU placement; returns (model, device)."""+ import psutil+ from transformers import Qwen3VLForConditionalGeneration+ from .core import prepare, GatedMLPcheckpoint('load_weights')loading = time.monotonic()model = Qwen3VLForConditionalGeneration.from_pretrained(folder, dtype=torch.bfloat16,@@ -104,7 +98,6 @@ def run(folder, value, *, stats=None):stats['load_seconds'] = time.monotonic() - loadingpreparing = time.monotonic()prepare(model)- from .core import GatedMLPaccelerations = []if isinstance(model.model.language_model.layers[0].mlp, GatedMLP):accelerations += ['merged_gate_up', 'per_image_sdpa', 'chunked_vision_mlp']@@ -116,6 +109,7 @@ def run(folder, value, *, stats=None):checkpoint('placement')placing = time.monotonic()mapping = {'': 'cpu'}+ device = 'cpu'if torch.cuda.is_available():from accelerate import dispatch_model, infer_auto_device_mapfrom .. import gpu_budget@@ -135,51 +129,116 @@ def run(folder, value, *, stats=None):if 'disk' in mapping.values():raise ValueError('ram_space')model = dispatch_model(model, mapping)- inputs = inputs.to('cuda:0' if any(v == 0 for v in mapping.values()) else 'cpu')+ device = 'cuda:0' if any(v == 0 for v in mapping.values()) else 'cpu'stats.update(placement_seconds=time.monotonic() - placing,cpu_offload=any(v == 'cpu' for v in mapping.values()) and any(v == 0 for v in mapping.values()),- execution_device=str(inputs.input_ids.device), device_map=mapping)- loaded = time.monotonic()- checkpoint('prefill', 'rewriting')+ execution_device=device, device_map=mapping)+ return model, device+++def generate(torch, model, inputs, max_new_tokens, started, on_token):+ """Greedy decoding; on_token(timing) sees first-output and decode speed."""+ from transformers import StoppingCriteria, StoppingCriteriaList+ prompt = inputs.input_ids.shape[-1]+ timing = {}class Progress(StoppingCriteria):- shown = 0.first = Nonedef __call__(self, input_ids, scores, **kwargs):now = time.monotonic()- tokens = int(input_ids.shape[-1] - inputs.input_ids.shape[-1])+ tokens = int(input_ids.shape[-1] - prompt)if self.first is None:if inputs.input_ids.is_cuda:torch.cuda.synchronize()now = time.monotonic()self.first = now- stats['time_to_first_output_seconds'] = now - loaded- stats.update(output_tokens=tokens, decode_seconds=now - self.first,- decode_tokens_per_second=(tokens - 1) / (now - self.first) if now > self.first else None)- if now - self.shown > .5:- checkpoint('decode', 'rewriting')- self.shown = now+ timing['first_output_seconds'] = now - started+ timing.update(output_tokens=tokens, decode_seconds=now - self.first,+ decode_tokens_per_second=(tokens - 1) / (now - self.first) if now > self.first else None)+ on_token(timing)return Falsewith torch.inference_mode():- output = model.generate(**inputs, max_new_tokens=1800, do_sample=False, use_cache=True,+ output = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False, use_cache=True,stopping_criteria=StoppingCriteriaList([Progress()]))- ids = output[0, inputs.input_ids.shape[-1]:]+ return output[0, prompt:], timing+++def run(folder, value, *, stats=None):+ stats = {} if stats is None else stats+ return rewrite(folder, value, stats)+++def rewrite(folder, value, stats):+ stats.update(stage='imports', pid=os.getpid(), image_count=len(value['media']),+ mode=value['mode'], dtype='bfloat16', attention='sdpa', kv_cache='dynamic',+ backend='transformers', accelerations=[],+ persistent_model=False)+ torch, checkpoint = begin(stats)+ from transformers import AutoProcessor+ from .rules import DIALOGUE_RETRY, instruction, language, missing_lines, user_text, validate_output+ checkpoint('preprocess')+ preparing = time.monotonic()+ processor = AutoProcessor.from_pretrained(folder, local_files_only=True, trust_remote_code=False)+ messages = [{'role': 'system', 'content': instruction(value)}]+ content = []+ for index, row in enumerate(value['media'], 1):+ content.extend([{'type': 'text', 'text': f'<Picture {index}> ({row["role"]})'},+ {'type': 'image', 'image': open_image(row['path'])}])+ content.append({'type': 'text', 'text': user_text(value)})+ messages.append({'role': 'user', 'content': content})+ inputs = tokenize(processor, messages)+ if inputs.input_ids.shape[-1] > 6500:+ raise ValueError('context_length')+ stats.update(input_tokens=int(inputs.input_ids.shape[-1]), preprocess_seconds=time.monotonic() - preparing)+ model, device = load_model(folder, torch, stats, checkpoint)+ inputs = inputs.to(device)+ loaded = time.monotonic()+ checkpoint('prefill', 'rewriting')+ shown = [0.]+ def on_token(timing):+ stats.update(output_tokens=timing['output_tokens'], decode_seconds=timing['decode_seconds'],+ decode_tokens_per_second=timing['decode_tokens_per_second'])+ stats['time_to_first_output_seconds'] = timing['first_output_seconds']+ if time.monotonic() - shown[0] > .5:+ checkpoint('decode', 'rewriting')+ shown[0] = time.monotonic()+ ids, _ = generate(torch, model, inputs, 1800, loaded, on_token)stats.update(rewrite_seconds=time.monotonic() - loaded, output_tokens=len(ids))checkpoint('validate', 'rewriting')if len(ids) >= 1800:raise ValueError('context_length')- rewritten = validate_output(processor.decode(ids, skip_special_tokens=True), value)+ text = processor.decode(ids, skip_special_tokens=True)+ missing = missing_lines(text, value['text'])+ if missing:+ # One correction turn when the user's dialogue was dropped; keep the better draft.+ retry = messages + [{'role': 'assistant', 'content': text}, {'role': 'user', 'content': DIALOGUE_RETRY + '\n'.join(+ '- [%s] %s' % (language(line), line) for line in missing)}]+ retry_inputs = tokenize(processor, retry)+ if retry_inputs.input_ids.shape[-1] <= 6500:+ again, _ = generate(torch, model, retry_inputs.to(device), 1800, time.monotonic(), lambda timing: None)+ second = processor.decode(again, skip_special_tokens=True)+ stats.update(dialogue_retry=True, retry_output_tokens=len(again),+ rewrite_seconds=time.monotonic() - loaded)+ try:+ validate_output(second, value)+ if len(again) < 1800 and len(missing_lines(second, value['text'])) < len(missing):+ text = second+ except ValueError:+ pass+ rewritten = validate_output(text, value)stats['stage'] = 'complete'emit(phase='complete', text=rewritten, diagnostics=dict(stats))def main():stats = {}+ value = {}try:- value = json.loads(sys.stdin.buffer.read(512 * 1024))+ value = json.loads(sys.stdin.buffer.read(1024 * 1024))run(Path(sys.argv[1]), value, stats=stats)except Exception as error:gpu_snapshot(stats)- emit(phase='failed', diagnostics=stats, **failure(error))+ mode = value.get('mode') if isinstance(value, dict) else None+ emit(phase='failed', diagnostics=stats, **failure(error, mode))return 1return 0diff --git a/freevideo_engine/provision.py b/freevideo_engine/provision.pyindex 1ec1b9c..555a1b5 100644--- a/freevideo_engine/provision.py+++ b/freevideo_engine/provision.py@@ -254,8 +254,11 @@ def models(plan):if time.monotonic() - last[0] >= .5:model_progress.update(row, phase='downloading', done=done, rate=speed)last[0] = time.monotonic()+ # Setup's approval to start a file over when its source cannot resume+ # (model_transfer passes it for the large files) covers the tables too.network.download(network.model_urls(networking, row), path, row['sha256'], progress,- network=dict(networking, quiet=True), size=row['bytes'],+ network=dict(networking, quiet=True, allow_model_restart=plan.get('allow_model_restart', False)),+ size=row['bytes'],category=network.model_family(row), headers_for=model_headers,keep_partial=True, stall_seconds=30, slow_seconds=15, low_speed_limit=64 * 1024)complete(row, path, dict(file_identity(path, row), method='full_content_hash_resumable_download'),diff --git a/freevideo_engine/proxy.py b/freevideo_engine/proxy.pyindex d54c3a6..cc97e97 100644--- a/freevideo_engine/proxy.py+++ b/freevideo_engine/proxy.py@@ -15,7 +15,8 @@ GIT_PROXY_PATTERN = r'^(http\..*proxy|https\.proxy|remote\..*\.proxy|core\.gitprdef inherited(environ=None):- env = dict(os.environ if environ is None else environ)+ from .linux_bundle import child_environment+ env = child_environment(environ)# GUI processes on Windows often have no proxy environment variables.# Read the user's OS proxy without editing its settings. Explicit child# overrides (including NO_PROXY) always take precedence.diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.jsonindex 36eca6a..0c32e63 100644--- a/freevideo_engine/release_notes.json+++ b/freevideo_engine/release_notes.json@@ -1,25 +1,62 @@{"schema": 1,- "product_version": "0.3.20",+ "product_version": "0.3.21","en": {- "summary": "Offline installations now open FreeVideo in ComfyUI, and on Linux, GPUs with memory to spare generate faster.",+ "summary": "FreeVideo comes to Linux desktops as an AppImage, images in Media can be edited in place, and videos on Windows generate faster and more reliably when GPU memory or RAM is tight.","changes": [- "Offline installations imported from the environment package now open FreeVideo in ComfyUI: the launcher installs the FreeVideo node that the package does not carry. Before, ComfyUI started without FreeVideo and the launch stopped at \"could not load FreeVideo\". A retry now also restarts the ComfyUI that an earlier attempt left running, and the message no longer suggests repairing the environment.",- "Offline installations in a longer folder path now also get their desktop and Start menu shortcuts. Windows cannot create a shortcut to a program whose path is 260 characters or longer, and the folders of an offline installation could make the launcher copy's path that long; the copy now goes to a shorter folder in that case.",- "On Linux, when the GPU has memory to spare, attention now runs 28 or all 56 heads at a time instead of 16; how many model layers stay on the GPU, and what is kept in system memory, does not change. On a 96 GB GPU, sampling a 10-second 1344×768 video took about 11% less time; with a 16–20 GB budget the gain is about 6–9%. Smaller GPUs and Windows keep their current settings. The same seed can give a slightly different video than before, as it already does between GPUs with different memory.",- "On Linux, video decoding now uses its FP16 cache on every GPU (it was on for some only). Decoding a 10-second 1344×768 video on a 96 GB GPU took 15.4 s instead of 19.2 s and 4.2 GB less memory, with identical output."+ "FreeVideo comes to Linux desktops as an AppImage with the same launcher as Windows and macOS: it installs ComfyUI, the runtime and the models, adds FreeVideo to the application menu and updates itself. In a terminal, ./setup.sh now continues until FreeVideo is open, and freevideo opens it again later. On a GPU server, freevideo server keeps FreeVideo running for other computers to use.",+ "Images in Media can now be edited without leaving FreeVideo: click Edit on a picture to crop it to the video's shape, add text and shapes, adjust light and color, and work with layers, masks and selections. Spot healing fills each stroke with texture from the surrounding picture, and Captions only removes burned-in captions. Text uses FreeVideo's built-in open-source fonts. The original file is kept, and opening the edit again brings back every layer.",+ "The FreeVideo toolbar with the Create and Nodes switch can now be dragged anywhere on the page, like a window. It stays where you leave it after ComfyUI, FreeVideo or the browser restarts, and in other browsers too. Double-click an empty part of the toolbar to put it back at the top.",+ "Prompt enhancement now keeps the lines written for characters to say as spoken dialogue, word for word, instead of turning them into on-screen text, and puts each section of the enhanced prompt on its own line.",+ "On Windows, FreeVideo now leaves room for the GPU memory other applications are using, so videos no longer slow down or start over when the GPU fills up. On a test GPU limited to 8 GB, with 2.6 GB used by another application, a 5-second 960×544 video took 208 s instead of 290 s. On computers with little free RAM, the second pass also no longer loads the video model again.",+ "On Windows, int8 videos sample faster on GPUs with 6 to 16 GB of memory. When memory allows, attention is computed in larger groups without using more video memory: on a Windows test GPU limited to 12 GB, a 1344×768 step took 58.2 s instead of 63.3 s, about 8% faster. 16 GB RTX 40 and 30 series cards with 13.5 to 14 GB free now copy the next model layer while the current one computes, as RTX 50 series cards already did. The same seed can give a slightly different video, as it already does between GPUs with different memory.",+ "On Windows computers short of RAM, model layers read from the drive are now read ahead while the previous layer computes, without using more memory; in our tests this cut each sampling step by about 20%. While the last steps run, FreeVideo also reads ahead as much of the video decoder as free RAM allows, instead of skipping it when the whole decoder does not fit. The same seed gives the same video as before.",+ "Videos spend less time getting ready. A new prompt or video size no longer makes FreeVideo compile its GPU kernels again, which took about 7 seconds per video on a Windows test machine, and a long ComfyUI session keeps them compiled instead of falling back to a much slower path. The second sampling step no longer compiles part of the model again, which on Windows could stop an attempt when the GPU was nearly full. The same seed gives the same video as before.",+ "On Mac, the installer shows and checks free space the same way Finder does, including space macOS frees on its own, such as local Time Machine snapshots. Below the install location it names the disk and its free space, Choose another disk lists the other connected disks, and when space runs short it suggests one with enough room. A new installation needs about 73 GB instead of about 110 GB, and exFAT, FAT32, read-only and disconnected disks are explained before installation starts.",+ "Installation is harder to interrupt and easier to follow: the overall progress moves with the model download, a small file whose download breaks off is fetched again, and the launcher reinstalls its loader when the FreeVideo folder in ComfyUI's custom nodes had its original files put back.",+ "Offline-package installations take less disk space. Once the installation holds and has verified everything in the imported ZIP files, FreeVideo offers to delete them, so the packages no longer take the space twice; nothing is deleted without confirmation. The first start after installing or updating removes unpacked package folders and download leftovers that are no longer needed and shows how much space was freed, and models copied from another disk come with a note on how to avoid the copy.",+ "Fixes: FreeVideo's page now loads with ad-block filter lists that blocked one of its scripts by name, and the page check names any FreeVideo file a browser extension blocks. Enlarging a video to full screen in the node view no longer shows the \"did not load completely\" message. Newer ComfyUI versions no longer print an asset registration warning after every video. Local optimization works when the second pass keeps part of its data in RAM, as on 8 GB Windows GPUs."]},"zh": {- "summary": "离线安装可以在 ComfyUI 中打开 FreeVideo;在 Linux 上,显存有富余的显卡生成更快。",+ "summary": "FreeVideo 推出 Linux 桌面版 AppImage,素材图片可以直接编辑,Windows 上显存或内存紧张时生成更快、更稳定。","changes": [- "用环境包导入的离线安装现在可以在 ComfyUI 中打开 FreeVideo:启动器会安装环境包里没有带的 FreeVideo 节点。之前 ComfyUI 启动时没有加载 FreeVideo,启动停在“无法加载 FreeVideo”。重试时也会重启上一次留下的 ComfyUI,提示也不再让你去修复运行环境。",- "离线安装放在较长的文件夹路径下时,现在也能创建桌面和开始菜单快捷方式。Windows 无法为路径达到 260 个字符的程序创建快捷方式,而离线安装的目录层级可能让启动器副本的路径超过这个长度;这种情况下,副本会改放到路径较短的位置。",- "在 Linux 上,显存有富余时,注意力改为每次计算 28 个或全部 56 个头(原来每次 16 个);留在显卡上的模型层数和放在内存里的内容都不变。在 96 GB 显卡上,生成 10 秒 1344×768 视频的采样时间缩短约 11%;显存预算在 16–20 GB 时约缩短 6–9%。显存较小的显卡和 Windows 保持现有设置。同一个种子生成的视频可能与以前略有不同,就像在显存不同的显卡上本来就会有差异一样。",- "在 Linux 上,所有显卡的视频解码都使用 FP16 缓存(以前只有部分显卡开启)。在 96 GB 显卡上解码 10 秒 1344×768 视频从 19.2 秒降到 15.4 秒,少占 4.2 GB 显存,输出完全一致。"+ "Linux 桌面可以使用 FreeVideo 的 AppImage,启动器与 Windows、macOS 相同:自动安装 ComfyUI、运行环境和模型,加入应用菜单,并能自动更新。在终端里,./setup.sh 现在会一直进行到打开 FreeVideo,之后输入 freevideo 会再次打开它。在 GPU 服务器上,freevideo server 会让 FreeVideo 保持运行,供其他电脑使用。",+ "素材里的图片现在可以直接在 FreeVideo 中编辑:点击图片上的“编辑”,可以裁剪成视频比例、添加文字和形状、调整光线和颜色,并使用图层、蒙版和选区。污点修复会用周围画面的纹理填补,“只去字幕”可以去掉烧进画面的字幕。文字使用 FreeVideo 内置的开源字体。原图会保留,再次打开编辑时所有图层都在。",+ "带“创作面板 / 节点视图”切换的 FreeVideo 工具栏现在可以像窗口一样拖到页面任意位置。重启 ComfyUI、FreeVideo 或浏览器后,它仍在原处,换一个浏览器也一样。双击工具栏空白处,可以让它回到顶部。",+ "提示词增强现在会把写给角色说的台词原样保留为对白,不再变成画面里的文字;增强后的提示词每个部分各占一行。",+ "在 Windows 上,FreeVideo 现在会给其他程序占用的显存留出空间,显卡被占满时生成不再变慢或中止重来。在一块限制为 8 GB、其中 2.6 GB 被其他程序占用的测试显卡上,生成 5 秒 960×544 视频从 290 秒缩短到 208 秒。在空闲内存较少的电脑上,第二遍也不再重新加载视频模型。",+ "在 Windows 上,6–16 GB 显存的显卡生成 int8 视频更快。显存允许时,注意力以更大的分组计算,显存占用不增加:在一块限制为 12 GB 的 Windows 测试显卡上,1344×768 视频每步从 63.3 秒缩短到 58.2 秒,约快 8%。空闲显存为 13.5 到 14 GB 的 16 GB RTX 40 和 30 系列显卡,现在也会在当前层计算的同时复制下一层,与 RTX 50 系列此前的做法相同。同一个种子生成的视频可能略有不同,就像在显存不同的显卡上本来就会有差异一样。",+ "在内存不足的 Windows 电脑上,需要从硬盘读取的模型层现在会在上一层计算时提前读取,而且不额外占用内存;在我们的测试中,每个采样步缩短约 20%。在最后几个采样步进行时,FreeVideo 还会在空闲内存允许的范围内预先读取尽可能多的视频解码器,不再因为放不下整个解码器就完全不读。同一个种子生成的视频与以前相同。",+ "视频开始生成前的等待更短。换提示词或视频尺寸后,FreeVideo 不再重新编译显卡算子(在 Windows 测试机上每个视频约省 7 秒),在较长的 ComfyUI 会话中也不会退回慢得多的未编译方式。第二个采样步不再重新编译部分模型;在 Windows 上,这次编译曾在显卡快满时使尝试中止。同一个种子生成的视频与以前相同。",+ "在 Mac 上,安装器显示和检查的可用空间现在与访达一致,包括 macOS 需要时会自动释放的空间,例如 Time Machine 本地快照。安装位置下方会显示所在硬盘和可用空间,点“换一块硬盘”可以选择其他已连接的硬盘,空间不够时会推荐一块够用的硬盘。全新安装所需的空间从约 110 GB 降到约 73 GB;exFAT、FAT32、只读或没有连接的硬盘,会在安装开始前说明原因。",+ "安装更不容易中断,过程也更清楚:整体进度会随模型下载推进;小文件下载中断时会重新下载;ComfyUI 自定义节点里的 FreeVideo 文件夹被放回原始文件后,启动器会重新装上加载器。",+ "用离线包安装后,占用的硬盘空间更少。安装已包含并校验完导入的压缩包里的全部内容后,FreeVideo 会提示删除这些压缩包,离线包不再占两份空间;删除前需要确认。安装或更新后第一次启动时,FreeVideo 会清理不再需要的离线包解压目录和下载残留,并显示释放了多少空间;从另一块硬盘复制来的模型,会附一句说明,讲清楚怎样避免这份复制。",+ "修复:部分广告拦截列表会按文件名拦下 FreeVideo 的一个脚本,导致创作面板不显示,现在页面可以正常加载,页面检查也会指出被浏览器插件拦截的文件。在节点视图里把视频放大到全屏时,不再出现“没有完整加载”的提示。较新的 ComfyUI 不再在每个视频完成后打印资源登记警告。第二遍需要把部分数据放在内存里时(例如 8 GB Windows 显卡),本地优化可以正常运行。"]},"history": [+ {+ "product_version": "0.3.20",+ "en": {+ "summary": "Offline installations now open FreeVideo in ComfyUI, and on Linux, GPUs with memory to spare generate faster.",+ "changes": [+ "Offline installations imported from the environment package now open FreeVideo in ComfyUI: the launcher installs the FreeVideo node that the package does not carry. Before, ComfyUI started without FreeVideo and the launch stopped at \"could not load FreeVideo\". A retry now also restarts the ComfyUI that an earlier attempt left running, and the message no longer suggests repairing the environment.",+ "Offline installations in a longer folder path now also get their desktop and Start menu shortcuts. Windows cannot create a shortcut to a program whose path is 260 characters or longer, and the folders of an offline installation could make the launcher copy's path that long; the copy now goes to a shorter folder in that case.",+ "On Linux, when the GPU has memory to spare, attention now runs 28 or all 56 heads at a time instead of 16; how many model layers stay on the GPU, and what is kept in system memory, does not change. On a 96 GB GPU, sampling a 10-second 1344×768 video took about 11% less time; with a 16–20 GB budget the gain is about 6–9%. Smaller GPUs and Windows keep their current settings. The same seed can give a slightly different video than before, as it already does between GPUs with different memory.",+ "On Linux, video decoding now uses its FP16 cache on every GPU (it was on for some only). Decoding a 10-second 1344×768 video on a 96 GB GPU took 15.4 s instead of 19.2 s and 4.2 GB less memory, with identical output."+ ]+ },+ "zh": {+ "summary": "离线安装可以在 ComfyUI 中打开 FreeVideo;在 Linux 上,显存有富余的显卡生成更快。",+ "changes": [+ "用环境包导入的离线安装现在可以在 ComfyUI 中打开 FreeVideo:启动器会安装环境包里没有带的 FreeVideo 节点。之前 ComfyUI 启动时没有加载 FreeVideo,启动停在“无法加载 FreeVideo”。重试时也会重启上一次留下的 ComfyUI,提示也不再让你去修复运行环境。",+ "离线安装放在较长的文件夹路径下时,现在也能创建桌面和开始菜单快捷方式。Windows 无法为路径达到 260 个字符的程序创建快捷方式,而离线安装的目录层级可能让启动器副本的路径超过这个长度;这种情况下,副本会改放到路径较短的位置。",+ "在 Linux 上,显存有富余时,注意力改为每次计算 28 个或全部 56 个头(原来每次 16 个);留在显卡上的模型层数和放在内存里的内容都不变。在 96 GB 显卡上,生成 10 秒 1344×768 视频的采样时间缩短约 11%;显存预算在 16–20 GB 时约缩短 6–9%。显存较小的显卡和 Windows 保持现有设置。同一个种子生成的视频可能与以前略有不同,就像在显存不同的显卡上本来就会有差异一样。",+ "在 Linux 上,所有显卡的视频解码都使用 FP16 缓存(以前只有部分显卡开启)。在 96 GB 显卡上解码 10 秒 1344×768 视频从 19.2 秒降到 15.4 秒,少占 4.2 GB 显存,输出完全一致。"+ ]+ }+ },{"product_version": "0.3.19","en": {@@ -234,25 +271,6 @@"从启动器打开 FreeVideo 时,即使 ComfyUI 恢复了上次的标签页,FreeVideo 工作流也会显示在最前面。"]}- },- {- "product_version": "0.3.8",- "en": {- "summary": "Downloads that cannot resume now start again by themselves, and the ComfyUI setup panel explains why Install / repair is unavailable.",- "changes": [- "When an interrupted model download cannot be resumed, installation now downloads that file again from the start instead of stopping at every retry. The incomplete copy is kept aside.",- "If model preparation stops, the message now names the file and the reason instead of a generic \"preparation stopped\".",- "In the ComfyUI setup panel, a short note under the buttons explains why Install / repair is unavailable: run Detect & review, tick the agreement, or resolve the problems shown in the plan. Changing a setting clears the outdated plan."- ]- },- "zh": {- "summary": "无法续传的下载会自动从头重新下载;ComfyUI 内的安装面板会说明「安装/修复」暂不可用的原因。",- "changes": [- "模型下载中断且无法续传时,安装会自动从头重新下载该文件,不再每次重试都停下;未完成的文件会另行保留。",- "模型准备停止时,提示会写明具体的文件和原因,而不是笼统的「准备已停止」。",- "ComfyUI 内的安装面板会在按钮下方说明「安装/修复」暂不可用的原因:需要先「检测并预览」、勾选同意,或先解决计划中标红的问题;修改设置后会清除过期的计划。"- ]- }}]}diff --git a/freevideo_engine/row_kernels.py b/freevideo_engine/row_kernels.pynew file mode 100644index 0000000..ecf50d3--- /dev/null+++ b/freevideo_engine/row_kernels.py@@ -0,0 +1,90 @@+"""Compile the row-wise fused block kernels once for every row count.++The fused pointwise kernels of a transformer block -- the RMSNorm + AdaLN+affine before each sub-layer, the gated residual add after it, the SwiGLU+activation, QK-norm + rope and the softmax gate -- work row by row. Upstream+compiles them with dynamic=False, so dynamo keeps one graph per row count, and+the row count is the request's video tokens plus the prompt's text tokens (and+an FF tile's remainder). Every new prompt length therefore compiles these+kernels again, and so does every new canvas. In a fresh process each of+those is an FX graph cache miss and a full compile:++ RTX 5060 Ti, Windows, 768x1344x56 two-pass, same prompt 154.3 s+ the same request with prompts of two other lengths 163.9, 167 s++Twelve graphs missed there. On Linux the same request with a new prompt+recompiled _pre_ref and _post_into_branch three times each and _qk_prep_body+and _swiglu_ref twice each, and nothing else; a new canvas missed those ten and+seven linear-attention graphs, which depend on the frame layout and stay+static here. A resident ComfyUI session keeps the graphs on one code object,+and from dynamo's recompile limit (eight) on a new length runs eager: _pre_ref+at 17478 rows took 2.76 ms a call instead of 0.26.++Only the row dimension is marked dynamic, on an alias of each row-indexed+argument so the caller's tensor carries no mark into any other compiled+function. Everything else -- hidden size, heads, head dimension, tables --+stays specialised as upstream compiles it. A row-wise kernel does the same+arithmetic on every row whatever their number; inductor's reduction over the+static hidden dimension is unchanged. Against the per-row-count graphs, on an+RTX PRO 6000 at 4400 to 73043 rows, all five kernels were bitwise identical+and ran at the same speed (pre 1.080 ms against 1.080 at 73043 rows, post+1.581 against 1.582). Complete two-pass requests produced the same latents+as before at 768x1344x56 and 1344x768x243 with int8, and at 768x1344x56 with+FP8 and with an online LoRA, and the same steady step times. A row count of+0 or 1 still specialises, as dynamo always does.+"""+import torch++_ROWS = '_freevideo_dynamic_rows'+# (residual, gate, indices, branch) of a gated residual add.+POST_ROWS = ((0, -2), (2, 0), (3, -2))+++def dynamic_rows(compiled, rows):+ """Call `compiled` with the token dimension of some arguments dynamic.++ `rows` pairs an argument's position with its token dimension: the residual+ stream is [batch, tokens, hidden], so its tokens are dimension -2, while+ the AdaLN indices are [tokens]. Marking the batch dimension instead does+ nothing -- a size-1 dimension always specialises -- and the token symbol+ of the indices is then forced equal to the stream's fixed count.+ """+ mark = torch._dynamo.maybe_mark_dynamic++ def call(*args):+ args = list(args)+ for index, dim in rows:+ alias = args[index].view(args[index].shape)+ mark(alias, dim % alias.dim())+ args[index] = alias+ return compiled(*args)+ setattr(call, _ROWS, True)+ call.__wrapped__ = compiled+ return call+++def install():+ """Put dynamic-row compiles of upstream's fused kernels in upstream's caches.++ Upstream looks each kernel up by name and compiles it on first use, so an+ entry placed here before the first call is the one every block uses.+ Idempotent; an entry from an earlier engine in this process is replaced+ once, which compiles the dynamic graph once.+ """+ from src.models.ops import fused_block+ from src.models.softmax_attention import kernels+ entries = (+ # (hidden, weight, eps, scale, shift, indices)+ (fused_block._CACHE, 'pre', fused_block._pre_ref, ((0, -2), (5, 0))),+ # (residual, gate, indices, branch)+ (fused_block._CACHE, 'post', fused_block._post_ref, POST_ROWS),+ # (projected [tokens, 2 * width])+ (fused_block._CACHE, 'swiglu', fused_block._swiglu_ref, ((0, 0),)),+ # (q or k [tokens, heads, head_dim], weight, eps, cos [tokens, rotary], sin)+ (kernels._QK_PREP_CACHE, 'fn', kernels._qk_prep_body, ((0, 0), (3, 0), (4, 0))),+ # (softmax output [tokens, heads, head_dim], gate [tokens, heads])+ (kernels._SOFTMAX_GATE_CACHE, 'fn', kernels._softmax_gate_body, ((0, 0), (1, 0))),+ )+ for cache, name, body, rows in entries:+ if not getattr(cache.get(name), _ROWS, False):+ cache[name] = dynamic_rows(torch.compile(body, dynamic=False), rows)diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.pyindex 6331819..d3625c7 100644--- a/freevideo_engine/runtime.py+++ b/freevideo_engine/runtime.py@@ -349,6 +349,9 @@ class Engine:# Engine supplies every window call, including the official cuDNN/FA4# pair. Avoid upstream auto importing an unselected optional FA4 package.set_softmax_backend(model, 'flex')+ if inference_kernels:+ from .row_kernels import install as install_row_kernels+ install_row_kernels()set_inference_mode(model, inference_kernels)self.attention.install(model)if head_chunk:@@ -611,7 +614,8 @@ class Engine:base_peak = max(pass_cache.get('workspace_peak_bytes', 0), peak - cache_peak)pass_cache['workspace_peak_bytes'] = base_peaklive_budget = budget_refresh('sample', lambda limit: offloader.cache_between_steps(- min(cached, max(0, limit - base_peak - 512 * 2**20)), allow_growth=False))+ min(cached, max(0, limit - base_peak - 512 * 2**20)), allow_growth=False),+ workspace=base_peak)if len(self) < active_steps:from .two_pass import pass_cache_allowancefrom .system import system_memory@@ -620,10 +624,19 @@ class Engine:commit = system_memory().get('commit_available_bytes')from .two_pass import reusable_cache_bytesheld = reusable_cache_bytes(cached, owner.device_backend.memory_reserved(), base_peak)+ # Other applications' memory counts once the device is+ # full: growing into it made Windows cut this process's+ # budget below its own workspace. Unread: no extra bound.+ room = getattr(budget_refresh, 'device_headroom', None)+ headroom = room() if callable(room) else None+ if type(headroom) is not int:+ headroom = Noneallowance = pass_cache_allowance(live_budget, base_peak, free + held,- gpu_reserve_bytes, None if commit is None else commit + held)+ gpu_reserve_bytes, None if commit is None else commit + held,+ device_free=None if headroom is None else headroom + held)pass_cache.update(gpu_budget_bytes=live_budget, measured_peak_reserved_bytes=peak,- live_free_bytes=free, commit_available_bytes=commit, admitted_bytes=allowance)+ live_free_bytes=free, commit_available_bytes=commit, admitted_bytes=allowance,+ device_headroom_bytes=headroom)# New planes fill during the next step and only save a# transfer on a subsequent step. The two-step refine# pass therefore cannot benefit from a late fill.diff --git a/freevideo_engine/sampling_assets.py b/freevideo_engine/sampling_assets.pyindex 5a5b5e6..434186a 100644--- a/freevideo_engine/sampling_assets.py+++ b/freevideo_engine/sampling_assets.py@@ -8,6 +8,7 @@ import jsonfrom functools import lru_cachefrom pathlib import Pathimport time+from . import disk_spaceCOMMUNITY_PREFIX = 'community-sigma3-'WORKERS = 6@@ -203,7 +204,7 @@ def prepare(root, machine, sampling, task, *, progress, interrupted=None, envirostarted = time.monotonic()total = sum(row['bytes'] for _, row, _ in missing)shared.mkdir(parents=True, exist_ok=True)- free = shutil.disk_usage(shared).free+ free = disk_space.free_bytes(shared)if free < total + 256 * 2**20:raise ValueError('Not enough disk space for sampling caches: %.0f MiB needed, %.0f MiB free in %s. ''Free space and retry.' % ((total + 256 * 2**20) / 2**20, free / 2**20, shared))diff --git a/freevideo_engine/sampling_memory.py b/freevideo_engine/sampling_memory.pyindex 1729131..c25ef8a 100644--- a/freevideo_engine/sampling_memory.py+++ b/freevideo_engine/sampling_memory.py@@ -96,7 +96,10 @@ class SamplingMemory:old['over_budget_samples'] += sample['usage_bytes'] > sample['budget_bytes']def complete(self, seconds):- row = dict(step=self.index, seconds=seconds, elapsed_seconds=time.monotonic()-self.started)+ # The absolute monotonic end lets the report place the GPU monitor's+ # samples (another process, same clock) inside each step.+ now = time.monotonic()+ row = dict(step=self.index, seconds=seconds, elapsed_seconds=now-self.started, monotonic_seconds=now)current_compiler = compilation.snapshot()row['compiler'] = compilation.difference(self.previous_compiler, current_compiler)self.previous_compiler = current_compilerdiff --git a/freevideo_engine/support_report.py b/freevideo_engine/support_report.pyindex 2ca4e40..9a2bcdd 100644--- a/freevideo_engine/support_report.py+++ b/freevideo_engine/support_report.py@@ -163,7 +163,7 @@ def summarize(report, engine, encoding):sampling_reused=sampling_reused,sampling_memory=sampling_memory or None,decoder_read_ahead={key: decoder_read_ahead[key] for key in (- 'state', 'read_bytes', 'total_bytes', 'allowance_bytes',+ 'state', 'read_bytes', 'total_bytes', 'allowance_bytes', 'target_bytes','elapsed_seconds', 'gpu_allocation_bytes', 'private_buffer_bytes','sampling') if key in decoder_read_ahead} or None,device_memory=mapping(engine.get('device_memory')) or None,@@ -187,6 +187,7 @@ def summarize(report, engine, encoding):host_prefetch_wait_seconds=offload.get('host_prefetch_wait_seconds'),host_prefetch_buffer_bytes=offload.get('host_prefetch_buffer_bytes'),host_prefetch_disabled_reason=offload.get('host_prefetch_disabled_reason'),+ host_prefetch_shared_reason=offload.get('host_prefetch_shared_reason'),h2d_seconds=offload.get('h2d_seconds'), timing_scope='Transfer/wait timers may overlap; do not add to wall time.',pinning_scope='pin_host_gb is requested decimal GB. pinned_model_bytes is actual weight payload; ''pinned_host_allocated_bytes includes rounded active and cached host allocations at load. '@@ -282,6 +283,10 @@ def write(output, report=None, bridge=None, *, _retry=None, live=False):engine_output = Path(_retry['retained']) / output.name if video_retry else outputengine = mapping(request.get('video')) or read_json('.engine.json', engine_output.with_suffix('.engine.json'))engine = sampling_sidecar(engine, engine_output)+ steps = mapping(engine.get('sampling_memory')).get('steps')+ if isinstance(steps, list) and steps:+ from .monitoring import step_activity+ step_activity(engine_output.with_suffix('.engine.gpu.csv'), steps)encoding = mapping(request.get('encoding')) or read_json('.encoding.json')if encoder_retry:request = dict(request, success=False, phase='encoder_oom')diff --git a/freevideo_engine/system.py b/freevideo_engine/system.pyindex 6fb115f..3f9b83b 100644--- a/freevideo_engine/system.py+++ b/freevideo_engine/system.py@@ -29,6 +29,28 @@ def missing_curl_message(env=None):return 'Missing curl for bounded downloads and HTTP/SOCKS proxy support. Run ./setup.sh to install it.'+def linux_tools_command(names, which=shutil.which, root=None):+ """The package command for missing build tools, as ./setup.sh would run it.++ The desktop launcher cannot ask for a password in a terminal, so its plan+ names the command; ./setup.sh installs the same packages itself.+ """+ manager = next((m for m in ('apt-get', 'dnf', 'yum', 'zypper') if which(m)), None)+ if manager is None:+ return None+ packages = []+ for name in names:+ package = {'g++': 'build-essential' if manager == 'apt-get' else 'gcc-c++',+ 'make': 'build-essential' if manager == 'apt-get' else 'make'}.get(name, name)+ if package not in packages:+ packages.append(package)+ install = {'apt-get': 'apt-get install -y', 'dnf': 'dnf install -y', 'yum': 'yum install -y',+ 'zypper': 'zypper --non-interactive install'}[manager]+ privilege = '' if (root if root is not None else os.geteuid() == 0) else 'sudo '+ update = privilege + 'apt-get update && ' if manager == 'apt-get' else ''+ return update + privilege + install + ' ' + ' '.join(packages)++def source_root():"""Find the checkout/ZIP by package location, never by the caller's cwd.diff --git a/freevideo_engine/two_pass.py b/freevideo_engine/two_pass.pyindex bde5664..dc94171 100644--- a/freevideo_engine/two_pass.py+++ b/freevideo_engine/two_pass.py@@ -150,6 +150,12 @@ def ensure_checkpoint():return path+# Host RAM the upscaler needs beside a resident engine. latent_upscale moves+# each checkpoint tensor (at most 13.5 MiB) to the device as it is read; this+# covers one in flight plus the reader's buffers, with ample margin.+UPSCALER_HOST_BYTES = 256 * 2**20++def upscale_workspace(canvas):"""Conservative admission estimate, not a measured capacity guarantee."""latent_frames = (canvas['frames'] - 5) // 17 * 5 + 2@@ -165,12 +171,15 @@ def upscale_workspace(canvas):WINDOWS_PASS_CACHE_MARGIN = 512 * 2**20-def pass_cache_allowance(budget, peak_reserved, free, reserve, commit_available=None, windows=None):+def pass_cache_allowance(budget, peak_reserved, free, reserve, commit_available=None, windows=None,+ device_free=None):"""Spare capacity after one real step, bounded independently by live space.Keep another 512 MiB beyond the existing OS reserve for pass-local growth,and on Windows another WINDOWS_PASS_CACHE_MARGIN below the local budget.Windows GPU allocations can also consume commit; retain host workspace.+ `device_free` is what the whole device can still take with every other+ process counted (Windows' budget and CUDA's free memory leave them out)."""if windows is None:import os@@ -178,6 +187,8 @@ def pass_cache_allowance(budget, peak_reserved, free, reserve, commit_available=if windows:budget -= WINDOWS_PASS_CACHE_MARGINbounds = [budget - peak_reserved, free - reserve]+ if device_free is not None:+ bounds.append(device_free - reserve)if commit_available is not None:# Sampling workspace has already been exercised. This cache creates no# new host tensors, so do not reserve the full model-loading allowancediff --git a/freevideo_engine/version_cleanup.py b/freevideo_engine/version_cleanup.pyindex 34a6b11..72dcd95 100644--- a/freevideo_engine/version_cleanup.py+++ b/freevideo_engine/version_cleanup.py@@ -414,7 +414,8 @@ def run(*, launcher_root=None, launcher_source=None, launcher_build=None, runnincomfy_root=None, engine_source=None, server_source=None, receipt=True):"""Remove what the current launcher and installation no longer use; report what was freed."""from .locking import runtime_lock- result = dict(released_bytes=0, removed=[], kept=[])+ # download_bytes: installer downloads this installation no longer needs (PyTorch wheels), part of released_bytes.+ result = dict(released_bytes=0, download_bytes=0, removed=[], kept=[])snapshot = references()def drop(path, root, kind):@@ -501,12 +502,21 @@ def run(*, launcher_root=None, launcher_source=None, launcher_build=None, runninfor path in environments(engine, current):drop(path, engine, 'comfyui-environment')result['released_bytes'] += finish_retired(engine / 'envs', engine, ENVIRONMENT)+ # Offline package extractions and download leftovers that duplicate verified model files.+ from .package_cleanup import run as package_leftovers+ leftovers = package_leftovers(engine, comfy_root, running=snapshot)+ result['released_bytes'] += leftovers['released_bytes']+ result['removed'] += leftovers['removed']+ result['kept'] += leftovers['kept']+ result['copied_model_bytes'] = leftovers['copied_model_bytes']+ result['copied_model_reason'] = leftovers['copied_model_reason']if machine and machine.get('ready') is True and all(python.is_file() for python in pythons):for path in torch_wheels(engine, pythons):try:size = path.stat().st_sizepath.unlink()result['released_bytes'] += size+ result['download_bytes'] += sizeresult['removed'].append(dict(kind='torch-wheel', path=str(path), bytes=size))except OSError:result['kept'].append(dict(kind='torch-wheel', path=str(path), reason='in use'))diff --git a/freevideo_engine/windows_ux.py b/freevideo_engine/windows_ux.pyindex ec9657c..eef47fc 100644--- a/freevideo_engine/windows_ux.py+++ b/freevideo_engine/windows_ux.py@@ -22,6 +22,16 @@ def open_browser(url):import osos.startfile(url)return True+ from .linux_bundle import child_environment, frozen_linux+ if frozen_linux():+ # webbrowser would hand the launcher's own environment to the browser.+ import shutil+ import subprocess+ opener = shutil.which('xdg-open')+ if opener:+ subprocess.Popen([opener, url], env=child_environment(), stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)+ return Trueimport webbrowserreturn webbrowser.open(url, new=2)diff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.pyindex 1db4750..d2eb52a 100644--- a/freevideo_engine/worker.py+++ b/freevideo_engine/worker.py@@ -92,7 +92,7 @@ def generate(request, resident=None):live_budget = LiveGPUBudget(torch, metrics['device_memory'],request.get('gpu_capacity_bytes', metrics['device_memory']['device_total_bytes']) - reserve, reserve)- def refresh_budget(stage, reclaim=None):+ def refresh_budget(stage, reclaim=None, workspace=None):def release(target):if reclaim is not None:reclaim(target)@@ -102,10 +102,13 @@ def generate(request, resident=None):breakif role != 'engine' or stage == 'decode':resident.drop(role, 'Live GPU budget decreased')- limit = live_budget.refresh(stage, release)+ limit = live_budget.refresh(stage, release, workspace=workspace)if resident is not None:resident.gpu_budget = limitreturn limit+ if live_budget is not None:+ # The pass cache grows only into memory no other process holds.+ refresh_budget.device_headroom = live_budget.device_headroomif resident is not None:limit = metrics['device_memory'].get('effective_allocator_limit_bytes')if limit is not None:@@ -279,8 +282,12 @@ def generate(request, resident=None):if live_budget is not None:refresh_budget('upscale')need = upscale_workspace(sampling_plan['upscale_target']) if sampling_plan['upscaler_sha256'] else 0- if need and resident is not None and not resident.ram_fits(2 * 2**30):- resident.make_room('latent_upscaler', need, ram_need=2 * 2**30)+ # Its weights go straight to the GPU. Charging 2 GiB of+ # host RAM evicted the second pass's own engine on+ # tight-RAM machines, which then reloaded every block.+ from .two_pass import UPSCALER_HOST_BYTES+ if need and resident is not None and not resident.ram_fits(UPSCALER_HOST_BYTES):+ resident.make_room('latent_upscaler', need, ram_need=UPSCALER_HOST_BYTES)torch.cuda.empty_cache()def upscale_available():free, _ = torch.cuda.mem_get_info()@@ -321,7 +328,7 @@ def generate(request, resident=None):else:engine.close()if resident is not None:- resident.make_room('latent_upscaler', need, ram_need=2 * 2**30)+ resident.make_room('latent_upscaler', need, ram_need=UPSCALER_HOST_BYTES)import gcgc.collect()torch.cuda.empty_cache()diff --git a/scripts/bootstrap_linux.sh b/scripts/bootstrap_linux.shindex c1e8c22..b5ebc2f 100644--- a/scripts/bootstrap_linux.sh+++ b/scripts/bootstrap_linux.sh@@ -36,9 +36,11 @@ fv_help() {cat <<'EOF'FreeVideo Linux launcher- ./setup.sh Detect missing tools, prepare Python, then review installation+ ./setup.sh Install FreeVideo and ComfyUI, then open FreeVideo in the browser+ ./freevideo Open FreeVideo again (starts ComfyUI in the background if needed)+ ./freevideo server Keep FreeVideo running for other computers; see ./freevideo server --help+ ./freevideo stop Stop ComfyUI; ./freevideo status shows whether it runs./test.sh Generate and retain videos, timings and memory reports- ./freevideo optimize Validate lightweight tuning from the previous test./freevideo diagnose Export a small local diagnostic ZIPSetup launcher options:@@ -50,6 +52,7 @@ Setup launcher options:--network official Upstream sources only; compare proxy/direct connections--model-downloader xet Require HF Xet for large weights; stop instead of falling back--reuse-models PATH Verify and reuse compatible models in an existing folder+ --no-launch Stop after the engine; do not install ComfyUI or open FreeVideoNo Python, pip, virtual environment or CUDA toolkit installation is needed beforehand.Default installation: this checkout's directory (independent of the current directory).@@ -279,7 +282,11 @@ freevideo_bootstrap_linux() {export FREEVIDEO_HOME="$fv_root"export FREEVIDEO_BOOTSTRAP_ROOT="${FREEVIDEO_BOOTSTRAP_ROOT:-$fv_root/.freevideo/bootstrap}"[[ "$mode" != cli || "$command_name" != setup ]] || mode=setup- [[ "$mode" != cli || -n "$command_name" ]] || help=1+ # ./freevideo alone opens an installed FreeVideo. Before ./setup.sh it only+ # shows how to install: nothing is downloaded without that explicit step.+ if [[ "$mode" == cli && -z "$command_name" ]] && (( ! help )); then+ if [[ -f "$fv_root/machine.json" ]]; then command_name=open; FREEVIDEO_BOOTSTRAP_ARGS+=(open); else help=1; fi+ fiif (( bootstrap_only || fv_allow_system )) && [[ "$mode" != setup ]]; thenfv_fail '--bootstrap-only and --install-system-deps are setup options.'; return 1fidiff --git a/scripts/build_linux.py b/scripts/build_linux.pynew file mode 100644index 0000000..b1988c2--- /dev/null+++ b/scripts/build_linux.py@@ -0,0 +1,245 @@+"""Build the shared launcher as a Linux x86_64 AppImage with Python 3.12.++The release workflow runs this in a manylinux_2_34 container: PySide6 6.11 needs+glibc 2.34, so the AppImage starts on Ubuntu 22.04, Debian 12, Fedora 36, RHEL 9+and newer (older systems use ./setup.sh). The Python must have a shared libpython (a+python-build-standalone build, as `uv python install 3.12` provides) with+constraints/linux-launcher.txt installed. appimagetool and the AppImage runtime+are pinned and verified before they run.+"""+import argparse+import hashlib+import json+import os+from pathlib import Path+import platform+import re+import shutil+import subprocess+import sys+import sysconfig+import urllib.request++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))+from freevideo_engine.desktop_runtime import check_launcher_dependencies, source_files+from freevideo_engine.launcher_update import LINUX_CHANNEL, RELEASE_ASSETS, build_identity+from freevideo_engine.release_notes import markdown+from scripts.build_launcher_notices import collect as collect_notices+from scripts.build_windows import build_info, bundle_data_args, stamp_source++APP_ID = 'org.flashml.FreeVideo'+NAME = RELEASE_ASSETS[LINUX_CHANNEL][0]+TOOLS = {+ 'appimagetool': dict(url='https://github.com/AppImage/appimagetool/releases/download/1.9.1/appimagetool-x86_64.AppImage',+ sha256='ed4ce84f0d9caff66f50bcca6ff6f35aae54ce8135408b3fa33abfc3cb384eb0'),+ 'runtime': dict(url='https://github.com/AppImage/type2-runtime/releases/download/20251108/runtime-x86_64',+ sha256='2fca8b443c92510f1483a883f60061ad09b46b978b2631c807cd873a47ec260d'),+ # Noto Sans CJK SC 2.004 (SIL Open Font License 1.1), cut down to the launcher's own characters.+ 'font-regular': dict(url='https://raw.githubusercontent.com/notofonts/noto-cjk/Sans2.004/Sans/OTF/SimplifiedChinese/NotoSansCJKsc-Regular.otf',+ sha256='2c76254f6fc379fddfce0a7e84fb5385bb135d3e399294f6eeb6680d0365b74b'),+ 'font-bold': dict(url='https://raw.githubusercontent.com/notofonts/noto-cjk/Sans2.004/Sans/OTF/SimplifiedChinese/NotoSansCJKsc-Bold.otf',+ sha256='b5f0d1a190a7f9b43c310a8850630af12553df32c4c050543f9059732d9b4c0a'),+ 'font-license': dict(url='https://raw.githubusercontent.com/notofonts/noto-cjk/Sans2.004/LICENSE',+ sha256='6a73f9541c2de74158c0e7cf6b0a58ef774f5a780bf191f2d7ec9cc53efe2bf2'),+}+FONT_FAMILY = 'FreeVideo Sans SC'+# Characters the launcher can show that desktop Latin fonts may lack: Chinese text+# (pages, messages, release notes) and the arrows and check marks next to it+# (✓ for a finished step, ↗ for a link); Noto Sans, for one, has neither.+CJK = re.compile(r'[\u2190-\u21ff\u2700-\u27bf\u2e80-\u9fff\uf900-\ufaff\ufe30-\ufe4f\uff00-\uffef\u3000-\u303f]')+# Qt's X11 platform plugin needs these, and common desktop installations lack+# some of them (libxcb-cursor0 above all). Everything else, glibc, the GPU+# driver's libGL/libEGL, X11, Wayland, fontconfig and freetype, comes from the+# system the AppImage runs on.+SYSTEM_LIBRARIES = ('libxcb-cursor.so.0', 'libxcb-icccm.so.4', 'libxcb-image.so.0', 'libxcb-keysyms.so.1',+ 'libxcb-render-util.so.0', 'libxcb-util.so.1', 'libxkbcommon-x11.so.0', 'libxkbcommon.so.0')+DESKTOP = '''[Desktop Entry]+Type=Application+Name=FreeVideo+Comment=Install and open FreeVideo in ComfyUI+Comment[zh_CN]=安装并在 ComfyUI 中打开 FreeVideo+Exec=FreeVideo+Icon={app}+Terminal=false+Categories=AudioVideo;Video;Graphics;+StartupWMClass=FreeVideo+'''.format(app=APP_ID)+APP_RUN = '''#!/bin/sh+# The AppImage runtime sets APPDIR; resolve it here for extracted runs too.+HERE="$(dirname "$(readlink -f "$0")")"+exec "$HERE/usr/lib/FreeVideo/FreeVideo" "$@"+'''+++def identity(root):+ return build_identity(dict(build_info(root), channel=LINUX_CHANNEL, target='linux-x86_64', packaging='appimage'))+++def tool(cache, name):+ """A pinned tool, downloaded once and checked on every use."""+ spec = TOOLS[name]+ path = cache / Path(spec['url']).name+ if not path.is_file():+ cache.mkdir(parents=True, exist_ok=True)+ stage = path.with_suffix('.partial')+ with urllib.request.urlopen(spec['url'], timeout=60) as reply, stage.open('wb') as stream:+ shutil.copyfileobj(reply, stream)+ stage.replace(path)+ if hashlib.sha256(path.read_bytes()).hexdigest() != spec['sha256']:+ raise SystemExit('Pinned %s does not match its checksum: %s' % (name, path))+ if not name.startswith('font'):+ path.chmod(0o755)+ return path+++def launcher_characters(root):+ text = ''+ for path in [*(root / 'freevideo_engine').rglob('*.py'), *(root / 'freevideo_engine').rglob('*.qml'),+ *(root / 'freevideo_engine').glob('*.json')]:+ text += path.read_text(encoding='utf-8', errors='ignore')+ # Latin text uses the system's font; the subset covers Chinese and the symbols.+ return ''.join(sorted(set(CJK.findall(text))))+++def make_fonts(root, tools, destination):+ """Desktops without Chinese fonts would show the launcher's Chinese as boxes."""+ from fontTools import subset+ from fontTools.ttLib import TTFont+ characters = launcher_characters(root)+ destination.mkdir(parents=True)+ notices = set()+ for weight in ('Regular', 'Bold'):+ options = subset.Options()+ options.layout_features = ['*']+ # OFL 2: every copy keeps the copyright notice (0) and the licence (13, 14).+ options.name_IDs = [0, 13, 14]+ font = TTFont(tool(tools, 'font-' + weight.lower()))+ notices.add(font['name'].getDebugName(0))+ subsetter = subset.Subsetter(options)+ subsetter.populate(text=characters)+ subsetter.subset(font)+ # A renamed subset never stands in for a complete Noto Sans CJK the system has.+ for record, value in ((1, FONT_FAMILY), (2, weight), (4, FONT_FAMILY + ' ' + weight),+ (6, FONT_FAMILY.replace(' ', '') + '-' + weight), (16, FONT_FAMILY), (17, weight)):+ font['name'].setName(value, record, 3, 1, 0x409)+ font.save(destination / ('FreeVideoSansSC-%s.otf' % weight))+ # noto-cjk's LICENSE is the licence text alone; the copyright line comes from the font.+ if len(notices) != 1 or not all(notices):+ raise SystemExit('The bundled fonts do not carry one copyright notice: %r' % sorted(map(str, notices)))+ licence = tool(tools, 'font-license').read_text(encoding='utf-8')+ (destination / 'OFL.txt').write_text(notices.pop() + '\n\n' + licence, encoding='utf-8')+ return len(characters)+++def system_library(name, extra=None):+ """The build system's copy of a shared library: --libraries first, then the linker cache."""+ if extra is not None and (extra / name).exists():+ return extra / name+ listing = subprocess.run(['/sbin/ldconfig', '-p'], capture_output=True, text=True).stdout+ for line in listing.splitlines():+ parts = line.strip().split(' => ')+ if len(parts) == 2 and parts[0].split(' ')[0] == name and 'x86-64' in parts[0]:+ return Path(parts[1])+ return None+++def bundle_libraries(internal, extra=None):+ found = []+ for name in SYSTEM_LIBRARIES:+ if (internal / name).exists():+ continue+ path = system_library(name, extra)+ if path is None:+ raise SystemExit('Install %s on the build system; Qt needs it on desktops that lack it.' % name)+ shutil.copy2(path.resolve(), internal / name)+ found.append(name)+ return found+++def appdir(out, dist, icon):+ folder = out / 'AppDir'+ shutil.copytree(dist, folder / 'usr/lib/FreeVideo', symlinks=True)+ (folder / 'AppRun').write_text(APP_RUN, encoding='utf-8')+ (folder / 'AppRun').chmod(0o755)+ (folder / (APP_ID + '.desktop')).write_text(DESKTOP, encoding='utf-8')+ shutil.copyfile(icon, folder / (APP_ID + '.png'))+ themed = folder / 'usr/share/icons/hicolor/512x512/apps'+ themed.mkdir(parents=True)+ shutil.copyfile(icon, themed / (APP_ID + '.png'))+ (folder / '.DirIcon').symlink_to(APP_ID + '.png')+ return folder+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--out', type=Path, required=True)+ parser.add_argument('--tools', type=Path, help='Folder for the pinned appimagetool and runtime downloads')+ parser.add_argument('--libraries', type=Path, help='Folder searched first for the system libraries bundled for Qt')+ args = parser.parse_args()+ if platform.system() != 'Linux' or platform.machine() != 'x86_64' or sys.version_info[:2] != (3, 12):+ parser.error('Build this artifact on Linux x86_64 with Python 3.12')+ if not sysconfig.get_config_var('Py_ENABLE_SHARED'):+ parser.error('This Python has no shared libpython; use a python-build-standalone 3.12 (uv python install 3.12)')+ try:+ check_launcher_dependencies()+ from PySide6 import QtQml, QtQuick, QtQuickControls2, QtWidgets # noqa: F401+ except ImportError as error:+ parser.error('Launcher build dependencies are missing or broken: %s. Run this Python with '+ '-m pip install -r constraints/linux-launcher.txt before building.' % error)+ out = args.out.resolve()+ out.mkdir(parents=True, exist_ok=False)+ tools = (args.tools or out / 'tools').resolve()+ appimagetool, runtime = tool(tools, 'appimagetool'), tool(tools, 'runtime')+ build = identity(ROOT)+ build_file = out / 'launcher-build.json'+ build_file.write_text(json.dumps(build, indent=2), encoding='utf-8')+ staged = out / 'engine-source'+ for path in source_files(ROOT):+ if path.is_relative_to(ROOT / 'freevideo_engine/launcher/licenses/bundled'):+ continue+ target = staged / path.relative_to(ROOT)+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(path, target)+ stamp = stamp_source(staged, build)+ notices = staged / 'freevideo_engine/launcher/licenses/bundled'+ collect_notices(ROOT, notices)+ fonts = out / 'fonts'+ glyphs = make_fonts(ROOT, tools, fonts)+ shutil.copyfile(fonts / 'OFL.txt', notices / 'Noto-Sans-CJK-SC-OFL.txt')+ command = [sys.executable, '-m', 'PyInstaller', '--noconfirm', '--windowed', '--noupx', '--onedir',+ '--name', 'FreeVideo', '--distpath', str(out / 'dist'), '--workpath', str(out / 'build'), '--specpath', str(out),+ '--paths', str(ROOT), '--add-data', str(staged) + os.pathsep + 'engine-source',+ '--add-data', str(build_file) + os.pathsep + '.',+ '--add-data', str(stamp) + os.pathsep + 'freevideo_engine',+ '--add-data', str(stamp.parent / 'build-identity.json') + os.pathsep + 'freevideo_engine',+ '--add-data', str(notices) + os.pathsep + 'freevideo_engine/launcher/licenses/bundled',+ '--add-data', str(fonts) + os.pathsep + 'freevideo_engine/assets/fonts',+ *bundle_data_args(ROOT),+ '--hidden-import', 'psutil',+ # Run by name when the launcher supervises setup and ComfyUI (processes.module_command).+ '--hidden-import', 'freevideo_engine.linux_process_host',+ '--exclude-module', 'torch', '--exclude-module', 'triton', '--exclude-module', 'numpy',+ '--exclude-module', 'transformers', '--exclude-module', 'tkinter',+ str(ROOT / 'scripts/linux_app.py')]+ subprocess.run(command, cwd=ROOT, check=True)+ dist = out / 'dist' / 'FreeVideo'+ bundled = bundle_libraries(dist / '_internal', args.libraries.resolve() if args.libraries else None)+ folder = appdir(out, dist, ROOT / 'freevideo_engine/assets/icon.png')+ release = out / 'release'+ release.mkdir()+ executable = release / NAME+ env = dict(os.environ, ARCH='x86_64', APPIMAGE_EXTRACT_AND_RUN='1')+ subprocess.run([str(appimagetool), '--no-appstream', '--runtime-file', str(runtime), str(folder), str(executable)],+ cwd=out, env=env, check=True)+ digest = hashlib.sha256(executable.read_bytes()).hexdigest()+ (release / 'SHA256SUMS.txt').write_text(digest + ' ' + NAME + '\n', encoding='utf-8')+ (release / 'launcher-build.json').write_text(json.dumps(build, indent=2), encoding='utf-8')+ (release / 'RELEASE_NOTES.md').write_text(markdown(build), encoding='utf-8')+ shutil.copytree(notices, release / 'licenses')+ print(json.dumps({'appimage': str(executable), 'bytes': executable.stat().st_size, 'sha256': digest,+ 'bundled_system_libraries': bundled, 'font_characters': glyphs}))+++if __name__ == '__main__':+ main()diff --git a/scripts/linux_app.py b/scripts/linux_app.pynew file mode 100644index 0000000..5bb6997--- /dev/null+++ b/scripts/linux_app.py@@ -0,0 +1,5 @@+"""PyInstaller entry point for the Linux AppImage; model modules stay out of the launcher."""+from freevideo_engine.modern_launcher import main++if __name__ == '__main__':+ main()diff --git a/scripts/publish_release.py b/scripts/publish_release.pyindex 4c44c72..aca1ff5 100644--- a/scripts/publish_release.py+++ b/scripts/publish_release.py@@ -1,10 +1,11 @@"""Publish the built launchers: the rolling nightly, or a stable vX.Y.Z release for every platform.-The release workflow runs this after the Windows and Mac jobs. A stable release also refreshes the-platform tags (windows-preview, macos-preview) that launchers from before combined releases read.+The release workflow runs this after the Windows, Mac and Linux jobs. A stable release also refreshes+the platform tags (windows-preview, macos-preview) that launchers from before combined releases read;+Linux has no such launchers.Writes go through the gh CLI with retries. Update metadata is uploaded last and bound to theimmutable asset IDs, so a reader never pairs new metadata with an old executable.-Usage: publish_release.py --track stable|nightly --windows DIR --macos DIR --sha COMMIT+Usage: publish_release.py --track stable|nightly --windows DIR --macos DIR --linux DIR --sha COMMIT"""import argparseimport hashlib@@ -19,11 +20,13 @@ import timeROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT))-from freevideo_engine.launcher_update import (CHANNEL, MAC_CHANNEL, NIGHTLY_TAG, RELEASE_ASSETS, # noqa: E402- build_identity, build_track)+from freevideo_engine.launcher_update import (CHANNEL, LINUX_CHANNEL, MAC_CHANNEL, NIGHTLY_TAG, # noqa: E402+ RELEASE_ASSETS, build_identity, build_track)from freevideo_engine.release_notes import notes # noqa: E402-PLATFORMS = (CHANNEL, MAC_CHANNEL)+PLATFORMS = (CHANNEL, MAC_CHANNEL, LINUX_CHANNEL)+LEGACY_PLATFORMS = (CHANNEL, MAC_CHANNEL)+NAMES = {CHANNEL: 'Windows', MAC_CHANNEL: 'Mac', LINUX_CHANNEL: 'Linux'}PAGE = 'https://github.com/FlashML-org/FreeVideo'LOGO = '''<div align="center"><picture>@@ -66,9 +69,9 @@ def digest(path):return value.hexdigest()-def load_builds(windows, macos):+def load_builds(windows, macos, linux):builds = {}- for channel, folder in ((CHANNEL, Path(windows)), (MAC_CHANNEL, Path(macos))):+ for channel, folder in ((CHANNEL, Path(windows)), (MAC_CHANNEL, Path(macos)), (LINUX_CHANNEL, Path(linux))):raw = json.loads((folder / 'launcher-build.json').read_text(encoding='utf-8'))identity = build_identity(raw)if identity['channel'] != channel:@@ -80,9 +83,9 @@ def load_builds(windows, macos):versions = {b['identity'].get('product_version') for b in builds.values()}tracks = {build_track(b['identity']) for b in builds.values()}if len(versions) != 1 or None in versions:- raise SystemExit('Windows and Mac builds must carry the same product version: %s' % sorted(map(str, versions)))+ raise SystemExit('The Windows, Mac and Linux builds must carry the same product version: %s' % sorted(map(str, versions)))if len(tracks) != 1:- raise SystemExit('Windows and Mac builds come from different release tracks')+ raise SystemExit('The Windows, Mac and Linux builds come from different release tracks')return builds@@ -104,7 +107,8 @@ def whats_new(raw):def downloads(base):return ['| | |', '|---|---|','| **Windows** 10/11 · NVIDIA GPU | [FreeVideo.exe](%sFreeVideo.exe) |' % base,- '| **macOS** 14+ · Apple silicon | [FreeVideo-Mac-arm64.dmg](%sFreeVideo-Mac-arm64.dmg) |' % base, '']+ '| **macOS** 14+ · Apple silicon | [FreeVideo-Mac-arm64.dmg](%sFreeVideo-Mac-arm64.dmg) |' % base,+ '| **Linux** x86_64 · NVIDIA GPU | [FreeVideo-Linux-x86_64.AppImage](%sFreeVideo-Linux-x86_64.AppImage) |' % base, '']def checksums(builds):@@ -121,11 +125,17 @@ def stable_body(builds, tag):'**macOS:** open the DMG and drag FreeVideo.app into Applications. If macOS asks you to confirm the first ''launch, see the [first-open steps](%s/blob/main/docs/Mac.md#first-open).' % PAGE,'',+ '**Linux:** make the AppImage executable (`chmod +x FreeVideo-Linux-x86_64.AppImage`) and open it, as on '+ 'Windows. On a server or from a terminal, see [Linux](%s/blob/main/docs/Linux.md).' % PAGE,+ '','**Windows:** 运行 FreeVideo.exe,选择已有的 ComfyUI 或安装新的 ComfyUI,点击 **安装并启动**。''离线包见[夸克网盘](https://pan.quark.cn/s/c51235b84618)。','','**macOS:** 打开 DMG,将 FreeVideo.app 拖入「应用程序」。首次打开如需确认,请参考''[首次打开步骤](%s/blob/main/docs/Mac.zh-CN.md#首次打开)。' % PAGE,+ '',+ '**Linux:** 给 AppImage 加上可执行权限(`chmod +x FreeVideo-Linux-x86_64.AppImage`)后打开,用法与 Windows 相同。'+ '在服务器或终端中使用请参考 [Linux 说明](%s/blob/main/docs/Linux.zh-CN.md)。' % PAGE,'']rows += whats_new(builds[CHANNEL]['raw'])rows += checksums(builds)@@ -143,10 +153,10 @@ def nightly_body(builds, sha):'基于 `main` 的自动构建,每次合并后更新。日常使用请下载[最新正式版](%s/releases/latest)。' % PAGE,'']rows += downloads(PAGE + '/releases/download/' + NIGHTLY_TAG + '/')- rows += ['| commit | built (UTC) | version | Windows | macOS |', '|---|---|---|---|---|',- '| [`%s`](%s/commit/%s) | %s | %s | %s | %s |' % (sha[:9], PAGE, sha, built,- escape('v' + builds[CHANNEL]['identity']['product_version']),- size[CHANNEL], size[MAC_CHANNEL]), '']+ rows += ['| commit | built (UTC) | version | Windows | macOS | Linux |', '|---|---|---|---|---|---|',+ '| [`%s`](%s/commit/%s) | %s | %s | %s | %s | %s |' % (sha[:9], PAGE, sha, built,+ escape('v' + builds[CHANNEL]['identity']['product_version']),+ size[CHANNEL], size[MAC_CHANNEL], size[LINUX_CHANNEL]), '']rows += checksums(builds)return '\n'.join(rows)@@ -218,9 +228,9 @@ def publish_stable(releases, builds, sha, folder):gh('Publish %s' % tag, 'release', 'edit', tag, '--draft=false', '--prerelease=false', '--latest','--title', title, '--notes-file', body)# Launchers from before combined releases read the platform tags; keep them current.- for channel in PLATFORMS:+ for channel in LEGACY_PLATFORMS:build = builds[channel]- name = 'Windows' if channel == CHANNEL else 'Mac'+ name = NAMES[channel]legacy = write(folder, 'legacy-%s.md' % channel,'The latest FreeVideo is on the [latest release](%s/releases/latest) page.\n\n''最新版本请前往[最新正式版](%s/releases/latest)下载。\n' % (PAGE, PAGE))@@ -284,10 +294,11 @@ def main():parser.add_argument('--track', choices=('stable', 'nightly'), required=True)parser.add_argument('--windows', type=Path, required=True)parser.add_argument('--macos', type=Path, required=True)+ parser.add_argument('--linux', type=Path, required=True)parser.add_argument('--sha', required=True)parser.add_argument('--repository', default=os.environ.get('GH_REPO', 'FlashML-org/FreeVideo'))args = parser.parse_args()- builds = load_builds(args.windows, args.macos)+ builds = load_builds(args.windows, args.macos, args.linux)if build_track(builds[CHANNEL]['identity']) != args.track:raise SystemExit('The builds are %s builds, not %s' % (build_track(builds[CHANNEL]['identity']), args.track))releases = Releases(args.repository)diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjsindex a1c8da3..5bede02 100644--- a/scripts/test_freevideo_entry.mjs+++ b/scripts/test_freevideo_entry.mjs@@ -44,7 +44,7 @@ test('main browser entry registers both views and preserves node hooks', async (refreshNavigation: () => refreshed++, preferredView: () => null,attachReferencePicker() {}, referenceItems: () => [], syncReferencePrompt() {},shareButton: () => new Element('button'), reportFileName: () => 'FreeVideo-report-20261008-101530.json',- rememberPromptDraft() {}, savePromptDraft: async () => false,+ rememberPromptDraft() {}, savePromptDraft: async () => false, openImageEditor: async () => null, icon: () => '',};const previous = new Map();for (const [name, value] of Object.entries({@@ -72,6 +72,7 @@ test('main browser entry registers both views and preserves node hooks', async (.replace("import { reportFileName } from './report_issue.js';", 'const {reportFileName} = globalThis.__freevideoEntryTest;').replace("import { rememberPromptDraft, savePromptDraft } from './prompt_draft.js';", 'const {rememberPromptDraft,savePromptDraft} = globalThis.__freevideoEntryTest;').replace("import { regenerateResult, upscaleResult } from './studio_queue.js';", 'const {regenerateResult,upscaleResult} = globalThis.__freevideoEntryTest;')+ .replace("import { openImageEditor, icon } from './image_editor.js';", 'const {openImageEditor,icon} = globalThis.__freevideoEntryTest;').replace("import { installNavigation, refreshNavigation, preferredView } from './view_navigation.js';", 'const {installNavigation,refreshNavigation,preferredView} = globalThis.__freevideoEntryTest;');await import('data:text/javascript;base64,' + Buffer.from(source).toString('base64'));const extension = extensions.find(row => row.name === 'FreeVideo.UnifiedMedia');diff --git a/web/assets/icon.svg b/web/assets/icon.svgindex 2f0e4c9..a0a0dce 100644--- a/web/assets/icon.svg+++ b/web/assets/icon.svg@@ -1,5 +1,5 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="FreeToken">- <title>FreeToken</title>+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="FreeVideo">+ <title>FreeVideo</title><rect x="0" y="0" width="512" height="512" rx="115" fill="#14171c"></rect><g color="#58a6f0"><g transform="translate(0.0,0.0) scale(1)"><g transform="translate(19.8,23.8) scale(0.5556) skewX(-9.486)">diff --git a/web/fonts.js b/web/fonts.jsnew file mode 100644index 0000000..44789b1--- /dev/null+++ b/web/fonts.js@@ -0,0 +1,55 @@+// Fonts for text that FreeVideo draws into pictures and videos (the image editor's text+// layers, the share card): open-source faces that ship with FreeVideo in web/fonts, built+// by scripts/build_web_fonts.py. A font installed on the computer is never used for them:+// each stack ends with FreeVideo Box, whose one glyph, a box, stands for every character,+// so a character none of the bundled fonts has shows a box instead of a system font.+const FAMILIES = {+ sans: {family: 'FreeVideo Sans SC', files: {400: 'FreeVideoSansSC-Regular.woff2', 700: 'FreeVideoSansSC-Bold.woff2'}},+ serif: {family: 'FreeVideo Serif SC', files: {400: 'FreeVideoSerifSC-Regular.woff2', 700: 'FreeVideoSerifSC-Bold.woff2'}},+ // LXGW WenKai has no bold: its Medium is the heavier face, served as weight 700.+ kai: {family: 'FreeVideo Kai SC', files: {400: 'FreeVideoKaiSC-Regular.woff2', 700: 'FreeVideoKaiSC-Medium.woff2'}},+ mono: {family: 'FreeVideo Mono SC', files: {400: 'FreeVideoMonoSC-Regular.woff2', 700: 'FreeVideoMonoSC-Bold.woff2'}},+};+// One face for every weight, so a bold line never gets a synthesized bold box.+const BOX = {family: 'FreeVideo Box', file: 'FreeVideoBox.woff2', weights: '100 900'};+export const FONT_KEYS = Object.keys(FAMILIES);+export const FONT_WEIGHTS = [400, 700];++const key = name => FAMILIES[name] ? name : 'sans';+// The bundled weight nearest to the one asked for.+export const fontWeight = weight => Number(weight) >= 550 ? 700 : 400;+export function fontFamily(name) { return FAMILIES[key(name)].family; }+// The CSS font list for a family: itself, the sans for what it lacks, then the box.+export function fontStack(name) {+ const k = key(name), names = [FAMILIES[k].family];+ if (k !== 'sans') names.push(FAMILIES.sans.family);+ names.push(BOX.family);+ return names.map(family => `"${family}"`).join(',');+}+export const fontCSS = (name, weight, size) => `${fontWeight(weight)} ${size}px ${fontStack(name)}`;++const faces = new Map(), ready = new Set();+function face(family, file, weight, descriptor = String(weight)) {+ const id = `${family}@${weight}`;+ if (!faces.has(id)) {+ const url = new URL(`./fonts/${file}`, import.meta.url).href;+ const font = new FontFace(family, `url("${url}") format("woff2")`, {weight: descriptor, style: 'normal', display: 'block'});+ document.fonts.add(font);+ // A face that failed to load is tried again next time.+ faces.set(id, font.load().then(() => { ready.add(id); }, error => { faces.delete(id); document.fonts.delete(font); throw error; }));+ }+ return faces.get(id);+}+// Load what drawing a family at a weight needs: that face, the sans fallback at the same weight and the box.+export function loadFont(name, weight = 400) {+ const k = key(name), w = fontWeight(weight), loads = [face(FAMILIES[k].family, FAMILIES[k].files[w], w), face(BOX.family, BOX.file, 400, BOX.weights)];+ if (k !== 'sans') loads.push(face(FAMILIES.sans.family, FAMILIES.sans.files[w], w));+ return Promise.all(loads);+}+// Whether a family at a weight is ready to draw now (measuring before that would use other metrics).+export function fontLoaded(name, weight = 400) {+ const k = key(name), w = fontWeight(weight);+ return ready.has(`${FAMILIES[k].family}@${w}`) && ready.has(`${BOX.family}@400`)+ && (k === 'sans' || ready.has(`${FAMILIES.sans.family}@${w}`));+}+export const loadFonts = pairs => Promise.all(pairs.map(([name, weight]) => loadFont(name, weight)));diff --git a/web/fonts/FreeVideoBox.woff2 b/web/fonts/FreeVideoBox.woff2new file mode 100644index 0000000..c476161Binary files /dev/null and b/web/fonts/FreeVideoBox.woff2 differdiff --git a/web/fonts/FreeVideoKaiSC-Medium.woff2 b/web/fonts/FreeVideoKaiSC-Medium.woff2new file mode 100644index 0000000..24eb560Binary files /dev/null and b/web/fonts/FreeVideoKaiSC-Medium.woff2 differdiff --git a/web/fonts/FreeVideoKaiSC-Regular.woff2 b/web/fonts/FreeVideoKaiSC-Regular.woff2new file mode 100644index 0000000..7dd131fBinary files /dev/null and b/web/fonts/FreeVideoKaiSC-Regular.woff2 differdiff --git a/web/fonts/FreeVideoMonoSC-Bold.woff2 b/web/fonts/FreeVideoMonoSC-Bold.woff2new file mode 100644index 0000000..7613c41Binary files /dev/null and b/web/fonts/FreeVideoMonoSC-Bold.woff2 differdiff --git a/web/fonts/FreeVideoMonoSC-Regular.woff2 b/web/fonts/FreeVideoMonoSC-Regular.woff2new file mode 100644index 0000000..46d45ceBinary files /dev/null and b/web/fonts/FreeVideoMonoSC-Regular.woff2 differdiff --git a/web/fonts/FreeVideoSansSC-Bold.woff2 b/web/fonts/FreeVideoSansSC-Bold.woff2new file mode 100644index 0000000..6d61a28Binary files /dev/null and b/web/fonts/FreeVideoSansSC-Bold.woff2 differdiff --git a/web/fonts/FreeVideoSansSC-Regular.woff2 b/web/fonts/FreeVideoSansSC-Regular.woff2new file mode 100644index 0000000..f013c5bBinary files /dev/null and b/web/fonts/FreeVideoSansSC-Regular.woff2 differdiff --git a/web/fonts/FreeVideoSerifSC-Bold.woff2 b/web/fonts/FreeVideoSerifSC-Bold.woff2new file mode 100644index 0000000..cb97675Binary files /dev/null and b/web/fonts/FreeVideoSerifSC-Bold.woff2 differdiff --git a/web/fonts/FreeVideoSerifSC-Regular.woff2 b/web/fonts/FreeVideoSerifSC-Regular.woff2new file mode 100644index 0000000..dbb933dBinary files /dev/null and b/web/fonts/FreeVideoSerifSC-Regular.woff2 differdiff --git a/web/freevideo.js b/web/freevideo.jsindex cdf9f06..681bf70 100644--- a/web/freevideo.js+++ b/web/freevideo.js@@ -13,6 +13,7 @@ import { shareButton } from './share.js';import { reportFileName } from './report_issue.js';import { rememberPromptDraft, savePromptDraft } from './prompt_draft.js';import { regenerateResult, upscaleResult } from './studio_queue.js';+import { openImageEditor, icon } from './image_editor.js';const languageOverride = typeof location !== 'undefined'? new URLSearchParams(location.search).get('freevideo_lang') : null;@@ -98,6 +99,65 @@ function mediaPanel(node, mount = null) {const update = rows => { serialized.value = JSON.stringify(rows); node.graph?.change(); window.dispatchEvent(new CustomEvent('freevideo-media', {detail: node.id})); };const changed = event => { if (String(event.detail) === String(node.id)) render(); };window.addEventListener('freevideo-media', changed);+ // The video this panel feeds: its canvas is the natural shape for a keyframe crop.+ const graphLink = id => node.graph?.links?.get?.(id) ?? node.graph?.links?.[id];+ const videoSize = () => {+ for (const other of node.graph?._nodes || node.graph?.nodes || []) {+ const input = other.inputs?.find(i => i.name === 'media' && i.link != null);+ if (!input || String(graphLink(input.link)?.origin_id) !== String(node.id)) continue;+ const size = name => Number(other.widgets?.find(w => w.name === name)?.value);+ if (size('width') > 0 && size('height') > 0) return {width: size('width'), height: size('height')};+ }+ return null;+ };+ // One file into ComfyUI's input folder, through FreeVideo's streaming upload.+ async function uploadOne(file) {+ const body = new FormData(); body.append('file', file);+ const response = await api.fetchApi('/freevideo/media/upload', {method: 'POST', body});+ const result = await response.json(); if (!response.ok) throw new Error(result.error || response.statusText);+ return result;+ }+ async function editImage(file, tool = null) {+ if (node.isUploading) return;+ const original = read().find(row => row.file === file);+ if (!original) return;+ const source = original.source || original.file;+ // Other pictures in this panel can be placed on the image as layers.+ const library = read().filter(row => row.file !== file && mediaKind(row.file) === 'image')+ .map(row => ({file: row.file, label: (row.source || row.file).split('/').pop()}));+ let outcome;+ try {+ outcome = await openImageEditor({source, name: source, target: videoSize(), edit: original.edit || null, role: original.role,+ t: text, resolve: viewURL, upload: uploadOne, library, tool});+ } catch (error) { message(text('The image could not be opened for editing.', '这张图片无法打开编辑。'), true); return; }+ if (!outcome) return;+ // The cards may have changed meanwhile; find this one again by its file.+ const rows = read(), at = rows.findIndex(row => row.file === file);+ if (at < 0) return;+ if (outcome.restore) {+ const {source: kept, edit: _, ...rest} = rows[at];+ rows[at] = {...rest, file: kept || rest.file}; update(rows);+ message(text('Restored the original image.', '已恢复原图。')); return;+ }+ node.isUploading = true; add.disabled = true; addAudio.disabled = true;+ message(text('Uploading the edited image…', '正在上传编辑后的图片…'));+ try {+ const result = await uploadOne(new File([outcome.blob], outcome.name, {type: outcome.blob.type}));+ const latest = read(), index = latest.findIndex(row => row.file === file);+ if (index < 0) return;+ latest[index] = {...latest[index], file: result.file, source, edit: outcome.edit}; update(latest);+ message(text(`Saved the edited image, ${outcome.width}×${outcome.height}. The original is kept.`,+ `已保存编辑后的图片(${outcome.width}×${outcome.height}),原图保留。`));+ } catch (error) { message(error.message, true); }+ finally { node.isUploading = false; add.disabled = false; addAudio.disabled = false; }+ }+ function restoreImage(file) {+ const rows = read(), at = rows.findIndex(row => row.file === file);+ if (at < 0 || !rows[at].source) return;+ const {source, edit: _, ...rest} = rows[at];+ rows[at] = {...rest, file: source}; update(rows);+ message(text('Restored the original image. Edit it again to reapply the changes.', '已恢复原图;再次编辑可以重新应用修改。'));+ }function render() {for (const preview of cards.querySelectorAll("video,audio")) {preview.pause(); preview.removeAttribute("src"); preview.load();@@ -131,19 +191,45 @@ function mediaPanel(node, mount = null) {const top = el("div", undefined, "fv-row");const enabled = el("input"); enabled.type = "checkbox"; enabled.checked = row.enabled !== false;enabled.setAttribute("aria-label", text("Use media", "使用素材")); enabled.onchange = () => { rows[index].enabled = enabled.checked; update(rows); };- const label = el("span", row.file.split("/").pop(), "fv-file"); label.title = row.file;+ const label = el("span", (row.source || row.file).split("/").pop(), "fv-file"); label.title = row.file;const select = el("select"); select.setAttribute("aria-label", text("Media role", "素材用途"));const kind = mediaKind(row.file);for (const [value, title] of (kind === "image" ? [["reference", text("Reference", "参考")], ["first", text("First frame", "首帧")], ["last", text("Last frame", "尾帧")]] : [["reference", text("Reference", "参考")]])) {const option = el("option", title); option.value = value; select.append(option);}select.value = row.role; select.onchange = () => { rows[index].role = select.value; update(rows); };- top.append(enabled, label, select); card.append(top);+ top.append(enabled, label);+ if (row.source) top.append(el('span', text('Edited', '已编辑'), 'fv-edited'));+ top.append(select); card.append(top);const preview = el(kind === "image" ? "img" : kind); preview.className = "fv-preview";preview.src = viewURL(row.file);- if (kind === "image") { preview.loading = "lazy"; preview.alt = label.textContent; }- else { preview.controls = true; preview.preload = "metadata"; if (kind === "video") { preview.muted = true; preview.playsInline = true; } }- card.append(preview);+ if (kind === "image") {+ preview.loading = "lazy"; preview.alt = label.textContent;+ // The picture itself opens the editor; a badge says so on hover.+ const wrap = el("div", undefined, "fv-preview-wrap");+ const badge = el("button", undefined, "fv-preview-edit"); badge.type = "button";+ badge.innerHTML = icon("edit", 14); badge.append(el("span", text("Edit", "编辑")));+ badge.title = text("Crop, retouch, add text or layers", "裁剪、修图、加文字或图层");+ badge.onclick = event => { event.stopPropagation(); editImage(row.file); };+ preview.title = text("Edit image", "编辑图片"); preview.onclick = () => editImage(row.file);+ wrap.append(preview, badge); card.append(wrap);+ const size = videoSize();+ if (size && (row.role === "first" || row.role === "last")) {+ // A keyframe of another shape is centre-cropped when the video starts; offer the crop now.+ preview.addEventListener("load", () => {+ const off = Math.abs(Math.log((preview.naturalWidth / preview.naturalHeight) / (size.width / size.height))) > .02;+ if (!off || !preview.isConnected) return;+ const note = el("div", undefined, "fv-shape-note");+ note.append(el("span", text(`Its shape differs from the video (${size.width}×${size.height}); the edges are cropped when generating.`,+ `比例与视频(${size.width}×${size.height})不同,生成时会居中裁掉多出的部分。`)),+ button(text("Adjust crop", "调整裁剪"), text("Choose what the video keeps", "选择视频保留的画面"), () => editImage(row.file, "crop")));+ wrap.after(note);+ }, {once: true});+ }+ } else {+ preview.controls = true; preview.preload = "metadata"; if (kind === "video") { preview.muted = true; preview.playsInline = true; }+ card.append(preview);+ }if (kind !== "image") {// References are cut to the generated length (at most 15 s); say so before the run.const length = el("div", "", "fv-note"); length.hidden = true; card.append(length);@@ -156,6 +242,10 @@ function mediaPanel(node, mount = null) {}const controls = el("div", undefined, "fv-row");const move = delta => { const target = index + delta; if (target < 0 || target >= rows.length) return; [rows[index], rows[target]] = [rows[target], rows[index]]; update(rows); };+ if (kind === "image") {+ controls.append(button(text("Edit", "编辑"), text("Crop, retouch, add text or layers", "裁剪、修图、加文字或图层"), () => editImage(row.file)));+ if (row.source) controls.append(button(text("Original", "恢复原图"), text("Use the original image again; the edit can be reopened", "改回原图;之后仍可重新编辑"), () => restoreImage(row.file)));+ }controls.append(button("↑", text("Move earlier", "向前移动"), () => move(-1)), button("↓", text("Move later", "向后移动"), () => move(1)),button(text("Remove", "移除"), text("Remove from this request; keep the uploaded file", "从本次请求移除,保留已上传文件"), () => { rows.splice(index, 1); update(rows); }));card.append(controls); cards.append(card);@@ -174,9 +264,7 @@ function mediaPanel(node, mount = null) {const rows = read(); if (rows.length >= 32) throw new Error(text("Use at most 32 media items", "最多使用 32 个素材"));const kind = mediaKind(file.name);message(`${text("Uploading", "正在上传")} ${index + 1}/${files.length} · ${file.name}`);- const body = new FormData(); body.append("file", file);- const response = await api.fetchApi("/freevideo/media/upload", {method: "POST", body});- const result = await response.json(); if (!response.ok) throw new Error(result.error || response.statusText);+ const result = await uploadOne(file);rows.push({file: result.file, role: kind === "image" ? role.value : "reference", enabled: true}); update(rows);}} catch (error) { message(error.message, true); }diff --git a/web/health.js b/web/health.jsindex a775997..f2b3f0d 100644--- a/web/health.js+++ b/web/health.js@@ -10,11 +10,11 @@ const t = (en, zh) => cn ? zh : en;// launcher.js removes this flag during setup; read it before that.const launchVisit = query.get('freevideo') === 'launch';// Every script this folder ships; a test keeps the list in step with web/*.js.-export const MODULES = ['branding.js', 'compatibility.js', 'error_panel.js', 'freevideo.js', 'generation_progress.js',- 'health.js', 'launcher.js', 'library.js', 'motion.js', 'output_download.js', 'preview_scene.js',+export const MODULES = ['compatibility.js', 'error_panel.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',+ 'health.js', 'image_editor.js', 'image_editor_engine.js', 'launcher.js', 'library.js', 'motion.js', 'output_download.js', 'preview_scene.js','progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'report_issue.js','result_actions.js', 'sampling_effort.js', 'setup.js', 'share.js', 'studio.js', 'studio_queue.js',- 'updates.js', 'view_navigation.js'];+ 'toolbar_position.js', 'updates.js', 'view_navigation.js', 'wordmark.js'];const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));// A file the browser failed to load stays failed for the page's lifetime even// once the server sends it again, and a plain reload can take the same broken@@ -115,8 +115,55 @@ const ADVICE = {cache: t('FreeVideo already reloaded this page once with fresh copies of its files. Press Ctrl+F5. If it still fails, turn off browser extensions that block scripts on this page or open the same address in another browser, then copy the details and send them to us.','FreeVideo 已经用重新下载的文件自动刷新过一次页面。请按 Ctrl+F5 强制刷新;仍然出现时,请停用会拦截此页面脚本的浏览器插件,或换一个浏览器打开同一地址,然后复制详情发给我们。'),relaunch: t('Click Start in the FreeVideo launcher again.', '请在 FreeVideo 启动器里重新点击“启动”。'),+ blocked: t(`This is usually an ad blocker. Allow ${location.hostname} in it (uBlock Origin, AdGuard and Adblock Plus can all be turned off for this site), then reload the page.`,+ `通常是广告拦截插件所致。请在插件里允许 ${location.hostname}(uBlock Origin、AdGuard、Adblock Plus 都可以对当前网站停用拦截),然后刷新页面。`),};+// Requests url the way a script (modulepreload) or a stylesheet (preload) is+// loaded, without running or applying it. The result is for this file alone:+// its load event does not wait for what it imports. true when it loads, false+// when the browser stops it, null when this browser cannot tell.+function loadsAs(kind, url) {+ const link = document.createElement('link');+ const rel = kind === 'script' ? 'modulepreload' : 'preload';+ if (!link.relList?.supports?.(rel)) return Promise.resolve(null);+ link.rel = rel;+ if (kind === 'style') link.as = 'style';+ return new Promise(resolve => {+ const done = value => { clearTimeout(timer); link.remove(); resolve(value); };+ const timer = setTimeout(() => done(null), 10000);+ link.onload = () => done(true); link.onerror = () => done(false);+ link.href = url; document.head.append(link);+ });+}+// An address this page has never requested: no module-map entry, no cached copy.+const freshURL = name => `${new URL(name, base).href}?freevideo-check=${Date.now()}`;+// Blocked: a new address that downloads with fetch but will not load as a+// script or stylesheet, which is what an ad blocker's rule for a file name+// does. false when it loads; null when the browser cannot tell or the address+// does not download either.+async function blockedAs(kind, name) {+ const url = freshURL(name), loads = await loadsAs(kind, url);+ if (loads !== false) return loads === null ? null : false;+ return (await probe(url)).ok ? true : null;+}+// The scripts among names that import a blocked one, directly or through another of them.+async function importers(names, blocked) {+ const reach = new Set(blocked), imports = new Map();+ await Promise.all(names.map(async name => {+ let text = '';+ try { text = await (await fetch(new URL(name, base), {cache: 'no-store'})).text(); } catch { /* Imports nothing we know of. */ }+ imports.set(name, [...text.matchAll(/\b(?:import|export)\b[^'"`;]*?\bfrom\s*['"]\.\/([\w.-]+\.js)['"]|\bimport\s*['"]\.\/([\w.-]+\.js)['"]/g)]+ .map(match => match[1] || match[2]));+ }));+ for (let grew = true; grew;) {+ grew = false;+ for (const [name, list] of imports) if (!reach.has(name) && list.some(item => reach.has(item))) { reach.add(name); grew = true; }+ }+ return names.filter(name => reach.has(name));+}+const listNames = names => names.length > 3 ? `${names.slice(0, 3).join(cn ? '、' : ', ')}${t(` and ${names.length - 3} more`, ` 等 ${names.length} 个文件`)}` : names.join(cn ? '、' : ', ');+// What the HTTP cache holds for a file, which is what a module load reads.async function cachedCopy(url) {try {@@ -128,9 +175,10 @@ async function cachedCopy(url) {// One sentence per finding, naming the file and the reason.async function diagnoseModules() {- const found = [];+ const found = [], fetched = new Map();for (const name of MODULES) {const url = new URL(name, base).href, result = await probe(url);+ fetched.set(name, result);if (!result.ok) {found.push({text: result.status? t(`Script ${name} could not be loaded: the server answered HTTP ${result.status}.`, `脚本 ${name} 无法加载:服务器返回 HTTP ${result.status}。`)@@ -149,17 +197,38 @@ async function diagnoseModules() {failed.set(message, [...(failed.get(message) || []), name]);}}+ const kindOf = message => /does not provide an export/.test(message) ? 'mixed'+ : /SyntaxError|Unexpected token|Unexpected identifier|is not a function|is not defined|is not a constructor/.test(message) ? 'browser' : 'reload';+ // A file that downloads but will not load as a script even from a new+ // address is blocked, by an ad blocker or another browser extension, and a+ // reload cannot help. The scripts that import it fail with it.+ const unloaded = [...failed].filter(([message]) => kindOf(message) === 'reload').flatMap(([, names]) => names);+ const results = await Promise.all(unloaded.map(name => blockedAs('script', name)));+ const blocked = unloaded.filter((name, index) => results[index] === true);+ const checks = unloaded.map((name, index) => `${name}: fetch HTTP ${fetched.get(name).status} ${fetched.get(name).type || 'no type'}; `+ + `as a script from a new address: ${results[index] ? 'blocked' : results[index] === false ? 'loads' : 'unknown'}`);+ if (blocked.length) {+ const dependents = await importers(unloaded.filter(name => !blocked.includes(name)), blocked);+ const named = new Set([...blocked, ...dependents]);+ for (const [message, names] of failed) {+ const rest = names.filter(name => !named.has(name));+ if (rest.length) failed.set(message, rest); else failed.delete(message);+ }+ // The card says what happened; the copied details keep the evidence.+ const more = dependents.length;+ if (more) checks.push(`could not run without ${blocked.join(', ')}: ${dependents.join(', ')}`);+ found.push({text: t(`The browser blocked ${listNames(blocked)}${more ? `, so ${more} more ${more === 1 ? 'script' : 'scripts'} could not run.` : '.'}`,+ `浏览器拦截了 ${listNames(blocked)}${more ? `,因此另有 ${more} 个脚本无法运行。` : '。'}`), advice: 'blocked', retry: false, checks});+ }for (const [message, names] of failed) {- const list = names.length > 3 ? `${names.slice(0, 3).join(cn ? '、' : ', ')}${t(` and ${names.length - 3} more`, ` 等 ${names.length} 个文件`)}` : names.join(cn ? '、' : ', ');- const kind = /does not provide an export/.test(message) ? 'mixed'- : /SyntaxError|Unexpected token|Unexpected identifier|is not a function|is not defined|is not a constructor/.test(message) ? 'browser' : 'reload';+ const kind = kindOf(message);const cache = [];for (const name of names) cache.push(`${name}: ${await cachedCopy(new URL(name, base).href)}`);// Reachable files the browser would not run, or old and new copies mixed:- // fresh copies and one reload resolve both.- const retry = kind !== 'browser';- found.push({text: t(`The browser could not run ${list}: ${message}`, `浏览器无法运行 ${list}:${message}`),- advice: retry && retried ? 'cache' : kind, retry, cache});+ // fresh copies and one reload resolve both, unless a file is blocked.+ const retry = kind !== 'browser' && !blocked.length;+ found.push({text: t(`The browser could not run ${listNames(names)}: ${message}`, `浏览器无法运行 ${listNames(names)}:${message}`),+ advice: retry && retried ? 'cache' : kind, retry, cache, checks: found.length ? [] : checks});}return found;}@@ -172,6 +241,9 @@ function themeApplied() {return value === '#111720';}+const blockedSheet = name => ({text: t(`The browser blocked the stylesheet ${name}.`, `浏览器拦截了样式文件 ${name}。`), advice: 'blocked',+ checks: [`${name}: downloads with fetch; as a stylesheet from a new address: blocked`]});+async function diagnoseStyles() {if (themeApplied()) return [];const found = [];@@ -189,7 +261,8 @@ async function diagnoseStyles() {: result.type !== 'text/css'? {text: t(`Stylesheet ${name} was refused: the server sent it as “${result.type || 'no type'}”.`,`样式文件 ${name} 被浏览器拒绝:服务器发送的类型是“${result.type || '未标明'}”。`), advice: 'type'}- : {text: t(`Stylesheet ${name} did not load.`, `样式文件 ${name} 没有生效。`), advice: 'reload'});+ : await blockedAs('style', name) ? blockedSheet(name)+ : {text: t(`Stylesheet ${name} did not load.`, `样式文件 ${name} 没有生效。`), advice: 'reload'});}if (!found.length) {found.push({text: links.length@@ -246,6 +319,13 @@ function covered(bar) {return !!top && !bar.contains(top) && !top.closest(OVERLAYS);}+// A video enlarged to full screen (the maximize button on a node's video, or+// the player's own) hides the rest of the page until it is left again.+function fullscreenOver(element) {+ const shown = document.fullscreenElement || document.webkitFullscreenElement;+ return !!shown && !shown.contains(element);+}+// Our sheets are same-origin and never empty: rules that cannot be read were not loaded.function sheetLoaded(name) {const link = [...document.querySelectorAll('link[rel="stylesheet"]')].find(item => ours(item.href) && fileName(item.href) === name);@@ -266,7 +346,7 @@ function workspaceProblem(app) {return sheetLoaded('view_navigation.css')? {text: t('The FreeVideo toolbar that opens the creative workspace is hidden or covered by other page elements.', '打开创作面板的 FreeVideo 工具栏被页面上的其他元素隐藏或遮挡了。'), advice: 'plugin'}: {text: t('The FreeVideo toolbar that opens the creative workspace cannot be seen: its stylesheet view_navigation.css did not load.',- '看不到打开创作面板的 FreeVideo 工具栏:样式文件 view_navigation.css 没有加载。'), advice: 'reload'};+ '看不到打开创作面板的 FreeVideo 工具栏:样式文件 view_navigation.css 没有加载。'), advice: 'reload', sheet: 'view_navigation.css'};}// Looks again as the page changes, such as another workflow coming to the@@ -276,6 +356,7 @@ async function watchWorkspace(app) {for (;;) {await sleep(2500);if (document.hidden) continue;+ if (fullscreenOver(document.querySelector('.fv-view-navigation') || document.body)) { missed = ''; continue; }const problem = workspaceProblem(app);if (!problem) { missed = ''; continue; }if (missed !== problem.text) {@@ -284,8 +365,12 @@ async function watchWorkspace(app) {continue;}if (shown === problem.text) continue;+ const named = problem.sheet && await blockedAs('style', problem.sheet) ? blockedSheet(problem.sheet) : problem;+ // The page can change while the stylesheet is checked.+ if (document.hidden || fullscreenOver(document.querySelector('.fv-view-navigation') || document.body)+ || workspaceProblem(app)?.text !== problem.text) continue;shown = problem.text;- const problems = distinct([...lastProblems, problem, ...reports.filter(item => item.type === 'error').map(reportText), ...pluginErrors()]);+ const problems = distinct([...lastProblems, named, ...reports.filter(item => item.type === 'error').map(reportText), ...pluginErrors()]);show(problems); send('error', problems);}}@@ -303,6 +388,7 @@ const distinct = problems => problems.filter((problem, index) => problems.findInlet card = null, lastProblems = [];function details(problems) {const cache = problems.flatMap(p => p.cache || []);+ const checks = problems.flatMap(p => p.checks || []);const before = retried && Array.isArray(retryRecord.before) ? retryRecord.before : [];return [`FreeVideo page check · ${new Date().toISOString()}`,`Page: ${location.origin}${location.pathname}`,@@ -311,6 +397,7 @@ function details(problems) {`FreeVideo UI: ${JSON.stringify(window.FreeVideoUI || {})}`,`Automatic reload: ${retried ? new Date(Number(retryRecord.at)).toISOString() : retryRecord ? 'not needed' : 'unavailable (no session storage)'}`,'', 'Problems:', ...problems.map(p => `- ${p.text}`),+ ...(checks.length ? ['', 'Load check:', ...checks.map(row => `- ${row}`)] : []),...(cache.length ? ['', 'Browser cache:', ...cache.map(row => `- ${row}`)] : []),...(before.length ? ['', 'Browser cache before the automatic reload:', ...before.map(row => `- ${row}`)] : []),'', 'Errors seen while loading:', ...(seen.length ? seen.map(row => `- [${row.kind}] ${row.text}`) : ['- none'])].join('\n');@@ -347,12 +434,12 @@ function show(problems) {Object.assign(list.style, {margin: '0 0 10px', paddingLeft: '18px'});for (const problem of problems) {const row = document.createElement('li'); row.textContent = problem.text;- Object.assign(row.style, {margin: '2px 0', overflowWrap: 'anywhere'});+ Object.assign(row.style, {margin: '2px 0', overflowWrap: 'anywhere', textWrap: 'balance'});list.append(row);}const advice = document.createElement('div');advice.textContent = [...new Set(problems.map(p => ADVICE[p.advice] || ADVICE.reload))].join(' ');- Object.assign(advice.style, {color: '#a5b3c6', marginBottom: '14px'});+ Object.assign(advice.style, {color: '#a5b3c6', marginBottom: '14px', textWrap: 'pretty'});const actions = document.createElement('div');Object.assign(actions.style, {display: 'flex', flexWrap: 'wrap', gap: '8px'});const action = (label, run, primary = false) => {@@ -374,19 +461,26 @@ function show(problems) {action(t('Close', '关闭'), () => { card?.remove(); card = null; });card.append(title, list, advice, actions);document.body.append(card);- // A modal such as an unstyled workspace sits in the top layer; a manual- // popover joins it and returns to the front whenever a dialog opens.if (typeof card.showPopover === 'function') {card.popover = 'manual';Object.assign(card.style, {right: 'auto', bottom: 'auto', margin: '0'});- card.showPopover();+ raise();}consoleError.call(console, '[FreeVideo] Page check:\n' + details(problems));}-new MutationObserver(() => {- if (!card?.isConnected || typeof card.showPopover !== 'function' || !document.querySelector('dialog[open]')) return;- try { card.hidePopover(); card.showPopover(); } catch { /* Shown below the dialog instead. */ }-}).observe(document.documentElement, {subtree: true, attributeFilter: ['open']});+// A modal such as an unstyled workspace sits in the top layer; a manual+// popover joins it and returns to the front whenever a dialog opens. Not in+// front of a video watched full screen: the card waits until it is left.+function raise() {+ if (!card?.isConnected || typeof card.showPopover !== 'function' || fullscreenOver(card)) return;+ try {+ if (card.matches(':popover-open')) card.hidePopover();+ card.showPopover();+ } catch { /* Shown below the dialog instead. */ }+}+new MutationObserver(() => { if (document.querySelector('dialog[open]')) raise(); })+ .observe(document.documentElement, {subtree: true, attributeFilter: ['open']});+for (const name of ['fullscreenchange', 'webkitfullscreenchange']) document.addEventListener(name, raise);let sent = '', latest = null;const comfyApi = () => comfy()?.api || window.comfyAPI?.api?.api;diff --git a/web/image_editor.css b/web/image_editor.cssnew file mode 100644index 0000000..e03b6a2--- /dev/null+++ b/web/image_editor.css@@ -0,0 +1,245 @@+/* Image editor. A dark work surface in FreeVideo's tokens (theme.css): tools on+ the left, the active tool's options above the picture, adjustments and+ layers on the right. The stage stays dark in every theme so colours read true. */+.fv-image-editor{box-sizing:border-box;width:min(1520px,calc(100vw - 24px));height:min(960px,calc(100dvh - 24px));max-width:none;max-height:none;+ margin:auto;padding:0;border:1px solid var(--fv-border);border-radius:var(--fv-r-lg);background:var(--fv-card);color:var(--fv-ink);+ font:var(--fv-body)/1.45 var(--fv-font);display:none;flex-direction:column;overflow:hidden;box-shadow:0 28px 90px rgba(0,0,0,.6)}+.fv-image-editor[open]{display:flex;animation:fv-dialog-enter .28s cubic-bezier(.2,.7,.2,1)}+.fv-image-editor::backdrop{background:rgba(5,8,13,.74);animation:fv-backdrop-enter .22s ease}+.fv-image-editor *{box-sizing:border-box}+/* ComfyUI has no global [hidden] rule, and our display values would beat the browser's. */+.fv-image-editor [hidden]{display:none!important}+.fv-image-editor :focus-visible{outline:2px solid var(--fv-accent);outline-offset:2px}+.fv-image-editor button{font:inherit;color:var(--fv-ink);cursor:pointer;touch-action:manipulation;-webkit-tap-highlight-color:transparent}+.fv-image-editor button:disabled{opacity:.38;cursor:default}+.fv-image-editor input,.fv-image-editor select,.fv-image-editor textarea{font:inherit;color:var(--fv-ink)}++/* Header: name and size, zoom in the middle, history and leave on the right. */+.fv-ie-header{display:grid;grid-template-columns:minmax(0,1fr) auto minmax(0,1fr);align-items:center;gap:12px;padding:10px 14px;border-bottom:1px solid var(--fv-border);background:var(--fv-card)}+.fv-ie-title{display:flex;align-items:baseline;gap:10px;min-width:0}+.fv-ie-title strong{font-size:var(--fv-strong);font-weight:var(--fv-semibold);white-space:nowrap}+.fv-ie-file{color:var(--fv-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}+.fv-ie-size{color:var(--fv-muted);font-variant-numeric:tabular-nums;white-space:nowrap;font-size:var(--fv-micro);padding:1px 7px;border:1px solid var(--fv-border);border-radius:999px}+button.fv-ie-size{font-family:inherit;line-height:inherit;background:transparent;cursor:pointer}+button.fv-ie-size:hover{background:var(--fv-hover);color:var(--fv-ink)}+.fv-ie-zoom{display:flex;align-items:center;gap:2px;padding:2px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-canvas)}+.fv-ie-zoom .fv-ie-icon{border:0;background:transparent;min-width:28px;height:28px}+.fv-ie-zoom-label{min-width:58px;height:28px;border:0;border-radius:6px;background:transparent;font-variant-numeric:tabular-nums;font-size:var(--fv-micro)}+.fv-ie-zoom-label:hover,.fv-ie-zoom .fv-ie-icon:hover{background:var(--fv-hover)}+.fv-ie-actions{display:flex;align-items:center;justify-content:flex-end;gap:8px;flex-wrap:wrap}++.fv-ie-button{min-height:var(--fv-h-sm);padding:5px 12px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-raised);font-weight:var(--fv-medium);white-space:nowrap}+.fv-ie-button:hover:not(:disabled){background:var(--fv-hover)}+.fv-ie-primary{background:var(--fv-accent);border-color:var(--fv-accent);color:#08131f;min-width:84px}+.fv-ie-primary:hover:not(:disabled){background:var(--fv-accent-hover)}+.fv-ie-danger{color:var(--fv-danger);border-color:color-mix(in srgb,var(--fv-danger) 60%,transparent)}+.fv-ie-quiet{background:transparent}+.fv-ie-active{background:var(--fv-selected)!important;border-color:var(--fv-accent)!important;color:var(--fv-accent)!important}+.fv-ie-icon{display:inline-grid;place-items:center;min-width:var(--fv-h-sm);height:var(--fv-h-sm);padding:0 7px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-raised)}+.fv-ie-icon:hover:not(:disabled){background:var(--fv-hover)}++.fv-ie-main{flex:1;min-height:0;display:grid;grid-template-columns:52px minmax(0,1fr) 308px}++/* Tool strip. */+.fv-ie-toolbar{display:flex;flex-direction:column;align-items:center;gap:3px;padding:10px 0;border-right:1px solid var(--fv-border);background:var(--fv-canvas);overflow:auto;scrollbar-width:none}+.fv-ie-tool{display:grid;place-items:center;width:36px;height:36px;padding:0;border:1px solid transparent;border-radius:var(--fv-r-sm);background:transparent;color:var(--fv-muted);flex:none}+.fv-ie-tool:hover{background:var(--fv-raised);color:var(--fv-ink)}+.fv-ie-tool[aria-pressed=true]{background:var(--fv-selected);border-color:var(--fv-accent-dim);color:var(--fv-accent)}+.fv-ie-tool-gap{display:block;width:22px;height:1px;margin:5px 0;background:var(--fv-border);flex:none}+.fv-ie-tool-fill{flex:1;min-height:10px}+.fv-ie-colors{position:relative;width:40px;height:44px;flex:none}+.fv-ie-colors input[type=color]{position:absolute;width:24px;height:24px;padding:0;border:2px solid var(--fv-card);border-radius:5px;background:none;cursor:pointer;box-shadow:0 0 0 1px var(--fv-sheen)}+.fv-ie-colors input[type=color]::-webkit-color-swatch-wrapper{padding:0}.fv-ie-colors input[type=color]::-webkit-color-swatch{border:0;border-radius:3px}+.fv-ie-colors input[type=color]::-moz-color-swatch{border:0;border-radius:3px}+.fv-ie-fg{left:3px;top:2px;z-index:1}.fv-ie-bg{left:14px;top:13px}+.fv-ie-swap{position:absolute;right:-2px;top:-2px;width:18px;height:18px;padding:0;border:0;background:transparent;color:var(--fv-muted);display:grid;place-items:center}+.fv-ie-swap svg{width:13px;height:13px}.fv-ie-swap:hover{color:var(--fv-ink)}++/* Options bar. */+.fv-ie-workspace{min-width:0;min-height:0;display:grid;grid-template-rows:auto minmax(0,1fr)}+.fv-ie-options{display:flex;align-items:center;gap:8px 10px;flex-wrap:wrap;min-height:48px;padding:7px 12px;border-bottom:1px solid var(--fv-border);background:var(--fv-card)}+.fv-ie-opt-title{font-weight:var(--fv-semibold);padding-right:4px;white-space:nowrap}+.fv-ie-opt-label{color:var(--fv-muted);font-size:var(--fv-micro);white-space:nowrap}+.fv-ie-opt-note{color:var(--fv-muted);font-size:var(--fv-micro);line-height:1.4}+.fv-ie-sep{width:1px;height:22px;background:var(--fv-border);flex:none}+.fv-ie-check{display:inline-flex;align-items:center;gap:6px;color:var(--fv-ink);font-size:var(--fv-micro);cursor:pointer;white-space:nowrap}+.fv-ie-check input{accent-color:var(--fv-accent);margin:0}+.fv-ie-select{min-height:var(--fv-h-sm);padding:4px 8px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-raised);max-width:100%}+.fv-ie-seg{display:inline-flex;padding:2px;gap:2px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-canvas);flex-wrap:wrap}+.fv-ie-seg-item{min-height:26px;padding:2px 10px;border:0;border-radius:6px;background:transparent;color:var(--fv-muted);font-size:var(--fv-micro);white-space:nowrap}+.fv-ie-seg-item:hover{color:var(--fv-ink);background:var(--fv-raised)}+.fv-ie-seg-item[aria-pressed=true]{background:var(--fv-selected);color:var(--fv-accent)}+.fv-ie-seg-icon{display:grid;place-items:center;width:30px;padding:0}+/* Text fonts: four equal segments, each name in its own face, large enough to tell them apart. */+.fv-ie-font-row{display:grid;gap:4px}+.fv-ie-fonts{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));width:100%;flex-wrap:nowrap}+.fv-ie-fonts .fv-ie-seg-item{min-height:44px;padding:2px 4px;font-size:16px;font-weight:400;color:var(--fv-ink);overflow:hidden;text-overflow:ellipsis}+.fv-ie-fonts .fv-ie-seg-item[aria-pressed=true]{color:var(--fv-accent)}+.fv-image-editor input.fv-ie-range{appearance:none;-webkit-appearance:none;background:transparent;height:16px;margin:0;min-width:0;cursor:pointer}+.fv-image-editor input.fv-ie-range:disabled{opacity:.5;cursor:default}+.fv-image-editor input.fv-ie-range:focus-visible{outline:none}+.fv-image-editor input.fv-ie-range::-webkit-slider-runnable-track{height:4px;border-radius:2px;+ background:linear-gradient(to right,var(--fv-border) 0 calc((7px + (100% - 14px) * var(--fv-lo, 0)) * var(--fv-two, 1)),var(--fv-accent) calc((7px + (100% - 14px) * var(--fv-lo, 0)) * var(--fv-two, 1)) calc(7px + (100% - 14px) * var(--fv-hi, 0)),var(--fv-border) calc(7px + (100% - 14px) * var(--fv-hi, 0)) 100%)}+.fv-image-editor input.fv-ie-range::-moz-range-track{height:4px;border-radius:2px;+ background:linear-gradient(to right,var(--fv-border) 0 calc((7px + (100% - 14px) * var(--fv-lo, 0)) * var(--fv-two, 1)),var(--fv-accent) calc((7px + (100% - 14px) * var(--fv-lo, 0)) * var(--fv-two, 1)) calc(7px + (100% - 14px) * var(--fv-hi, 0)),var(--fv-border) calc(7px + (100% - 14px) * var(--fv-hi, 0)) 100%)}+.fv-image-editor input.fv-ie-range::-webkit-slider-thumb{-webkit-appearance:none;margin-top:-5px;width:14px;height:14px;border-radius:50%;background:#f4f7fb;border:0;box-shadow:0 1px 3px rgb(0 0 0 / .45)}+.fv-image-editor input.fv-ie-range::-moz-range-thumb{width:14px;height:14px;border-radius:50%;background:#f4f7fb;border:0;box-shadow:0 1px 3px rgb(0 0 0 / .45)}+.fv-image-editor input.fv-ie-range:hover::-webkit-slider-thumb{box-shadow:0 1px 3px rgb(0 0 0 / .45),0 0 0 3px color-mix(in srgb,var(--fv-accent) 35%,transparent)}+.fv-image-editor input.fv-ie-range:hover::-moz-range-thumb{box-shadow:0 1px 3px rgb(0 0 0 / .45),0 0 0 3px color-mix(in srgb,var(--fv-accent) 35%,transparent)}+.fv-image-editor input.fv-ie-range:focus-visible::-webkit-slider-thumb{box-shadow:0 1px 3px rgb(0 0 0 / .45),0 0 0 3px var(--fv-accent)}+.fv-image-editor input.fv-ie-range:focus-visible::-moz-range-thumb{box-shadow:0 1px 3px rgb(0 0 0 / .45),0 0 0 3px var(--fv-accent)}+.fv-image-editor input.fv-ie-range::-moz-range-progress{background:transparent}+.fv-ie-options .fv-ie-slider{display:flex;align-items:center;gap:8px}+.fv-ie-options .fv-ie-slider label{color:var(--fv-muted);font-size:var(--fv-micro);white-space:nowrap}+.fv-ie-options .fv-ie-slider input{width:110px}+.fv-ie-options .fv-ie-slider output{order:3;min-width:46px;font-size:var(--fv-micro);font-variant-numeric:tabular-nums}++/* Stage. */+.fv-ie-stage{position:relative;min-width:0;min-height:0;overflow:hidden;touch-action:none;+ background:radial-gradient(circle at 1px 1px,rgba(255,255,255,.045) 1px,transparent 0) 0 0/18px 18px,#0a0e14}+/* The stage takes keyboard focus for shortcuts; the active tool shows that, not a ring. */+.fv-image-editor .fv-ie-stage:focus,.fv-image-editor .fv-ie-stage:focus-visible{outline:none}+.fv-ie-view,.fv-ie-ants,.fv-ie-overlay{position:absolute;inset:0;width:100%;height:100%}+.fv-ie-ants{pointer-events:none}+.fv-ie-overlay{overflow:visible}+.fv-ie-stage[data-tool=move]{cursor:default}.fv-ie-stage[data-tool=crop],.fv-ie-stage[data-tool=marquee],.fv-ie-stage[data-tool=lasso],.fv-ie-stage[data-tool=wand],.fv-ie-stage[data-tool=gradient],.fv-ie-stage[data-tool=shape]{cursor:crosshair}+.fv-ie-stage[data-tool=brush],.fv-ie-stage[data-tool=eraser],.fv-ie-stage[data-tool=heal],.fv-ie-stage[data-tool=clone],.fv-ie-stage[data-tool=blur]{cursor:none}+.fv-ie-stage[data-tool=text]{cursor:text}.fv-ie-stage[data-tool=eyedropper]{cursor:copy}+.fv-ie-stage[data-tool=hand],.fv-ie-stage[data-pan=true]{cursor:grab}.fv-ie-stage[data-pan=true]:active{cursor:grabbing}+.fv-ie-overlay .fv-ie-dim{fill:rgba(5,8,13,.62);pointer-events:none}+.fv-ie-overlay .fv-ie-dim-soft{fill:rgba(5,8,13,.42)}+.fv-ie-overlay .fv-ie-crop-frame{fill:none;stroke:#fff;stroke-width:1.2;pointer-events:none}+.fv-ie-overlay .fv-ie-dashed{stroke:rgba(255,255,255,.55);stroke-dasharray:4 4}+.fv-ie-overlay .fv-ie-third{stroke:rgba(255,255,255,.28);stroke-width:1;pointer-events:none}+.fv-ie-overlay .fv-ie-handle{fill:#fff;stroke:rgba(7,10,15,.6);stroke-width:1;cursor:pointer;filter:drop-shadow(0 1px 2px rgba(0,0,0,.5))}+.fv-ie-overlay .fv-ie-handle[data-handle=nw],.fv-ie-overlay .fv-ie-handle[data-handle=se]{cursor:nwse-resize}+.fv-ie-overlay .fv-ie-handle[data-handle=ne],.fv-ie-overlay .fv-ie-handle[data-handle=sw]{cursor:nesw-resize}+.fv-ie-overlay .fv-ie-handle[data-handle=n],.fv-ie-overlay .fv-ie-handle[data-handle=s]{cursor:ns-resize}+.fv-ie-overlay .fv-ie-handle[data-handle=e],.fv-ie-overlay .fv-ie-handle[data-handle=w]{cursor:ew-resize}+.fv-ie-overlay .fv-ie-rotate{fill:var(--fv-accent);cursor:grab}+.fv-ie-overlay .fv-ie-box{fill:none;stroke:var(--fv-accent);stroke-width:1.3;pointer-events:none}+.fv-ie-overlay .fv-ie-brush{fill:none;stroke:#fff;stroke-width:1.2;pointer-events:none;filter:drop-shadow(0 0 1px rgba(0,0,0,.9))}+.fv-ie-overlay .fv-ie-source{fill:none;stroke:var(--fv-accent);stroke-width:2;pointer-events:none}+.fv-ie-overlay .fv-ie-drag{fill:rgba(109,184,250,.08);stroke:#fff;stroke-width:1.2;stroke-dasharray:5 4;pointer-events:none}+.fv-ie-overlay polyline.fv-ie-drag,.fv-ie-overlay line.fv-ie-drag{fill:none}+.fv-ie-hint{position:absolute;left:50%;bottom:14px;transform:translateX(-50%);max-width:calc(100% - 32px);padding:6px 12px;border:1px solid var(--fv-border);border-radius:999px;+ background:rgba(22,30,41,.92);color:var(--fv-ink);font-size:var(--fv-micro);text-align:center;pointer-events:none;backdrop-filter:blur(6px)}+.fv-ie-popover{position:absolute;top:12px;right:12px;width:min(320px,calc(100% - 24px));display:flex;flex-direction:column;gap:10px;padding:14px;+ border:1px solid var(--fv-border);border-radius:var(--fv-r-md);background:var(--fv-card);box-shadow:0 14px 40px rgba(0,0,0,.5);z-index:2}+.fv-ie-popover h3{margin:0;font-size:var(--fv-body);font-weight:var(--fv-semibold)}+.fv-ie-pad-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}+/* Image size: presets as wide as their words, width and height either side of the chain. */+.fv-ie-image-size p{margin:0}+.fv-ie-presets{display:flex;flex-wrap:nowrap}+.fv-ie-presets .fv-ie-seg-item{flex:1 1 auto;min-height:30px}+.fv-ie-presets .fv-ie-seg-item:disabled{opacity:.45;cursor:default;background:transparent;color:var(--fv-muted)}+.fv-ie-dims{display:grid;grid-template-columns:minmax(0,1fr) auto minmax(0,1fr);gap:8px;align-items:end}+.fv-ie-dims .fv-ie-field{flex-direction:column;align-items:stretch;gap:3px}+.fv-ie-chain{min-height:30px;height:30px;color:var(--fv-muted)}+.fv-ie-chain[aria-pressed=true]{color:var(--fv-accent);background:var(--fv-selected)}+.fv-ie-notes{display:flex;flex-direction:column;gap:4px}+.fv-ie-note-warn{color:var(--fv-warning)}++/* Fields. */+.fv-ie-field{display:flex;align-items:center;gap:8px;min-width:0}+.fv-ie-field label{color:var(--fv-muted);font-size:var(--fv-micro);white-space:nowrap;min-width:52px}+.fv-ie-field input[type=number],.fv-ie-rename{width:100%;min-width:0;min-height:30px;padding:3px 8px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-raised)}+.fv-ie-field input[type=color]{width:44px;height:28px;padding:0 2px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-raised);cursor:pointer}+.fv-ie-field input[type=checkbox]{accent-color:var(--fv-accent);margin:0}+.fv-ie-field .fv-ie-select{flex:1;min-width:0}+.fv-ie-row{display:flex;gap:6px;flex-wrap:wrap;align-items:center}+.fv-ie-end{justify-content:flex-end}+.fv-ie-pair{display:grid;grid-template-columns:minmax(0,1.4fr) minmax(0,1fr);gap:8px}+.fv-ie-pair .fv-ie-field{flex-direction:column;align-items:stretch;gap:3px}++/* Right panel: properties above, layers below. */+.fv-ie-panel{min-width:0;min-height:0;display:grid;grid-template-rows:minmax(0,1fr) minmax(170px,42%);border-left:1px solid var(--fv-border);background:var(--fv-canvas)}+.fv-ie-props{min-height:0;overflow:auto;padding:12px 14px 16px;display:flex;flex-direction:column;gap:12px}+.fv-ie-section-head{display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0}+.fv-ie-section-head h3{margin:0;font-size:var(--fv-micro);font-weight:var(--fv-semibold);color:var(--fv-muted);letter-spacing:.06em;text-transform:uppercase;white-space:nowrap}+.fv-ie-props-name{color:var(--fv-ink);font-size:var(--fv-micro);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}+.fv-ie-basics{display:flex;flex-direction:column;gap:8px;padding-bottom:10px;border-bottom:1px solid var(--fv-border)}+.fv-ie-props .fv-ie-slider,.fv-ie-popover .fv-ie-slider{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:2px 8px;align-items:center}+.fv-ie-props .fv-ie-slider label{font-size:var(--fv-micro);color:var(--fv-muted)}+.fv-ie-props .fv-ie-slider input{grid-column:1/-1;width:100%}+.fv-ie-props .fv-ie-slider output{font-size:var(--fv-micro);font-variant-numeric:tabular-nums;color:var(--fv-ink)}+.fv-ie-adjust{display:flex;flex-direction:column;gap:6px}+.fv-ie-group{border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-card)}+.fv-ie-group summary{display:flex;align-items:center;gap:8px;padding:8px 10px;cursor:pointer;font-weight:var(--fv-medium);list-style:none}+.fv-ie-group summary::-webkit-details-marker{display:none}+.fv-ie-group summary::after{content:"";margin-left:auto;width:7px;height:7px;border-right:1.5px solid var(--fv-muted);border-bottom:1.5px solid var(--fv-muted);transform:rotate(-45deg);transition:transform var(--fv-quick) var(--fv-ease)}+.fv-ie-group[open] summary::after{transform:rotate(45deg)}+.fv-ie-group[open]{padding-bottom:8px}+.fv-ie-group .fv-ie-slider{padding:3px 10px}+.fv-ie-count{min-width:18px;height:18px;padding:0 5px;border-radius:999px;background:var(--fv-selected);color:var(--fv-accent);font-size:11px;display:inline-grid;place-items:center}+.fv-ie-fields{display:flex;flex-direction:column;gap:10px}+.fv-ie-textarea{width:100%;min-height:72px;resize:vertical;padding:8px 10px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-raised);line-height:1.5}++.fv-ie-layers{min-height:0;display:flex;flex-direction:column;border-top:1px solid var(--fv-border)}+.fv-ie-layers>.fv-ie-section-head{padding:10px 12px 8px}+.fv-ie-layer-tools{display:flex;gap:2px;align-items:center}+.fv-ie-layer-tools .fv-ie-icon,.fv-ie-menu summary{min-width:26px;height:26px;padding:0 4px;border:0;background:transparent;color:var(--fv-muted)}+.fv-ie-layer-tools .fv-ie-icon svg,.fv-ie-menu summary svg{width:16px;height:16px}+.fv-ie-layer-tools .fv-ie-icon:hover:not(:disabled),.fv-ie-menu summary:hover{background:var(--fv-raised);color:var(--fv-ink)}+.fv-ie-menu{position:relative}+.fv-ie-menu summary{display:grid;place-items:center;border-radius:var(--fv-r-sm);cursor:pointer;list-style:none}+.fv-ie-menu summary::-webkit-details-marker{display:none}+.fv-ie-menu-list{position:absolute;right:0;bottom:calc(100% + 6px);z-index:3;width:236px;max-height:300px;overflow:auto;padding:6px;border:1px solid var(--fv-border);border-radius:var(--fv-r-md);background:var(--fv-card);box-shadow:0 14px 40px rgba(0,0,0,.5);display:flex;flex-direction:column;gap:2px}+.fv-ie-menu-label{padding:6px 8px 2px;color:var(--fv-muted);font-size:11px}+.fv-ie-menu-item{display:flex;align-items:center;gap:8px;width:100%;padding:6px 8px;border:0;border-radius:6px;background:transparent;text-align:left}+.fv-ie-menu-item:hover{background:var(--fv-hover)}+.fv-ie-menu-item img{width:40px;height:28px;object-fit:cover;border-radius:4px;background:#0a0e14;flex:none}+.fv-ie-menu-item span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.fv-ie-layer-list{list-style:none;margin:0;padding:0 8px 10px;overflow:auto;min-height:0;display:flex;flex-direction:column;gap:2px}+.fv-ie-layer{display:flex;align-items:center;gap:6px;padding:4px 6px;border:1px solid transparent;border-radius:var(--fv-r-sm);cursor:pointer;min-width:0}+.fv-ie-layer:hover{background:var(--fv-raised)}+.fv-ie-layer[aria-selected=true]{background:var(--fv-selected);border-color:var(--fv-accent-dim)}+.fv-ie-eye{display:grid;place-items:center;width:24px;height:24px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--fv-muted);flex:none}+.fv-ie-eye svg{width:15px;height:15px}.fv-ie-eye:hover{color:var(--fv-ink)}+.fv-ie-thumb{width:48px;height:34px;border-radius:4px;flex:none;box-shadow:0 0 0 1px var(--fv-border)}+.fv-ie-thumb.fv-ie-target{box-shadow:0 0 0 2px var(--fv-accent)}+.fv-ie-layer-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.fv-ie-lock,.fv-ie-layer-opacity{color:var(--fv-muted);font-size:11px;display:grid;place-items:center;flex:none}++.fv-ie-confirm{display:flex;align-items:center;justify-content:flex-end;gap:10px;flex-wrap:wrap;padding:10px 16px;border-top:1px solid var(--fv-border);background:var(--fv-danger-subtle)}+.fv-ie-confirm span{flex:1 1 220px}+.fv-ie-status{padding:0 16px;color:var(--fv-muted);font-size:var(--fv-micro)}+.fv-ie-status:empty{display:none}+.fv-ie-status:not(:empty){padding:7px 16px;border-top:1px solid var(--fv-border)}++@media (max-width:900px){+ .fv-image-editor{width:100vw;height:100dvh;border:0;border-radius:0}+ .fv-ie-header{grid-template-columns:minmax(0,1fr) auto;padding:8px 10px}+ .fv-ie-zoom{display:none}+ .fv-ie-main{grid-template-columns:minmax(0,1fr);grid-template-rows:auto minmax(240px,1fr) minmax(0,38dvh)}+ .fv-ie-toolbar{flex-direction:row;padding:6px 8px;border-right:0;border-bottom:1px solid var(--fv-border);overflow-x:auto}+ .fv-ie-tool-gap{width:1px;height:22px;margin:0 4px}+ .fv-ie-tool-fill{flex:1;min-width:6px}+ /* One scrolling column under the picture: properties, then layers, never squeezed. */+ .fv-ie-panel{display:flex;flex-direction:column;border-left:0;border-top:1px solid var(--fv-border);overflow:auto}+ .fv-ie-props,.fv-ie-layers{flex:none;min-height:auto;overflow:visible}+ .fv-ie-layer-list{overflow:visible}+ .fv-ie-options{overflow-x:auto;flex-wrap:nowrap}+ .fv-ie-file,.fv-ie-size{display:none}+}+@media (max-width:560px){+ .fv-ie-actions .fv-ie-button:not(.fv-ie-primary):not(.fv-ie-danger){padding:5px 9px}+ .fv-ie-popover{left:12px;width:auto}+ .fv-ie-reset{display:none}+}+@media (prefers-reduced-motion:reduce){.fv-image-editor[open],.fv-image-editor::backdrop{animation:none!important}}++/* Media cards: the picture is the entry to the editor. */+.fv-panel .fv-preview-wrap{position:relative;margin:8px 0;border-radius:var(--fv-r-sm);overflow:hidden;background:var(--fv-bg)}+.fv-panel .fv-preview-wrap .fv-preview{margin:0;border-radius:0;cursor:zoom-in}+.fv-panel .fv-preview-edit{position:absolute;top:8px;right:8px;display:inline-flex;align-items:center;gap:5px;min-height:28px;padding:3px 10px;+ border:1px solid rgba(255,255,255,.18);border-radius:999px;background:rgba(14,20,28,.78);color:#fff;font:inherit;font-size:var(--fv-micro);font-weight:var(--fv-medium);+ cursor:pointer;opacity:0;transform:translateY(-3px);transition:opacity var(--fv-quick) var(--fv-ease),transform var(--fv-quick) var(--fv-ease);backdrop-filter:blur(6px)}+.fv-panel .fv-preview-edit svg{width:14px;height:14px}+.fv-panel .fv-preview-wrap:hover .fv-preview-edit,.fv-panel .fv-preview-edit:focus-visible{opacity:1;transform:none}+@media (hover:none){.fv-panel .fv-preview-edit{opacity:1;transform:none}}+.fv-panel .fv-edited{display:inline-flex;align-items:center;gap:4px;padding:1px 7px;border-radius:var(--fv-r-xs);background:var(--fv-selected);color:var(--fv-accent);font-size:var(--fv-micro);white-space:nowrap}+.fv-panel .fv-shape-note{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:0 0 8px;padding:7px 10px;border:1px solid color-mix(in srgb,var(--fv-warning) 35%,var(--fv-border));+ border-radius:var(--fv-r-sm);background:color-mix(in srgb,var(--fv-warning) 9%,transparent);color:var(--fv-ink);font-size:var(--fv-micro)}+.fv-panel .fv-shape-note span{flex:1 1 180px}+.fv-panel .fv-shape-note button{min-height:26px;padding:2px 10px}diff --git a/web/image_editor.js b/web/image_editor.jsnew file mode 100644index 0000000..299817c--- /dev/null+++ b/web/image_editor.js@@ -0,0 +1,1530 @@+// Image editor for media cards: layers, selections, retouching, text, shapes,+// colour, crop and canvas size, in the spirit of a desktop photo editor and in+// FreeVideo's own look. The original file is never changed: saving renders a+// new image and keeps the document, so the next visit starts from the original+// with every layer and step in place. Closing frees every canvas it made.+import {BLENDS, uid, emptyAdjust, migrate, orientedSize, orientMatrix, canvasRect, layerMatrix, resizeDocument, scaleSelection,+ paintLayer, rasterKinds, measureText, Renderer} from './image_editor_engine.js';+import {FONT_KEYS, fontStack, fontLoaded, loadFont, loadFonts} from './fonts.js';++const css = document.createElement('link');+css.rel = 'stylesheet'; css.href = new URL('./image_editor.css', import.meta.url).href;+document.head.append(css);++const RATIOS = [['video', null], ['original', null], ['free', null], ['16:9', 16 / 9], ['9:16', 9 / 16], ['1:1', 1], ['4:3', 4 / 3], ['3:4', 3 / 4]];+const HISTORY = 80;+const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));+const SVG = (body, size = 18) => `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;+// Line icons on a 24-unit grid; eyedropper, hand, crop, link and unlink follow Lucide (ISC, see THIRD_PARTY_NOTICES.md).+export const ICONS = {+ move: '<path d="M12 3v18M3 12h18"/><path d="m9 6 3-3 3 3M9 18l3 3 3-3M6 9l-3 3 3 3M18 9l3 3-3 3"/>',+ crop: '<path d="M6 2v14a2 2 0 0 0 2 2h14"/><path d="M2 6h14a2 2 0 0 1 2 2v14"/>',+ marquee: '<rect x="4" y="5" width="16" height="14" rx="1" stroke-dasharray="2.6 2.4"/>',+ ellipse: '<ellipse cx="12" cy="12" rx="9" ry="7" stroke-dasharray="2.6 2.4"/>',+ lasso: '<path d="M7 17c-3-1.5-4-4-3-6.5C5.5 6.5 10 4.5 14.5 5S21 8.5 20 12s-6 5-10 4.5"/><path d="M7 17c0 2 1.5 3.5 3.5 3"/><circle cx="7" cy="17" r="1.6"/>',+ polygon: '<path d="M5 18 4 8l8-4 8 6-4 9z" stroke-dasharray="2.6 2.4"/>',+ wand: '<path d="m4 20 11-11"/><path d="M15 4v2M18.5 5.5l-1.4 1.4M20 9h-2M18.5 12.5l-1.4-1.4M12 5.5l1.4 1.4"/>',+ brush: '<path d="M18.4 3.6a2 2 0 0 1 2.8 2.8L11 16.6 7.4 13z"/><path d="M7.4 13c-2.6 0-4 1.8-4 4.2 0 1.6-.6 2.6-1.4 3.2 4.6.6 8.6-.6 9-4.2"/>',+ eraser: '<path d="m7 21-4-4a2 2 0 0 1 0-2.8L13.2 4a2 2 0 0 1 2.8 0l4 4a2 2 0 0 1 0 2.8L10 21z"/><path d="M21 21H7M8.5 9.5l6 6"/>',+ heal: '<rect x="2.8" y="8.2" width="18.4" height="7.6" rx="3.8" transform="rotate(-45 12 12)"/><path d="M10.5 10.5h.01M13.5 13.5h.01M10.5 13.5h.01M13.5 10.5h.01"/>',+ clone: '<path d="M9 3h6v4a3 3 0 0 1-1 2.2L13 10v3h-2v-3l-1-.8A3 3 0 0 1 9 7z"/><path d="M5 13h14v4H5zM7 21h10"/>',+ blur: '<path d="M12 3s6 6.6 6 11a6 6 0 0 1-12 0c0-4.4 6-11 6-11z"/>',+ gradient: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 4v16M11 4v16" opacity=".55"/><path d="M15 4v16" opacity=".3"/>',+ text: '<path d="M5 6V4h14v2M12 4v16M9 20h6"/>',+ shape: '<rect x="3" y="11" width="9" height="9" rx="1"/><circle cx="15.5" cy="8.5" r="5.5"/>',+ eyedropper: '<path d="m2 22 1-1h3l9-9"/><path d="M3 21v-3l9-9"/><path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3z"/>',+ hand: '<path d="M18 11V6a2 2 0 0 0-4 0v5M14 10V4a2 2 0 0 0-4 0v6M10 10.5V6a2 2 0 0 0-4 0v8"/><path d="M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.9-6-2.4l-3.6-3.6a2 2 0 0 1 2.8-2.8L7 15"/>',+ undo: '<path d="M8 4 3 9l5 5"/><path d="M3 9h11.5a5.5 5.5 0 0 1 0 11H10"/>',+ redo: '<path d="m16 4 5 5-5 5"/><path d="M21 9H9.5a5.5 5.5 0 0 0 0 11H14"/>',+ ccw: '<path d="M4 12a8 8 0 1 0 2.34-5.66"/><path d="M4 4v5h5"/>',+ cw: '<path d="M20 12a8 8 0 1 1-2.34-5.66"/><path d="M20 4v5h-5"/>',+ flipX: '<path d="M12 3v18" stroke-dasharray="2 2.5"/><path d="M9.5 7v10L3.5 12z"/><path d="M14.5 7v10l6-5z"/>',+ flipY: '<path d="M3 12h18" stroke-dasharray="2 2.5"/><path d="M7 9.5h10l-5-6z"/><path d="M7 14.5h10l-5 6z"/>',+ eye: '<path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/>',+ eyeOff: '<path d="M3 3l18 18M10.6 5.1A10.4 10.4 0 0 1 12 5c6.4 0 10 7 10 7a17.6 17.6 0 0 1-3.2 4.1M6.6 6.6C3.9 8.4 2 12 2 12s3.6 7 10 7a9.7 9.7 0 0 0 5.4-1.6"/><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2"/>',+ lock: '<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>',+ link: '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>',+ unlink: '<path d="m18.84 12.25 1.72-1.71h-.02a5 5 0 0 0-.12-7.07 5 5 0 0 0-6.95 0l-1.72 1.71"/><path d="m5.17 11.75-1.71 1.71a5 5 0 0 0 .12 7.07 5 5 0 0 0 6.95 0l1.71-1.71"/><path d="M8 2v3M2 8h3M16 19v3M19 16h3"/>',+ plus: '<path d="M12 5v14M5 12h14"/>',+ image: '<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="2"/><path d="m21 16-5-5L5 20"/>',+ copy: '<rect x="8" y="8" width="13" height="13" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/>',+ trash: '<path d="M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14"/>',+ up: '<path d="m6 14 6-6 6 6"/>',+ down: '<path d="m6 10 6 6 6-6"/>',+ mask: '<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="12" cy="12" r="4.5" fill="currentColor" stroke="none" opacity=".75"/>',+ swap: '<path d="M7 4 4 7l3 3"/><path d="M4 7h11a5 5 0 0 1 5 5v1"/><path d="m17 20 3-3-3-3"/>',+ minus: '<path d="M5 12h14"/>',+ edit: '<path d="M4 20h4L18.5 9.5a2.1 2.1 0 0 0-3-3L5 17z"/><path d="m14 8 2 2"/>',+};+export const icon = (name, size = 18) => SVG(ICONS[name], size);++function el(tag, text, className) {+ const node = document.createElement(tag);+ if (text != null) node.textContent = text;+ if (className) node.className = className;+ return node;+}+function button(label, title, action, className = 'fv-ie-button') {+ const b = el('button', label, className); b.type = 'button';+ // A visible label is the accessible name; the title only adds the hint.+ if (title) { b.title = title; if (!label) b.setAttribute('aria-label', title); }+ if (action) b.onclick = action;+ return b;+}+function iconButton(name, title, action, className = 'fv-ie-icon') {+ const b = button('', title, action, className); b.innerHTML = SVG(ICONS[name]); return b;+}+function paint(input) {+ const min = Number(input.min), max = Number(input.max), value = Number(input.value);+ const p = (value - min) / (max - min), z = min < 0 && max > 0 ? -min / (max - min) : 0;+ input.style.setProperty('--fv-lo', Math.min(p, z));+ input.style.setProperty('--fv-hi', Math.max(p, z));+ // A one-way slider fills from its left end, not from under the thumb's centre.+ input.style.setProperty('--fv-two', z > 0 ? 1 : 0);+}+function slider(id, label, min, max, step, value, onInput, onChange, unit = '') {+ const row = el('div', null, 'fv-ie-slider');+ const input = el('input'); Object.assign(input, {type: 'range', min, max, step, value, id});+ input.classList.add('fv-ie-range'); paint(input);+ const lab = el('label', label); lab.htmlFor = id;+ const out = el('output', String(value) + unit); out.htmlFor = id;+ input.oninput = () => { paint(input); out.textContent = input.value + unit; onInput(Number(input.value)); };+ input.onchange = () => onChange?.(Number(input.value));+ // Double-click a slider to put it back to zero.+ input.ondblclick = () => { input.value = String(clamp(0, min, max)); input.oninput(); input.onchange(); };+ row.append(lab, out, input);+ return {row, input, out};+}+function segmented(options, value, onPick, label) {+ const group = el('div', null, 'fv-ie-seg'); group.setAttribute('role', 'group');+ if (label) group.setAttribute('aria-label', label);+ const buttons = options.map(([id, text, icon]) => {+ const b = icon ? iconButton(icon, text, null, 'fv-ie-seg-item fv-ie-seg-icon') : button(text, null, null, 'fv-ie-seg-item');+ b.dataset.value = id; group.append(b);+ b.onclick = () => { set(id); onPick(id); };+ return b;+ });+ const set = v => buttons.forEach(b => b.setAttribute('aria-pressed', String(b.dataset.value === v)));+ set(value);+ return {group, set};+}+function loadImage(src) {+ return new Promise((resolve, reject) => {+ const image = new Image(); image.onload = () => resolve(image); image.onerror = () => reject(new Error('load')); image.src = src;+ });+}+const strip = d => JSON.stringify({...d, active: null, layers: d.layers.map(l => ({...l, name: ''}))});++/**+ * Open the editor over everything else.+ * Resolves to {blob, name, edit, width, height} on Save, {restore: true} when+ * every change was undone, or null when the person leaves without saving.+ * source: original image file; resolve(file) → URL; upload(file) → {file};+ * target: {width, height} of the video, if known; library: [{file, label}] other media images.+ */+export async function openImageEditor({source, name, target = null, edit = null, role = 'reference', t, resolve,+ upload = null, library = [], tool: startTool = null}) {+ const baseImage = await loadImage(resolve(source));+ const renderer = new Renderer(resolve);+ const fresh = !edit;+ const original = () => { const d = migrate(null, source, baseImage); d.layers[0].name = t('Original', '原图'); return d; };+ let doc = edit ? migrate(edit, source, baseImage) : original();+ doc = {...doc, layers: doc.layers.map(l => l.id === 'base' ? {...l, name: t('Original', '原图')} : l)};+ if (fresh && target && role !== 'reference') {+ // A keyframe becomes the first or last frame of the video: start from its shape.+ doc = {...doc, ratio: 'video', crop: fitRect(target.width / target.height, canvasRect(doc))};+ }+ // Text draws with the fonts that ship with FreeVideo; the text tool starts in bold sans.+ await Promise.all([renderer.preload(doc), loadFont('sans', 700)]);+ // A text box measured with other fonts (or by another renderer) fits its text again,+ // keeping its place and scale. It is part of opening, not a change to undo or save.+ doc = {...doc, layers: doc.layers.map(l => {+ if (l.kind !== 'text') return l;+ const size = measureText(l.text);+ if (Math.abs(size.nw - l.nw) <= 1 && Math.abs(size.nh - l.nh) <= 1) return l;+ const sx = l.w / l.nw, sy = l.h / l.nh;+ return {...l, ...size, w: size.nw * sx, h: size.nh * sy};+ })};+ const initial = doc;+ let history = [doc], future = [];+ let selection = null; // {parts, feather, invert}; not part of the saved document+ let maskTarget = false; // painting goes to the active layer's mask+ let fg = '#ffffff', bg = '#111111';+ let healing = null; // a heal stroke about to be applied; Save and leaving wait for it+ let tool = 'move';+ const opts = {+ marquee: {shape: 'rect', mode: 'replace', feather: 0}, lasso: {type: 'free', mode: 'replace', feather: 0},+ wand: {tolerance: 24, contiguous: true, mode: 'replace'},+ brush: {size: .02, hardness: .85, opacity: 1}, eraser: {size: .035, hardness: .7, opacity: 1},+ heal: {size: .025, hardness: .6, text: false}, clone: {size: .035, hardness: .6, opacity: 1, source: null, offset: null, picking: false},+ blur: {size: .05, hardness: .4, strength: .6}, gradient: {shape: 'linear', end: 'bg'},+ text: {font: 'sans', weight: 700, align: 'left', outline: false, shadow: true},+ shape: {type: 'rect', width: 6},+ move: {auto: true},+ };+ const extension = /\.jpe?g$/i.test(name) ? 'jpg' : 'png';+ const stem = name.split('/').pop().replace(/\.[^.]+$/, '').replace(/-edit$/, '');++ // ----- frame --------------------------------------------------------------+ const dialog = el('dialog', null, 'fv-image-editor');+ dialog.setAttribute('aria-label', t('Edit image', '编辑素材图'));+ const header = el('header', null, 'fv-ie-header');+ const title = el('div', null, 'fv-ie-title');+ // The picture's size; clicking it opens Image size.+ const sizeLabel = el('button', '', 'fv-ie-size'); sizeLabel.type = 'button';+ sizeLabel.title = t('Image size…', '图像大小…'); sizeLabel.onclick = () => imageSizeDialog();+ title.append(el('strong', t('Edit image', '编辑素材图')), el('span', name.split('/').pop(), 'fv-ie-file'), sizeLabel);+ const zoomLabel = button('100%', t('Fit to window (Ctrl+0)', '适合窗口(Ctrl+0)'), () => fit(), 'fv-ie-zoom-label');+ const zoom = el('div', null, 'fv-ie-zoom');+ zoom.append(iconButton('minus', t('Zoom out (Ctrl −)', '缩小(Ctrl −)'), () => zoomBy(1 / 1.25)), zoomLabel,+ iconButton('plus', t('Zoom in (Ctrl +)', '放大(Ctrl +)'), () => zoomBy(1.25)));+ const undo = iconButton('undo', t('Undo (Ctrl+Z)', '撤销(Ctrl+Z)'), () => step(-1));+ const redo = iconButton('redo', t('Redo (Ctrl+Shift+Z)', '重做(Ctrl+Shift+Z)'), () => step(1));+ const reset = button(t('Reset', '全部重置'), t('Back to the original image', '回到原图,清除全部修改'), () => { deselectQuiet(); const next = original(); followSize(doc, next); commit(next); }, 'fv-ie-button fv-ie-reset');+ const cancel = button(t('Cancel', '取消'), null, () => leave());+ const save = button(t('Save', '保存'), t('Save (Ctrl+Enter)', '保存(Ctrl+Enter)'), () => finish(), 'fv-ie-button fv-ie-primary');+ const actions = el('div', null, 'fv-ie-actions'); actions.append(undo, redo, reset, cancel, save);+ header.append(title, zoom, actions);++ const main = el('div', null, 'fv-ie-main');+ const toolbar = el('nav', null, 'fv-ie-toolbar'); toolbar.setAttribute('aria-label', t('Tools', '工具'));+ const workspace = el('div', null, 'fv-ie-workspace');+ const optionsBar = el('div', null, 'fv-ie-options');+ const stage = el('div', null, 'fv-ie-stage'); stage.tabIndex = -1;+ const view = el('canvas', null, 'fv-ie-view');+ const ants = el('canvas', null, 'fv-ie-ants');+ const overlay = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); overlay.classList.add('fv-ie-overlay');+ const hint = el('div', '', 'fv-ie-hint'); hint.hidden = true;+ stage.append(view, ants, overlay, hint);+ workspace.append(optionsBar, stage);+ const panel = el('aside', null, 'fv-ie-panel');+ const props = el('section', null, 'fv-ie-props');+ const layersBox = el('section', null, 'fv-ie-layers');+ panel.append(props, layersBox);+ main.append(toolbar, workspace, panel);+ const confirmBar = el('div', null, 'fv-ie-confirm'); confirmBar.hidden = true;+ confirmBar.append(el('span', t('Leave without saving? Your changes to this image will be lost.', '不保存就离开?对这张图的修改会丢失。')),+ button(t('Discard', '放弃修改'), null, () => close(null), 'fv-ie-button fv-ie-danger'),+ button(t('Keep editing', '继续编辑'), null, () => { confirmBar.hidden = true; save.focus(); }));+ const status = el('div', '', 'fv-ie-status'); status.setAttribute('role', 'status');+ const filePicker = el('input'); filePicker.type = 'file'; filePicker.accept = 'image/*'; filePicker.hidden = true;+ dialog.append(header, main, confirmBar, status, filePicker);+ document.body.append(dialog);++ // ----- tools ----------------------------------------------------------------+ const TOOLS = [+ ['move', t('Move', '移动'), 'V'], ['crop', t('Crop and canvas', '裁剪与画布'), 'C'], null,+ ['marquee', t('Marquee', '选框'), 'M'], ['lasso', t('Lasso', '套索'), 'L'], ['wand', t('Magic wand', '魔棒'), 'W'], null,+ ['brush', t('Brush', '画笔'), 'B'], ['eraser', t('Eraser', '橡皮擦'), 'E'], ['heal', t('Spot healing', '污点修复'), 'J'],+ ['clone', t('Clone stamp', '仿制图章'), 'S'], ['blur', t('Blur', '模糊'), 'R'], ['gradient', t('Gradient', '渐变'), 'G'], null,+ ['text', t('Text', '文字'), 'T'], ['shape', t('Shape', '形状'), 'U'], ['eyedropper', t('Eyedropper', '吸管'), 'I'], ['hand', t('Hand', '抓手'), 'H'],+ ];+ const toolButtons = {};+ for (const entry of TOOLS) {+ if (!entry) { toolbar.append(el('span', null, 'fv-ie-tool-gap')); continue; }+ const [id, label, key] = entry;+ const b = iconButton(id === 'marquee' ? 'marquee' : id, `${label} (${key})`, () => select(id), 'fv-ie-tool');+ b.dataset.tool = id; toolButtons[id] = b; toolbar.append(b);+ }+ const colors = el('div', null, 'fv-ie-colors');+ const fgInput = el('input'); fgInput.type = 'color'; fgInput.className = 'fv-ie-fg'; fgInput.value = fg;+ fgInput.title = t('Foreground color', '前景色'); fgInput.setAttribute('aria-label', fgInput.title);+ const bgInput = el('input'); bgInput.type = 'color'; bgInput.className = 'fv-ie-bg'; bgInput.value = bg;+ bgInput.title = t('Background color', '背景色'); bgInput.setAttribute('aria-label', bgInput.title);+ fgInput.oninput = () => { fg = fgInput.value; };+ bgInput.oninput = () => { bg = bgInput.value; };+ colors.append(bgInput, fgInput, iconButton('swap', t('Swap colors (X)', '交换前景色和背景色(X)'), () => swapColors(), 'fv-ie-swap'));+ toolbar.append(el('span', null, 'fv-ie-tool-fill'), colors);+ function swapColors() { [fg, bg] = [bg, fg]; fgInput.value = fg; bgInput.value = bg; }++ // ----- geometry ---------------------------------------------------------------+ let viewState = {zoom: 1, panX: 0, panY: 0};+ let layout = {w: 1, h: 1, k: 1, fitK: 1, ox: 0, oy: 0, dpr: 1};+ const rect = () => canvasRect(doc);+ function computeLayout() {+ // Layout size, not the on-screen box: the dialog's opening animation scales it slightly.+ const box = {width: stage.clientWidth, height: stage.clientHeight}, r = rect(), pad = 56;+ const fitK = Math.max(.001, Math.min((box.width - pad) / r.w, (box.height - pad) / r.h));+ const k = fitK * viewState.zoom;+ layout = {w: Math.max(1, box.width), h: Math.max(1, box.height), k, fitK, dpr: Math.min(window.devicePixelRatio || 1, 2),+ ox: (box.width - r.w * k) / 2 + viewState.panX - r.x * k, oy: (box.height - r.h * k) / 2 + viewState.panY - r.y * k};+ }+ // Screen ↔ oriented ↔ document ↔ layer fractions.+ const toO = (sx, sy) => [(sx - layout.ox) / layout.k, (sy - layout.oy) / layout.k];+ const fromO = (x, y) => [layout.ox + x * layout.k, layout.oy + y * layout.k];+ const toD = ([x, y]) => { const p = orientMatrix(doc).inverse().transformPoint(new DOMPoint(x, y)); return [p.x, p.y]; };+ const fromD = ([x, y]) => { const p = orientMatrix(doc).transformPoint(new DOMPoint(x, y)); return [p.x, p.y]; };+ const toLocal = (layer, [x, y]) => { const p = layerMatrix(layer).inverse().transformPoint(new DOMPoint(x, y)); return [p.x / layer.nw, p.y / layer.nh]; };+ const pointer = event => {+ const box = stage.getBoundingClientRect(), sx = stage.clientWidth / (box.width || 1), sy = stage.clientHeight / (box.height || 1);+ return [(event.clientX - box.left) * sx, (event.clientY - box.top) * sy];+ };+ function fitRect(aspect, r) {+ if (!aspect) return {...r};+ let w = r.w, h = r.w / aspect;+ if (h > r.h) { h = r.h; w = h * aspect; }+ return {x: r.x + (r.w - w) / 2, y: r.y + (r.h - h) / 2, w, h};+ }+ const active = () => doc.layers.find(l => l.id === doc.active) || doc.layers[0];+ const replaceLayer = (id, patch) => ({...doc, layers: doc.layers.map(l => l.id === id ? {...l, ...(typeof patch === 'function' ? patch(l) : patch)} : l)});+ // A new layer that reads upright on screen whatever the canvas orientation;+ // angle is its tilt as seen on screen.+ function upright(w, h, angle = 0) {+ const mirrored = doc.flipX !== doc.flipY;+ return {w, h, rotation: (mirrored ? -angle : angle) - doc.rotate, flipX: doc.flipX, flipY: doc.flipY};+ }+ // Brush sizes are fractions of the picture's shorter side, in document pixels.+ const brushPixels = size => size * Math.min(doc.width, doc.height);++ // ----- history ------------------------------------------------------------------+ // panels: true redraws the side panels and options; 'layers' only the layer list.+ function commit(next, panels = true) {+ // The same state twice (a slider that reports its change again) is one step.+ const last = history[history.length - 1];+ if (next !== last && JSON.stringify(next) === JSON.stringify(last)) { doc = last; refresh(panels); return; }+ doc = next;+ if (next === last) { refresh(panels); return; }+ history.push(doc); if (history.length > HISTORY) history.shift();+ future = [];+ refresh(panels);+ }+ // A step being dragged: drawn, not yet in the history.+ function preview(next) { doc = next; refresh(false); }+ function step(direction) {+ const before = doc;+ if (direction < 0 && history.length > 1) { future.push(history.pop()); doc = history[history.length - 1]; }+ else if (direction > 0 && future.length) { history.push(future.pop()); doc = history[history.length - 1]; }+ else return;+ followSize(before, doc);+ if (!doc.layers.some(l => l.id === doc.active)) doc = {...doc, active: doc.layers[doc.layers.length - 1].id};+ if (maskTarget && !active().mask) maskTarget = false;+ refresh(true);+ }+ const changed = () => history.length > 1 && strip(doc) !== strip(initial);+ async function refresh(panels) {+ if (doc.layers.some(l => l.src && !renderer.loaded(l.src))) await renderer.preload(doc);+ computeLayout(); draw(); controls();+ if (panels === 'layers') renderLayers();+ else if (panels) { renderPanels(); renderOptions(); keepFocus(); }+ }+ // Re-rendered controls can take the focused button with them: keep keys in the editor.+ function keepFocus() {+ if (dialog.open && !dialog.contains(document.activeElement)) stage.focus({preventScroll: true});+ }++ // ----- drawing ------------------------------------------------------------------+ let composited = null; // {scale, canvas, doc}+ let liveStroke = null; // stroke in progress, drawn over the picture+ function previewScale() {+ const want = Math.min(1, layout.k * layout.dpr);+ let s = 1; while (s / 2 >= want && s > 1 / 64) s /= 2;+ return s;+ }+ function picture() {+ const s = previewScale();+ if (!composited || composited.scale !== s || composited.doc !== doc) {+ if (composited && composited.scale !== s) renderer.prune(renderer.scales(doc, s));+ composited = {scale: s, doc, canvas: renderer.composite(doc, s)};+ }+ return composited;+ }+ function draw() {+ const ctx = view.getContext('2d'), dpr = layout.dpr;+ const w = Math.round(layout.w * dpr), h = Math.round(layout.h * dpr);+ if (view.width !== w || view.height !== h) { view.width = w; view.height = h; ants.width = w; ants.height = h; }+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, w, h);+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ const r = rect(), [x0, y0] = fromO(r.x, r.y);+ // Transparency shows as a checkerboard.+ ctx.fillStyle = checker(ctx); ctx.fillRect(x0, y0, r.w * layout.k, r.h * layout.k);+ const {canvas: pic} = picture();+ ctx.imageSmoothingQuality = 'high';+ ctx.drawImage(pic, x0, y0, r.w * layout.k, r.h * layout.k);+ if (liveStroke) drawLiveStroke(ctx);+ drawOverlay();+ }+ let checkerPattern = null;+ function checker(ctx) {+ if (!checkerPattern) {+ const c = document.createElement('canvas'); c.width = c.height = 16; const x = c.getContext('2d');+ x.fillStyle = '#262d39'; x.fillRect(0, 0, 16, 16); x.fillStyle = '#313948'; x.fillRect(0, 0, 8, 8); x.fillRect(8, 8, 8, 8);+ checkerPattern = ctx.createPattern(c, 'repeat');+ }+ return checkerPattern;+ }+ function drawLiveStroke(ctx) {+ const {points, size, color, kind, opacity} = liveStroke;+ ctx.save(); ctx.lineCap = 'round'; ctx.lineJoin = 'round';+ ctx.strokeStyle = ctx.fillStyle = kind === 'paint' ? color : 'rgba(255,255,255,.4)';+ ctx.globalAlpha = kind === 'paint' ? opacity : 1;+ ctx.lineWidth = size;+ const pts = points.map(p => fromO(...fromD(p)));+ ctx.beginPath();+ if (pts.length === 1) { ctx.arc(pts[0][0], pts[0][1], size / 2, 0, Math.PI * 2); ctx.fill(); }+ else { ctx.moveTo(...pts[0]); for (const p of pts.slice(1)) ctx.lineTo(...p); ctx.stroke(); }+ ctx.restore();+ }++ // Overlay: crop frame, transform box, brush cursor, drags in progress.+ const svg = (tag, attrs = {}) => { const n = document.createElementNS('http://www.w3.org/2000/svg', tag); for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, v); return n; };+ let cursorPos = null, gesture = null, antsPhase = 0;+ function drawOverlay() {+ overlay.replaceChildren();+ overlay.setAttribute('width', layout.w); overlay.setAttribute('height', layout.h);+ const r = rect(), [cx0, cy0] = fromO(r.x, r.y);+ const c = doc.crop, [x, y] = fromO(c.x, c.y), w = c.w * layout.k, h = c.h * layout.k;+ const full = Math.abs(r.x - c.x) < .5 && Math.abs(r.y - c.y) < .5 && Math.abs(r.w - c.w) < .5 && Math.abs(r.h - c.h) < .5;+ if (!full || tool === 'crop') {+ overlay.append(svg('path', {d: `M${cx0},${cy0}h${r.w * layout.k}v${r.h * layout.k}h${-r.w * layout.k}z M${x},${y}v${h}h${w}v${-h}z`,+ class: tool === 'crop' ? 'fv-ie-dim' : 'fv-ie-dim fv-ie-dim-soft', 'fill-rule': 'evenodd'}));+ overlay.append(svg('rect', {x, y, width: w, height: h, class: tool === 'crop' ? 'fv-ie-crop-frame' : 'fv-ie-crop-frame fv-ie-dashed'}));+ }+ if (tool === 'crop') {+ for (const i of [1, 2]) {+ overlay.append(svg('line', {x1: x + w * i / 3, y1: y, x2: x + w * i / 3, y2: y + h, class: 'fv-ie-third'}));+ overlay.append(svg('line', {x1: x, y1: y + h * i / 3, x2: x + w, y2: y + h * i / 3, class: 'fv-ie-third'}));+ }+ for (const [id, hx, hy] of [['nw', x, y], ['n', x + w / 2, y], ['ne', x + w, y], ['e', x + w, y + h / 2], ['se', x + w, y + h], ['s', x + w / 2, y + h], ['sw', x, y + h], ['w', x, y + h / 2]])+ overlay.append(svg('rect', {x: hx - 5, y: hy - 5, width: 10, height: 10, rx: 2, class: 'fv-ie-handle', 'data-handle': id}));+ }+ if (gesture?.preview) overlay.append(gesture.preview());+ if (tool === 'move' && !maskTarget) drawTransformBox();+ if (['brush', 'eraser', 'heal', 'clone', 'blur'].includes(tool) && cursorPos) {+ const radius = brushPixels(opts[tool].size) * layout.k / 2;+ overlay.append(svg('circle', {cx: cursorPos[0], cy: cursorPos[1], r: Math.max(2, radius), class: 'fv-ie-brush'}));+ if (tool === 'clone' && opts.clone.source) {+ const [sx, sy] = fromO(...fromD(opts.clone.source));+ overlay.append(svg('path', {d: `M${sx - 8},${sy}h16M${sx},${sy - 8}v16`, class: 'fv-ie-source'}));+ }+ }+ drawAnts();+ }+ function layerCorners(layer) {+ const m = new DOMMatrix(orientMatrix(doc)).multiplySelf(layerMatrix(layer));+ return [[0, 0], [layer.nw, 0], [layer.nw, layer.nh], [0, layer.nh]].map(([px, py]) => { const p = m.transformPoint(new DOMPoint(px, py)); return fromO(p.x, p.y); });+ }+ function drawTransformBox() {+ const layer = active();+ if (!layer || layer.locked || !layer.visible) return;+ const pts = layerCorners(layer);+ overlay.append(svg('polygon', {points: pts.map(p => p.join(',')).join(' '), class: 'fv-ie-box'}));+ const mid = (a, b) => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];+ const list = [['c0', pts[0]], ['e01', mid(pts[0], pts[1])], ['c1', pts[1]], ['e12', mid(pts[1], pts[2])], ['c2', pts[2]], ['e23', mid(pts[2], pts[3])], ['c3', pts[3]], ['e30', mid(pts[3], pts[0])]];+ for (const [id, [hx, hy]] of list) overlay.append(svg('rect', {x: hx - 5, y: hy - 5, width: 10, height: 10, rx: 2, class: 'fv-ie-handle', 'data-handle': id}));+ const top = mid(pts[0], pts[1]), centre = mid(pts[0], pts[2]);+ const len = Math.hypot(top[0] - centre[0], top[1] - centre[1]) || 1;+ const knob = [top[0] + (top[0] - centre[0]) / len * 26, top[1] + (top[1] - centre[1]) / len * 26];+ overlay.append(svg('line', {x1: top[0], y1: top[1], x2: knob[0], y2: knob[1], class: 'fv-ie-box'}));+ overlay.append(svg('circle', {cx: knob[0], cy: knob[1], r: 6, class: 'fv-ie-handle fv-ie-rotate', 'data-handle': 'rotate'}));+ }+ // Marching ants: the selection's edge, striped, moving.+ let antsEdge = null;+ function selectionEdge() {+ const s = previewScale(), key = JSON.stringify([selection, s]) + (selection?.parts.some(p => p.shape === 'wand') ? composited?.doc === doc : '');+ if (antsEdge?.key === key && antsEdge.doc === doc) return antsEdge.canvas;+ const mask = renderer.selectionMask(doc, selection, {layer: canvasLayer(), scale: s});+ const shifted = (dx, dy) => { const c = document.createElement('canvas'); c.width = mask.width; c.height = mask.height; const x = c.getContext('2d');+ x.drawImage(mask, 0, 0); x.globalCompositeOperation = 'xor'; x.drawImage(mask, dx, dy); return c; };+ const edge = shifted(1, 0); edge.getContext('2d').drawImage(shifted(0, 1), 0, 0);+ antsEdge = {key, doc, canvas: edge};+ return edge;+ }+ function drawAnts() {+ const ctx = ants.getContext('2d');+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, ants.width, ants.height);+ if (!selection) return;+ const edge = selectionEdge(), r = rect(), [x0, y0] = fromO(r.x, r.y), dpr = layout.dpr;+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.imageSmoothingEnabled = false;+ ctx.drawImage(edge, x0, y0, r.w * layout.k, r.h * layout.k);+ ctx.globalCompositeOperation = 'source-in';+ const stripe = document.createElement('canvas'); stripe.width = stripe.height = 8; const st = stripe.getContext('2d');+ st.fillStyle = '#fff'; st.fillRect(0, 0, 8, 8); st.fillStyle = '#0b0f15'; st.fillRect(0, 0, 4, 8);+ const pattern = ctx.createPattern(stripe, 'repeat');+ pattern.setTransform?.(new DOMMatrix().translateSelf(antsPhase, 0).rotateSelf(45));+ ctx.fillStyle = pattern; ctx.fillRect(0, 0, layout.w, layout.h);+ ctx.globalCompositeOperation = 'source-over';+ }+ function canvasLayer() {+ const r = rect(), centre = toD([r.x + r.w / 2, r.y + r.h / 2]);+ return {id: '#canvas', nw: r.w, nh: r.h, w: r.w, h: r.h, cx: centre[0], cy: centre[1], rotation: -doc.rotate, flipX: doc.flipX, flipY: doc.flipY};+ }+ const antsTimer = setInterval(() => { if (selection && dialog.open) { antsPhase = (antsPhase + 1) % 8; drawAnts(); } }, 120);++ // ----- tool options ---------------------------------------------------------------+ function controls() {+ undo.disabled = history.length < 2; redo.disabled = !future.length;+ const c = doc.crop; sizeLabel.textContent = `${Math.round(c.w)} × ${Math.round(c.h)}`;+ zoomLabel.textContent = Math.round(layout.k * 100) + '%';+ for (const [id, b] of Object.entries(toolButtons)) b.setAttribute('aria-pressed', String(id === tool));+ stage.dataset.tool = tool;+ }+ function select(id) {+ commitText();+ gesture?.cancel?.(); gesture = null;+ tool = id; renderOptions(); controls(); draw(); showHint(); keepFocus();+ }+ function showHint() {+ const layer = active();+ let text = '';+ if (['eraser', 'heal', 'clone', 'blur'].includes(tool) && !rasterKinds.has(layer.kind)) text = t('Pick an image or paint layer to work on its pixels.', '请选择图片图层或绘画图层再处理像素。');+ else if (tool === 'clone' && !opts.clone.source) text = t('Alt-click to set the source, then paint.', '先按住 Alt 点击设置取样点,再涂抹。');+ else if (tool === 'move' && layer.locked && doc.layers.length > 1) text = t('The original image is locked. Click another layer to move it.', '原图图层已锁定;点击其他图层即可移动。');+ else if (tool === 'lasso' && opts.lasso.type === 'polygon') text = t('Click to add corners; double-click or press Enter to close.', '单击添加顶点;双击或按 Enter 闭合。');+ hint.textContent = text; hint.hidden = !text;+ }+ const ratioLabel = id => ({+ video: target ? t(`Video ${target.width}×${target.height}`, `视频画面 ${target.width}×${target.height}`) : t('Video', '视频画面'),+ original: t('Original', '原图比例'), free: t('Free', '自由'),+ })[id] || id;+ function renderOptions() {+ clearPanel(optionsBar);+ const add = (...nodes) => optionsBar.append(...nodes);+ const label = text => el('span', text, 'fv-ie-opt-label');+ const sep = () => el('span', null, 'fv-ie-sep');+ const note = text => el('span', text, 'fv-ie-opt-note');+ const sizeSlider = o => {+ const s = slider(`fv-ie-${tool}-size`, t('Size', '大小'), .002, .25, .001, o.size, v => { o.size = v; s.out.textContent = Math.round(brushPixels(v)) + ' px'; drawOverlay(); });+ s.out.textContent = Math.round(brushPixels(o.size)) + ' px';+ return s.row;+ };+ const pct = (o, key, text) => slider(`fv-ie-${tool}-${key}`, text, 0, 100, 1, Math.round(o[key] * 100), v => { o[key] = v / 100; }, null, '%').row;+ add(el('span', TOOLS.find(x => x?.[0] === tool)?.[1] || '', 'fv-ie-opt-title'));+ if (tool === 'move') {+ const auto = el('label', null, 'fv-ie-check'); const box = el('input'); box.type = 'checkbox'; box.checked = opts.move.auto;+ box.onchange = () => { opts.move.auto = box.checked; }; auto.append(box, el('span', t('Pick layer by clicking', '点击自动选择图层')));+ add(auto, sep(),+ iconButton('flipX', t('Flip layer horizontally', '水平翻转图层'), () => transformLayer(l => ({flipX: !l.flipX}))),+ iconButton('flipY', t('Flip layer vertically', '垂直翻转图层'), () => transformLayer(l => ({flipY: !l.flipY}))),+ button(t('Reset size', '原始大小'), null, () => transformLayer(l => ({w: l.nw, h: l.nh, ...upright(l.nw, l.nh), cx: l.cx, cy: l.cy}))),+ button(t('Cover canvas', '铺满画布'), null, () => transformLayer(cover)));+ } else if (tool === 'crop') {+ const ratio = el('select', null, 'fv-ie-select'); ratio.id = 'fv-ie-ratio'; ratio.setAttribute('aria-label', t('Shape', '比例'));+ for (const [id] of RATIOS) { if (id === 'video' && !target) continue; const o = el('option', ratioLabel(id)); o.value = id; ratio.append(o); }+ ratio.value = doc.ratio; ratio.onchange = () => setRatio(ratio.value);+ add(label(t('Shape', '比例')), ratio, sep(),+ iconButton('ccw', t('Rotate left 90°', '向左旋转 90°'), () => turn('ccw')), iconButton('cw', t('Rotate right 90°', '向右旋转 90°'), () => turn('cw')),+ iconButton('flipX', t('Flip horizontally', '水平翻转'), () => turn('flipX')), iconButton('flipY', t('Flip vertically', '垂直翻转'), () => turn('flipY')), sep());+ if (target) add(button(t('Pad to video shape', '补边到视频比例'), t('Extend the canvas with the background color instead of cropping', '用背景色补边到视频比例,不裁掉画面'), () => padToVideo()));+ add(button(t('Image size…', '图像大小…'), null, () => imageSizeDialog()), button(t('Canvas size…', '画布大小…'), null, () => canvasDialog()));+ } else if (tool === 'marquee' || tool === 'lasso' || tool === 'wand') {+ const o = opts[tool];+ if (tool === 'marquee') add(segmented([['rect', t('Rectangle', '矩形'), 'marquee'], ['ellipse', t('Ellipse', '椭圆'), 'ellipse']], o.shape, v => { o.shape = v; }, t('Shape', '形状')).group);+ if (tool === 'lasso') add(segmented([['free', t('Freehand', '自由套索'), 'lasso'], ['polygon', t('Polygonal', '多边形套索'), 'polygon']], o.type, v => { o.type = v; showHint(); }, t('Type', '类型')).group);+ if (tool === 'wand') {+ add(slider('fv-ie-wand-tolerance', t('Tolerance', '容差'), 0, 100, 1, o.tolerance, v => { o.tolerance = v; }).row);+ const c = el('label', null, 'fv-ie-check'); const box = el('input'); box.type = 'checkbox'; box.checked = o.contiguous;+ box.onchange = () => { o.contiguous = box.checked; }; c.append(box, el('span', t('Contiguous', '连续'))); add(c);+ }+ add(sep(), segmented([['replace', t('New', '新选区')], ['add', t('Add · Shift', '添加 · Shift')], ['subtract', t('Subtract · Alt', '减去 · Alt')]], o.mode, v => { o.mode = v; }, t('Mode', '方式')).group);+ if (tool !== 'wand') add(slider(`fv-ie-${tool}-feather`, t('Feather', '羽化'), 0, 80, 1, o.feather, v => { o.feather = v; }, null, ' px').row);+ add(sep(), ...selectionActions());+ } else if (tool === 'brush' || tool === 'eraser') {+ const o = opts[tool];+ add(sizeSlider(o), pct(o, 'hardness', t('Hardness', '硬度')), pct(o, 'opacity', t('Opacity', '不透明度')));+ if (active().mask) add(sep(), maskToggle());+ else if (tool === 'eraser') add(note(t('Erases pixels of the selected layer.', '擦除当前图层的像素。')));+ } else if (tool === 'heal') {+ const o = opts.heal;+ add(sizeSlider(o), segmented([['all', t('Whole stroke', '整个涂抹区域')], ['text', t('Captions only', '只去字幕')]], o.text ? 'text' : 'all',+ v => { o.text = v === 'text'; renderOptions(); }, t('Heal', '修复范围')).group,+ note(o.text ? t('Paint over a caption: only its white letters and outline are replaced, the picture between them stays.', '涂过字幕即可:只替换白色文字和描边,字与字之间的画面保留。')+ : t('Paint over the whole mark in one stroke; it is filled with texture from around it.', '一笔涂满要去掉的部分,松开后用周围的纹理补上。')));+ } else if (tool === 'clone') {+ const o = opts.clone;+ const pick = button(o.picking ? t('Click the source…', '点击取样位置…') : t('Set source', '设置取样点'), t('Or Alt-click the picture', '也可以按住 Alt 点击画面'),+ () => { o.picking = !o.picking; renderOptions(); }, 'fv-ie-button' + (o.picking ? ' fv-ie-active' : ''));+ add(sizeSlider(o), pct(o, 'hardness', t('Hardness', '硬度')), pct(o, 'opacity', t('Opacity', '不透明度')), pick);+ } else if (tool === 'blur') {+ add(sizeSlider(opts.blur), pct(opts.blur, 'strength', t('Strength', '强度')));+ } else if (tool === 'gradient') {+ const o = opts.gradient;+ add(segmented([['linear', t('Linear', '线性')], ['radial', t('Radial', '径向')]], o.shape, v => { o.shape = v; }, t('Type', '类型')).group,+ segmented([['bg', t('To background color', '到背景色')], ['clear', t('To transparent', '到透明')]], o.end, v => { o.end = v; }, t('End', '终点')).group,+ note(t('Drag across the picture.', '在画面上拖动。')));+ } else if (tool === 'text') {+ add(note(t('Click the picture to add text; click text to edit it.', '点击画面添加文字;点击已有文字进行编辑。')));+ } else if (tool === 'shape') {+ const o = opts.shape;+ add(segmented([['rect', t('Rectangle', '矩形')], ['ellipse', t('Ellipse', '椭圆')], ['line', t('Line', '直线')]], o.type, v => { o.type = v; }, t('Shape', '形状')).group,+ note(t('Drag to draw in the foreground color.', '拖动绘制,使用前景色。')));+ } else if (tool === 'eyedropper') {+ add(note(t('Click to pick the foreground color; Alt-click for the background color.', '点击吸取前景色;按住 Alt 点击吸取背景色。')));+ } else if (tool === 'hand') {+ add(note(t('Drag to pan. With any tool, hold Space to pan; Ctrl + wheel zooms.', '拖动平移画面。任何工具下按住空格都能平移,Ctrl + 滚轮缩放。')));+ }+ }+ function maskToggle() {+ return segmented([['layer', t('On layer', '画在图层')], ['mask', t('On mask', '画在蒙版')]], maskTarget ? 'mask' : 'layer',+ v => { maskTarget = v === 'mask'; renderLayers(); }, t('Paint on', '绘制位置')).group;+ }+ function selectionActions() {+ const off = !selection;+ const list = [+ button(t('All', '全选'), t('Select all (Ctrl+A)', '全选(Ctrl+A)'), () => selectAll()),+ button(t('Invert', '反选'), t('Invert (Ctrl+Shift+I)', '反选(Ctrl+Shift+I)'), () => invertSelection()),+ button(t('Deselect', '取消选区'), t('Deselect (Ctrl+D)', '取消选择(Ctrl+D)'), () => deselect()),+ button(t('Fill', '填充'), t('Fill with the foreground color (Alt+Delete)', '用前景色填充(Alt+Delete)'), () => fillSelection()),+ button(t('Delete', '删除'), t('Clear the selected pixels (Delete)', '清除选中的像素(Delete)'), () => clearSelection()),+ button(t('To layer', '复制为图层'), t('Copy to a new layer (Ctrl+J)', '复制到新图层(Ctrl+J)'), () => copyToLayer()),+ button(t('Mask', '建立蒙版'), t('Show the layer only inside the selection', '只显示选区内的图层内容'), () => maskFromSelection()),+ ];+ list.slice(2).forEach(b => { b.disabled = off; });+ return list;+ }++ // ----- properties and layers -------------------------------------------------------+ function renderPanels() { renderProps(); renderLayers(); }+ // Empty a panel for redrawing. A focused field there leaves first, so its own change and+ // blur handlers run (and may redraw) before its panel is taken apart, not halfway through.+ function clearPanel(box) {+ if (box.contains(document.activeElement)) document.activeElement.blur();+ box.replaceChildren();+ }+ const blendNames = () => ({'source-over': t('Normal', '正常'), multiply: t('Multiply', '正片叠底'), screen: t('Screen', '滤色'), overlay: t('Overlay', '叠加'),+ 'soft-light': t('Soft light', '柔光'), darken: t('Darken', '变暗'), lighten: t('Lighten', '变亮'), 'color-dodge': t('Color dodge', '颜色减淡'),+ 'color-burn': t('Color burn', '颜色加深'), difference: t('Difference', '差值')});+ const field = (text, input) => { const f = el('div', null, 'fv-ie-field'); const l = el('label', text); l.htmlFor = input.id; f.append(l, input); return f; };+ function renderProps() {+ clearPanel(props);+ const layer = active();+ const head = el('div', null, 'fv-ie-section-head');+ head.append(el('h3', layer.kind === 'text' ? t('Text', '文字') : layer.kind === 'shape' ? t('Shape', '形状') : t('Adjust', '调整')),+ el('span', layer.name || '', 'fv-ie-props-name'));+ props.append(head);+ const opacity = slider('fv-ie-opacity', t('Opacity', '不透明度'), 0, 100, 1, Math.round(layer.opacity * 100),+ v => preview(replaceLayer(layer.id, {opacity: v / 100})), v => commit(replaceLayer(layer.id, {opacity: v / 100})), '%');+ const blend = el('select', null, 'fv-ie-select'); blend.id = 'fv-ie-blend';+ for (const [value, text] of Object.entries(blendNames())) { const o = el('option', text); o.value = value; blend.append(o); }+ blend.value = layer.blend || 'source-over'; blend.onchange = () => commit(replaceLayer(layer.id, {blend: blend.value}));+ const basics = el('div', null, 'fv-ie-basics'); basics.append(opacity.row, field(t('Blend', '混合'), blend));+ props.append(basics);+ if (layer.kind === 'text') props.append(textProps(layer));+ else if (layer.kind === 'shape') props.append(shapeProps(layer));+ else props.append(adjustProps(layer));+ }+ function adjustProps(layer) {+ const box = el('div', null, 'fv-ie-adjust');+ const groups = [+ ['light', t('Light', '光线'), [['exposure', t('Exposure', '曝光')], ['contrast', t('Contrast', '对比度')], ['highlights', t('Highlights', '高光')], ['shadows', t('Shadows', '阴影')]]],+ ['colour', t('Color', '颜色'), [['temperature', t('Temperature', '色温')], ['tint', t('Tint', '色调')], ['hue', t('Hue', '色相')], ['saturation', t('Saturation', '饱和度')], ['vibrance', t('Vibrance', '自然饱和度')]]],+ ['effects', t('Effects', '效果'), [['sharpen', t('Sharpen', '锐化')], ['blur', t('Blur', '模糊')], ['noise', t('Grain', '颗粒')], ['vignette', t('Vignette', '暗角')]]],+ ];+ for (const [id, name, items] of groups) {+ const g = el('details', null, 'fv-ie-group'); g.dataset.group = id;+ g.open = openGroups.has(id) || items.some(([k]) => layer.adjust?.[k]);+ g.ontoggle = () => { if (g.open) openGroups.add(id); else openGroups.delete(id); };+ const summary = el('summary', name);+ const touched = items.filter(([k]) => layer.adjust?.[k]).length;+ if (touched) summary.append(el('span', String(touched), 'fv-ie-count'));+ g.append(summary);+ for (const [key, text] of items) {+ const positive = ['sharpen', 'blur', 'noise'].includes(key), range = key === 'hue' ? 180 : 100;+ const set = v => l => ({adjust: {...(l.adjust || emptyAdjust()), [key]: v}});+ g.append(slider(`fv-ie-${key}`, text, positive ? 0 : -range, range, 1, layer.adjust?.[key] || 0,+ v => preview(replaceLayer(layer.id, set(v))), v => commit(replaceLayer(layer.id, set(v)))).row);+ }+ box.append(g);+ }+ box.append(button(t('Reset adjustments', '重置调整'), null, () => commit(replaceLayer(layer.id, {adjust: emptyAdjust()})), 'fv-ie-button fv-ie-quiet'));+ return box;+ }+ const openGroups = new Set(['light']);+ let textArea = null, textEditing = false;+ function textProps(layer) {+ const box = el('div', null, 'fv-ie-fields');+ textArea = el('textarea', null, 'fv-ie-textarea'); textArea.id = 'fv-ie-text'; textArea.value = layer.text.content; textArea.rows = 3;+ textArea.setAttribute('aria-label', t('Text', '文字内容'));+ textArea.oninput = () => { textEditing = true; preview(updateText(layer.id, {content: textArea.value})); };+ // Leaving the text box keeps the other controls in place: the one being clicked must stay.+ textArea.onblur = () => commitText('layers');+ // The bundled fonts only, each name set in its own face.+ const names = {sans: t('Sans', '黑体'), serif: t('Serif', '宋体'), kai: t('Kai', '楷体'), mono: t('Mono', '等宽')};+ const font = segmented(FONT_KEYS.map(k => [k, names[k]]), FONT_KEYS.includes(layer.text.font) ? layer.text.font : 'sans',+ v => setTextFont(layer.id, {font: v}), t('Font', '字体'));+ font.group.id = 'fv-ie-font'; font.group.classList.add('fv-ie-fonts');+ for (const b of font.group.children) b.style.fontFamily = fontStack(b.dataset.value);+ loadFonts(FONT_KEYS.map(k => [k, 400])).catch(() => {});+ const size = el('input'); size.type = 'number'; size.min = '6'; size.max = '2000'; size.value = String(Math.round(layer.text.size)); size.id = 'fv-ie-font-size';+ size.onchange = () => commit(updateText(layer.id, {size: clamp(Number(size.value) || 12, 6, 2000)}));+ const color = el('input'); color.type = 'color'; color.value = layer.text.color; color.id = 'fv-ie-text-color';+ color.onchange = () => commit(updateText(layer.id, {color: color.value}));+ const fontRow = el('div', null, 'fv-ie-font-row'); fontRow.append(el('span', t('Font', '字体'), 'fv-ie-opt-label'), font.group);+ const row = el('div', null, 'fv-ie-pair'); row.append(field(t('Size', '字号'), size), field(t('Color', '颜色'), color));+ // Only the weights that ship: LXGW WenKai's heavier face is a medium.+ const heavy = layer.text.font === 'kai' ? t('Medium', '中粗') : t('Bold', '加粗');+ const style = segmented([['400', t('Regular', '常规')], ['700', heavy]], String(Number(layer.text.weight) >= 550 ? 700 : 400),+ v => setTextFont(layer.id, {weight: Number(v)}), t('Weight', '字重'));+ const align = segmented([['left', t('Left', '左')], ['center', t('Center', '中')], ['right', t('Right', '右')]], layer.text.align, v => commit(updateText(layer.id, {align: v})), t('Align', '对齐'));+ const effects = el('div', null, 'fv-ie-row');+ for (const [key, text] of [['shadow', t('Shadow', '阴影')], ['outline', t('Outline', '描边')]]) {+ const c = el('label', null, 'fv-ie-check'); const cb = el('input'); cb.type = 'checkbox'; cb.checked = !!layer.text[key];+ cb.onchange = () => commit(updateText(layer.id, {[key]: key === 'outline' ? (cb.checked ? '#000000' : false) : cb.checked}));+ c.append(cb, el('span', text)); effects.append(c);+ }+ const styles = el('div', null, 'fv-ie-row'); styles.append(style.group, align.group);+ box.append(textArea, fontRow, row, styles, effects);+ return box;+ }+ // A font or weight change waits for that font, so the text box is measured with it.+ async function setTextFont(id, patch) {+ const layer = doc.layers.find(l => l.id === id);+ if (!layer) return;+ const next = {...layer.text, ...patch};+ if (!fontLoaded(next.font, next.weight)) {+ message(t('Preparing the font…', '正在准备字体…'));+ try { await loadFont(next.font, next.weight); }+ catch { message(t('The font could not be loaded. Reload the page and try again.', '字体加载失败,请刷新页面后重试。')); renderProps(); return; }+ message('');+ }+ if (dialog.open && doc.layers.some(l => l.id === id)) commit(updateText(id, patch));+ }+ function updateText(id, patch) {+ return replaceLayer(id, l => { const text = {...l.text, ...patch}; const size = measureText(text);+ const sx = l.w / l.nw, sy = l.h / l.nh; return {text, ...size, w: size.nw * sx, h: size.nh * sy}; });+ }+ function commitText(panels = true) {+ if (!textEditing) return;+ textEditing = false;+ if (doc !== history[history.length - 1]) commit(doc, panels);+ }+ function shapeProps(layer) {+ const box = el('div', null, 'fv-ie-fields'), s = layer.shape;+ const update = patch => commit(replaceLayer(layer.id, l => ({shape: {...l.shape, ...patch}})));+ const colourRow = (key, text, fallback) => {+ const input = el('input'); input.type = 'color'; input.id = `fv-ie-shape-${key}`; input.value = s[key] || fallback;+ const on = el('input'); on.type = 'checkbox'; on.checked = !!s[key]; on.setAttribute('aria-label', text);+ input.onchange = () => update({[key]: input.value}); on.onchange = () => update({[key]: on.checked ? input.value : null});+ const f = field(text, input); f.prepend(on); return f;+ };+ const width = el('input'); width.type = 'number'; width.min = '1'; width.max = '400'; width.value = String(s.width); width.id = 'fv-ie-shape-width';+ width.onchange = () => update({width: clamp(Number(width.value) || 1, 1, 400)});+ if (s.type !== 'line') box.append(colourRow('fill', t('Fill', '填充'), fg));+ box.append(colourRow('stroke', t('Stroke', '描边'), bg), field(t('Stroke width', '描边粗细'), width));+ if (s.type === 'rect') {+ const radius = el('input'); radius.type = 'number'; radius.min = '0'; radius.max = '2000'; radius.value = String(s.radius || 0); radius.id = 'fv-ie-shape-radius';+ radius.onchange = () => update({radius: clamp(Number(radius.value) || 0, 0, 2000)});+ box.append(field(t('Corner radius', '圆角'), radius));+ }+ return box;+ }+ function renderLayers() {+ clearPanel(layersBox);+ const layer = active(), index = doc.layers.findIndex(l => l.id === layer.id);+ const head = el('div', null, 'fv-ie-section-head');+ head.append(el('h3', t('Layers', '图层')));+ const tools = el('div', null, 'fv-ie-layer-tools');+ const addMenu = el('details', null, 'fv-ie-menu');+ const summary = el('summary'); summary.innerHTML = SVG(ICONS.image, 16); summary.title = t('Add image layer', '添加图片图层'); summary.setAttribute('aria-label', summary.title);+ const menu = el('div', null, 'fv-ie-menu-list');+ if (upload) menu.append(button(t('From this computer…', '从电脑选择…'), null, () => { addMenu.open = false; filePicker.click(); }, 'fv-ie-menu-item'));+ if (library.length) menu.append(el('div', t('From Media', '来自素材'), 'fv-ie-menu-label'));+ for (const item of library) {+ const b = button('', null, () => { addMenu.open = false; addImageLayer(item.file, item.label); }, 'fv-ie-menu-item');+ const img = el('img'); img.src = resolve(item.file); img.alt = ''; img.loading = 'lazy';+ b.append(img, el('span', item.label)); menu.append(b);+ }+ addMenu.append(summary, menu);+ const del = iconButton('trash', t('Delete layer', '删除图层'), () => deleteLayer());+ const up = iconButton('up', t('Move up', '上移'), () => moveLayer(1)), down = iconButton('down', t('Move down', '下移'), () => moveLayer(-1));+ const maskButton = iconButton('mask', layer.mask ? t('Delete mask', '删除蒙版') : t('Add mask', '添加蒙版'), () => toggleMask(), 'fv-ie-icon' + (layer.mask ? ' fv-ie-active' : ''));+ del.disabled = !!layer.locked; up.disabled = index < 1 || index >= doc.layers.length - 1; down.disabled = index <= 1;+ maskButton.disabled = !rasterKinds.has(layer.kind);+ tools.append(iconButton('plus', t('New paint layer', '新建绘画图层'), () => addPaintLayer()), addMenu, maskButton,+ iconButton('copy', t('Duplicate layer', '复制图层'), () => duplicateLayer()), up, down, del);+ head.append(tools);+ const list = el('ol', null, 'fv-ie-layer-list'); list.setAttribute('aria-label', t('Layers', '图层'));+ for (const l of [...doc.layers].reverse()) {+ const row = el('li', null, 'fv-ie-layer'); row.dataset.id = l.id;+ row.setAttribute('aria-selected', String(l.id === doc.active));+ const eye = iconButton(l.visible ? 'eye' : 'eyeOff', l.visible ? t('Hide layer', '隐藏图层') : t('Show layer', '显示图层'),+ e => { e.stopPropagation(); commit(replaceLayer(l.id, {visible: !l.visible})); }, 'fv-ie-eye');+ const thumb = el('canvas', null, 'fv-ie-thumb'); thumb.width = 48; thumb.height = 34; drawThumb(thumb, l);+ const name = el('span', l.name || t('Layer', '图层'), 'fv-ie-layer-name');+ name.title = t('Double-click to rename', '双击重命名');+ name.ondblclick = e => { e.stopPropagation(); renameLayer(l, name); };+ row.append(eye, thumb);+ if (l.mask) {+ const m = el('canvas', null, 'fv-ie-thumb fv-ie-mask-thumb'); m.width = 48; m.height = 34; drawMaskThumb(m, l);+ m.title = t('Layer mask: click to paint on it', '图层蒙版:点击后画笔画在蒙版上');+ m.onclick = e => { e.stopPropagation(); setActive(l.id); maskTarget = true; renderLayers(); renderOptions(); };+ row.append(m);+ if (l.id === doc.active) (maskTarget ? m : thumb).classList.add('fv-ie-target');+ }+ row.append(name);+ if (l.locked) { const lk = el('span', null, 'fv-ie-lock'); lk.innerHTML = SVG(ICONS.lock, 14); lk.title = t('Locked', '已锁定'); row.append(lk); }+ else if (l.opacity < 1) row.append(el('span', Math.round(l.opacity * 100) + '%', 'fv-ie-layer-opacity'));+ row.onclick = () => { setActive(l.id); maskTarget = false; renderPanels(); renderOptions(); };+ list.append(row);+ }+ layersBox.append(head, list);+ }+ function drawThumb(c, layer) {+ try {+ const s = Math.min(1, 128 / Math.max(layer.nw, layer.nh));+ const img = renderer.layerImage(doc, layer, s);+ const ctx = c.getContext('2d'), k = Math.min(c.width / img.width, c.height / img.height);+ ctx.fillStyle = checker(ctx); ctx.fillRect(0, 0, c.width, c.height);+ ctx.drawImage(img, (c.width - img.width * k) / 2, (c.height - img.height * k) / 2, img.width * k, img.height * k);+ } catch { /* drawn on the next update once its image has loaded */ }+ }+ function drawMaskThumb(c, layer) {+ const m = renderer.maskRaster(doc, layer, Math.min(1, 128 / Math.max(layer.nw, layer.nh)));+ const ctx = c.getContext('2d'); ctx.fillStyle = '#000'; ctx.fillRect(0, 0, c.width, c.height);+ const k = Math.min(c.width / m.width, c.height / m.height);+ ctx.drawImage(m, (c.width - m.width * k) / 2, (c.height - m.height * k) / 2, m.width * k, m.height * k);+ }+ // Choosing a layer is not a step of its own: it rides on the current one.+ function setActive(id) {+ if (doc.active === id) return;+ doc = {...doc, active: id};+ if (history[history.length - 1].active !== id) history[history.length - 1] = {...history[history.length - 1], active: id};+ draw(); controls(); showHint();+ }+ function renameLayer(layer, node) {+ const input = el('input', null, 'fv-ie-rename'); input.value = layer.name; input.setAttribute('aria-label', t('Layer name', '图层名称'));+ node.replaceWith(input); input.focus(); input.select();+ let done = false;+ const finishRename = keep => { if (done) return; done = true; if (keep && input.value.trim() && input.value.trim() !== layer.name) commit(replaceLayer(layer.id, {name: input.value.trim()})); else renderLayers(); };+ input.onkeydown = e => { e.stopPropagation(); if (e.key === 'Enter') finishRename(true); if (e.key === 'Escape') { e.preventDefault(); finishRename(false); } };+ input.onblur = () => finishRename(true);+ input.onclick = e => e.stopPropagation();+ }+ function insertLayer(layer, base = doc) {+ const index = base.layers.findIndex(l => l.id === base.active);+ const layers = [...base.layers]; layers.splice(index + 1, 0, layer);+ maskTarget = false;+ commit({...base, layers, active: layer.id});+ }+ function addPaintLayer() {+ const n = doc.layers.filter(l => l.kind === 'paint').length + 1;+ insertLayer(paintLayer(doc, t(`Paint ${n}`, `绘画 ${n}`)));+ }+ async function addImageLayer(file, label) {+ try {+ const img = await renderer.image(file); renderer.images.get(file).value = img;+ const r = rect(), centre = toD([r.x + r.w / 2, r.y + r.h / 2]);+ // Fit inside two thirds of the canvas, upright on screen.+ const s = Math.min(1, r.w * .66 / img.naturalWidth, r.h * .66 / img.naturalHeight);+ insertLayer({id: uid('l'), kind: 'image', name: label || file.split('/').pop(), src: file, visible: true, locked: false, opacity: 1, blend: 'source-over',+ cx: centre[0], cy: centre[1], ...upright(img.naturalWidth * s, img.naturalHeight * s), nw: img.naturalWidth, nh: img.naturalHeight,+ ops: [], mask: null, adjust: emptyAdjust()});+ select('move');+ } catch { message(t('The image could not be added.', '图片无法添加。')); }+ }+ filePicker.onchange = async () => {+ const file = filePicker.files?.[0]; filePicker.value = '';+ if (!file || !upload) return;+ message(t('Uploading the image…', '正在上传图片…'));+ try { const result = await upload(file); message(''); await addImageLayer(result.file, file.name); }+ catch (error) { message(error.message || t('Upload failed.', '上传失败。')); }+ };+ function duplicateLayer() {+ const layer = active();+ insertLayer({...layer, id: uid('l'), locked: false, name: t(`${layer.name} copy`, `${layer.name} 副本`)});+ }+ function deleteLayer() {+ const layer = active(); if (layer.locked) return;+ const index = doc.layers.findIndex(l => l.id === layer.id);+ const layers = doc.layers.filter(l => l.id !== layer.id);+ maskTarget = false;+ commit({...doc, layers, active: layers[Math.max(0, index - 1)].id});+ }+ function moveLayer(delta) {+ const index = doc.layers.findIndex(l => l.id === doc.active), to = index + delta;+ if (index < 1 || to < 1 || to >= doc.layers.length) return;+ const layers = [...doc.layers]; [layers[index], layers[to]] = [layers[to], layers[index]];+ commit({...doc, layers});+ }+ function toggleMask() {+ const layer = active();+ if (layer.mask) { maskTarget = false; commit(replaceLayer(layer.id, {mask: null})); return; }+ if (!rasterKinds.has(layer.kind)) return;+ maskTarget = true;+ commit(replaceLayer(layer.id, {mask: {ops: selection ? [{id: uid('o'), type: 'fromSelection', selection}] : []}}));+ if (selection) deselect();+ }++ // ----- canvas: shape, orientation, size ----------------------------------------------+ function aspectOf(id, r = rect()) {+ if (id === 'video') return target ? target.width / target.height : null;+ if (id === 'original') return r.w / r.h;+ return RATIOS.find(x => x[0] === id)?.[1] || null;+ }+ function setRatio(id) {+ const r = rect(), aspect = aspectOf(id, r);+ let crop = {...doc.crop};+ if (aspect) {+ const fitted = fitRect(aspect, r), cx = crop.x + crop.w / 2, cy = crop.y + crop.h / 2;+ crop = {...fitted, x: clamp(cx - fitted.w / 2, r.x, r.x + r.w - fitted.w), y: clamp(cy - fitted.h / 2, r.y, r.y + r.h - fitted.h)};+ }+ commit({...doc, ratio: id, crop});+ }+ function turn(op) {+ const before = canvasRect(doc), next = {...doc}, e = doc.extend;+ if (op === 'cw' || op === 'ccw') {+ const mirrored = doc.flipX !== doc.flipY;+ next.rotate = (doc.rotate + ((op === 'cw') !== mirrored ? 90 : 270)) % 360;+ next.extend = op === 'cw' ? {...e, l: e.b, t: e.l, r: e.t, b: e.r} : {...e, l: e.t, t: e.r, r: e.b, b: e.l};+ } else {+ next[op] = !doc[op];+ next.extend = op === 'flipX' ? {...e, l: e.r, r: e.l} : {...e, t: e.b, b: e.t};+ }+ // The crop follows the picture.+ const map = ([x, y]) => {+ const u = (x - before.x) / before.w, v = (y - before.y) / before.h;+ return op === 'cw' ? [1 - v, u] : op === 'ccw' ? [v, 1 - u] : op === 'flipX' ? [1 - u, v] : [u, 1 - v];+ };+ const after = canvasRect(next), c = doc.crop, a = map([c.x, c.y]), b = map([c.x + c.w, c.y + c.h]);+ let crop = {x: after.x + Math.min(a[0], b[0]) * after.w, y: after.y + Math.min(a[1], b[1]) * after.h,+ w: Math.abs(a[0] - b[0]) * after.w, h: Math.abs(a[1] - b[1]) * after.h};+ if ((op === 'cw' || op === 'ccw') && doc.ratio !== 'free') {+ const aspect = aspectOf(doc.ratio, after);+ if (aspect) crop = fitRect(aspect, after);+ }+ commit({...next, crop});+ }+ // Pad (never crop) to the video's shape with the background colour.+ function padToVideo() {+ const [ow, oh] = orientedSize(doc), aspect = target.width / target.height;+ // Whole pixels in total, split between the two sides.+ let l = 0, r = 0, tp = 0, b = 0;+ if (ow / oh < aspect) { const extra = Math.round(oh * aspect - ow); l = Math.floor(extra / 2); r = extra - l; }+ else { const extra = Math.round(ow / aspect - oh); tp = Math.floor(extra / 2); b = extra - tp; }+ const next = {...doc, extend: {l, t: tp, r, b, color: bg}, ratio: 'video'};+ commit({...next, crop: canvasRect(next)});+ }+ function canvasDialog() {+ stage.querySelector('.fv-ie-popover')?.remove();+ const box = el('div', null, 'fv-ie-popover');+ const [ow, oh] = orientedSize(doc), e = doc.extend, inputs = {};+ const grid = el('div', null, 'fv-ie-pad-grid');+ for (const [key, text] of [['t', t('Top', '上')], ['b', t('Bottom', '下')], ['l', t('Left', '左')], ['r', t('Right', '右')]]) {+ const input = el('input'); input.type = 'number'; input.min = '0'; input.max = '20000'; input.value = String(Math.round(e[key])); input.id = `fv-ie-pad-${key}`;+ grid.append(field(text + ' (px)', input)); inputs[key] = input;+ }+ const color = el('input'); color.type = 'color'; color.value = e.color || bg; color.id = 'fv-ie-pad-color';+ const buttons = el('div', null, 'fv-ie-row fv-ie-end');+ buttons.append(button(t('Cancel', '取消'), null, () => box.remove()), button(t('Apply', '应用'), null, () => {+ const extend = {l: +inputs.l.value || 0, t: +inputs.t.value || 0, r: +inputs.r.value || 0, b: +inputs.b.value || 0, color: color.value};+ const next = {...doc, extend}; box.remove();+ commit({...next, crop: canvasRect(next), ratio: 'free'});+ }, 'fv-ie-button fv-ie-primary'));+ box.append(el('h3', t('Canvas size', '画布大小')), el('p', t(`The picture is ${ow} × ${oh} px. Add space on each side:`, `画面 ${ow} × ${oh} 像素,在四周补充空间:`), 'fv-ie-opt-note'),+ grid, field(t('Fill color', '补边颜色'), color), buttons);+ stage.append(box); inputs.t.focus();+ }++ // A selection and the clone source are kept in document pixels: when a step changes the+ // image size they follow it.+ function followSize(before, after) {+ if (before.width === after.width && before.height === after.height) return;+ const sx = after.width / before.width, sy = after.height / before.height;+ selection = scaleSelection(selection, sx, sy); antsEdge = null;+ if (opts.clone.source) opts.clone.source = [opts.clone.source[0] * sx, opts.clone.source[1] * sy];+ }+ // Image size: the whole picture at another size, every layer with it, in one step.+ function imageSizeDialog() {+ commitText();+ stage.querySelector('.fv-ie-popover')?.remove();+ const box = el('div', null, 'fv-ie-popover fv-ie-image-size');+ const cw = doc.crop.w, ch = doc.crop.h, now = [Math.round(cw), Math.round(ch)];+ const sized = k => [Math.max(1, Math.round(cw * k)), Math.max(1, Math.round(ch * k))];+ const long = Math.max(cw, ch), video = target ? Math.max(target.width / cw, target.height / ch) : null;+ const vsize = target ? `${target.width} × ${target.height}` : '';+ // [id, label, size or null when it would not make the picture smaller, why not]+ const presets = [+ ...(target ? [['video', t('Video size', '视频尺寸'), video < 1 ? sized(video) : null,+ t('The picture is no larger than the video', '图片已经不比视频大')]] : []),+ ['half', '50%', sized(.5), ''],+ ['long', t('Long side 2048', '长边 2048'), long > 2048 ? sized(2048 / long) : null,+ t('The long side is already 2048 px or less', '长边已经不超过 2048 像素')],+ ];+ let keep = true, preset = null;+ const choice = segmented(presets.map(([id, text]) => [id, text]), null, id => {+ const size = presets.find(p => p[0] === id)[2];+ width.value = String(size[0]); height.value = String(size[1]); preset = id; update();+ }, t('Presets', '预设'));+ choice.group.classList.add('fv-ie-presets');+ choice.group.querySelectorAll('.fv-ie-seg-item').forEach((b, i) => { if (!presets[i][2]) { b.disabled = true; b.title = presets[i][3]; } });+ const width = el('input'), height = el('input');+ for (const [input, id, v] of [[width, 'fv-ie-size-w', now[0]], [height, 'fv-ie-size-h', now[1]]]) {+ Object.assign(input, {type: 'number', min: '1', max: '20000', step: '1', value: String(v), id}); input.inputMode = 'numeric';+ }+ const number = input => Number(input.value);+ const valid = v => Number.isInteger(v) && v >= 1 && v <= 20000;+ const chain = iconButton('link', t('Keep proportions', '锁定比例'), () => {+ keep = !keep; chain.innerHTML = icon(keep ? 'link' : 'unlink'); chain.setAttribute('aria-pressed', String(keep));+ if (keep && valid(number(width))) height.value = String(Math.max(1, Math.round(number(width) * ch / cw)));+ update();+ }, 'fv-ie-icon fv-ie-chain');+ chain.setAttribute('aria-pressed', 'true');+ width.oninput = () => { preset = null; if (keep && valid(number(width))) height.value = String(Math.max(1, Math.round(number(width) * ch / cw))); update(); };+ height.oninput = () => { preset = null; if (keep && valid(number(height))) width.value = String(Math.max(1, Math.round(number(height) * cw / ch))); update(); };+ const dims = el('div', null, 'fv-ie-dims');+ dims.append(field(t('Width (px)', '宽 (px)'), width), chain, field(t('Height (px)', '高 (px)'), height));+ const notes = el('div', null, 'fv-ie-notes'), result = el('p', '', 'fv-ie-opt-note');+ const stretch = el('p', t('With the proportions changed, pictures and shapes stretch; text keeps its shape.', '比例改变后,图片和形状会拉伸,文字保持原样。'), 'fv-ie-opt-note');+ const vector = doc.layers.some(l => l.kind === 'text' || l.kind === 'shape');+ const texts = doc.layers.some(l => l.kind === 'text');+ const scales = el('p', t('Text and shape layers scale too and stay editable.', '文字和形状图层会一起缩放,仍然可以编辑。'), 'fv-ie-opt-note');+ notes.append(result, stretch, scales);+ const cancel = button(t('Cancel', '取消'), null, () => { box.remove(); stage.focus(); });+ const ok = button(t('Apply', '应用'), null, () => apply(), 'fv-ie-button fv-ie-primary');+ const buttons = el('div', null, 'fv-ie-row fv-ie-end'); buttons.append(cancel, ok);+ let same = true;+ function update() {+ choice.set(preset);+ const w = number(width), h = number(height), kx = w / cw, ky = h / ch;+ // Proportions unchanged when the other side is the rounded one (either way round).+ same = Math.abs(h - Math.round(w * ch / cw)) <= 1 || Math.abs(w - Math.round(h * cw / ch)) <= 1;+ const k = Math.max(kx, ky), pct = v => `${Math.round(v * 100)}%`;+ // How big against the original; verb is the Chinese 缩到 or 放大到.+ const share = verb => same ? t(`${pct(k)} of the original`, `${verb}原来的 ${pct(k)}`)+ : t(`Width ${pct(kx)} and height ${pct(ky)} of the original`, `宽为原来的 ${pct(kx)}、高为原来的 ${pct(ky)}`);+ let text, warn = false, allowed = true;+ if (!valid(w) || !valid(h)) { text = t('Enter whole numbers from 1 to 20000.', '请输入 1 到 20000 的整数。'); warn = true; allowed = false; }+ else if (k > 2 + 1e-9) { text = t('You can enlarge up to 200% of the original.', '最多放大到原来的 200%。'); warn = true; allowed = false; }+ else if (w * h > 64e6) { text = t('Up to 64 megapixels; reduce the width or height.', '最多 6400 万像素,请减小宽或高。'); warn = true; allowed = false; }+ else if (w === now[0] && h === now[1]) { text = t('The same size as now.', '和现在一样大。'); allowed = false; }+ else if (kx > 1 + 1e-9 || ky > 1 + 1e-9) {+ text = t(`${share()}; enlarging makes the picture softer.`, `${share('放大到')},画面会变模糊。`); warn = true;+ } else if (target && presets[0][2] && w === presets[0][2][0] && h === presets[0][2][1]) {+ text = t(`${share()}; fills a ${vsize} video.`, `${share('缩到')},刚好铺满 ${vsize} 的视频。`);+ } else if (target && Math.max(target.width / w, target.height / h) > 1 + 1e-9) {+ text = t(`Smaller than the ${vsize} video; the result will look softer.`, `比 ${vsize} 的视频小,生成的画面会变模糊。`); warn = true;+ } else text = t(`${share()}.`, `${share('缩到')}。`);+ result.textContent = text; result.classList.toggle('fv-ie-note-warn', warn);+ // With the proportions changed, the stretch note says what happens to each kind of layer.+ stretch.hidden = same || !texts || !valid(w) || !valid(h);+ scales.hidden = !vector || !stretch.hidden;+ ok.disabled = !allowed;+ }+ function apply() {+ if (ok.disabled) return;+ const next = resizeDocument(doc, number(width), number(height), keep || same);+ followSize(doc, next);+ box.remove(); stage.focus();+ commit(next);+ }+ box.addEventListener('keydown', event => {+ if (event.key === 'Enter' && !event.ctrlKey && !event.metaKey && event.target.tagName === 'INPUT') { event.preventDefault(); event.stopPropagation(); apply(); }+ });+ box.append(el('h3', t('Image size', '图像大小')),+ el('p', t(`Now ${now[0]} × ${now[1]} px`, `现在 ${now[0]} × ${now[1]} 像素`), 'fv-ie-opt-note'),+ choice.group, dims, notes, buttons);+ update();+ stage.append(box); width.focus(); width.select();+ }++ // ----- selections ---------------------------------------------------------------------+ function addPart(part, mode) {+ if (mode === 'replace' || !selection) selection = {parts: [{...part, mode: 'replace'}], feather: part.feather || 0, invert: false};+ else selection = {...selection, parts: [...selection.parts, {...part, mode}]};+ antsEdge = null; renderOptions(); draw();+ }+ function selectAll() { selection = {parts: [{shape: 'all', mode: 'replace'}], feather: 0, invert: false}; antsEdge = null; renderOptions(); draw(); }+ function deselectQuiet() { selection = null; antsEdge = null; }+ function deselect() { deselectQuiet(); renderOptions(); draw(); }+ function invertSelection() {+ selection = selection ? {...selection, invert: !selection.invert} : {parts: [{shape: 'all', mode: 'replace'}], feather: 0, invert: true};+ antsEdge = null; renderOptions(); draw();+ }+ function pixelLayer() {+ const layer = active();+ if (!rasterKinds.has(layer.kind)) { message(t('Pick an image or paint layer first.', '请先选择图片图层或绘画图层。')); return null; }+ return layer;+ }+ function pushOp(layer, op, base = doc) {+ const entry = {id: uid('o'), ...op};+ doc = base;+ // Only the brush and eraser paint a mask (hide / reveal); every other tool works on pixels.+ if (layer.mask && (op.tool === 'hide' || op.tool === 'reveal')) commit(replaceLayer(layer.id, l => ({mask: {ops: [...l.mask.ops, entry]}})));+ else commit(replaceLayer(layer.id, l => ({ops: [...l.ops, entry]})));+ }+ function fillSelection(color = fg) { const layer = pixelLayer(); if (layer) pushOp(layer, {type: 'fill', color, selection}); }+ function clearSelection() { const layer = pixelLayer(); if (layer && selection) pushOp(layer, {type: 'clear', selection}); }+ function copyToLayer() {+ const layer = pixelLayer(); if (!layer) return;+ const copy = {...layer, id: uid('l'), locked: false, src: null, name: t(`${layer.name} part`, `${layer.name} 局部`), ops: [], mask: null,+ copyOf: {layer: layer.id, upto: layer.ops.length, selection}, adjust: {...layer.adjust}};+ deselectQuiet(); insertLayer(copy); select('move');+ }+ function maskFromSelection() {+ const layer = pixelLayer(); if (!layer || !selection) return;+ maskTarget = true;+ commit(replaceLayer(layer.id, {mask: {ops: [{id: uid('o'), type: 'fromSelection', selection}]}}));+ deselect();+ }++ // ----- pointer ----------------------------------------------------------------------------+ let spaceHeld = false;+ function panGesture(start) {+ const from = {...viewState};+ return {move: p => { viewState = {...from, panX: from.panX + p[0] - start[0], panY: from.panY + p[1] - start[1]}; computeLayout(); draw(); controls(); }};+ }+ stage.addEventListener('pointerdown', event => {+ if (event.target.closest('.fv-ie-popover, .fv-ie-hint')) return;+ stage.focus({preventScroll: true});+ const p = pointer(event);+ if (event.button === 1 || spaceHeld || tool === 'hand') gesture = panGesture(p);+ else if (event.button !== 0) return;+ else if (gesture?.keep) { /* a polygon in progress takes the click on release */ }+ else gesture = startGesture(event, p);+ if (gesture) { stage.setPointerCapture(event.pointerId); event.preventDefault(); }+ });+ stage.addEventListener('pointermove', event => {+ const p = pointer(event); cursorPos = p;+ if (gesture?.move) gesture.move(p, event); else drawOverlay();+ });+ const release = event => {+ if (!gesture) return;+ const g = gesture; if (!g.keep) gesture = null;+ g.up?.(pointer(event), event);+ if (!g.keep) draw();+ };+ stage.addEventListener('pointerup', release);+ stage.addEventListener('pointercancel', event => { if (gesture && !gesture.keep) { gesture.cancel?.(); gesture = null; draw(); } void event; });+ stage.addEventListener('pointerleave', () => { cursorPos = null; drawOverlay(); });+ stage.addEventListener('dblclick', event => {+ if (gesture?.close) { gesture.close(); return; }+ if (tool === 'move' || tool === 'text') {+ const hit = hitLayer(pointer(event));+ if (hit?.kind === 'text') { setActive(hit.id); renderPanels(); textArea?.focus(); textArea?.select(); }+ }+ });+ stage.addEventListener('wheel', event => {+ event.preventDefault();+ if (event.ctrlKey || event.metaKey) zoomAt(pointer(event), Math.exp(-event.deltaY * .0025));+ else { viewState = {...viewState, panX: viewState.panX - event.deltaX, panY: viewState.panY - event.deltaY}; computeLayout(); draw(); controls(); }+ }, {passive: false});++ function hitLayer(p) {+ const d = toD(toO(...p));+ for (const layer of [...doc.layers].reverse()) {+ if (!layer.visible || layer.locked) continue;+ const [u, v] = toLocal(layer, d);+ if (u >= 0 && u <= 1 && v >= 0 && v <= 1) return layer;+ }+ return null;+ }+ function startGesture(event, p) {+ const o = toO(...p), d = toD(o), layer = active();+ const mode = event.shiftKey ? 'add' : event.altKey ? 'subtract' : null;+ if (tool === 'crop') return cropGesture(event, o);+ if (tool === 'move') return moveGesture(event, p, d);+ if (tool === 'marquee') {+ const om = opts.marquee;+ return dragBox(o, (a, b) => {+ const [x1, y1] = toD(a), [x2, y2] = toD(b);+ const part = {shape: om.shape, x: Math.min(x1, x2), y: Math.min(y1, y2), w: Math.abs(x2 - x1), h: Math.abs(y2 - y1), feather: om.feather};+ if (part.w * layout.k < 3 && part.h * layout.k < 3) { if ((mode || om.mode) === 'replace') deselect(); return; }+ addPart(part, mode || om.mode);+ }, om.shape === 'ellipse');+ }+ if (tool === 'lasso') return lassoGesture(o, mode || opts.lasso.mode);+ if (tool === 'wand') {+ const src = rasterKinds.has(layer.kind) ? layer : doc.layers[0];+ const [u, v] = toLocal(src, d);+ if (u < 0 || v < 0 || u > 1 || v > 1) return null;+ addPart({shape: 'wand', layer: src.id, u, v, tolerance: opts.wand.tolerance, contiguous: opts.wand.contiguous, upto: src.ops.length}, mode || opts.wand.mode);+ return null;+ }+ if (tool === 'eyedropper') {+ const {canvas: pic, scale} = picture(), r = rect();+ const x = Math.floor((o[0] - r.x) * scale), y = Math.floor((o[1] - r.y) * scale);+ if (x < 0 || y < 0 || x >= pic.width || y >= pic.height) return null;+ const px = pic.getContext('2d', {willReadFrequently: true}).getImageData(x, y, 1, 1).data;+ if (px[3] < 16) { message(t('Nothing to pick here: this part is transparent.', '这里是透明的,没有可吸取的颜色。')); return null; }+ const hex = '#' + [px[0], px[1], px[2]].map(v => v.toString(16).padStart(2, '0')).join('');+ if (event.altKey) { bg = hex; bgInput.value = hex; } else { fg = hex; fgInput.value = hex; }+ message(t(`Picked ${hex}.`, `已吸取 ${hex}。`));+ return null;+ }+ if (tool === 'text') {+ const hit = hitLayer(p);+ if (hit?.kind === 'text') { setActive(hit.id); renderPanels(); textArea?.focus(); return null; }+ addText(d); return null;+ }+ if (tool === 'shape') return shapeGesture(o);+ // Pixel tools.+ let target = layer, base = doc;+ if ((tool === 'brush' || tool === 'gradient') && (!rasterKinds.has(layer.kind) || (layer.locked && !maskTarget))) {+ // Paint goes on a layer of its own above the picture, so it can be erased or hidden alone.+ const reuse = tool === 'brush' && [...doc.layers].reverse().find(l => l.kind === 'paint' && l.visible);+ if (reuse) { target = reuse; base = {...doc, active: reuse.id}; }+ else {+ const n = doc.layers.filter(l => l.kind === 'paint').length + 1;+ target = paintLayer(doc, tool === 'gradient' ? t('Gradient', '渐变') : t(`Paint ${n}`, `绘画 ${n}`));+ const index = doc.layers.findIndex(l => l.id === doc.active);+ const layers = [...doc.layers]; layers.splice(index + 1, 0, target);+ base = {...doc, layers, active: target.id};+ }+ } else if (!rasterKinds.has(layer.kind)) { message(t('Pick an image or paint layer to work on its pixels.', '请选择图片图层或绘画图层再处理像素。')); return null; }+ if (tool === 'gradient') {+ return dragLine(o, (a, b) => {+ const from = toLocal(target, toD(a)), to = toLocal(target, toD(b));+ pushOp(target, {type: 'gradient', shape: opts.gradient.shape, from, to, c1: fg, c2: opts.gradient.end === 'bg' ? bg : 'transparent', selection}, base);+ });+ }+ if (tool === 'clone' && (event.altKey || opts.clone.picking)) {+ opts.clone.source = d; opts.clone.picking = false; opts.clone.offset = null;+ renderOptions(); showHint(); drawOverlay(); return null;+ }+ if (tool === 'clone' && !opts.clone.source) { message(t('Alt-click to set the source first.', '请先按住 Alt 点击设置取样点。')); return null; }+ return strokeGesture(target, d, base);+ }+ function strokeGesture(layer, d, base) {+ const o = opts[tool], kind = tool === 'brush' ? 'paint' : tool === 'eraser' ? 'erase' : tool, started = doc;+ const sizePx = brushPixels(o.size), points = [d];+ liveStroke = {points, size: sizePx * layout.k, color: fg, kind, opacity: o.opacity ?? 1};+ draw();+ return {+ move(p) {+ const next = toD(toO(...p)), last = points[points.length - 1];+ if (Math.hypot(next[0] - last[0], next[1] - last[1]) * layout.k < 1.5) return;+ points.push(next); draw();+ },+ up() {+ const held = liveStroke;+ liveStroke = null;+ // Kept in this layer's own pixels: fractions of its size, a size relative to its shorter side.+ const pts = points.map(q => toLocal(layer, q).map(v => Math.round(v * 1e5) / 1e5));+ const op = {type: 'stroke', tool: kind, pts, size: sizePx * (layer.nw / layer.w) / Math.min(layer.nw, layer.nh),+ hardness: o.hardness ?? 1, opacity: o.opacity ?? 1, color: fg, selection};+ if (kind === 'clone') {+ const src = toLocal(layer, opts.clone.source), start = toLocal(layer, points[0]);+ // Aligned: the first stroke after picking a source fixes the offset.+ if (!opts.clone.offset) opts.clone.offset = [start[0] - src[0], start[1] - src[1]];+ op.offset = opts.clone.offset;+ }+ if (kind === 'blur') op.strength = o.strength;+ if (kind === 'heal' && o.text) op.text = true;+ if (maskTarget && layer.mask) op.tool = kind === 'paint' ? 'hide' : kind === 'erase' ? 'reveal' : kind;+ if (kind === 'heal') {+ // Healing a large stroke takes a moment: say so, and keep the stroke on screen until it is done.+ liveStroke = held; message(t('Healing…', '正在修复…')); draw();+ healing = new Promise(resolve => setTimeout(() => {+ if (liveStroke === held) liveStroke = null;+ const current = dialog.open && doc.layers.find(l => l.id === layer.id);+ if (current) pushOp(current, op, doc);+ healing = null; message(''); resolve();+ }, 40));+ return;+ }+ // Onto the latest document, unless this stroke made its own layer.+ pushOp(layer, op, base === started ? doc : base);+ },+ cancel() { liveStroke = null; },+ };+ }+ function dragBox(start, done, ellipse = false) {+ let end = start;+ return {+ move(p, event) {+ end = toO(...p);+ if (event?.shiftKey) { const s = Math.max(Math.abs(end[0] - start[0]), Math.abs(end[1] - start[1])); end = [start[0] + Math.sign(end[0] - start[0] || 1) * s, start[1] + Math.sign(end[1] - start[1] || 1) * s]; }+ drawOverlay();+ },+ up() { done(start, end); },+ preview() {+ const [x1, y1] = fromO(...start), [x2, y2] = fromO(...end);+ if (ellipse) return svg('ellipse', {cx: (x1 + x2) / 2, cy: (y1 + y2) / 2, rx: Math.abs(x2 - x1) / 2, ry: Math.abs(y2 - y1) / 2, class: 'fv-ie-drag'});+ return svg('rect', {x: Math.min(x1, x2), y: Math.min(y1, y2), width: Math.abs(x2 - x1), height: Math.abs(y2 - y1), class: 'fv-ie-drag'});+ },+ };+ }+ function dragLine(start, done) {+ let end = start;+ return {+ move(p) { end = toO(...p); drawOverlay(); },+ up() { if (Math.hypot(end[0] - start[0], end[1] - start[1]) * layout.k > 3) done(start, end); },+ preview() { const [x1, y1] = fromO(...start), [x2, y2] = fromO(...end); return svg('line', {x1, y1, x2, y2, class: 'fv-ie-drag'}); },+ };+ }+ function lassoGesture(start, mode) {+ const pts = [start];+ const finish = () => {+ gesture = null;+ if (pts.length < 3) { if (mode === 'replace') deselect(); else draw(); return; }+ addPart({shape: 'poly', pts: pts.map(toD), feather: opts.lasso.feather}, mode);+ };+ const line = extra => svg('polyline', {points: [...pts, ...(extra ? [extra] : [])].map(q => fromO(...q).join(',')).join(' '), class: 'fv-ie-drag'});+ if (opts.lasso.type === 'free') return {move(p) { pts.push(toO(...p)); drawOverlay(); }, up: finish, preview: () => line()};+ // Polygonal: each click adds a corner; double-click, Enter or the first corner closes it.+ let hover = null, first = true;+ return {+ keep: true,+ move(p) { hover = toO(...p); drawOverlay(); },+ up(p) {+ if (first) { first = false; return; }+ const q = toO(...p), [fx, fy] = fromO(...pts[0]), last = fromO(...pts[pts.length - 1]);+ if (pts.length > 2 && Math.hypot(fx - p[0], fy - p[1]) < 9) { finish(); return; }+ if (Math.hypot(last[0] - p[0], last[1] - p[1]) > 2) pts.push(q);+ drawOverlay();+ },+ close: finish,+ cancel() { gesture = null; drawOverlay(); },+ preview: () => line(hover),+ };+ }+ function shapeGesture(o) {+ const kind = opts.shape.type;+ return {...dragBox(o, (a, b) => {+ const width = opts.shape.width, dx = b[0] - a[0], dy = b[1] - a[1];+ if (Math.hypot(dx, dy) * layout.k < 4) return;+ const centre = toD([(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]);+ let w, h, angle = 0;+ if (kind === 'line') { w = Math.hypot(dx, dy); h = Math.max(width * 2, 8); angle = Math.atan2(dy, dx) * 180 / Math.PI; }+ else { w = Math.max(4, Math.abs(dx)); h = Math.max(4, Math.abs(dy)); }+ const shape = {type: kind, fill: kind === 'line' ? null : fg, stroke: kind === 'line' ? fg : null, width, radius: 0};+ insertLayer({id: uid('l'), kind: 'shape', name: {rect: t('Rectangle', '矩形'), ellipse: t('Ellipse', '椭圆'), line: t('Line', '直线')}[kind],+ visible: true, locked: false, opacity: 1, blend: 'source-over', cx: centre[0], cy: centre[1], ...upright(w, h, angle),+ nw: Math.max(1, Math.round(w)), nh: Math.max(1, Math.round(h)), shape, ops: [], mask: null, adjust: emptyAdjust()});+ }, kind === 'ellipse'), ...(kind === 'line' ? {preview: null} : {})};+ }+ function cropGesture(event, o) {+ const handle = event.target.dataset?.handle;+ const r = rect(), c0 = {...doc.crop};+ const inside = o[0] >= c0.x && o[0] <= c0.x + c0.w && o[1] >= c0.y && o[1] <= c0.y + c0.h;+ const kind = handle ? 'resize' : inside ? 'move' : 'new';+ const ratio = kind === 'new' && doc.ratio === 'original' ? 'free' : doc.ratio;+ const aspect = () => aspectOf(ratio, r);+ const limit = c => {+ let {x, y, w, h} = c; const a = aspect();+ w = clamp(w, 8, r.w); h = clamp(h, 8, r.h);+ if (a) { if (w / h > a) w = h * a; else h = w / a; if (w > r.w) { w = r.w; h = w / a; } if (h > r.h) { h = r.h; w = h * a; } }+ return {x: clamp(x, r.x, r.x + r.w - w), y: clamp(y, r.y, r.y + r.h - h), w, h};+ };+ return {+ move(p) {+ const q = toO(...p);+ let c;+ if (kind === 'move') c = {...c0, x: clamp(c0.x + q[0] - o[0], r.x, r.x + r.w - c0.w), y: clamp(c0.y + q[1] - o[1], r.y, r.y + r.h - c0.h)};+ else if (kind === 'new') {+ let w = Math.abs(q[0] - o[0]), h = Math.abs(q[1] - o[1]); const a = aspect();+ if (a) { if (w / Math.max(h, 1e-6) > a) w = h * a; else h = w / a; }+ c = limit({x: q[0] < o[0] ? o[0] - w : o[0], y: q[1] < o[1] ? o[1] - h : o[1], w, h});+ } else {+ let left = c0.x, top = c0.y, right = c0.x + c0.w, bottom = c0.y + c0.h;+ if (handle.includes('w')) left = clamp(q[0], r.x, right - 8);+ if (handle.includes('e')) right = clamp(q[0], left + 8, r.x + r.w);+ if (handle.includes('n')) top = clamp(q[1], r.y, bottom - 8);+ if (handle.includes('s')) bottom = clamp(q[1], top + 8, r.y + r.h);+ let w = right - left, h = bottom - top; const a = aspect();+ if (a) {+ if (handle === 'n' || handle === 's') w = h * a; else if (handle === 'e' || handle === 'w') h = w / a; else if (w / h > a) w = h * a; else h = w / a;+ const ax = handle.includes('w') ? right : handle.includes('e') ? left : c0.x + c0.w / 2;+ const ay = handle.includes('n') ? bottom : handle.includes('s') ? top : c0.y + c0.h / 2;+ left = handle.includes('w') ? ax - w : handle.includes('e') ? ax : ax - w / 2;+ top = handle.includes('n') ? ay - h : handle.includes('s') ? ay : ay - h / 2;+ }+ c = limit({x: left, y: top, w, h});+ }+ preview({...doc, crop: c, ratio});+ },+ up() {+ if (kind === 'new' && (doc.crop.w * layout.k < 6 || doc.crop.h * layout.k < 6)) { doc = history[history.length - 1]; refresh(false); return; }+ if (doc !== history[history.length - 1]) commit(doc);+ },+ cancel() { doc = history[history.length - 1]; refresh(false); },+ };+ }+ function moveGesture(event, p, d) {+ let layer = active();+ const handle = event.target.dataset?.handle;+ if (!handle && opts.move.auto) {+ const hit = hitLayer(p);+ if (hit && hit.id !== layer.id) { setActive(hit.id); maskTarget = false; renderPanels(); layer = hit; }+ }+ if (layer.locked) { showHint(); return null; }+ const l0 = {...layer};+ const frame = new DOMMatrix().translateSelf(l0.cx, l0.cy).rotateSelf(l0.rotation);+ const local = q => { const r = frame.inverse().transformPoint(new DOMPoint(q[0], q[1])); return [r.x, r.y]; };+ // A handle names a corner or edge of the box as drawn; find its side in the layer's own axes.+ let sx = 0, sy = 0;+ if (handle && handle !== 'rotate') {+ const corners = layerCorners(l0);+ const at = handle.startsWith('c') ? corners[+handle[1]] : [(corners[+handle[1]][0] + corners[+handle[2]][0]) / 2, (corners[+handle[1]][1] + corners[+handle[2]][1]) / 2];+ const lp = local(toD(toO(...at)));+ sx = Math.abs(lp[0]) > l0.w * .25 ? Math.sign(lp[0]) : 0; sy = Math.abs(lp[1]) > l0.h * .25 ? Math.sign(lp[1]) : 0;+ }+ return {+ move(pp, ev) {+ const q = toD(toO(...pp));+ let patch;+ if (!handle) patch = {cx: l0.cx + q[0] - d[0], cy: l0.cy + q[1] - d[1]};+ else if (handle === 'rotate') {+ const mirrored = (doc.flipX !== doc.flipY);+ let delta = (Math.atan2(q[1] - l0.cy, q[0] - l0.cx) - Math.atan2(d[1] - l0.cy, d[0] - l0.cx)) * 180 / Math.PI;+ let angle = l0.rotation + delta;+ if (ev?.shiftKey) angle = Math.round(angle / 15) * 15;+ void mirrored; patch = {rotation: angle};+ } else {+ const lq = local(q);+ let w = l0.w, h = l0.h;+ if (sx) w = Math.max(4, sx > 0 ? lq[0] + l0.w / 2 : l0.w / 2 - lq[0]);+ if (sy) h = Math.max(4, sy > 0 ? lq[1] + l0.h / 2 : l0.h / 2 - lq[1]);+ // Corners keep the proportions (Shift frees them); edges stretch one side.+ if (sx && sy && !ev?.shiftKey) { const s = Math.max(w / l0.w, h / l0.h); w = l0.w * s; h = l0.h * s; }+ const c = frame.transformPoint(new DOMPoint(sx ? sx * (w - l0.w) / 2 : 0, sy ? sy * (h - l0.h) / 2 : 0));+ patch = {w, h, cx: c.x, cy: c.y};+ }+ preview(replaceLayer(layer.id, patch));+ },+ up() { if (doc !== history[history.length - 1]) commit(doc); },+ cancel() { doc = history[history.length - 1]; refresh(false); },+ };+ }+ function transformLayer(fn) {+ const layer = active(); if (layer.locked) { showHint(); return; }+ commit(replaceLayer(layer.id, fn(layer)));+ }+ function cover(layer) {+ const r = rect(), centre = toD([r.x + r.w / 2, r.y + r.h / 2]);+ const s = Math.max(r.w / layer.nw, r.h / layer.nh);+ return {cx: centre[0], cy: centre[1], ...upright(layer.nw * s, layer.nh * s)};+ }+ function addText(d) {+ const size = Math.max(16, Math.round(Math.min(doc.width, doc.height) / 12));+ const text = {content: t('Text', '文字'), font: opts.text.font, size, color: fg, weight: opts.text.weight, align: opts.text.align,+ shadow: opts.text.shadow, outline: opts.text.outline, lineHeight: 1.25};+ const {nw, nh} = measureText(text);+ insertLayer({id: uid('l'), kind: 'text', name: t('Text', '文字'), visible: true, locked: false, opacity: 1, blend: 'source-over',+ cx: d[0], cy: d[1], ...upright(nw, nh), nw, nh, text, ops: [], mask: null, adjust: emptyAdjust()});+ requestAnimationFrame(() => { textArea?.focus(); textArea?.select(); });+ }++ // ----- zoom --------------------------------------------------------------------------------+ function zoomAt(p, factor) {+ const before = toO(...p);+ viewState = {...viewState, zoom: clamp(viewState.zoom * factor, .05, 64)};+ computeLayout();+ const after = fromO(...before);+ viewState = {...viewState, panX: viewState.panX + p[0] - after[0], panY: viewState.panY + p[1] - after[1]};+ computeLayout(); draw(); controls();+ }+ function zoomBy(f) { zoomAt([layout.w / 2, layout.h / 2], f); }+ function fit() { viewState = {zoom: 1, panX: 0, panY: 0}; computeLayout(); draw(); controls(); }+ function actualSize() { viewState = {zoom: 1 / layout.fitK, panX: 0, panY: 0}; computeLayout(); draw(); controls(); }++ // ----- keys ----------------------------------------------------------------------------------+ const KEYS = {v: 'move', c: 'crop', m: 'marquee', l: 'lasso', w: 'wand', b: 'brush', e: 'eraser', j: 'heal', s: 'clone', r: 'blur', g: 'gradient', t: 'text', u: 'shape', i: 'eyedropper', h: 'hand'};+ function keys(event) {+ const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(event.target.tagName) && !['range', 'checkbox', 'color', 'radio'].includes(event.target.type);+ const mod = event.ctrlKey || event.metaKey, key = event.key.toLowerCase();+ // Nothing typed here reaches ComfyUI's canvas shortcuts behind the dialog.+ if (event.key !== 'Escape' && event.key !== 'Tab') event.stopPropagation();+ if (typing) { if (mod && key === 'enter') { event.preventDefault(); finish(); } return; }+ if (mod && key === 'z') { event.preventDefault(); step(event.shiftKey ? 1 : -1); return; }+ if (mod && key === 'y') { event.preventDefault(); step(1); return; }+ if (mod && key === 'enter') { event.preventDefault(); finish(); return; }+ if (mod && key === 'a') { event.preventDefault(); selectAll(); return; }+ if (mod && key === 'd') { event.preventDefault(); deselect(); return; }+ if (mod && event.shiftKey && key === 'i') { event.preventDefault(); invertSelection(); return; }+ if (mod && key === 'j') { event.preventDefault(); copyToLayer(); return; }+ if (mod && (key === '=' || key === '+')) { event.preventDefault(); zoomBy(1.25); return; }+ if (mod && key === '-') { event.preventDefault(); zoomBy(1 / 1.25); return; }+ if (mod && key === '0') { event.preventDefault(); fit(); return; }+ if (mod && key === '1') { event.preventDefault(); actualSize(); return; }+ if (mod || event.altKey && key !== 'backspace' && key !== 'delete') return;+ if (event.key === ' ') { event.preventDefault(); if (!spaceHeld) { spaceHeld = true; stage.dataset.pan = 'true'; } return; }+ if ((event.key === 'Delete' || event.key === 'Backspace') && event.altKey) { event.preventDefault(); fillSelection(); return; }+ if (event.key === 'Delete' || event.key === 'Backspace') { event.preventDefault(); clearSelection(); return; }+ if (event.key === 'Enter' && gesture?.close) { event.preventDefault(); gesture.close(); return; }+ if (key === 'x') { swapColors(); return; }+ if (key === 'd') { fg = '#ffffff'; bg = '#111111'; fgInput.value = fg; bgInput.value = bg; return; }+ if (key === '[' || key === ']') {+ const o = opts[tool]; if (!o || o.size === undefined) return;+ if (event.shiftKey && o.hardness !== undefined) o.hardness = clamp(o.hardness + (key === ']' ? .1 : -.1), 0, 1);+ else o.size = clamp(o.size * (key === ']' ? 1.2 : 1 / 1.2), .002, .25);+ renderOptions(); drawOverlay(); return;+ }+ if (KEYS[key]) {+ if (key === 'm' && tool === 'marquee' && event.shiftKey) opts.marquee.shape = opts.marquee.shape === 'rect' ? 'ellipse' : 'rect';+ if (key === 'l' && tool === 'lasso' && event.shiftKey) opts.lasso.type = opts.lasso.type === 'free' ? 'polygon' : 'free';+ select(KEYS[key]);+ }+ }+ function keyup(event) { if (event.key === ' ') { spaceHeld = false; delete stage.dataset.pan; } }+ // Keys pressed while focus has slipped out of the dialog still belong to the editor.+ function stray(event) {+ if (!dialog.open || dialog.contains(event.target) || event.key === 'Escape') return;+ (event.type === 'keydown' ? keys : keyup)(event);+ event.stopPropagation();+ }+ dialog.addEventListener('keydown', keys);+ dialog.addEventListener('keyup', keyup);+ window.addEventListener('keydown', stray, true);+ window.addEventListener('keyup', stray, true);+ dialog.addEventListener('cancel', event => {+ event.preventDefault();+ if (gesture?.cancel) { gesture.cancel(); gesture = null; draw(); return; }+ // Escape in a text field ends typing there; the next one leaves. In a popover it closes it.+ const field = document.activeElement;+ const open = field?.closest?.('.fv-ie-popover');+ if (open && stage.contains(open)) { open.remove(); stage.focus(); return; }+ if (dialog.contains(field) && /^(INPUT|TEXTAREA)$/.test(field.tagName)+ && !['range', 'checkbox', 'color', 'radio'].includes(field.type)) { commitText(); stage.focus(); return; }+ const pop = stage.querySelector('.fv-ie-popover'); if (pop) { pop.remove(); return; }+ if (selection) { deselect(); return; }+ if (!confirmBar.hidden) close(null); else leave();+ });++ // ----- leave / save ----------------------------------------------------------------------------+ let resolveResult;+ const result = new Promise(r => { resolveResult = r; });+ let messageTimer = null;+ function message(text) { status.textContent = text; clearTimeout(messageTimer); if (text) messageTimer = setTimeout(() => { status.textContent = ''; }, 5000); }+ async function leave() {+ if (healing) await healing;+ commitText();+ if (changed()) { confirmBar.hidden = false; confirmBar.querySelector('.fv-ie-danger').focus(); return; }+ close(null);+ }+ async function finish() {+ if (healing) await healing;+ commitText();+ if (strip(doc) === strip(original())) { close(fresh ? null : {restore: true}); return; }+ if (!changed() && !fresh) { close(null); return; }+ save.disabled = cancel.disabled = true; message(t('Saving the edited image…', '正在保存编辑后的图片…'));+ try {+ const {blob, width, height} = await renderer.export(doc, extension === 'jpg' ? 'image/jpeg' : 'image/png');+ close({blob, name: `${stem}-edit.${extension}`, edit: doc, width, height});+ } catch {+ message(t('The image could not be rendered. Try a smaller canvas or reload the page.', '图片生成失败,请缩小画布或刷新页面后重试。'));+ save.disabled = cancel.disabled = false;+ }+ }+ function close(value) {+ clearInterval(antsTimer); clearTimeout(messageTimer);+ observer.disconnect();+ dialog.removeEventListener('keydown', keys); dialog.removeEventListener('keyup', keyup);+ window.removeEventListener('keydown', stray, true); window.removeEventListener('keyup', stray, true);+ if (dialog.open) dialog.close();+ // Give every canvas back: this editor holds nothing once it is closed.+ renderer.release();+ for (const c of [view, ants]) { c.width = c.height = 0; }+ composited = null; antsEdge = null;+ dialog.remove();+ resolveResult(value);+ }++ // A read-only view of the editor for automation and tests.+ dialog.freevideoEditor = {+ state: () => ({doc, selection, tool, fg, bg, zoom: layout.k, maskTarget, history: history.length, future: future.length, healing: !!healing}),+ pictureBox: () => { const b = stage.getBoundingClientRect(), r = rect(), [x, y] = fromO(r.x, r.y); return {x: b.left + x, y: b.top + y, width: r.w * layout.k, height: r.h * layout.k}; },+ };++ // ----- start -------------------------------------------------------------------------------------+ const observer = new ResizeObserver(() => { computeLayout(); draw(); controls(); });+ observer.observe(stage);+ dialog.showModal();+ computeLayout();+ renderPanels();+ select(startTool || (fresh && target && role !== 'reference' ? 'crop' : 'move'));+ save.focus();+ // The other fonts load in the background, so switching to one is immediate.+ loadFonts(FONT_KEYS.flatMap(k => [[k, 400], [k, 700]])).catch(() => {});+ return result;+}diff --git a/web/image_editor_engine.js b/web/image_editor_engine.jsnew file mode 100644index 0000000..e941708--- /dev/null+++ b/web/image_editor_engine.js@@ -0,0 +1,1055 @@+// Document model and rendering for the image editor. Nothing here touches the+// page: the editor UI owns events and drawing on screen.+//+// Spaces:+// document (D): pixels of the original image, origin at its top left;+// oriented (O): the document after the canvas rotation and flips;+// canvas: O plus any extension on each side; the crop is a rectangle of it.+// Layers live in D (centre, size, rotation, flips); a layer's own edits live in+// its local pixels as fractions, so they survive moves and preview scales.+// Every edit is an entry in a list, so a saved document reopens from the+// original image with each step still in place.++import {fontCSS, fontLoaded, loadFonts} from './fonts.js';++export const BLENDS = ['source-over', 'multiply', 'screen', 'overlay', 'soft-light', 'darken', 'lighten',+ 'color-dodge', 'color-burn', 'difference'];+export const ADJUSTMENTS = ['exposure', 'contrast', 'highlights', 'shadows', 'temperature', 'tint', 'hue', 'saturation',+ 'vibrance', 'sharpen', 'blur', 'noise', 'vignette'];++let counter = 0;+export const uid = prefix => `${prefix}${Date.now().toString(36)}${(counter++).toString(36)}`;+const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));++function canvas(width, height) {+ const c = document.createElement('canvas');+ c.width = Math.max(1, Math.round(width)); c.height = Math.max(1, Math.round(height));+ return c;+}+// Pixel work stays in system memory: Chrome keeps willReadFrequently canvases off the GPU.+const context = c => c.getContext('2d', {willReadFrequently: true});++export function emptyAdjust() {+ return Object.fromEntries(ADJUSTMENTS.map(k => [k, 0]));+}+function baseLayer(file, image) {+ const w = image.naturalWidth, h = image.naturalHeight;+ return {id: 'base', kind: 'image', name: '', src: file, visible: true, locked: true, opacity: 1, blend: 'source-over',+ cx: w / 2, cy: h / 2, w, h, rotation: 0, flipX: false, flipY: false, nw: w, nh: h,+ ops: [], mask: null, adjust: emptyAdjust()};+}+export function newDocument(file, image) {+ const w = image.naturalWidth, h = image.naturalHeight;+ return {version: 2, width: w, height: h, rotate: 0, flipX: false, flipY: false,+ extend: {l: 0, t: 0, r: 0, b: 0, color: '#000000'}, crop: {x: 0, y: 0, w, h}, ratio: 'original',+ layers: [baseLayer(file, image)], active: 'base'};+}+// Edits saved before layers: crop and strokes in fractions of the oriented picture.+export function migrate(edit, file, image) {+ if (!edit) return newDocument(file, image);+ if (edit.version === 2) return edit;+ const doc = newDocument(file, image);+ doc.rotate = edit.rotate || 0; doc.flipX = !!edit.flipX; doc.flipY = !!edit.flipY; doc.ratio = edit.ratio || 'original';+ const [ow, oh] = orientedSize(doc);+ const c = edit.crop || {x: 0, y: 0, w: 1, h: 1};+ doc.crop = {x: c.x * ow, y: c.y * oh, w: c.w * ow, h: c.h * oh};+ const a = edit.adjust || {};+ doc.layers[0].adjust = {...emptyAdjust(), exposure: a.brightness || 0, contrast: a.contrast || 0, saturation: a.saturation || 0};+ if (edit.strokes?.length) {+ // Old strokes were drawn in oriented fractions; a paint layer covering O holds them.+ // Its pixels must land on O unrotated: the layer transform is the inverse orientation.+ const paint = paintLayer(doc, 'Drawing');+ Object.assign(paint, {cx: doc.width / 2, cy: doc.height / 2, w: ow, h: oh, nw: ow, nh: oh,+ rotation: -doc.rotate, flipX: doc.flipX, flipY: doc.flipY});+ paint.ops = edit.strokes.map(s => ({id: uid('o'), type: 'stroke', tool: s.erase ? 'erase' : 'paint', pts: s.points,+ size: s.size, hardness: 1, opacity: 1, color: s.color}));+ doc.layers.push(paint);+ }+ return doc;+}++export function orientedSize(doc) {+ return doc.rotate % 180 ? [doc.height, doc.width] : [doc.width, doc.height];+}+// D → O: rotate about the document, then mirror in O.+export function orientMatrix(doc) {+ const [ow, oh] = orientedSize(doc);+ const m = new DOMMatrix();+ m.translateSelf(ow / 2, oh / 2);+ m.scaleSelf(doc.flipX ? -1 : 1, doc.flipY ? -1 : 1);+ m.rotateSelf(doc.rotate);+ m.translateSelf(-doc.width / 2, -doc.height / 2);+ return m;+}+export function canvasRect(doc) {+ const [ow, oh] = orientedSize(doc), e = doc.extend;+ return {x: -e.l, y: -e.t, w: ow + e.l + e.r, h: oh + e.t + e.b};+}+export function layerMatrix(layer) {+ const m = new DOMMatrix();+ m.translateSelf(layer.cx, layer.cy);+ m.rotateSelf(layer.rotation);+ m.scaleSelf(layer.flipX ? -1 : 1, layer.flipY ? -1 : 1);+ m.translateSelf(-layer.w / 2, -layer.h / 2);+ m.scaleSelf(layer.w / layer.nw, layer.h / layer.nh);+ return m; // layer native pixels → D+}+// The document area the canvas covers, for sizing new paint layers.+export function documentBounds(doc) {+ const c = canvasRect(doc), inv = orientMatrix(doc).inverse();+ const pts = [[c.x, c.y], [c.x + c.w, c.y], [c.x, c.y + c.h], [c.x + c.w, c.y + c.h]].map(([x, y]) => inv.transformPoint(new DOMPoint(x, y)));+ const xs = pts.map(p => p.x), ys = pts.map(p => p.y);+ return {x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys)};+}+export function paintLayer(doc, name) {+ const b = documentBounds(doc);+ return {id: uid('l'), kind: 'paint', name, visible: true, locked: false, opacity: 1, blend: 'source-over',+ cx: b.x + b.w / 2, cy: b.y + b.h / 2, w: b.w, h: b.h, rotation: 0, flipX: false, flipY: false,+ nw: Math.round(b.w), nh: Math.round(b.h), ops: [], mask: null, adjust: emptyAdjust()};+}+export const rasterKinds = new Set(['image', 'paint']);+// The bundled fonts a document's text layers draw with, as [family, weight] pairs.+export const textFonts = doc => doc.layers.filter(l => l.kind === 'text').map(l => [l.text.font, l.text.weight]);+export const textFontsLoaded = doc => textFonts(doc).every(([name, weight]) => fontLoaded(name, weight));++// Native size of a text block, from the same font settings it is drawn with. The font must+// be loaded (textFonts): measuring before that would use another font's metrics.+export function measureText(text) {+ const ctx = document.createElement('canvas').getContext('2d');+ ctx.font = fontCSS(text.font, text.weight, text.size);+ const lines = String(text.content || ' ').split('\n');+ const width = Math.max(...lines.map(line => ctx.measureText(line || ' ').width));+ return {nw: Math.ceil(width + text.size * .4), nh: Math.ceil(text.size * (.4 + (lines.length - 1) * (text.lineHeight || 1.25) + 1.1))};+}++// ---------------------------------------------------------------------------+// Image size++// A selection's shapes are in document pixels, so they scale with it (sx, sy along D's axes).+export function scaleSelection(selection, sx, sy) {+ if (!selection) return selection;+ const k = Math.sqrt(sx * sy);+ const part = p => {+ const q = {...p};+ if (p.feather) q.feather = p.feather * k;+ if (p.shape === 'rect' || p.shape === 'ellipse') Object.assign(q, {x: p.x * sx, y: p.y * sy, w: p.w * sx, h: p.h * sy});+ if (p.pts) q.pts = p.pts.map(([x, y]) => [x * sx, y * sy]);+ return q;+ };+ return {...selection, feather: (selection.feather || 0) * k, parts: selection.parts.map(part)};+}++// The document at another size: its picture (the crop) becomes width × height pixels. Every+// place and length in document pixels scales with it: the canvas, the crop, each layer's place+// and size, the selections kept with edits. Image layers keep their own pixels and are drawn at+// the new size; paint layers and shapes are remade at it and text at its new font size, so they+// stay sharp and editable. A layer's own edits are fractions of it and follow by themselves.+// keep (proportions locked): the same scale both ways, just enough to fill width × height, and+// the fraction of a pixel left over is cut from the right and bottom. Otherwise each way scales+// on its own: pictures and shapes stretch, text keeps its shape. The text fonts must be loaded.+export function resizeDocument(doc, width, height, keep = true) {+ const c = doc.crop;+ let kx = width / c.w, ky = height / c.h;+ if (keep) kx = ky = Math.max(kx, ky);+ const [sx, sy] = doc.rotate % 180 ? [ky, kx] : [kx, ky];+ const k = Math.sqrt(sx * sy);+ // How much a layer turned by rotation grows along its own width and height.+ const stretch = rotation => {+ const a = rotation * Math.PI / 180, cos = Math.cos(a), sin = Math.sin(a);+ return [Math.hypot(sx * cos, sy * sin), Math.hypot(sx * sin, sy * cos)];+ };+ const scaleOps = ops => ops.map(op => op.selection ? {...op, selection: scaleSelection(op.selection, sx, sy)} : op);+ // Floating-point dust (1344.0000000000002) is rounded away; real fractions stay.+ const tidy = v => Math.abs(v - Math.round(v)) < 1e-6 ? Math.round(v) : v;+ const layers = doc.layers.map(l => {+ const [fx, fy] = stretch(l.rotation || 0);+ const next = {...l, cx: tidy(l.cx * sx), cy: tidy(l.cy * sy), w: tidy(l.w * fx), h: tidy(l.h * fy)};+ if (l.ops) next.ops = scaleOps(l.ops);+ if (l.mask) next.mask = {...l.mask, ops: scaleOps(l.mask.ops)};+ if (l.copyOf?.selection) next.copyOf = {...l.copyOf, selection: scaleSelection(l.copyOf.selection, sx, sy)};+ if (l.kind === 'text') {+ const text = {...l.text, size: Math.max(1, Math.round(l.text.size * k * 10) / 10)}, size = measureText(text);+ return {...next, text, ...size, w: size.nw * l.w / l.nw, h: size.nh * l.h / l.nh};+ }+ if (l.kind === 'shape') {+ const shape = {...l.shape, width: (l.shape.width || 0) * k};+ if (l.shape.radius) shape.radius = l.shape.radius * k;+ return {...next, shape, nw: tidy(l.nw * fx), nh: tidy(l.nh * fy)};+ }+ if (l.kind === 'paint' && !l.copyOf) return {...next, nw: tidy(l.nw * fx), nh: tidy(l.nh * fy)};+ return next;+ });+ const e = doc.extend;+ return {...doc, width: tidy(doc.width * sx), height: tidy(doc.height * sy),+ extend: {...e, l: tidy(e.l * kx), r: tidy(e.r * kx), t: tidy(e.t * ky), b: tidy(e.b * ky)},+ crop: {x: tidy(c.x * kx), y: tidy(c.y * ky), w: width, h: height}, layers};+}++// ---------------------------------------------------------------------------+// Pixels++function hexRGB(hex) {+ const v = parseInt(String(hex || '#000').slice(1).padEnd(6, '0'), 16);+ return [(v >> 16) & 255, (v >> 8) & 255, v & 255];+}+function mulberry(seed) {+ return () => { seed |= 0; seed = seed + 0x6D2B79F5 | 0; let t = Math.imul(seed ^ seed >>> 15, 1 | seed);+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; };+}+function hashString(s) { let h = 2166136261; for (const ch of String(s)) h = Math.imul(h ^ ch.charCodeAt(0), 16777619); return h >>> 0; }++let blurFilter;+function canvasBlur() {+ if (blurFilter === undefined) {+ const ctx = document.createElement('canvas').getContext('2d');+ blurFilter = 'filter' in ctx && (ctx.filter = 'blur(2px)', ctx.filter === 'blur(2px)');+ }+ return blurFilter;+}+// Gaussian-like blur; ctx.filter where it works, three box passes elsewhere.+export function blurred(source, radius) {+ const out = canvas(source.width, source.height), ctx = context(out);+ if (radius <= 0) { ctx.drawImage(source, 0, 0); return out; }+ if (canvasBlur()) {+ // Pad by mirroring the edge so the border does not fade to transparent.+ const pad = Math.ceil(radius * 3);+ const big = canvas(source.width + pad * 2, source.height + pad * 2), b = context(big);+ b.drawImage(source, pad, pad);+ b.drawImage(source, 0, 0, 1, source.height, 0, pad, pad, source.height);+ b.drawImage(source, source.width - 1, 0, 1, source.height, pad + source.width, pad, pad, source.height);+ b.drawImage(big, 0, pad, big.width, 1, 0, 0, big.width, pad);+ b.drawImage(big, 0, pad + source.height - 1, big.width, 1, 0, pad + source.height, big.width, pad);+ ctx.filter = `blur(${radius}px)`;+ ctx.drawImage(big, -pad, -pad);+ ctx.filter = 'none';+ return out;+ }+ ctx.drawImage(source, 0, 0);+ const image = ctx.getImageData(0, 0, out.width, out.height);+ boxBlur(image.data, out.width, out.height, Math.max(1, Math.round(radius * .6)));+ ctx.putImageData(image, 0, 0);+ return out;+}+function boxBlur(d, w, h, r) {+ const tmp = new Float32Array(d.length);+ for (let pass = 0; pass < 3; pass++) {+ for (let y = 0; y < h; y++) for (let c = 0; c < 4; c++) {+ let acc = 0;+ for (let x = -r; x <= r; x++) acc += d[(y * w + clamp(x, 0, w - 1)) * 4 + c];+ for (let x = 0; x < w; x++) {+ tmp[(y * w + x) * 4 + c] = acc / (2 * r + 1);+ acc += d[(y * w + clamp(x + r + 1, 0, w - 1)) * 4 + c] - d[(y * w + clamp(x - r, 0, w - 1)) * 4 + c];+ }+ }+ for (let x = 0; x < w; x++) for (let c = 0; c < 4; c++) {+ let acc = 0;+ for (let y = -r; y <= r; y++) acc += tmp[(clamp(y, 0, h - 1) * w + x) * 4 + c];+ for (let y = 0; y < h; y++) {+ d[(y * w + x) * 4 + c] = acc / (2 * r + 1);+ acc += tmp[(clamp(y + r + 1, 0, h - 1) * w + x) * 4 + c] - tmp[(clamp(y - r, 0, h - 1) * w + x) * 4 + c];+ }+ }+ }+}++// Light and colour first, per pixel; then sharpening, blur, noise and vignette.+export function adjusted(source, adjust, seed, scale) {+ const a = adjust || {};+ const active = ADJUSTMENTS.some(k => a[k]);+ if (!active) return source;+ let work = canvas(source.width, source.height);+ let ctx = context(work);+ ctx.drawImage(source, 0, 0);+ const tonal = ['exposure', 'contrast', 'highlights', 'shadows', 'temperature', 'tint', 'hue', 'saturation', 'vibrance'].some(k => a[k]);+ if (tonal) {+ const image = ctx.getImageData(0, 0, work.width, work.height), d = image.data;+ const gain = Math.pow(2, (a.exposure || 0) / 50), contrast = 1 + (a.contrast || 0) / 100;+ const temp = (a.temperature || 0) / 100, tint = (a.tint || 0) / 100;+ const hi = (a.highlights || 0) / 100, sh = (a.shadows || 0) / 100;+ const sat = 1 + (a.saturation || 0) / 100, vib = (a.vibrance || 0) / 100;+ const angle = (a.hue || 0) * Math.PI / 180, cos = Math.cos(angle), sin = Math.sin(angle);+ // CSS hue-rotate matrix.+ const hr = [.213 + cos * .787 - sin * .213, .715 - cos * .715 - sin * .715, .072 - cos * .072 + sin * .928,+ .213 - cos * .213 + sin * .143, .715 + cos * .285 + sin * .140, .072 - cos * .072 - sin * .283,+ .213 - cos * .213 - sin * .787, .715 - cos * .715 + sin * .715, .072 + cos * .928 + sin * .072];+ for (let i = 0; i < d.length; i += 4) {+ let r = d[i] / 255 * gain, g = d[i + 1] / 255 * gain, b = d[i + 2] / 255 * gain;+ if (temp) { r += temp * .12; b -= temp * .12; }+ if (tint) { g -= tint * .1; r += tint * .04; b += tint * .04; }+ if (hi || sh) {+ const lum = .2126 * r + .7152 * g + .0722 * b;+ const lift = hi * Math.max(0, lum - .5) * .8 + sh * Math.max(0, .5 - lum) * .8;+ r += lift; g += lift; b += lift;+ }+ if (contrast !== 1) { r = (r - .5) * contrast + .5; g = (g - .5) * contrast + .5; b = (b - .5) * contrast + .5; }+ if (angle) { const nr = hr[0] * r + hr[1] * g + hr[2] * b, ng = hr[3] * r + hr[4] * g + hr[5] * b; b = hr[6] * r + hr[7] * g + hr[8] * b; r = nr; g = ng; }+ let s = sat;+ if (vib) { const mx = Math.max(r, g, b), mn = Math.min(r, g, b); s *= 1 + vib * (1 - clamp(mx - mn, 0, 1)); }+ if (s !== 1) {+ const nr = (.213 + .787 * s) * r + (.715 - .715 * s) * g + (.072 - .072 * s) * b;+ const ng = (.213 - .213 * s) * r + (.715 + .285 * s) * g + (.072 - .072 * s) * b;+ b = (.213 - .213 * s) * r + (.715 - .715 * s) * g + (.072 + .928 * s) * b; r = nr; g = ng;+ }+ d[i] = clamp(r, 0, 1) * 255; d[i + 1] = clamp(g, 0, 1) * 255; d[i + 2] = clamp(b, 0, 1) * 255;+ }+ ctx.putImageData(image, 0, 0);+ }+ // Radii follow the raster's size, so a saved image matches what was shown.+ const unit = Math.min(work.width, work.height) / 100;+ if (a.blur > 0) work = blurred(work, a.blur / 100 * unit * 4);+ if (a.sharpen > 0) {+ const soft = blurred(work, Math.max(.6, unit * .35));+ const sd = context(soft).getImageData(0, 0, soft.width, soft.height).data;+ ctx = context(work);+ const image = ctx.getImageData(0, 0, work.width, work.height), d = image.data, amount = a.sharpen / 100 * 1.6;+ for (let i = 0; i < d.length; i += 4) for (let c = 0; c < 3; c++) d[i + c] = clamp(d[i + c] + (d[i + c] - sd[i + c]) * amount, 0, 255);+ ctx.putImageData(image, 0, 0);+ }+ if (a.noise > 0 || a.vignette) {+ ctx = context(work);+ const image = ctx.getImageData(0, 0, work.width, work.height), d = image.data, w = work.width, h = work.height;+ const random = mulberry(seed), amount = (a.noise || 0) / 100 * 60, v = (a.vignette || 0) / 100;+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {+ const i = (y * w + x) * 4;+ let f = 1;+ if (v) { const dx = (x / w - .5) * 2, dy = (y / h - .5) * 2, r = Math.min(1, Math.sqrt(dx * dx + dy * dy) / Math.SQRT2);+ f = v > 0 ? 1 - v * r * r * 1.1 : 1 - v * r * r * .8; }+ const n = amount ? (random() + random() - 1) * amount : 0;+ d[i] = clamp(d[i] * f + n, 0, 255); d[i + 1] = clamp(d[i + 1] * f + n, 0, 255); d[i + 2] = clamp(d[i + 2] * f + n, 0, 255);+ }+ ctx.putImageData(image, 0, 0);+ }+ return work;+}++// Soft round brush mask for a stroke, in the raster's pixels.+function strokeMask(width, height, op) {+ const m = canvas(width, height), ctx = context(m);+ const size = Math.max(1, op.size * Math.min(width, height));+ const hard = clamp(op.hardness ?? 1, 0, 1);+ const core = size * (.4 + .6 * hard), soft = size * (1 - hard) * .55;+ ctx.lineCap = 'round'; ctx.lineJoin = 'round';+ ctx.strokeStyle = ctx.fillStyle = '#fff';+ // A shadow-only stroke gives a soft edge without overlapping dabs stacking up.+ const shift = soft ? width + size * 4 : 0;+ if (soft) { ctx.shadowColor = '#fff'; ctx.shadowBlur = soft; ctx.shadowOffsetX = shift; }+ ctx.lineWidth = core;+ const pts = op.pts.map(([u, v]) => [u * width - shift, v * height]);+ ctx.beginPath();+ if (pts.length === 1) { ctx.arc(pts[0][0], pts[0][1], core / 2, 0, Math.PI * 2); ctx.fill(); }+ else { ctx.moveTo(...pts[0]); for (const p of pts.slice(1)) ctx.lineTo(...p); ctx.stroke(); }+ return m;+}+function maskWith(target, mask) {+ const ctx = target.getContext('2d');+ ctx.globalCompositeOperation = 'destination-in'; ctx.drawImage(mask, 0, 0); ctx.globalCompositeOperation = 'source-over';+ return target;+}++// Area average: each new pixel is the mean of the source area it covers, edge pixels counted+// by the part inside. Colours are averaged weighted by alpha, so clear pixels add no colour.+function spans(n, m) {+ const k = n / m, start = new Int32Array(m), count = new Int32Array(m), weights = [];+ for (let o = 0; o < m; o++) {+ const a = o * k, b = a + k, i0 = Math.floor(a), i1 = Math.min(n, Math.ceil(b - 1e-9));+ start[o] = i0; count[o] = i1 - i0;+ for (let i = i0; i < i1; i++) weights.push((Math.min(b, i + 1) - Math.max(a, i)) / k);+ }+ return {start, count, weight: Float32Array.from(weights)};+}+export function areaResize(src, sw, sh, w, h) {+ let opaque = true;+ for (let i = 3; i < src.length; i += 4) if (src[i] !== 255) { opaque = false; break; }+ const X = spans(sw, w), Y = spans(sh, h), n = w * 4, xs = X.start, xc = X.count, xw = X.weight;+ // One source row at a time, averaged across into line; a row on the border of two new+ // rows is used by both, so the last one is kept.+ const line = new Float32Array(n), acc = new Float32Array(n), out = new Uint8ClampedArray(w * h * 4);+ let last = -1;+ const across = y => {+ const row = y * sw * 4;+ for (let o = 0, p = 0, t = 0; o < w; o++, t += 4) {+ let r = 0, g = 0, b = 0, a = 0, i = row + xs[o] * 4;+ if (opaque) for (let j = xc[o]; j > 0; j--, p++, i += 4) { const q = xw[p]; r += src[i] * q; g += src[i + 1] * q; b += src[i + 2] * q; }+ else for (let j = xc[o]; j > 0; j--, p++, i += 4) { const q = xw[p] * src[i + 3]; r += src[i] * q; g += src[i + 1] * q; b += src[i + 2] * q; a += q; }+ line[t] = r; line[t + 1] = g; line[t + 2] = b; line[t + 3] = a;+ }+ };+ for (let o = 0, p = 0; o < h; o++) {+ acc.fill(0);+ for (let j = Y.count[o], y = Y.start[o]; j > 0; j--, p++, y++) {+ if (y !== last) { across(y); last = y; }+ const q = Y.weight[p];+ for (let i = 0; i < n; i++) acc[i] += line[i] * q;+ }+ const base = o * n;+ for (let i = 0; i < n; i += 4) {+ const a = opaque ? 1 : acc[i + 3];+ if (a > 0) { out[base + i] = acc[i] / a + .5; out[base + i + 1] = acc[i + 1] / a + .5; out[base + i + 2] = acc[i + 2] / a + .5; }+ out[base + i + 3] = opaque ? 255 : a + .5;+ }+ }+ return out;+}+// A picture drawn into w × h pixels. On screen the browser's own scaling is enough; for a saved+// picture made smaller the pixels are averaged by area, so fine detail does not shimmer or alias.+function drawSource(ctx, image, w, h, exact) {+ const sw = image.naturalWidth || image.width, sh = image.naturalHeight || image.height;+ if (!exact || w >= sw || h >= sh) { ctx.drawImage(image, 0, 0, w, h); return; }+ const full = canvas(sw, sh), fctx = context(full);+ fctx.drawImage(image, 0, 0);+ const pixels = fctx.getImageData(0, 0, sw, sh).data;+ full.width = full.height = 0;+ ctx.putImageData(new ImageData(areaResize(pixels, sw, sh, w, h), w, h), 0, 0);+}++// Pull-push interpolation: known values (col, already multiplied by their+// weight wt) are averaged down a pyramid and pushed back up into the gaps.+// It works at the precision of the arrays it is given.+function pullPush(col, wt, bw, bh) {+ const levels = [{w: bw, h: bh, col, wt}], Values = col.constructor, Weights = wt.constructor;+ let cw = bw, ch = bh;+ while (cw > 1 || ch > 1) {+ const nw = Math.max(1, cw >> 1), nh = Math.max(1, ch >> 1), ncol = new Values(nw * nh * 4), nwt = new Weights(nw * nh);+ for (let y = 0; y < nh; y++) for (let x = 0; x < nw; x++) {+ let sw = 0; const acc = [0, 0, 0, 0];+ for (let dy = 0; dy < 2; dy++) for (let dx = 0; dx < 2; dx++) {+ const sx = Math.min(cw - 1, x * 2 + dx), sy = Math.min(ch - 1, y * 2 + dy), j = sy * cw + sx;+ sw += wt[j]; for (let c = 0; c < 4; c++) acc[c] += col[j * 4 + c];+ }+ const i = y * nw + x; nwt[i] = Math.min(1, sw);+ for (let c = 0; c < 4; c++) ncol[i * 4 + c] = sw > 0 ? acc[c] / sw * Math.min(1, sw) : 0;+ }+ cw = nw; ch = nh; col = ncol; wt = nwt; levels.push({w: cw, h: ch, col, wt});+ }+ for (let l = levels.length - 2; l >= 0; l--) {+ const cur = levels[l], up = levels[l + 1];+ for (let y = 0; y < cur.h; y++) for (let x = 0; x < cur.w; x++) {+ const i = y * cur.w + x, k = cur.wt[i];+ if (k >= 1) continue;+ // Bilinear sample of the coarser level.+ const fx = clamp((x + .5) / 2 - .5, 0, up.w - 1), fy = clamp((y + .5) / 2 - .5, 0, up.h - 1);+ const ix = Math.floor(fx), iy = Math.floor(fy), tx = fx - ix, ty = fy - iy;+ const jx = Math.min(up.w - 1, ix + 1), jy = Math.min(up.h - 1, iy + 1);+ for (let c = 0; c < 4; c++) {+ const s = (up.col[(iy * up.w + ix) * 4 + c] * (1 - tx) + up.col[(iy * up.w + jx) * 4 + c] * tx) * (1 - ty)+ + (up.col[(jy * up.w + ix) * 4 + c] * (1 - tx) + up.col[(jy * up.w + jx) * 4 + c] * tx) * ty;+ const sw = (up.wt[iy * up.w + ix] * (1 - tx) + up.wt[iy * up.w + jx] * tx) * (1 - ty) + (up.wt[jy * up.w + ix] * (1 - tx) + up.wt[jy * up.w + jx] * tx) * ty;+ const norm = sw > 0 ? s / sw : 0;+ cur.col[i * 4 + c] = cur.col[i * 4 + c] + norm * (1 - k);+ }+ cur.wt[i] = 1;+ }+ }+ return levels[0].col;+}++// Spot healing is a patch-based fill: coarse to fine, every 7×7 patch that+// touches the stroke takes the most similar patch outside it, and the stroke's+// pixels become the weighted vote of those patches, so the fill takes real+// texture from around the mark. Each level searches once and votes once:+// - the coarsest level starts by peeling the hole from its edge inwards, then+// compares every patch with every source patch;+// - each finer level starts from the coarser fill, upsampled, and compares the+// patches in a fixed window around twice the offset found one level coarser,+// and nothing else: 3 pixels each way, 1 on a level with very many patches;+// - at full size, the difference between the fill and the picture just around+// the hole is spread smoothly across it, so the fill meets it without a seam.+// Distances count estimated pixels less than real ones and prefer nearby+// sources. There is no randomness: the same stroke always heals the same way.+const HEAL_PATCH = 3, HEAL_COARSE = 24, HEAL_WINDOW = 3, HEAL_MARGIN = 384, HEAL_PEEL = 2048;+// Above this many patches to place, a level searches the window of radius HEAL_WINDOW_FINE.+const HEAL_SEARCH = 60000, HEAL_WINDOW_FINE = 1;+// A whole stroke leans on nearby patches; a caption's thin strokes have picture all around them.+const HEAL_NEAR = 4, HEAL_NEAR_TEXT = .25, HEAL_GUESS = .1, HEAL_TEXT_OUTLINE = .15;+// Pixels within r of a set pixel (a square neighbourhood).+function dilate(map, w, h, r) {+ const rows = new Uint8Array(w * h), out = new Uint8Array(w * h);+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {+ let v = 0; for (let k = Math.max(0, x - r); k <= Math.min(w - 1, x + r) && !v; k++) v = map[y * w + k];+ rows[y * w + x] = v;+ }+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {+ let v = 0; for (let k = Math.max(0, y - r); k <= Math.min(h - 1, y + r) && !v; k++) v = rows[k * w + x];+ out[y * w + x] = v;+ }+ return out;+}+// The coarsest level's start: ring by ring from the edge inwards, each hole+// pixel takes the centre of the source patch that best matches its filled neighbours.+function peel(E, hole, sources, pr, lw, lh) {+ const filled = new Uint8Array(lw * lh);+ for (let i = 0; i < lw * lh; i++) filled[i] = hole[i] ? 0 : 1;+ const stride = Math.max(1, Math.ceil(sources.length / HEAL_PEEL)), S = sources.filter((_, k) => k % stride === 0);+ const qs = new Int32Array((2 * pr + 1) ** 2), ks = new Uint8Array(qs.length);+ for (;;) {+ const grown = dilate(filled, lw, lh, 1), front = [];+ for (let i = 0; i < lw * lh; i++) if (hole[i] && !filled[i] && grown[i]) front.push(i);+ if (!front.length) break;+ const chosen = front.map(f => {+ const fx = f % lw, fy = (f - fx) / lw;+ let n = 0, count = 0;+ for (let dy = -pr; dy <= pr; dy++) for (let dx = -pr; dx <= pr; dx++, n++) {+ qs[n] = Math.min(lh - 1, Math.max(0, fy + dy)) * lw + Math.min(lw - 1, Math.max(0, fx + dx));+ ks[n] = filled[qs[n]]; count += ks[n];+ }+ let best = S[0], bestV = Infinity;+ for (const s of S) {+ const sx = s % lw, sy = (s - sx) / lw;+ let num = 0, k = 0;+ for (let dy = -pr; dy <= pr && num / count < bestV; dy++) for (let dx = -pr; dx <= pr; dx++, k++) {+ if (!ks[k]) continue;+ const a = qs[k] * 4, b = ((sy + dy) * lw + sx + dx) * 4;+ const e0 = E[a] - E[b], e1 = E[a + 1] - E[b + 1], e2 = E[a + 2] - E[b + 2], e3 = E[a + 3] - E[b + 3];+ num += e0 * e0 + e1 * e1 + e2 * e2 + e3 * e3;+ }+ if (num / count < bestV) { bestV = num / count; best = s; }+ }+ return best;+ });+ front.forEach((f, k) => { for (let c = 0; c < 4; c++) E[f * 4 + c] = E[chosen[k] * 4 + c]; filled[f] = 1; });+ }+}+// The fill of the hole pixels (Float32Array RGBA of the region), or null when no patch fits.+function patchFill(region, hole, w, h, holeSize, near) {+ const pr = HEAL_PATCH, area = (2 * pr + 1) * (2 * pr + 1);+ let count = 1 + Math.max(0, Math.ceil(Math.log2(holeSize / HEAL_COARSE)));+ while (count > 1 && Math.min(w >> (count - 1), h >> (count - 1)) < 4 * (2 * pr + 1)) count--;+ const levels = [{w, h, img: region, hole}];+ for (let l = 1; l < count; l++) {+ const p = levels[l - 1], nw = Math.max(1, p.w >> 1), nh = Math.max(1, p.h >> 1);+ const img = new Float32Array(nw * nh * 4), nhole = new Uint8Array(nw * nh);+ for (let y = 0; y < nh; y++) for (let x = 0; x < nw; x++) {+ const i = y * nw + x;+ for (let dy = 0; dy < 2; dy++) for (let dx = 0; dx < 2; dx++) {+ const j = Math.min(p.h - 1, y * 2 + dy) * p.w + Math.min(p.w - 1, x * 2 + dx);+ if (p.hole[j]) nhole[i] = 1;+ for (let c = 0; c < 4; c++) img[i * 4 + c] += p.img[j * 4 + c] / 4;+ }+ }+ levels.push({w: nw, h: nh, img, hole: nhole});+ }+ let nnf = null, E = null;+ for (let l = count - 1; l >= 0; l--) {+ const {w: lw, h: lh, img, hole: lhole} = levels[l];+ const nearHole = dilate(lhole, lw, lh, pr);+ const targets = [], valid = new Uint8Array(lw * lh), sources = [];+ for (let y = 0; y < lh; y++) for (let x = 0; x < lw; x++) {+ const i = y * lw + x;+ if (nearHole[i]) targets.push(i);+ else if (x >= pr && y >= pr && x < lw - pr && y < lh - pr) { valid[i] = 1; sources.push(i); }+ }+ if (!sources.length) return null;+ E = new Float32Array(img);+ const coarse = l === count - 1 ? null : levels[l + 1];+ if (!coarse) peel(E, lhole, sources, pr, lw, lh);+ else for (let i = 0; i < lw * lh; i++) {+ // This level starts from the coarser fill, upsampled bilinearly.+ if (!lhole[i]) continue;+ const x = i % lw, y = (i - x) / lw, uw = coarse.w, uh = coarse.h, ce = nnf.E;+ const fx = clamp((x + .5) / 2 - .5, 0, uw - 1), fy = clamp((y + .5) / 2 - .5, 0, uh - 1);+ const ix = Math.floor(fx), iy = Math.floor(fy), ax = fx - ix, ay = fy - iy;+ const jx = Math.min(uw - 1, ix + 1), jy = Math.min(uh - 1, iy + 1);+ for (let k = 0; k < 4; k++) {+ E[i * 4 + k] = (ce[(iy * uw + ix) * 4 + k] * (1 - ax) + ce[(iy * uw + jx) * 4 + k] * ax) * (1 - ay)+ + (ce[(jy * uw + ix) * 4 + k] * (1 - ax) + ce[(jy * uw + jx) * 4 + k] * ax) * ay;+ }+ }+ const span2 = Math.max(1, holeSize / (1 << l)) ** 2;+ // How much each pixel's difference counts: estimated (hole) pixels less than real ones.+ const weight = new Float64Array(lw * lh);+ for (let i = 0; i < lw * lh; i++) weight[i] = lhole[i] ? HEAL_GUESS : 1;+ // Patch distance times a preference for nearby sources. limit: stop early once the+ // distance is clearly above it (the margin keeps the choice exact).+ const cost = (t, s, limit) => {+ const tx = t % lw, ty = (t - tx) / lw, sx = s % lw, sy = (s - sx) / lw;+ const ddx = sx - tx, ddy = sy - ty, factor = 1 + near * (ddx * ddx + ddy * ddy) / span2, stop = limit * 1.000001;+ let d = 0;+ if (tx >= pr && ty >= pr && tx < lw - pr && ty < lh - pr) {+ // Inside the region: no edge to clamp at.+ for (let dy = -pr; dy <= pr; dy++) {+ let q = t + dy * lw - pr, a = q * 4, b = (s + dy * lw - pr) * 4;+ for (let k = -pr; k <= pr; k++, q++, a += 4, b += 4) {+ const e0 = E[a] - E[b], e1 = E[a + 1] - E[b + 1], e2 = E[a + 2] - E[b + 2], e3 = E[a + 3] - E[b + 3];+ d += weight[q] * (e0 * e0 + e1 * e1 + e2 * e2 + e3 * e3);+ }+ if (d * factor > stop) return Infinity;+ }+ return d * factor;+ }+ for (let dy = -pr; dy <= pr; dy++) {+ const row = Math.min(lh - 1, Math.max(0, ty + dy)) * lw, srow = (sy + dy) * lw;+ for (let dx = -pr; dx <= pr; dx++) {+ const q = row + Math.min(lw - 1, Math.max(0, tx + dx)), a = q * 4, b = (srow + sx + dx) * 4;+ const e0 = E[a] - E[b], e1 = E[a + 1] - E[b + 1], e2 = E[a + 2] - E[b + 2], e3 = E[a + 3] - E[b + 3];+ d += weight[q] * (e0 * e0 + e1 * e1 + e2 * e2 + e3 * e3);+ }+ if (d * factor > stop) return Infinity;+ }+ return d * factor;+ };+ // Every source, in order; the first of equal ones wins.+ const everywhere = t => {+ let best = -1, bestD = Infinity;+ for (const s of sources) { const d = cost(t, s, bestD); if (d < bestD) { best = s; bestD = d; } }+ return [best, bestD];+ };+ // A level with many patches to place (a large stroke on a large picture, when it is saved)+ // looks only next to twice the coarser offset: the coarser levels have already searched+ // wider, and the full window there costs seconds for no visible gain.+ const win = targets.length > HEAL_SEARCH ? HEAL_WINDOW_FINE : HEAL_WINDOW, side = 2 * win + 1;+ const next = new Int32Array(lw * lh).fill(-1), D = new Float64Array(lw * lh);+ for (const t of targets) {+ let best = -1, bestD = Infinity, bestK = Infinity;+ if (coarse) {+ // The fixed window around twice the coarser offset. Its centre is compared first, so+ // most others stop early; of equal ones the first in reading order wins.+ const tx = t % lw, ty = (t - tx) / lw;+ const cx = Math.min(coarse.w - 1, tx >> 1), cy = Math.min(coarse.h - 1, ty >> 1), s0 = nnf.map[cy * coarse.w + cx];+ if (s0 >= 0) {+ const ox = tx + 2 * (s0 % coarse.w - cx), oy = ty + 2 * (Math.floor(s0 / coarse.w) - cy);+ const centre = win * side + win;+ for (let n = -1; n < side * side; n++) {+ if (n === centre) continue;+ const k = n < 0 ? centre : n, x = ox - win + k % side, y = oy - win + Math.floor(k / side);+ if (x < 0 || y < 0 || x >= lw || y >= lh || !valid[y * lw + x]) continue;+ const d = cost(t, y * lw + x, bestD);+ if (d < bestD || (d === bestD && k < bestK)) { best = y * lw + x; bestD = d; bestK = k; }+ }+ }+ }+ // The coarsest level, or a window with no source in it: search everywhere.+ if (best < 0) [best, bestD] = everywhere(t);+ next[t] = best; D[t] = bestD;+ }+ // Each hole pixel: the weighted vote of the patches that cover it.+ const acc = new Float64Array(lw * lh * 4), sum = new Float64Array(lw * lh);+ for (const t of targets) {+ const tx = t % lw, ty = (t - tx) / lw, s = next[t], sx = s % lw, sy = (s - sx) / lw;+ const weight = 1 / (1 + D[t] / (area * 4) / 100);+ for (let dy = -pr; dy <= pr; dy++) for (let dx = -pr; dx <= pr; dx++) {+ const x = tx + dx, y = ty + dy;+ if (x < 0 || y < 0 || x >= lw || y >= lh || !lhole[y * lw + x]) continue;+ const i = y * lw + x, j = ((sy + dy) * lw + sx + dx) * 4;+ for (let c = 0; c < 4; c++) acc[i * 4 + c] += weight * E[j + c];+ sum[i] += weight;+ }+ }+ for (let i = 0; i < lw * lh; i++) if (sum[i] > 0) for (let c = 0; c < 4; c++) E[i * 4 + c] = acc[i * 4 + c] / sum[i];+ if (l === 0) {+ // What the chosen patches say about the known pixels just around the hole, against what is there:+ // spread that difference smoothly across the hole, so the fill meets its surroundings without a seam.+ const ring = dilate(lhole, lw, lh, 2);+ for (let i = 0; i < lw * lh; i++) if (lhole[i]) ring[i] = 0;+ const pa = new Float64Array(lw * lh * 4), pt = new Float64Array(lw * lh);+ for (const t of targets) {+ const tx = t % lw, ty = (t - tx) / lw, s = next[t], sx = s % lw, sy = (s - sx) / lw;+ const weight = 1 / (1 + D[t] / (area * 4) / 100);+ for (let dy = -pr; dy <= pr; dy++) for (let dx = -pr; dx <= pr; dx++) {+ const x = tx + dx, y = ty + dy;+ if (x < 0 || y < 0 || x >= lw || y >= lh || !ring[y * lw + x]) continue;+ const i = y * lw + x, j = ((sy + dy) * lw + sx + dx) * 4;+ for (let c = 0; c < 4; c++) pa[i * 4 + c] += weight * E[j + c];+ pt[i] += weight;+ }+ }+ const diff = new Float64Array(lw * lh * 4), wt = new Float64Array(lw * lh);+ for (let i = 0; i < lw * lh; i++) {+ if (!ring[i] || !(pt[i] > 0)) continue;+ wt[i] = 1;+ for (let c = 0; c < 4; c++) diff[i * 4 + c] = img[i * 4 + c] - pa[i * 4 + c] / pt[i];+ }+ const smooth = pullPush(diff, wt, lw, lh);+ for (let i = 0; i < lw * lh; i++) if (lhole[i]) for (let c = 0; c < 4; c++) E[i * 4 + c] = clamp(E[i * 4 + c] + smooth[i * 4 + c], 0, 255);+ }+ nnf = {map: next, E};+ }+ return E;+}++// The caption inside a stroke: thin, bright, colourless strokes and their outline.+// Null when the stroke holds no such text, or so much (over 70%) that it is not a caption.+function textHole(d, hole, w, h, brush) {+ const core = new Uint8Array(w * h);+ let found = 0, total = 0;+ for (let i = 0; i < w * h; i++) {+ if (!hole[i]) continue;+ total++;+ const r = d[i * 4], g = d[i * 4 + 1], b = d[i * 4 + 2];+ if ((77 * r + 150 * g + 29 * b) >> 8 >= 190 && Math.max(r, g, b) - Math.min(r, g, b) <= 60) core[i] = 1;+ }+ // Letters are thin: what survives thinning by a tenth of the brush (a white+ // shirt, a lamp) is picture, and so is anything right beside it.+ const t = Math.max(1, Math.round(.1 * brush)), gaps = core.map(v => 1 - v), thinned = dilate(gaps, w, h, t).map(v => 1 - v);+ const thick = dilate(thinned, w, h, t + 2);+ for (let i = 0; i < w * h; i++) if (thick[i]) core[i] = 0;+ // Specks (a highlight on a buckle) are not letters either.+ const least = Math.max(4, Math.round((.12 * brush) ** 2)), seen = new Uint8Array(w * h);+ for (let start = 0; start < w * h; start++) {+ if (!core[start] || seen[start]) continue;+ seen[start] = 1;+ const part = [], stack = [start];+ while (stack.length) {+ const i = stack.pop(), x = i % w, y = (i - x) / w;+ part.push(i);+ for (let ny = y - 1; ny <= y + 1; ny++) for (let nx = x - 1; nx <= x + 1; nx++) {+ if (ny < 0 || nx < 0 || ny >= h || nx >= w) continue;+ const j = ny * w + nx;+ if (core[j] && !seen[j]) { seen[j] = 1; stack.push(j); }+ }+ }+ if (part.length < least) for (const i of part) core[i] = 0;+ else found += part.length;+ }+ if (!found || found * 10 > total * 7) return null;+ const grown = dilate(core, w, h, Math.max(2, Math.round(HEAL_TEXT_OUTLINE * brush)));+ for (let i = 0; i < w * h; i++) grown[i] &= hole[i];+ return grown;+}++// Spot healing: fill the stroke (only its caption when text is set, and+// nothing when it holds none) from patches of the picture around it; the+// stroke's soft outer edge blends into the picture. Without room for patches+// (a stroke over nearly everything) it fills smoothly from the surroundings.+function heal(raster, mask, text = false, brush = 0) {+ const w = raster.width, h = raster.height;+ const mctx = context(mask), md = mctx.getImageData(0, 0, w, h).data;+ const box = () => {+ let x0 = w, y0 = h, x1 = -1, y1 = -1;+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (md[(y * w + x) * 4 + 3] > 8) { x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y); }+ return [x0, y0, x1, y1];+ };+ let [x0, y0, x1, y1] = box();+ if (x1 < 0) return;+ const rctx = context(raster);+ if (text) {+ // Only the caption is replaced, and the work centres on it rather than on the stroke.+ const bw = x1 - x0 + 1, bh = y1 - y0 + 1, hole = new Uint8Array(bw * bh);+ for (let y = 0; y < bh; y++) for (let x = 0; x < bw; x++) hole[y * bw + x] = md[((y + y0) * w + x + x0) * 4 + 3] > 8 ? 1 : 0;+ const words = textHole(rctx.getImageData(x0, y0, bw, bh).data, hole, bw, bh, brush);+ if (!words) return; // no caption under the stroke: nothing to remove+ for (let i = 3; i < md.length; i += 4) md[i] = 0;+ for (let y = 0; y < bh; y++) for (let x = 0; x < bw; x++) md[((y + y0) * w + x + x0) * 4 + 3] = words[y * bw + x] ? 255 : 0;+ [x0, y0, x1, y1] = box();+ }+ const size = Math.max(x1 - x0 + 1, y1 - y0 + 1);+ const margin = Math.max(24, Math.min(HEAL_MARGIN, Math.round(size * .8)));+ const rx0 = Math.max(0, x0 - margin), ry0 = Math.max(0, y0 - margin), rx1 = Math.min(w - 1, x1 + margin), ry1 = Math.min(h - 1, y1 + margin);+ const rw = rx1 - rx0 + 1, rh = ry1 - ry0 + 1;+ const image = rctx.getImageData(rx0, ry0, rw, rh), d = image.data;+ const alpha = new Uint8Array(rw * rh), hole = new Uint8Array(rw * rh);+ for (let y = 0; y < rh; y++) for (let x = 0; x < rw; x++) {+ const a = md[((y + ry0) * w + x + rx0) * 4 + 3]; alpha[y * rw + x] = a; hole[y * rw + x] = a > 8 ? 1 : 0;+ }+ const fill = patchFill(new Float32Array(d), hole, rw, rh, size, text ? HEAL_NEAR_TEXT : HEAL_NEAR);+ if (fill) {+ for (let i = 0; i < rw * rh; i++) {+ if (!hole[i]) continue;+ const k = Math.min(1, alpha[i] / 128);+ for (let c = 0; c < 4; c++) d[i * 4 + c] = d[i * 4 + c] * (1 - k) + fill[i * 4 + c] * k;+ }+ } else {+ const col = new Float32Array(rw * rh * 4), wt = new Float32Array(rw * rh);+ for (let i = 0; i < rw * rh; i++) { const known = 1 - alpha[i] / 255; wt[i] = known; for (let c = 0; c < 4; c++) col[i * 4 + c] = d[i * 4 + c] * known; }+ const smooth = pullPush(col, wt, rw, rh);+ for (let i = 0; i < rw * rh; i++) { const a = alpha[i] / 255; if (a) for (let c = 0; c < 4; c++) d[i * 4 + c] = d[i * 4 + c] * (1 - a) + smooth[i * 4 + c] * a; }+ }+ rctx.putImageData(image, rx0, ry0);+}++// Pixels similar to the seed, as an alpha mask of the raster.+export function wand(raster, u, v, tolerance, contiguous) {+ const w = raster.width, h = raster.height;+ const sx = clamp(Math.floor(u * w), 0, w - 1), sy = clamp(Math.floor(v * h), 0, h - 1);+ const d = context(raster).getImageData(0, 0, w, h).data;+ const s = (sy * w + sx) * 4, ref = [d[s], d[s + 1], d[s + 2], d[s + 3]], tol = tolerance * 2.55;+ const near = i => Math.abs(d[i] - ref[0]) <= tol && Math.abs(d[i + 1] - ref[1]) <= tol && Math.abs(d[i + 2] - ref[2]) <= tol && Math.abs(d[i + 3] - ref[3]) <= tol;+ const sel = new Uint8Array(w * h);+ if (contiguous) {+ const stack = [sy * w + sx]; sel[sy * w + sx] = 1;+ while (stack.length) {+ const p = stack.pop(), x = p % w, y = (p - x) / w;+ for (const [nx, ny] of [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]]) {+ if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue;+ const q = ny * w + nx;+ if (!sel[q] && near(q * 4)) { sel[q] = 1; stack.push(q); }+ }+ }+ } else for (let p = 0; p < w * h; p++) sel[p] = near(p * 4) ? 1 : 0;+ const m = canvas(w, h), mctx = context(m), image = mctx.createImageData(w, h);+ for (let p = 0; p < w * h; p++) if (sel[p]) { image.data[p * 4] = image.data[p * 4 + 1] = image.data[p * 4 + 2] = image.data[p * 4 + 3] = 255; }+ mctx.putImageData(image, 0, 0);+ return m;+}++// ---------------------------------------------------------------------------+// Rendering with caches. A layer's raster is rebuilt only when its edits change.++export class Renderer {+ constructor(resolve) {+ this.resolve = resolve;+ this.images = new Map();+ this.layers = new Map();+ }+ async load(doc) {+ const files = new Set(doc.layers.filter(l => l.src).map(l => l.src));+ await Promise.all([...files].map(f => this.image(f)));+ }+ image(file) {+ if (!this.images.has(file)) {+ this.images.set(file, new Promise((resolve, reject) => {+ const image = new Image();+ image.onload = () => resolve(image); image.onerror = () => reject(new Error('load'));+ image.src = this.resolve(file);+ }));+ }+ return this.images.get(file);+ }+ loaded(file) { return this.images.get(file)?.value; }+ async preload(doc) {+ for (const l of doc.layers) if (l.src) { const img = await this.image(l.src); this.images.get(l.src).value = img; }+ await loadFonts(textFonts(doc));+ }+ // Raster of a layer at scale × its native pixels, edits applied (before+ // adjustments and mask), reusing the cached prefix of its edits. exact: for a saved+ // picture, its source image is made smaller by area average.+ raster(doc, layer, scale, upto = layer.ops.length, exact = false) {+ // An earlier state (a wand or copy made before later edits) gets its own entry.+ // At full size the saved picture's raster is the same as the one on screen.+ const at = exact && scale < 1 ? `${scale}!` : scale;+ const key = upto === layer.ops.length ? `${layer.id}@${at}` : `${layer.id}@${at}^${upto}`;+ const w = Math.max(1, Math.round(layer.nw * scale)), h = Math.max(1, Math.round(layer.nh * scale));+ let entry = this.layers.get(key);+ const ops = layer.ops.slice(0, upto);+ const prefix = entry && entry.source === this.sourceKey(layer) && entry.ops.length <= ops.length && entry.ops.every((id, i) => id === ops[i].id);+ if (!prefix) {+ const c = canvas(w, h), ctx = context(c);+ if (layer.kind === 'image' && layer.src) drawSource(ctx, this.images.get(layer.src).value, w, h, exact);+ if (layer.copyOf) {+ const src = doc.layers.find(l => l.id === layer.copyOf.layer);+ if (src) {+ ctx.drawImage(this.raster(doc, src, scale, layer.copyOf.upto, exact), 0, 0, w, h);+ if (layer.copyOf.selection) maskWith(c, this.selectionMask(doc, layer.copyOf.selection, {layer: src, scale}));+ }+ }+ entry = {source: this.sourceKey(layer), ops: [], canvas: c};+ }+ for (const op of ops.slice(entry.ops.length)) { this.apply(doc, layer, entry.canvas, op, scale); entry.ops.push(op.id); }+ this.layers.set(key, entry);+ return entry.canvas;+ }+ sourceKey(layer) { return JSON.stringify([layer.src, layer.copyOf, layer.nw, layer.nh]); }+ // A layer as composited: edits, adjustments, mask; text and shapes drawn.+ layerImage(doc, layer, scale, exact = false) {+ if (layer.kind === 'text') return this.text(layer, scale);+ if (layer.kind === 'shape') return this.shape(layer, scale);+ const raster = this.raster(doc, layer, scale, layer.ops.length, exact);+ const key = `${layer.id}@${exact && scale < 1 ? `${scale}!` : scale}#look`;+ const look = JSON.stringify([layer.ops.map(o => o.id), layer.adjust, layer.mask?.ops.map(o => o.id), layer.src, layer.copyOf]);+ const cached = this.layers.get(key);+ if (cached?.look === look) return cached.canvas;+ let out = adjusted(raster, layer.adjust, hashString(layer.id), scale);+ if (layer.mask) {+ if (out === raster) { out = canvas(raster.width, raster.height); out.getContext('2d').drawImage(raster, 0, 0); }+ maskWith(out, this.maskRaster(doc, layer, scale));+ }+ this.layers.set(key, {look, canvas: out});+ return out;+ }+ maskRaster(doc, layer, scale) {+ const w = Math.max(1, Math.round(layer.nw * scale)), h = Math.max(1, Math.round(layer.nh * scale));+ const key = `${layer.id}@${scale}#mask`, ids = layer.mask.ops.map(o => o.id);+ let entry = this.layers.get(key);+ if (!(entry && entry.ops.length <= ids.length && entry.ops.every((id, i) => id === ids[i]))) {+ const c = canvas(w, h), ctx = context(c); ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, w, h);+ entry = {ops: [], canvas: c};+ }+ for (const op of layer.mask.ops.slice(entry.ops.length)) { this.apply(doc, layer, entry.canvas, op, scale, true); entry.ops.push(op.id); }+ this.layers.set(key, entry);+ return entry.canvas;+ }+ apply(doc, layer, target, op, scale, isMask = false) {+ const w = target.width, h = target.height, ctx = target.getContext('2d');+ const selection = op.selection ? this.selectionMask(doc, op.selection, {layer, scale}) : null;+ const within = img => selection ? maskWith(img, selection) : img;+ if (op.type === 'fromSelection') {+ ctx.clearRect(0, 0, w, h);+ if (op.selection) ctx.drawImage(selection, 0, 0); else { ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, w, h); }+ if (op.invert) { ctx.globalCompositeOperation = 'xor'; ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, w, h); ctx.globalCompositeOperation = 'source-over'; }+ return;+ }+ if (op.type === 'fill' || op.type === 'clear') {+ const layerFill = canvas(w, h), lctx = layerFill.getContext('2d');+ lctx.fillStyle = isMask ? '#fff' : op.color || '#000'; lctx.fillRect(0, 0, w, h);+ within(layerFill);+ ctx.globalCompositeOperation = op.type === 'clear' ? 'destination-out' : 'source-over';+ ctx.globalAlpha = op.opacity ?? 1; ctx.drawImage(layerFill, 0, 0);+ ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over';+ return;+ }+ if (op.type === 'gradient') {+ const g = canvas(w, h), gctx = g.getContext('2d');+ const [x1, y1, x2, y2] = [op.from[0] * w, op.from[1] * h, op.to[0] * w, op.to[1] * h];+ const grad = op.shape === 'radial' ? gctx.createRadialGradient(x1, y1, 0, x1, y1, Math.hypot(x2 - x1, y2 - y1) || 1)+ : gctx.createLinearGradient(x1, y1, x2, y2);+ grad.addColorStop(0, op.c1); grad.addColorStop(1, op.c2 === 'transparent' ? op.c1 + '00' : op.c2);+ gctx.fillStyle = grad; gctx.fillRect(0, 0, w, h);+ within(g); ctx.globalAlpha = op.opacity ?? 1; ctx.drawImage(g, 0, 0); ctx.globalAlpha = 1;+ return;+ }+ if (op.type !== 'stroke') return;+ const mask = within(strokeMask(w, h, op));+ const opacity = op.opacity ?? 1;+ if (op.tool === 'paint' || op.tool === 'reveal') {+ const paint = canvas(w, h), pctx = paint.getContext('2d');+ pctx.fillStyle = op.tool === 'reveal' ? '#fff' : op.color; pctx.fillRect(0, 0, w, h); maskWith(paint, mask);+ ctx.globalAlpha = opacity; ctx.drawImage(paint, 0, 0); ctx.globalAlpha = 1;+ } else if (op.tool === 'erase' || op.tool === 'hide') {+ ctx.globalCompositeOperation = 'destination-out'; ctx.globalAlpha = opacity; ctx.drawImage(mask, 0, 0);+ ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over';+ } else if (op.tool === 'clone') {+ const copy = canvas(w, h), cctx = copy.getContext('2d');+ cctx.drawImage(target, op.offset[0] * w, op.offset[1] * h); maskWith(copy, mask);+ ctx.globalAlpha = opacity; ctx.drawImage(copy, 0, 0); ctx.globalAlpha = 1;+ } else if (op.tool === 'blur') {+ const soft = blurred(target, Math.max(1, op.size * Math.min(w, h) * .25 * (op.strength ?? .6)));+ maskWith(soft, mask);+ ctx.globalAlpha = opacity; ctx.drawImage(soft, 0, 0); ctx.globalAlpha = 1;+ } else if (op.tool === 'heal') {+ heal(target, mask, !!op.text, op.size * Math.min(w, h));+ }+ }+ // A selection drawn into a layer's pixels (or into D when target.layer is absent).+ selectionMask(doc, selection, {layer, scale}) {+ const w = Math.max(1, Math.round(layer.nw * scale)), h = Math.max(1, Math.round(layer.nh * scale));+ const out = canvas(w, h), ctx = context(out);+ // D → layer pixels at this scale.+ const toLocal = new DOMMatrix().scaleSelf(scale, scale).multiplySelf(layerMatrix(layer).inverse());+ for (const part of selection.parts) {+ ctx.globalCompositeOperation = part.mode === 'subtract' ? 'destination-out' : part.mode === 'intersect' ? 'destination-in' : 'source-over';+ if (part.mode === 'replace') ctx.clearRect(0, 0, w, h);+ ctx.save();+ if (part.shape === 'wand') {+ const src = doc.layers.find(l => l.id === part.layer);+ if (src) {+ const r = this.raster(doc, src, scale, part.upto ?? src.ops.length);+ const m = wand(r, part.u, part.v, part.tolerance, part.contiguous);+ const toSrc = new DOMMatrix().scaleSelf(scale, scale).multiplySelf(layerMatrix(layer).inverse()).multiplySelf(layerMatrix(src)).scaleSelf(1 / scale, 1 / scale);+ ctx.setTransform(toSrc); ctx.drawImage(m, 0, 0);+ }+ } else {+ ctx.setTransform(toLocal);+ ctx.fillStyle = '#fff';+ ctx.beginPath();+ if (part.shape === 'rect') ctx.rect(part.x, part.y, part.w, part.h);+ else if (part.shape === 'ellipse') ctx.ellipse(part.x + part.w / 2, part.y + part.h / 2, Math.abs(part.w / 2), Math.abs(part.h / 2), 0, 0, Math.PI * 2);+ else if (part.shape === 'all') ctx.rect(-1e6, -1e6, 2e6, 2e6);+ else if (part.pts?.length > 2) { ctx.moveTo(...part.pts[0]); for (const p of part.pts.slice(1)) ctx.lineTo(...p); ctx.closePath(); }+ ctx.fill();+ }+ ctx.restore();+ }+ ctx.globalCompositeOperation = 'source-over';+ if (selection.invert) { ctx.globalCompositeOperation = 'xor'; ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, w, h); ctx.globalCompositeOperation = 'source-over'; }+ if (selection.feather > 0) {+ const px = selection.feather * scale * Math.max(layer.nw / layer.w, layer.nh / layer.h);+ return blurred(out, px);+ }+ return out;+ }+ text(layer, scale) {+ const key = `${layer.id}@${scale}#text`, look = JSON.stringify([layer.text, layer.nw, layer.nh]);+ const cached = this.layers.get(key);+ if (cached?.look === look) return cached.canvas;+ const t = layer.text, c = canvas(layer.nw * scale, layer.nh * scale), ctx = c.getContext('2d');+ ctx.scale(scale, scale);+ ctx.font = fontCSS(t.font, t.weight, t.size);+ ctx.fillStyle = t.color; ctx.textBaseline = 'top';+ ctx.textAlign = t.align || 'left';+ const x = t.align === 'center' ? layer.nw / 2 : t.align === 'right' ? layer.nw - t.size * .2 : t.size * .2;+ if (t.shadow) { ctx.shadowColor = 'rgba(0,0,0,.55)'; ctx.shadowBlur = t.size * .18; ctx.shadowOffsetY = t.size * .05; }+ if (t.outline) { ctx.lineWidth = Math.max(1, t.size * .08); ctx.strokeStyle = t.outline; ctx.lineJoin = 'round'; }+ String(t.content).split('\n').forEach((line, i) => {+ const y = t.size * .2 + i * t.size * (t.lineHeight || 1.25);+ if (t.outline) ctx.strokeText(line, x, y);+ ctx.fillText(line, x, y);+ });+ this.layers.set(key, {look, canvas: c});+ return c;+ }+ shape(layer, scale) {+ const key = `${layer.id}@${scale}#shape`, look = JSON.stringify([layer.shape, layer.nw, layer.nh]);+ const cached = this.layers.get(key);+ if (cached?.look === look) return cached.canvas;+ const s = layer.shape, c = canvas(layer.nw * scale, layer.nh * scale), ctx = c.getContext('2d');+ ctx.scale(scale, scale);+ const lw = s.stroke ? s.width : 0, inset = lw / 2;+ ctx.lineWidth = lw; ctx.strokeStyle = s.stroke || 'transparent'; ctx.fillStyle = s.fill || 'transparent';+ ctx.lineCap = 'round';+ ctx.beginPath();+ if (s.type === 'ellipse') ctx.ellipse(layer.nw / 2, layer.nh / 2, Math.max(1, layer.nw / 2 - inset), Math.max(1, layer.nh / 2 - inset), 0, 0, Math.PI * 2);+ else if (s.type === 'line') { ctx.moveTo(inset, layer.nh / 2); ctx.lineTo(layer.nw - inset, layer.nh / 2); }+ else ctx.roundRect ? ctx.roundRect(inset, inset, layer.nw - lw, layer.nh - lw, s.radius || 0) : ctx.rect(inset, inset, layer.nw - lw, layer.nh - lw);+ if (s.fill && s.type !== 'line') ctx.fill();+ if (s.stroke) ctx.stroke();+ this.layers.set(key, {look, canvas: c});+ return c;+ }+ // The scale a layer's pixels are made at: as fine as it is drawn, never finer than its own+ // pixels. On screen it is a power of two, so moving or resizing a layer keeps reusing them;+ // a saved picture (exact) makes them at the size drawn.+ layerScale(layer, scale, exact = false) {+ const need = scale * Math.max(Math.abs(layer.w / layer.nw), Math.abs(layer.h / layer.nh));+ if (need >= .999) return 1;+ if (exact) return need;+ let s = 1; while (s / 2 >= need * .999 && s > 1 / 64) s /= 2;+ return s;+ }+ // The scales the layers are made at for a picture at this scale (the ones to keep cached).+ scales(doc, scale) { return [scale, ...doc.layers.map(l => this.layerScale(l, scale))]; }+ // The whole canvas at scale × oriented pixels.+ composite(doc, scale, {skip = null, background = true, exact = false} = {}) {+ const rect = canvasRect(doc);+ const out = canvas(rect.w * scale, rect.h * scale), ctx = out.getContext('2d');+ if (background && (doc.extend.l || doc.extend.t || doc.extend.r || doc.extend.b)) {+ ctx.fillStyle = doc.extend.color; ctx.fillRect(0, 0, out.width, out.height);+ }+ const view = new DOMMatrix().scaleSelf(scale, scale).translateSelf(-rect.x, -rect.y).multiplySelf(orientMatrix(doc));+ for (const layer of doc.layers) {+ if (!layer.visible || layer.id === skip) continue;+ const s = this.layerScale(layer, scale, exact);+ const img = this.layerImage(doc, layer, s, exact);+ ctx.save();+ ctx.setTransform(new DOMMatrix(view).multiplySelf(layerMatrix(layer)).scaleSelf(1 / s, 1 / s));+ // A picture enlarged past its own pixels is smoothed with the finer filter when saved;+ // everything else is drawn at about its own size, where the plain one is as good and far quicker.+ if (exact && scale * Math.max(Math.abs(layer.w / layer.nw), Math.abs(layer.h / layer.nh)) > 1.001) ctx.imageSmoothingQuality = 'high';+ ctx.globalAlpha = layer.opacity; ctx.globalCompositeOperation = layer.blend || 'source-over';+ ctx.drawImage(img, 0, 0);+ ctx.restore();+ }+ return out;+ }+ async export(doc, type) {+ await this.preload(doc);+ const full = this.composite(doc, 1, {exact: true});+ const rect = canvasRect(doc), c = doc.crop;+ const out = canvas(c.w, c.h), ctx = out.getContext('2d');+ if (type === 'image/jpeg') { ctx.fillStyle = doc.extend.color || '#000'; ctx.fillRect(0, 0, out.width, out.height); }+ ctx.drawImage(full, Math.round(c.x - rect.x), Math.round(c.y - rect.y), out.width, out.height, 0, 0, out.width, out.height);+ const blob = await new Promise((resolve, reject) => out.toBlob(b => b ? resolve(b) : reject(new Error('render')), type, .95));+ return {blob, width: out.width, height: out.height};+ }+ // Drop cached rasters made at other preview scales (zooming leaves them behind).+ prune(scales) {+ const keep = new Set(scales.map(String));+ for (const [key, entry] of this.layers) {+ const scale = key.split('@')[1]?.split(/[#^]/)[0];+ if (scale !== undefined && !keep.has(scale) && parseFloat(scale) > .05) { if (entry.canvas) entry.canvas.width = entry.canvas.height = 0; this.layers.delete(key); }+ }+ }+ // Free every cached canvas; the browser reclaims their memory.+ release() {+ for (const entry of this.layers.values()) { if (entry.canvas) { entry.canvas.width = entry.canvas.height = 0; } }+ this.layers.clear(); this.images.clear();+ }+}diff --git a/web/setup.js b/web/setup.jsindex 56c2c77..b1c1bd9 100644--- a/web/setup.js+++ b/web/setup.js@@ -1,5 +1,5 @@import { api } from "../../scripts/api.js";-import { wordmark } from './branding.js';+import { wordmark } from './wordmark.js';import { openCompatibility } from './compatibility.js';import { animateDetails, closeDialog } from './motion.js';diff --git a/web/share.js b/web/share.jsindex 68463dd..f82b342 100644--- a/web/share.js+++ b/web/share.js@@ -1,6 +1,7 @@import {api} from '../../scripts/api.js';import {closeDialog} from './motion.js';import {effortFor, effortName} from './sampling_effort.js';+import {fontCSS, loadFont} from './fonts.js';const css=document.createElement('link'); css.rel='stylesheet'; css.href=new URL('./share.css',import.meta.url).href; document.head.append(css);const el=(tag,cls,text)=>{const e=document.createElement(tag);if(cls)e.className=cls;if(text)e.textContent=text;return e;};@@ -25,8 +26,10 @@ async function withGraph(blob,graph){const tint=(hex,alpha)=>{const v=parseInt(hex.slice(1),16);return `rgba(${v>>16},${v>>8&255},${v&255},${alpha})`;};let opened;-// Deterministic Canvas rendering: browser fonts cover CJK and no external-// resources or user prompt are included. The image window preserves every pixel.+// Deterministic Canvas rendering in FreeVideo's bundled sans (load it first: shareFonts), never a+// font of the computer; no external resources or user prompt are included. The image window+// preserves every pixel.+export const shareFonts=()=>Promise.all([loadFont('sans',400),loadFont('sans',700)]);export function shareLayout(width,height) {const w=width>=height?1200:900, scale=w/width, footer=w>=1000?148:200;const h=Math.round(Math.min(1800,height*scale)/2)*2, artWidth=Math.round(h*width/height/2)*2;@@ -48,12 +51,11 @@ export function drawShareCard(canvas,frame,logo,record,t) {const line=ctx.createLinearGradient(0,0,w,0);line.addColorStop(0,tint(accent,0));line.addColorStop(.5,tint(accent,.75));line.addColorStop(1,tint(accent,0));ctx.fillStyle=line;ctx.fillRect(0,y,w,2);if(frame)ctx.drawImage(frame,...shape.rect);- const font='"Segoe UI", "PingFang SC", "Microsoft YaHei", system-ui, sans-serif';- const fit=(text,weight,size,max)=>{while(size>12){ctx.font=`${weight} ${size}px ${font}`;if(ctx.measureText(text).width<=max)break;size--;}return ctx.measureText(text).width;};+ const fit=(text,weight,size,max)=>{while(size>12){ctx.font=fontCSS('sans',weight,size);if(ctx.measureText(text).width<=max)break;size--;}return ctx.measureText(text).width;};const logoWidth=wide?156:140, logoTop=wide?y+H/2-26:y+30;ctx.drawImage(logo,pad,logoTop,logoWidth,logoWidth*337/2016);const seconds=g.seconds||g.frames/(g.fps||24);- ctx.font=`400 14px ${font}`;ctx.fillStyle='#6f8399';ctx.textAlign=wide?'left':'right';+ ctx.font=fontCSS('sans',400,14);ctx.fillStyle='#6f8399';ctx.textAlign=wide?'left':'right';ctx.fillText(`${g.width} × ${g.height}${Number.isFinite(seconds)?' · '+seconds.toFixed(1)+' s':''}`,wide?pad:w-pad,wide?y+H/2+24:y+46);ctx.textAlign='left';const gpu=(record.gpu||t('GPU not recorded','显卡未记录')).replace(/^NVIDIA\s+/,'').replace(/GeForce\s+/,'');@@ -61,7 +63,7 @@ export function drawShareCard(canvas,frame,logo,record,t) {[t('Quality','质量'),tier?effortName(t,tier):(steps?t('Custom','自定义'):'—'),true]];const labelY=wide?y+H/2-16:y+H-80, valueY=wide?y+H/2+26:y+H-38;const drawStat=([label,value,pill],x,max)=>{- ctx.font=`500 13px ${font}`;ctx.fillStyle='#7d90a6';ctx.fillText(label,x,labelY);+ ctx.font=fontCSS('sans',500,13);ctx.fillStyle='#7d90a6';ctx.fillText(label,x,labelY);if(!pill){fit(value,600,28,max);ctx.fillStyle='#eef3fa';ctx.fillText(value,x,valueY);return;}const text=fit(value,650,20,max-32),pw=text+32;ctx.beginPath();ctx.roundRect(x,valueY-27,pw,34,17);ctx.fillStyle=tint(accent,.16);ctx.fill();@@ -70,7 +72,7 @@ export function drawShareCard(canvas,frame,logo,record,t) {};if(wide){// Right-aligned columns; each takes its own width, separated by hairlines.- const widths=stats.map(([label,value,pill])=>{ctx.font=`500 13px ${font}`;const l=ctx.measureText(label).width;+ const widths=stats.map(([label,value,pill])=>{ctx.font=fontCSS('sans',500,13);const l=ctx.measureText(label).width;const v=pill?Math.min(fit(value,650,20,220),220)+32:Math.min(fit(value,600,28,300),300);return Math.max(l,v);});let x=w-pad;for(let i=stats.length-1;i>=0;i--){@@ -161,7 +163,7 @@ export async function openShare(record,t){metadata=await response.json();[first,logo]=await Promise.all([image(api.apiURL('/freevideo/share/frame?'+new URLSearchParams({id}))),image(new URL('./assets/freevideo.svg',import.meta.url).href)]);if(disposed)return;- if(document.fonts?.ready)await document.fonts.ready;+ await shareFonts();if(document.fonts?.ready)await document.fonts.ready;shape=drawShareCard(canvas,null,logo,metadata,t);template=canvas.toDataURL('image/png').split(',')[1];preview.style.aspectRatio=`${shape.width}/${shape.height}`;player.style.cssText=`left:${shape.rect[0]/shape.width*100}%;top:0;width:${shape.rect[2]/shape.width*100}%;height:${shape.rect[3]/shape.height*100}%`;diff --git a/web/studio.js b/web/studio.jsindex ee761be..7b751d7 100644--- a/web/studio.js+++ b/web/studio.js@@ -2,7 +2,7 @@ import { createErrorPanel, errorText, createErrorReport } from './error_panel.jsimport { app } from '../../scripts/app.js';import { api } from '../../scripts/api.js';import { openSetup } from './setup.js';-import { wordmark } from './branding.js';+import { wordmark } from './wordmark.js';import { createGenerationProgress, referenceTrimText, thermalText } from './generation_progress.js';import { viewSwitch, viewChanged } from './view_navigation.js';import { createUpdateNotice, createVersionInfo, productVersion } from './updates.js';diff --git a/web/theme.css b/web/theme.cssindex bccbdac..41fbbd7 100644--- a/web/theme.css+++ b/web/theme.css@@ -1,7 +1,7 @@/* One token table for the web views, mirroring freevideo_engine/branding.py soa control looks the same in the launcher and in ComfyUI. Scope the tokens toour own views; never change ComfyUI's theme. */-:where(.fv-studio,.fv-setup,.fv-panel,.fv-generation-progress,.fv-view-navigation,.fv-prompt-guide,.fv-failure-dialog,.fv-reference-picker,.fv-release-notes){+:where(.fv-studio,.fv-setup,.fv-panel,.fv-generation-progress,.fv-view-navigation,.fv-prompt-guide,.fv-failure-dialog,.fv-reference-picker,.fv-release-notes,.fv-image-editor){/* Surfaces, from the backdrop up to a hovered control; mirrors branding.py. */--fv-bg:#111720;--fv-canvas:#161e29;--fv-card:#1a222e;--fv-raised:#212a37;--fv-hover:#2a3341;--fv-border:#2a3443;--fv-sheen:#35404e;diff --git a/web/toolbar_position.js b/web/toolbar_position.jsnew file mode 100644index 0000000..2de9827--- /dev/null+++ b/web/toolbar_position.js@@ -0,0 +1,253 @@+// Lets a floating panel be dragged anywhere on the page, the way a window is,+// and puts it back where it was on the next visit. The place lives in+// ComfyUI's user settings, so it survives a restart and follows the user to+// another browser; localStorage keeps a copy for frontends without settings.+import { app } from '../../scripts/app.js';++const SETTING = 'FreeVideo.Toolbar.Position';+const LOCAL = 'freevideo.toolbar-position';+// A press that moves no more than THRESHOLD is a click. A drop within EDGE of+// a side sticks to that side; within HOME of the default place, it goes home.+const THRESHOLD = 4, EDGE = 16, HOME = 12, MARGIN = 8;+const RESET = 'default';+const SIDES = ['left', 'right', 'center'];+const valid = value => !!value && typeof value === 'object' && SIDES.includes(value.side)+ && Number.isFinite(value.ratio) && Math.abs(value.ratio) <= 1 && Number.isFinite(value.top) && value.top >= 0;+const reduced = () => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;++// ComfyUI's user settings: the settings store, the older settings dialog, or none.+function settings() {+ try {+ const store = app?.extensionManager?.setting;+ if (typeof store?.get === 'function' && typeof store?.set === 'function') return {get: id => store.get(id), set: (id, value) => store.set(id, value)};+ const dialog = app?.ui?.settings;+ if (typeof dialog?.getSettingValue === 'function' && typeof dialog?.setSettingValue === 'function') {+ return {get: id => dialog.getSettingValue(id), set: (id, value) => dialog.setSettingValue(id, value)};+ }+ } catch { /* No settings: localStorage only. */ }+ return null;+}++// What the user saved, from ComfyUI's settings first; null means the default place.+function readSaved() {+ let stored;+ try { stored = settings()?.get(SETTING); } catch { /* localStorage below. */ }+ if (stored !== undefined && stored !== null) return valid(stored) ? stored : null;+ try {+ const local = JSON.parse(localStorage.getItem(LOCAL) || 'null');+ return valid(local) ? local : null;+ } catch { return null; }+}++function save(value) {+ try {+ if (value) localStorage.setItem(LOCAL, JSON.stringify(value)); else localStorage.removeItem(LOCAL);+ } catch { /* Private browsing: ComfyUI's settings still keep it. */ }+ // The default is saved too, so another browser's older copy does not come back.+ try { Promise.resolve(settings()?.set(SETTING, value || RESET)).catch(() => {}); } catch { /* localStorage has it. */ }+}++// ComfyUI's workflow tabs and side toolbar: the panel keeps clear of them.+const CHROME = ['.workflow-tabs-container', '.side-tool-bar-container'];++// Where a panel of this size may go: inside the window with a margin, below+// ComfyUI's workflow tabs and clear of its side toolbar while it fits there.+function area(width, height) {+ let left = MARGIN, right = innerWidth - MARGIN, top = MARGIN;+ const bottom = innerHeight - MARGIN;+ const tabs = document.querySelector(CHROME[0])?.getBoundingClientRect();+ if (tabs && tabs.height > 0 && tabs.top < 4 && tabs.width > innerWidth / 2 && bottom - (tabs.bottom + MARGIN) >= height) top = tabs.bottom + MARGIN;+ const side = document.querySelector(CHROME[1])?.getBoundingClientRect();+ if (side && side.width > 0 && side.height > innerHeight / 2) {+ if (side.left < innerWidth / 2 && right - (side.right + MARGIN) >= width) left = side.right + MARGIN;+ else if (side.left >= innerWidth / 2 && side.left - MARGIN - left >= width) right = side.left - MARGIN;+ }+ return {left, right, top, bottom, maxX: Math.max(left, right - width), maxY: Math.max(top, bottom - height)};+}++const clamp = (value, min, max) => Math.min(max, Math.max(min, value));++// ComfyUI's controls that float over the canvas in a corner: the run bar when+// it is not docked, the canvas tools and the minimap. They are not edges of+// the area: a place that covers one moves up or down to the nearest free spot.+const FLOATING = ['.actionbar', '.graph-canvas-panel .p-buttongroup', '.minimap-main-container'];+const GAP = 8;+function clearOf(left, top, width, height, room) {+ const blocks = [];+ for (const selector of FLOATING) {+ for (const element of document.querySelectorAll(selector)) {+ const r = element.getBoundingClientRect();+ if (r.width > 0 && r.height > 0 && r.left < left + width && r.right > left) blocks.push(r);+ }+ }+ if (!blocks.some(r => top < r.bottom && top + height > r.top)) return top;+ const free = y => blocks.every(r => y + height + GAP <= r.top || y >= r.bottom + GAP);+ const spots = blocks.flatMap(r => [r.top - GAP - height, r.bottom + GAP])+ .filter(y => y >= room.top && y <= room.maxY && free(y)).sort((a, b) => Math.abs(a - top) - Math.abs(b - top));+ return spots.length ? Math.round(spots[0]) : top;+}++// Across, the place is kept relative to the nearest side or the middle, as a+// share of the window's width; down, as its distance from the top.+function describe(left, top, width, height) {+ const room = area(width, height);+ const fromLeft = left - room.left, fromRight = room.right - (left + width);+ const offCenter = left + width / 2 - (room.left + room.right) / 2;+ const side = fromLeft < EDGE ? 'left' : fromRight < EDGE ? 'right'+ : Math.abs(offCenter) <= Math.min(fromLeft, fromRight) ? 'center' : fromLeft <= fromRight ? 'left' : 'right';+ const distance = side === 'left' ? Math.max(0, fromLeft) : side === 'right' ? Math.max(0, fromRight) : offCenter;+ return {side, ratio: fromLeft < EDGE || fromRight < EDGE ? 0 : distance / innerWidth, top: Math.round(top)};+}++function resolve(saved, width, height) {+ const room = area(width, height), offset = saved.ratio * innerWidth;+ const left = saved.side === 'left' ? room.left + offset : saved.side === 'right' ? room.right - width - offset+ : (room.left + room.right) / 2 + offset - width / 2;+ return {left: Math.round(clamp(left, room.left, room.maxX)), top: Math.round(clamp(saved.top, room.top, room.maxY))};+}++const interactive = target => !!target?.closest?.('button, a, input, select, textarea, [role="button"]');++// panel: a position:fixed element whose stylesheet gives its default place.+// Pressing anywhere on it and moving drags it; a press that does not move stays+// a click. Double-clicking its background puts it back in its default place.+export function makeMovable(panel) {+ let saved = readSaved(), press = null, frame = 0, suppressClick = false;+ const PLACED = ['left', 'top', 'transform', 'right', 'bottom'];++ const setPlace = ({left, top}) => Object.assign(panel.style, {left: `${left}px`, top: `${top}px`, transform: 'none', right: 'auto', bottom: 'auto'});+ const clearPlace = () => { for (const key of PLACED) panel.style.removeProperty(key); };+ // The stylesheet's place, below ComfyUI's run bar where that covers it (a narrow window).+ function placeHome() {+ clearPlace();+ const box = panel.getBoundingClientRect();+ if (!box.width) return;+ const top = clearOf(box.left, box.top, box.width, box.height, area(box.width, box.height));+ if (Math.abs(top - box.top) >= 1) panel.style.top = `${top}px`;+ }+ // The saved place as it fits the window now, clear of ComfyUI's controls.+ function spot(width, height) {+ const at = resolve(saved, width, height);+ return {left: at.left, top: clearOf(at.left, at.top, width, height, area(width, height))};+ }+ // Where home is for the panel as it is now.+ function home() {+ const kept = PLACED.map(key => panel.style.getPropertyValue(key));+ placeHome();+ const box = panel.getBoundingClientRect();+ clearPlace();+ PLACED.forEach((key, index) => { if (kept[index]) panel.style.setProperty(key, kept[index]); });+ return box;+ }+ // Moves to the new place in one short motion from where it is now.+ function glide(apply, duration) {+ const before = panel.getBoundingClientRect();+ apply();+ const after = panel.getBoundingClientRect();+ if (reduced() || typeof panel.animate !== 'function' || (Math.abs(before.left - after.left) < 1 && Math.abs(before.top - after.top) < 1)) return;+ panel.animate([{translate: `${before.left - after.left}px ${before.top - after.top}px`}, {translate: '0 0'}], {duration, easing: 'ease-out'});+ }++ function place() {+ if (!panel.isConnected || panel.hidden || press?.dragging) return;+ if (!saved) return placeHome();+ const box = panel.getBoundingClientRect();+ if (box.width) setPlace(spot(box.width, box.height));+ }++ function goHome(duration) {+ saved = null;+ glide(placeHome, duration);+ save(null);+ }++ function follow() {+ frame = 0;+ if (!press?.dragging) return;+ const room = area(press.width, press.height);+ const dx = clamp(press.left + press.dx, room.left, room.maxX) - press.left;+ const dy = clamp(press.top + press.dy, room.top, room.maxY) - press.top;+ panel.style.translate = `${dx}px ${dy}px`;+ }++ // Moves are followed on the window from the press on: a quick first move+ // can leave the panel before it counts as a drag. Capturing the pointer only+ // once it is a drag keeps a plain press a click on the button under it.+ const watch = on => {+ for (const [type, handler] of [['pointermove', move], ['pointerup', release], ['pointercancel', release]]) {+ (on ? addEventListener : removeEventListener)(type, handler, true);+ }+ };+ panel.addEventListener('pointerdown', event => {+ if (event.button !== 0 || !event.isPrimary) return;+ press = {id: event.pointerId, x: event.clientX, y: event.clientY, dx: 0, dy: 0, dragging: false};+ watch(true);+ });+ function move(event) {+ if (!press || event.pointerId !== press.id) return;+ press.dx = event.clientX - press.x; press.dy = event.clientY - press.y;+ if (!press.dragging) {+ if (Math.hypot(press.dx, press.dy) <= THRESHOLD) return;+ const box = panel.getBoundingClientRect();+ Object.assign(press, {dragging: true, left: box.left, top: box.top, width: box.width, height: box.height});+ setPlace({left: box.left, top: box.top});+ try { panel.setPointerCapture(event.pointerId); } catch { /* Still follows while over the panel. */ }+ panel.classList.add('fv-dragging');+ document.documentElement.classList.add('fv-toolbar-dragging');+ }+ event.preventDefault();+ if (!frame) frame = requestAnimationFrame(follow);+ }+ function release(event) {+ if (!press || event.pointerId !== press.id) return;+ const drag = press;+ press = null;+ watch(false);+ if (!drag.dragging) return;+ if (frame) { cancelAnimationFrame(frame); frame = 0; }+ panel.classList.remove('fv-dragging');+ document.documentElement.classList.remove('fv-toolbar-dragging');+ // The press ended a drag, not a click on whatever is under it.+ suppressClick = event.type === 'pointerup';+ setTimeout(() => { suppressClick = false; }, 0);+ const room = area(drag.width, drag.height);+ const left = clamp(drag.left + drag.dx, room.left, room.maxX), top = clamp(drag.top + drag.dy, room.top, room.maxY);+ panel.style.removeProperty('translate');+ setPlace({left, top});+ const start = home();+ if (Math.abs(left - start.left) < HOME && Math.abs(top - start.top) < HOME) return goHome(120);+ saved = describe(left, clearOf(left, top, drag.width, drag.height, room), drag.width, drag.height);+ glide(() => setPlace(spot(drag.width, drag.height)), 120);+ save(saved);+ }+ panel.addEventListener('click', event => {+ if (!suppressClick) return;+ suppressClick = false;+ event.preventDefault(); event.stopPropagation();+ }, true);+ panel.addEventListener('dblclick', event => { if (!interactive(event.target)) goHome(180); });++ addEventListener('resize', place);+ // Showing it again, a closed tip or a new notice changes its size; ComfyUI+ // draws its tabs and side toolbar after extensions start, and they can change.+ if (typeof ResizeObserver === 'function') {+ const sizes = new ResizeObserver(() => place()), watched = new Set();+ sizes.observe(panel);+ const hook = () => {+ for (const selector of CHROME) {+ const element = document.querySelector(selector);+ if (element && !watched.has(element)) { watched.add(element); sizes.observe(element); }+ }+ return watched.size >= CHROME.length;+ };+ if (!hook()) {+ let tries = 0;+ const timer = setInterval(() => { if (hook() || ++tries >= 60) clearInterval(timer); }, 1000);+ }+ }+ // The run bar shows up after extensions start and can be moved; the minimap+ // opens and closes. A panel they come to cover moves aside, and back after.+ setInterval(() => { if (!document.hidden) glide(place, 120); }, 2000);+ place();+ return {place, reset: () => goHome(0)};+}diff --git a/web/updates.js b/web/updates.jsindex d58dd87..18acbdd 100644--- a/web/updates.js+++ b/web/updates.js@@ -134,10 +134,11 @@ export function createUpdateNotice(cn) {element.append(label, details, apply, link, dismiss, stop, summary);const render = () => {const launcher = value?.launcher, phase = launcher?.phase || '', candidate = value?.available;- const mac = value?.channel === 'macos-preview';+ const mac = value?.channel === 'macos-preview', linux = value?.channel === 'linux-preview';link.href = value?.track === 'nightly' ? nightlyPage : releasePage;link.title = mac? t('After your task finishes, open the new FreeVideo.app to update.', '当前任务完成后,打开新版 FreeVideo.app 更新。')+ : linux ? t('After your task finishes, open the new FreeVideo AppImage to update.', '当前任务完成后,打开新版 FreeVideo AppImage 更新。'): t('After your task finishes, open the new FreeVideo.exe to update.', '当前任务完成后,打开新版 FreeVideo.exe 更新。');const progress = launcher?.progress, percent = progress?.total ? ' ' + Math.floor(100 * progress.done / progress.total) + '%' : '';// The last model state seen stays while ComfyUI is away.diff --git a/web/view_navigation.css b/web/view_navigation.cssindex b25642c..5fffdef 100644--- a/web/view_navigation.css+++ b/web/view_navigation.css@@ -15,3 +15,11 @@.fv-view-navigation{animation:fv-panel-enter .25s ease}@media(max-width:380px){.fv-view-row>.fv-wordmark{width:76px}.fv-view-navigation .fv-view-switch button{font-size:12px;padding:7px 8px}}@media(prefers-reduced-motion:reduce){.fv-view-navigation,.fv-view-navigation *{animation:none!important;transition:none!important}}+/* Dragged like a window: press anywhere on the bar and move. A press that does not move stays a click. */+.fv-view-navigation{padding-left:20px;padding-right:20px;cursor:grab;user-select:none;-webkit-user-select:none;touch-action:none}.fv-view-navigation img,.fv-view-navigation a{-webkit-user-drag:none}+.fv-view-navigation.fv-dragging{box-shadow:0 18px 48px #0008;border-color:color-mix(in srgb,var(--fv-border) 70%,var(--fv-ink))}+html.fv-toolbar-dragging,html.fv-toolbar-dragging *{cursor:grabbing!important;user-select:none!important;-webkit-user-select:none!important}+/* Six dots in the left padding, beside the first row, as on ComfyUI's own run bar. */+.fv-view-row{position:relative}.fv-view-grip{position:absolute;left:-14px;top:50%;translate:0 -50%;width:8px;height:12px;opacity:0;pointer-events:none;color:var(--fv-muted);transition:opacity .2s,color .2s;background:radial-gradient(circle,currentColor 1.1px,transparent 1.5px) 0 0/4px 4px}+.fv-view-navigation:hover .fv-view-grip{opacity:.75}.fv-view-navigation.fv-dragging .fv-view-grip{opacity:1;color:var(--fv-ink)}@media(hover:none){.fv-view-grip{opacity:.5}}+@media(max-width:480px){.fv-view-navigation .fv-version-info{display:none}}diff --git a/web/view_navigation.js b/web/view_navigation.jsindex 30805cf..d6c7534 100644--- a/web/view_navigation.js+++ b/web/view_navigation.js@@ -1,7 +1,8 @@import { app } from '../../scripts/app.js';import { openSetup } from './setup.js';-import { wordmark } from './branding.js';+import { wordmark } from './wordmark.js';import { createUpdateNotice, createVersionInfo } from './updates.js';+import { makeMovable } from './toolbar_position.js';const languageOverride = typeof location !== 'undefined'? new URLSearchParams(location.search).get('freevideo_lang') : null;@@ -53,6 +54,8 @@ export function installNavigation(openStudio) {toolbar = document.createElement('aside'); toolbar.className = 'fv-view-navigation';toolbar.setAttribute('aria-label', t('FreeVideo workspace', 'FreeVideo 工作区'));const row = document.createElement('div'); row.className = 'fv-view-row';+ // The whole bar drags like a window; these dots say so on hover.+ const grip = document.createElement('span'); grip.className = 'fv-view-grip'; grip.setAttribute('aria-hidden', 'true');const brand = wordmark();const choose = () => {const focused = Object.values(app.canvas?.selected_nodes || {}).find(n => n.comfyClass === 'FreeVideoGenerate' || n.type === 'FreeVideoGenerate');@@ -60,7 +63,7 @@ export function installNavigation(openStudio) {};const settings = document.createElement('button'); settings.type = 'button';settings.textContent = t('Settings', '设置'); settings.className = 'fv-view-settings'; settings.onclick = openSetup;- row.append(brand, viewSwitch('nodes', choose, () => {}), createVersionInfo(cn).element, settings); toolbar.append(row);+ row.append(grip, brand, viewSwitch('nodes', choose, () => {}), createVersionInfo(cn).element, settings); toolbar.append(row);let shown = false;try { shown = localStorage.getItem('freevideo.view-guide') === '1'; } catch { /* Show once this session. */ }if (!shown) {@@ -91,6 +94,7 @@ export function installNavigation(openStudio) {}toolbar.append(createUpdateNotice(cn).element);document.body.append(toolbar); refreshNavigation();+ makeMovable(toolbar);// health.js asks for this before it reports the toolbar missing. A// workspace removed without closing must not keep the toolbar hidden.globalThis.window?.addEventListener('freevideo-navigation-refresh', () => {diff --git a/web/branding.js b/web/wordmark.jssimilarity index 88%rename from web/branding.jsrename to web/wordmark.jsindex d066a5b..e9c2ad4 100644--- a/web/branding.js+++ b/web/wordmark.js@@ -1,4 +1,5 @@// All artwork is served by this custom node; no font/CDN request is needed.+// Not called branding.js: ad-block lists block scripts by that name.const css = document.createElement('link');css.rel = 'stylesheet'; css.href = new URL('./theme.css', import.meta.url).href;document.head.append(css);