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.
The launcher's phone access shows a QR code and an optional password, and follows the LAN switch...
Bowen Xued28f02af6b12
diff --git a/docs/Linux.md b/docs/Linux.mdindex d98840e..426fee6 100644--- a/docs/Linux.md+++ b/docs/Linux.md@@ -48,7 +48,7 @@ To connect from computers on your local network without SSH: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.+This prints an access link with a token, and a QR code of it to scan with a phone camera. 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.diff --git a/docs/Linux.zh-CN.md b/docs/Linux.zh-CN.mdindex 6023d78..92cd89a 100644--- a/docs/Linux.zh-CN.md+++ b/docs/Linux.zh-CN.md@@ -48,7 +48,7 @@ ssh -N -L 8188:127.0.0.1:8188 用户名@服务器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。+这会打印一个带访问令牌的链接和对应的二维码(可用手机相机扫描),持有链接的人都可以使用这台服务器上的 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` 会移除这个服务。diff --git a/freevideo_engine/comfy_launcher.py b/freevideo_engine/comfy_launcher.pyindex d64c422..345fd9c 100644--- a/freevideo_engine/comfy_launcher.py+++ b/freevideo_engine/comfy_launcher.py@@ -19,7 +19,7 @@ from .terminal_ui import clean, durationfrom .setup_progress import number, progress_text-FIREWALL_HINT = ('If Windows asks about the firewall the first time, choose Allow.', 'Windows 首次询问防火墙权限时,请选择“允许”。')+FIREWALL_HINT = ('Windows will ask for permission. Check "Private networks", then click "Allow access".', 'Windows 会弹出确认框,请勾选“专用网络”,再点“允许访问”。')BROWSER_STARTING = ('Still starting. Your browser will open automatically when ready.', '还在启动,好了会自动打开')diff --git a/freevideo_engine/comfy_service.py b/freevideo_engine/comfy_service.pyindex 8142841..3f4f54d 100644--- a/freevideo_engine/comfy_service.py+++ b/freevideo_engine/comfy_service.py@@ -544,14 +544,29 @@ def host_url(scheme, address, port):return '%s://%s:%d' % (scheme, '[%s]' % address if ':' in address else address, port)+def qr_lines(link):+ """The link as a terminal QR code for a phone camera; nothing when it cannot be drawn."""+ if not link:+ return []+ try:+ from . import qr_code+ return qr_code.terminal_lines(link)+ except (ImportError, ValueError):+ return []++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))+ links = ['%s/?freevideo=launch&token=%s' % (host_url(access['scheme'], address, access['port']), secret)+ for address in addresses(state.get('listen', ''))]+ for link in links:+ out(' ' + link)+ for line in qr_lines(links[0] if links else ''):+ out(' ' + line)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.')diff --git a/freevideo_engine/launcher/FIcon.qml b/freevideo_engine/launcher/FIcon.qmlindex a110e54..85668ba 100644--- a/freevideo_engine/launcher/FIcon.qml+++ b/freevideo_engine/launcher/FIcon.qml@@ -19,6 +19,7 @@ Canvas {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 if (kind === "eye" || kind === "eyeoff") { c.moveTo(2,12); c.quadraticCurveTo(12,3,22,12); c.quadraticCurveTo(12,21,2,12); c.moveTo(15,12); c.arc(12,12,3,0,Math.PI*2); if (kind === "eyeoff") { c.moveTo(4,4); c.lineTo(20,20) } }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/FQrCode.qml b/freevideo_engine/launcher/FQrCode.qmlnew file mode 100644index 0000000..4c36b54--- /dev/null+++ b/freevideo_engine/launcher/FQrCode.qml@@ -0,0 +1,45 @@+import QtQuick++// A QR code drawn from rows of "0"/"1" (see qr_code.py): dark modules on a white tile.+// Plain rectangles rather than a Canvas: a Canvas paints nothing on software-rendered setups.+Rectangle {+ id: tile+ property var rows: []+ property int size: 132+ readonly property int count: rows.length+ // The rows joined into one string, so a refresh that brings the same code changes nothing.+ readonly property string signature: rows.join("")+ // Whole pixels per module keep the edges sharp; the leftover space becomes the quiet zone.+ readonly property int cell: count ? Math.max(1, Math.floor((size - 12) / count)) : 0+ // Horizontal runs of dark modules: {x, y, n}.+ property var runs: []+ implicitWidth: size; implicitHeight: size+ radius: 8; color: "#ffffff"+ function rebuild() {+ var found = []+ for (var y = 0; y < rows.length; y++) {+ var row = rows[y], start = -1+ for (var x = 0; x <= row.length; x++) {+ var dark = x < row.length && row.charAt(x) === "1"+ if (dark && start < 0) start = x+ else if (!dark && start >= 0) { found.push({x: start, y: y, n: x - start}); start = -1 }+ }+ }+ runs = found+ }+ onSignatureChanged: rebuild()+ Component.onCompleted: rebuild()+ Item {+ anchors.centerIn: parent+ width: tile.cell * tile.count; height: width+ Repeater {+ model: tile.runs+ delegate: Rectangle {+ required property var modelData+ x: modelData.x * tile.cell; y: modelData.y * tile.cell+ width: modelData.n * tile.cell; height: tile.cell+ color: "#000000"; antialiasing: false+ }+ }+ }+}diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qmlindex 0d0383b..5b3d0d2 100644--- a/freevideo_engine/launcher/Main.qml+++ b/freevideo_engine/launcher/Main.qml@@ -15,6 +15,9 @@ ApplicationWindow {Connections { target: backend; function onChanged() { win.s = backend.state } }property bool settingsOpen: falseproperty bool terminalOpen: false+ property bool lanPasswordEditing: false+ function firstLanLink() { return s.access_links && s.access_links.length ? s.access_links[0] : "" }+ property bool lanPasswordShown: falseproperty bool confirmArchives: false // the in-place "delete the imported ZIPs?" stepproperty bool archivesExpanded: falseproperty string settingsTab: "downloads"@@ -1106,10 +1109,35 @@ ApplicationWindow {Layout.fillWidth: true; title: t("Local network", "局域网")FSwitch { objectName: "lanAccessSwitch"; Layout.fillWidth: true; text: t("LAN access", "局域网访问"); checked: !!s.form.lan_access; enabled: !s.busy; onToggled: backend.edit("lan_access", checked) }FText { objectName: "lanAccessMessage"; text: s.lan_message || ""; visible: !!text; color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }- FText { objectName: "lanAccessHint"; text: t("When on, other devices on the same network can open FreeVideo with the link below. Anyone with the link can use it, so keep it private.", "开启后,同一网络中的其他设备可以用下面的链接打开 FreeVideo。拿到链接的人都能使用,请勿公开。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }- FText { objectName: "lanFirewallHint"; visible: Qt.platform.os === "windows"; text: t("If Windows asks about the firewall the first time, choose Allow.", "Windows 首次询问防火墙权限时,请选择“允许”。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }+ FText { objectName: "lanAccessHint"; text: s.lan_password_set ? t("When on, other devices on the same network can open FreeVideo with the link below and enter the password the first time.", "开启后,同一网络中的其他设备可以用下面的链接打开 FreeVideo,第一次打开时要输入密码。") : t("When on, other devices on the same network can open FreeVideo with the link below. Anyone with the link can use it, so keep it private.", "开启后,同一网络中的其他设备可以用下面的链接打开 FreeVideo。拿到链接的人都能使用,请勿公开。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }+ // The Chinese line breaks after the comma, keeping the second half whole.+ Flow {+ objectName: "lanFirewallHint"+ visible: Qt.platform.os === "windows" && !!s.form.lan_access && !(s.lan_qr && s.lan_qr.length > 0)+ Layout.fillWidth: true+ FText { text: t("Windows will ask for permission. Check \"Private networks\", then click \"Allow access\".", "Windows 会弹出确认框,"); color: theme.muted; font.pixelSize: theme.micro; width: Math.min(implicitWidth, parent.width); wrapMode: Text.WordWrap }+ FText { text: "请勾选“专用网络”,再点“允许访问”。"; visible: s.zh; color: theme.muted; font.pixelSize: theme.micro; width: Math.min(implicitWidth, parent.width); wrapMode: Text.WordWrap }+ }+ GridLayout {+ id: lanQrRow; objectName: "lanQrRow"+ visible: !!s.lan_qr && s.lan_qr.length > 0+ Layout.fillWidth: true; columnSpacing: 16; rowSpacing: 12+ // The minimum launcher width stacks the code above its text.+ columns: width < 460 ? 1 : 2+ FQrCode { objectName: "lanQr"; rows: s.lan_qr || []; Layout.alignment: Qt.AlignTop }+ ColumnLayout {+ Layout.fillWidth: true; spacing: 10+ FText { objectName: "lanQrHint"; text: t("Connect your phone to the same Wi-Fi, then scan with its camera. You can also copy the link to another device.", "手机连同一个 Wi-Fi 后用相机扫码,也可以复制链接到其他设备打开。"); Layout.fillWidth: true }+ RowLayout {+ Layout.fillWidth: true; spacing: 8+ FField { objectName: "lanQrLink"; Layout.fillWidth: true; readOnly: true; text: firstLanLink(); onTextChanged: cursorPosition = 0; Component.onCompleted: cursorPosition = 0 }+ FButton { objectName: "lanQrCopy"; text: t("Copy link", "复制链接"); onClicked: backend.copy(firstLanLink()) }+ }+ }+ }Repeater {- model: s.access_links || []+ // More than one network address: the others stay available.+ model: (s.access_links || []).slice(1)delegate: RowLayout {required property string modelDataLayout.fillWidth: true; spacing: 8@@ -1117,6 +1145,55 @@ ApplicationWindow {FButton { text: t("Copy link", "复制链接"); onClicked: backend.copy(modelData) }}}+ FDivider { visible: lanPasswordRow.visible }+ ColumnLayout {+ id: lanPasswordRow; objectName: "lanPasswordRow"+ onVisibleChanged: if (!visible) lanPasswordEditing = false+ visible: !!s.form.lan_access && !!s.lan_password_available+ Layout.fillWidth: true; spacing: 10+ GridLayout {+ Layout.fillWidth: true; columnSpacing: 12; rowSpacing: 8+ columns: width < 460 ? 1 : 2+ ColumnLayout {+ Layout.fillWidth: true; spacing: 2+ FText { text: t("Password", "密码"); Layout.fillWidth: true }+ FText { text: t("Optional. Once set, other devices enter it the first time they open FreeVideo. Not needed on this computer.", "可选。设置后,其他设备第一次打开时要输入,本机不用。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }+ }+ RowLayout {+ visible: !lanPasswordEditing+ Layout.alignment: Qt.AlignRight | Qt.AlignVCenter; spacing: 8+ FText { objectName: "lanPasswordStatus"; text: s.lan_password_set ? t("On", "已设置") : t("Not set", "未设置"); color: theme.muted }+ FButton { objectName: "lanPasswordSet"; visible: !s.lan_password_set; text: t("Set password", "设置密码"); implicitHeight: theme.heightSm; font.pixelSize: theme.micro + 1; enabled: !lanPasswordEditing; onClicked: { lanPasswordEditing = true; lanPasswordShown = false; lanPasswordInput.text = ""; lanPasswordInput.forceActiveFocus() } }+ FButton { objectName: "lanPasswordChange"; visible: s.lan_password_set; text: t("Change", "修改"); implicitHeight: theme.heightSm; font.pixelSize: theme.micro + 1; enabled: !lanPasswordEditing; onClicked: { lanPasswordEditing = true; lanPasswordShown = false; lanPasswordInput.text = ""; lanPasswordInput.forceActiveFocus() } }+ FButton { objectName: "lanPasswordRemove"; visible: s.lan_password_set; text: t("Remove", "移除"); implicitHeight: theme.heightSm; font.pixelSize: theme.micro + 1; onClicked: { lanPasswordEditing = false; backend.removeLanPassword() } }+ }+ }+ GridLayout {+ objectName: "lanPasswordEditor"+ visible: lanPasswordEditing; Layout.fillWidth: true; columnSpacing: 8; rowSpacing: 8+ columns: width < 460 ? 1 : 2+ FField {+ id: lanPasswordInput; objectName: "lanPasswordField"; Layout.fillWidth: true+ echoMode: lanPasswordShown ? TextInput.Normal : TextInput.Password+ rightPadding: 40+ Accessible.name: t("Password", "密码")+ onAccepted: if (text.length >= (s.lan_password_min || 6)) lanPasswordSave.clicked()+ FButton {+ objectName: "lanPasswordEye"; flat: true; anchors.right: parent.right; anchors.verticalCenter: parent.verticalCenter+ width: 36; height: parent.height - 8; leftPadding: 0; rightPadding: 0+ Accessible.name: lanPasswordShown ? t("Hide", "隐藏") : t("Show", "显示")+ contentItem: FIcon { kind: lanPasswordShown ? "eyeoff" : "eye"; ink: theme.muted; implicitWidth: 16; implicitHeight: 16 }+ onClicked: lanPasswordShown = !lanPasswordShown+ }+ }+ RowLayout {+ Layout.alignment: Qt.AlignRight | Qt.AlignVCenter; spacing: 8+ FButton { objectName: "lanPasswordCancel"; text: t("Cancel", "取消"); onClicked: { lanPasswordEditing = false; lanPasswordInput.text = "" } }+ FButton { id: lanPasswordSave; objectName: "lanPasswordSave"; primary: true; text: t("Save", "保存"); enabled: lanPasswordInput.text.length >= (s.lan_password_min || 6); onClicked: { backend.setLanPassword(lanPasswordInput.text); lanPasswordInput.text = ""; lanPasswordEditing = false } }+ }+ }+ }+ FText { objectName: "lanRemedyHint"; visible: Qt.platform.os === "windows" && !!s.form.lan_access; text: t("Phone can't open it? Set this computer's Wi-Fi to \"Private\", then in Windows Security allow Python on private networks under \"Allow an app through firewall\".", "手机打不开?请把电脑连的 Wi-Fi 设为“专用网络”,并在 Windows 安全中心的“允许应用通过防火墙”里勾选 Python 的“专用”。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }}FGroup {Layout.fillWidth: true; title: t("Storage", "存储")@@ -1217,8 +1294,8 @@ ApplicationWindow {FGroup {Layout.fillWidth: true; title: t("ComfyUI address", "ComfyUI 地址")FField { objectName: "listenAddress"; Layout.fillWidth: true; value: s.form.url; enabled: !s.form.lan_access; onEditingFinished: backend.edit("url", text) }- FText { objectName: "listenAddressHint"; text: t("With 0.0.0.0 or this computer's LAN IP, devices on the same network can open FreeVideo without the access link.", "填 0.0.0.0 或本机的局域网 IP 后,同一网络中的设备不需要访问链接就能打开 FreeVideo。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }- FText { visible: Qt.platform.os === "windows"; text: t("If Windows asks about the firewall the first time, choose Allow.", "Windows 首次询问防火墙权限时,请选择“允许”。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }+ FText { objectName: "listenAddressHint"; text: s.lan_password_set ? t("With 0.0.0.0 or this computer's LAN IP, devices on the same network can open FreeVideo without the password.", "填 0.0.0.0 或本机的局域网 IP 后,同一网络中的设备不用密码就能打开 FreeVideo。") : t("With 0.0.0.0 or this computer's LAN IP, devices on the same network can open FreeVideo without the access link.", "填 0.0.0.0 或本机的局域网 IP 后,同一网络中的设备不需要访问链接就能打开 FreeVideo。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }+ FText { visible: Qt.platform.os === "windows"; text: t("Windows will ask for permission. Check \"Private networks\", then click \"Allow access\".", "Windows 会弹出确认框,请勾选“专用网络”,再点“允许访问”。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }}FGroup {Layout.fillWidth: true; title: t("Folders · optional", "目录 · 可选"); enabled: !s.portablediff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.pyindex 69e205f..719379c 100644--- a/freevideo_engine/launcher_session.py+++ b/freevideo_engine/launcher_session.py@@ -1,5 +1,6 @@"""Widget-independent state for the Qt launcher; uses the existing installer."""from copy import deepcopy+from functools import lru_cacheimport jsonimport osfrom pathlib import Path@@ -42,6 +43,15 @@ ARCHIVE_FAILURES = {}++@lru_cache(maxsize=4)+def _qr_rows(text):+ from .qr_code import encode+ try:+ return [''.join('1' if cell else '0' for cell in row) for row in encode(text)]+ except ValueError:+ return []+class Session:# A launcher started from an offline package (portable_launcher.PortableSession).bundled = False@@ -62,6 +72,7 @@ class Session:release_details = Noneadaln_thread = adaln_result = adaln_found = Noneadaln_polled = 0.+ lan_synced = 0.adaln_hidden = adaln_retry = False# The source whose earlier copies were removed once ComfyUI ran it.old_versions_retired = None@@ -1541,9 +1552,25 @@ class Session:self.t('Try again', '再试一次') if self.adaln_retry else self.t('Delete', '删除')),later_text=self.t('Not now', '暂不删除'))+ def sync_lan_from_store(self):+ """Follow a LAN switch changed from the page's phone panel (it writes the shared settings)."""+ now = time.monotonic()+ if now - self.lan_synced < RECEIPT_POLL_SECONDS or not self.selected:+ return+ if self.controller.busy or self.importer.busy or self.cleaner.busy or self.archives_busy:+ return # edit() would refuse and tell the user the app is busy; follow the store once it is idle+ self.lan_synced = now+ saved = self.store.read().get('installation') or {}+ if (saved.get('root') != self.selected.get('root') or saved.get('engine') != self.selected.get('engine')+ or type(saved.get('lan_access')) is not bool):+ return+ if saved['lan_access'] != (self.form.get('lan_access') is True):+ self.edit('lan_access', saved['lan_access'])+def tick(self):if isinstance(self.controller, Controller) and not self.controller.busy:self.controller.poll_access_proxy()+ self.sync_lan_from_store()self._finish_archives()imported = self.importer.stateif not self.importer.busy and imported is not self.imported_batch:@@ -1880,6 +1907,46 @@ class Session:terms=self.t(*value['terms']) if value['terms'] else '', url=value['link'], file=is_file(value['link']))for value in rows or [MODEL]]+ def lan_qr_rows(self):+ """The first access link as rows of '0'/'1' for the settings page to draw."""+ links = self.controller.access_links+ if self.controller.state.get('status') != 'open' or not isinstance(links, list) or not links:+ return []+ return _qr_rows(str(links[0]))++ def lan_password_state(self):+ """(supported, set) for the optional LAN password; unsupported without the access module."""+ engine = (self.controller.selection or {}).get('engine')+ try:+ from . import lan_password+ return True, bool(engine) and bool(lan_password.is_set(engine))+ except (ImportError, OSError):+ return False, False++ def lan_password_min(self):+ try:+ from . import lan_password+ return int(getattr(lan_password, 'MIN_LENGTH', 6))+ except (ImportError, OSError, TypeError, ValueError):+ return 6++ def change_lan_password(self, text=None):+ """Set or change the password (text), or remove it (None). Other devices must sign in again."""+ engine = (self.controller.selection or {}).get('engine')+ if not engine:+ return+ from . import lan_password+ if text is None:+ lan_password.remove(engine)+ else:+ text = str(text)+ least = self.lan_password_min()+ if len(text) < least:+ raise ValueError(self.t('Use at least %d characters.' % least, '至少 %d 个字符。' % least))+ lan_password.set_password(engine, text)+ # The links change with the password; do not wait for the next poll.+ self.controller.access_polled = 0+def snapshot(self):from .failure_details import REPAIR_KINDS, launcher_failure, redacted_launcher_error, display_launcher_errorfrom .launcher_copy import display, progress_view, source_name@@ -2093,6 +2160,8 @@ class Session:url=(self._browser_url(row.get('url', '')) if row.get('status') == 'open' else ''), shortcut=shortcut,access_links=(list(self.controller.access_links) if row.get('status') == 'open'and isinstance(self.controller.access_links, list) else []),+ lan_qr=self.lan_qr_rows(), lan_password_set=self.lan_password_state()[1],+ lan_password_available=self.lan_password_state()[0], lan_password_min=self.lan_password_min(),lan_message=(self.t('LAN access has stopped. Turn it on again.', '局域网访问已停止,请重新开启。')if row.get('lan_status') == 'stopped' elseself.t('No LAN address found. Connect to Wi-Fi or a wired network first.', '未找到局域网地址,请先连接 Wi-Fi 或有线网络。')diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.pyindex 8fad2d2..67fc54c 100644--- a/freevideo_engine/modern_launcher.py+++ b/freevideo_engine/modern_launcher.py@@ -243,6 +243,14 @@ def create_ui(session, *, show=True):def removeFolder(self, index):self.invoke(session.remove_folder, index)+ @Slot(str)+ def setLanPassword(self, value):+ self.invoke(session.change_lan_password, value)++ @Slot()+ def removeLanPassword(self):+ self.invoke(session.change_lan_password, None)+@Slot(str)def copy(self, value):app.clipboard().setText(value)diff --git a/freevideo_engine/qr_code.py b/freevideo_engine/qr_code.pynew file mode 100644index 0000000..8915069--- /dev/null+++ b/freevideo_engine/qr_code.py@@ -0,0 +1,264 @@+"""Small QR Code encoder for the LAN access address (byte mode, versions 1-10, error correction level M).++The launcher and `freevideo status` draw the result themselves, so there is no image library involved.+"""++MAX_VERSION = 10+# Per version (index 1..10): error correction codewords per block, and number of blocks, at level M.+_ECC_PER_BLOCK = (0, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26)+_BLOCKS = (0, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5)+_FORMAT_M = 0 # the two format bits for level M are 00+++def _alignment_positions(version):+ if version == 1:+ return []+ count = version // 7 + 2+ step = 26 if version == 32 else (version * 4 + count * 2 + 1) // (count * 2 - 2) * 2+ last = version * 4 + 10+ return [6] + [last - step * k for k in range(count - 2, -1, -1)]+++def _raw_modules(version):+ result = (16 * version + 128) * version + 64+ if version >= 2:+ count = version // 7 + 2+ result -= (25 * count - 10) * count - 55+ if version >= 7:+ result -= 36+ return result+++def _data_codewords(version):+ return _raw_modules(version) // 8 - _ECC_PER_BLOCK[version] * _BLOCKS[version]+++def _gf_multiply(x, y):+ result = 0+ for bit in range(7, -1, -1):+ result = (result << 1) ^ ((result >> 7) * 0x11D)+ result ^= ((y >> bit) & 1) * x+ return result+++def _generator(degree):+ result = [0] * (degree - 1) + [1]+ root = 1+ for _ in range(degree):+ for index in range(degree):+ result[index] = _gf_multiply(result[index], root)+ if index + 1 < degree:+ result[index] ^= result[index + 1]+ root = _gf_multiply(root, 2)+ return result+++def _remainder(data, generator):+ result = [0] * len(generator)+ for byte in data:+ factor = byte ^ result.pop(0)+ result.append(0)+ for index, coefficient in enumerate(generator):+ result[index] ^= _gf_multiply(coefficient, factor)+ return result+++def _codewords(data, version):+ blocks = _BLOCKS[version]+ ecc_length = _ECC_PER_BLOCK[version]+ raw = _raw_modules(version) // 8+ short_blocks = blocks - raw % blocks+ short_length = raw // blocks+ generator = _generator(ecc_length)+ split, position = [], 0+ for index in range(blocks):+ length = short_length - ecc_length + (0 if index < short_blocks else 1)+ block = data[position:position + length]+ position += length+ split.append(block + _remainder(block, generator))+ if index < short_blocks:+ split[-1].insert(length, None) # keeps columns aligned with the longer blocks+ result = []+ for column in range(len(split[-1])):+ for index, block in enumerate(split):+ if column != short_length - ecc_length or index >= short_blocks:+ result.append(block[column])+ return result+++class _Matrix:+ def __init__(self, version):+ self.size = version * 4 + 17+ self.modules = [[False] * self.size for _ in range(self.size)]+ self.function = [[False] * self.size for _ in range(self.size)]++ def set(self, x, y, dark, function=True):+ self.modules[y][x] = bool(dark)+ if function:+ self.function[y][x] = True+++def _draw_function_patterns(matrix, version):+ size = matrix.size+ for index in range(size):+ matrix.set(6, index, index % 2 == 0)+ matrix.set(index, 6, index % 2 == 0)++ def finder(cx, cy):+ for dy in range(-4, 5):+ for dx in range(-4, 5):+ x, y = cx + dx, cy + dy+ if 0 <= x < size and 0 <= y < size:+ distance = max(abs(dx), abs(dy))+ matrix.set(x, y, distance not in (2, 4))++ finder(3, 3); finder(size - 4, 3); finder(3, size - 4)+ positions = _alignment_positions(version)+ for i, cx in enumerate(positions):+ for j, cy in enumerate(positions):+ if (i == 0 and j == 0) or (i == 0 and j == len(positions) - 1) or (i == len(positions) - 1 and j == 0):+ continue+ for dy in range(-2, 3):+ for dx in range(-2, 3):+ matrix.set(cx + dx, cy + dy, max(abs(dx), abs(dy)) != 1)+ _draw_format(matrix, 0) # reserves the format areas; the real bits are written after masking+ if version >= 7:+ remainder = version+ for _ in range(12):+ remainder = (remainder << 1) ^ ((remainder >> 11) * 0x1F25)+ bits = version << 12 | remainder+ for index in range(18):+ dark = (bits >> index) & 1+ a, b = size - 11 + index % 3, index // 3+ matrix.set(a, b, dark); matrix.set(b, a, dark)+++def _draw_format(matrix, mask):+ size = matrix.size+ data = _FORMAT_M << 3 | mask+ remainder = data+ for _ in range(10):+ remainder = (remainder << 1) ^ ((remainder >> 9) * 0x537)+ bits = (data << 10 | remainder) ^ 0x5412++ def bit(index):+ return (bits >> index) & 1++ for index in range(0, 6):+ matrix.set(8, index, bit(index))+ matrix.set(8, 7, bit(6)); matrix.set(8, 8, bit(7)); matrix.set(7, 8, bit(8))+ for index in range(9, 15):+ matrix.set(14 - index, 8, bit(index))+ for index in range(0, 8):+ matrix.set(size - 1 - index, 8, bit(index))+ for index in range(8, 15):+ matrix.set(8, size - 15 + index, bit(index))+ matrix.set(8, size - 8, True)+++def _draw_codewords(matrix, codewords):+ size = matrix.size+ bits = [(byte >> shift) & 1 for byte in codewords for shift in range(7, -1, -1)]+ index = 0+ for right in range(size - 1, 0, -2):+ if right <= 6:+ right -= 1+ for vertical in range(size):+ for offset in range(2):+ x = right - offset+ upward = ((right + 1) & 2) == 0+ y = size - 1 - vertical if upward else vertical+ if not matrix.function[y][x] and index < len(bits):+ matrix.modules[y][x] = bool(bits[index]); index += 1+++_MASKS = (+ lambda x, y: (x + y) % 2 == 0,+ lambda x, y: y % 2 == 0,+ lambda x, y: x % 3 == 0,+ lambda x, y: (x + y) % 3 == 0,+ lambda x, y: (x // 3 + y // 2) % 2 == 0,+ lambda x, y: x * y % 2 + x * y % 3 == 0,+ lambda x, y: (x * y % 2 + x * y % 3) % 2 == 0,+ lambda x, y: ((x + y) % 2 + x * y % 3) % 2 == 0,+)+++def _apply_mask(matrix, mask):+ for y in range(matrix.size):+ for x in range(matrix.size):+ if not matrix.function[y][x] and _MASKS[mask](x, y):+ matrix.modules[y][x] = not matrix.modules[y][x]+++def _penalty(modules):+ size = len(modules)+ score = 0+ for lines in (modules, [list(column) for column in zip(*modules)]):+ for line in lines:+ run = 1+ for index in range(1, size):+ if line[index] == line[index - 1]:+ run += 1+ continue+ score += run - 2 if run >= 5 else 0+ run = 1+ score += run - 2 if run >= 5 else 0+ text = ''.join('1' if value else '0' for value in line)+ for pattern in ('10111010000', '00001011101'):+ start = text.find(pattern)+ while start != -1:+ score += 40+ start = text.find(pattern, start + 1)+ for y in range(size - 1):+ for x in range(size - 1):+ if modules[y][x] == modules[y][x + 1] == modules[y + 1][x] == modules[y + 1][x + 1]:+ score += 3+ dark = sum(row.count(True) for row in modules)+ total = size * size+ score += ((abs(dark * 20 - total * 10) + total - 1) // total - 1) * 10+ return score+++def encode(text):+ """Return the QR code for `text` as rows of booleans (True is a dark module), without the quiet zone."""+ payload = text.encode('utf-8')+ version = next((v for v in range(1, MAX_VERSION + 1) if len(payload) <= _data_codewords(v) - (2 if v < 10 else 3)), None)+ if version is None:+ raise ValueError('The text is too long for a QR code.')+ count_bits = 8 if version < 10 else 16+ bits = '0100' + format(len(payload), '0%db' % count_bits) + ''.join(format(byte, '08b') for byte in payload)+ capacity = _data_codewords(version) * 8+ bits += '0' * min(4, capacity - len(bits))+ bits += '0' * (-len(bits) % 8)+ data = [int(bits[index:index + 8], 2) for index in range(0, len(bits), 8)]+ pad = 0xEC+ while len(data) < capacity // 8:+ data.append(pad)+ pad ^= 0xEC ^ 0x11+ codewords = _codewords(data, version)+ best = None+ for mask in range(8):+ matrix = _Matrix(version)+ _draw_function_patterns(matrix, version)+ _draw_codewords(matrix, codewords)+ _apply_mask(matrix, mask)+ _draw_format(matrix, mask)+ score = _penalty(matrix.modules)+ if best is None or score < best[0]:+ best = (score, matrix.modules)+ return [list(row) for row in best[1]]+++def terminal_lines(text, quiet=2):+ """The code as lines of half-block characters, two module rows per line, dark modules drawn dark on light."""+ modules = encode(text)+ size = len(modules) + quiet * 2+ grid = [[False] * size for _ in range(size)]+ for y, row in enumerate(modules):+ for x, value in enumerate(row):+ grid[y + quiet][x + quiet] = value+ if size % 2:+ grid.append([False] * size)+ glyph = {(False, False): '█', (True, True): ' ', (False, True): '▀', (True, False): '▄'}+ return [''.join(glyph[(grid[y][x], grid[y + 1][x])] for x in range(size)) for y in range(0, len(grid), 2)]