The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(platform): Linux 无边框窗口在 KWin 上显示阴影
XiaoYouChRb10f759963ad
diff --git a/Ghost-Downloader-3.py b/Ghost-Downloader-3.pyindex 79a5ed96..bcd7a15f 100644--- a/Ghost-Downloader-3.py+++ b/Ghost-Downloader-3.py@@ -38,7 +38,7 @@ def setupEnvironment() -> None:setupHiddenSubprocess()from app.view.qfw_patch import (- patchFluentLabelThemeChanged, patchLinuxFramelessResize, patchMaskDialogAnimation, patchStackedWidgetAnimation,+ patchFluentLabelThemeChanged, patchLinuxFrameless, patchMaskDialogAnimation, patchStackedWidgetAnimation,)from app.view.components.labels import IconBodyLabelpatchFluentLabelThemeChanged()@@ -47,7 +47,7 @@ def setupEnvironment() -> None:if sys.platform != "linux":patchMaskDialogAnimation()else:- patchLinuxFramelessResize()+ patchLinuxFrameless()qconfig.themeChanged.connect(IconBodyLabel.clearCache)qconfig.load(f"{APP_DATA_DIR}/UserConfig.json", cfg)diff --git a/app/platform/shadow.py b/app/platform/shadow.pynew file mode 100644index 00000000..c68f57f5--- /dev/null+++ b/app/platform/shadow.py@@ -0,0 +1,323 @@+from __future__ import annotations++import math+import os+from ctypes import (+ CDLL,+ CFUNCTYPE,+ POINTER,+ Structure,+ Union,+ addressof,+ c_char_p,+ c_int,+ c_int32,+ c_uint32,+ c_void_p,+)+from dataclasses import dataclass+from functools import cache++from loguru import logger+from PySide6.QtCore import QEvent, QObject+from PySide6.QtGui import QGuiApplication, QPlatformSurfaceEvent, QWindow++# Breeze 默认 Large 档:两层高斯阴影叠加,(sigma, 下移, 不透明度)+LAYERS = ((10.0, 5, 0.22), (5.0, 2, 0.12))+# 阴影伸出窗口的距离:左、上、右、下+PADDING = (30, 25, 30, 35)+# 角上贴图向窗口内延伸到衰减走完,边上贴图才能按常数拉伸+INSET = 35++WL_MARSHAL_FLAG_DESTROY = 1+WL_SHM_FORMAT_ARGB8888 = 0+SHADOW_COMMIT, SHADOW_ATTACH_LEFT, SHADOW_SET_LEFT_OFFSET, SHADOW_DESTROY = 0, 1, 9, 13+++@dataclass(frozen=True)+class Tile:+ width: int+ height: int+ pixels: bytes # 预乘 ARGB8888+++def registerWindow(window: QWindow) -> None:+ """让合成器给无边框窗口画阴影,隐藏再显示后自动重挂;合成器不支持时什么也不做。"""+ if not QGuiApplication.platformName().startswith("wayland"):+ return+ kwinShadow = createKwinShadow()+ if kwinShadow is not None:+ WindowShadow(window, kwinShadow)+++class WindowShadow(QObject):+ def __init__(self, window: QWindow, kwinShadow: KwinShadow):+ super().__init__(window)+ self._kwinShadow = kwinShadow+ self._shadow: int | None = None+ window.installEventFilter(self)++ def eventFilter(self, window: QWindow, event: QEvent) -> bool:+ eventType = event.type()+ # 隐藏时 Qt 回收 wl_surface 但保留平台窗口,只等 PlatformSurface 会漏掉+ isSurfaceGone = eventType == QEvent.Type.Hide or (+ eventType == QEvent.Type.PlatformSurface+ and event.surfaceEventType() == QPlatformSurfaceEvent.SurfaceEventType.SurfaceAboutToBeDestroyed+ )+ if self._shadow is None and eventType == QEvent.Type.Expose and window.isExposed():+ self._shadow = self._kwinShadow.create(window)+ elif self._shadow is not None and isSurfaceGone:+ self._kwinShadow.destroy(self._shadow)+ self._shadow = None+ return False+++def buildTiles() -> list[Tile]:+ """按 attach 请求的顺序:左、左上、上、右上、右、右下、下、左下。"""+ left, top, right, bottom = PADDING++ def cdf(z: float) -> float:+ return 0.5 * (1 + math.erf(z / math.sqrt(2)))++ # 坐标相对窗口对应的边,向外为负+ def horizontal(x: int, side: str, sigma: float) -> float:+ if side == "middle":+ return 1.0+ if side == "left":+ return cdf((x + 0.5) / sigma)+ return cdf(-(x + 0.5) / sigma)++ def vertical(y: int, side: str, sigma: float, offset: int) -> float:+ if side == "middle":+ return 1.0+ if side == "top":+ return cdf((y + 0.5 - offset) / sigma)+ return cdf((offset - y - 0.5) / sigma)++ def build(columns: range, columnSide: str, rows: range, rowSide: str) -> Tile:+ # 高斯模糊的矩形可分离为横纵两个一维衰减之积+ layers = [+ (opacity, [horizontal(x, columnSide, sigma) for x in columns],+ [vertical(y, rowSide, sigma, offset) for y in rows])+ for sigma, offset, opacity in LAYERS+ ]+ pixels = bytearray(len(columns) * len(rows) * 4)+ index = 3+ for row in range(len(rows)):+ for column in range(len(columns)):+ transparency = 1.0+ for opacity, xs, ys in layers:+ transparency *= 1 - opacity * xs[column] * ys[row]+ pixels[index] = round(255 * (1 - transparency))+ index += 4+ return Tile(len(columns), len(rows), bytes(pixels))++ leftColumns, rightColumns, middle = range(-left, INSET), range(-INSET, right), range(1)+ topRows, bottomRows = range(-top, INSET), range(-INSET, bottom)+ return [+ build(range(-left, 0), "left", middle, "middle"),+ build(leftColumns, "left", topRows, "top"),+ build(middle, "middle", range(-top, 0), "top"),+ build(rightColumns, "right", topRows, "top"),+ build(range(right), "right", middle, "middle"),+ build(rightColumns, "right", bottomRows, "bottom"),+ build(middle, "middle", range(bottom), "bottom"),+ build(leftColumns, "left", bottomRows, "bottom"),+ ]+++# libwayland-client 的 C 结构,PySide6 没有 Wayland 绑定+class WlMessage(Structure):+ _fields_ = [("name", c_char_p), ("signature", c_char_p), ("types", POINTER(c_void_p))]+++class WlInterface(Structure):+ _fields_ = [+ ("name", c_char_p), ("version", c_int),+ ("method_count", c_int), ("methods", POINTER(WlMessage)),+ ("event_count", c_int), ("events", POINTER(WlMessage)),+ ]+++class WlArgument(Union):+ _fields_ = [("i", c_int32), ("s", c_char_p), ("o", c_void_p)]+++GlobalListener = CFUNCTYPE(None, c_void_p, c_void_p, c_uint32, c_char_p, c_uint32)+GlobalRemoveListener = CFUNCTYPE(None, c_void_p, c_void_p, c_uint32)+++class RegistryListener(Structure):+ _fields_ = [("global_", GlobalListener), ("global_remove", GlobalRemoveListener)]+++class Protocol:+ """手写的 org_kde_kwin_shadow 协议描述,结构须与代理同寿。"""++ def __init__(self, wayland: CDLL):+ surfaceInterface = addressof(WlInterface.in_dll(wayland, "wl_surface_interface"))+ bufferInterface = addressof(WlInterface.in_dll(wayland, "wl_buffer_interface"))+ self._arrays = []+ self.shadow = self._buildInterface(b"org_kde_kwin_shadow", 2, [+ (b"commit", b"", []),+ *[(b"attach_" + side, b"o", [bufferInterface]) for side in (+ b"left", b"top_left", b"top", b"top_right", b"right", b"bottom_right", b"bottom", b"bottom_left")],+ *[(b"set_" + side + b"_offset", b"f", [None]) for side in (b"left", b"top", b"right", b"bottom")],+ (b"destroy", b"2", []),+ ])+ self.manager = self._buildInterface(b"org_kde_kwin_shadow_manager", 2, [+ (b"create", b"no", [addressof(self.shadow), surfaceInterface]),+ (b"unset", b"o", [surfaceInterface]),+ (b"destroy", b"2", []),+ ])++ def _buildInterface(self, name: bytes, version: int, methods: list[tuple[bytes, bytes, list]]) -> WlInterface:+ messages = (WlMessage * len(methods))()+ self._arrays.append(messages)+ for message, (methodName, signature, types) in zip(messages, methods):+ typeArray = (c_void_p * max(len(types), 1))(*types)+ self._arrays.append(typeArray)+ message.name, message.signature, message.types = methodName, signature, typeArray+ return WlInterface(name, version, len(methods), messages, 0, None)+++def marshal(wayland: CDLL, proxy: int, opcode: int, args: list, interface: WlInterface | None = None,+ version: int = 0, flags: int = 0) -> int:+ """args 里 int 按 int32/uint32 传,c_void_p 按对象传,None 占位 new_id,float 转 wl_fixed。"""+ array = (WlArgument * max(len(args), 1))()+ for argument, value in zip(array, args):+ if isinstance(value, bytes):+ argument.s = value+ elif isinstance(value, float):+ argument.i = round(value * 256)+ elif isinstance(value, int):+ argument.i = value+ else:+ argument.o = value+ if interface is not None and not version:+ version = wayland.wl_proxy_get_version(proxy)+ return wayland.wl_proxy_marshal_array_flags(+ proxy, opcode, addressof(interface) if interface is not None else None, version, flags, array,+ )+++class KwinShadow:+ """org_kde_kwin_shadow 的客户端:阴影由 KWin 画在 surface 外,不改窗口几何。"""++ def __init__(self, wayland: CDLL, display: int, surfaceByWindow, protocol: Protocol,+ manager: int, managerVersion: int, buffers: list[int]):+ self._wayland = wayland+ self._display = display+ self._surfaceByWindow = surfaceByWindow+ self._protocol = protocol+ self._manager = manager+ self._managerVersion = managerVersion+ self._buffers = buffers # 所有窗口共用++ def create(self, window: QWindow) -> int | None:+ surface = self._surfaceByWindow(window)+ if not surface:+ return None+ wayland = self._wayland+ shadow = marshal(wayland, self._manager, 0, [None, c_void_p(surface)], self._protocol.shadow)+ for opcode, buffer in enumerate(self._buffers, start=SHADOW_ATTACH_LEFT):+ marshal(wayland, shadow, opcode, [c_void_p(buffer)])+ for opcode, offset in enumerate(PADDING, start=SHADOW_SET_LEFT_OFFSET):+ marshal(wayland, shadow, opcode, [float(offset)])+ marshal(wayland, shadow, SHADOW_COMMIT, [])+ wayland.wl_display_flush(self._display)+ # 阴影随下一次 wl_surface.commit 生效+ window.requestUpdate()+ return shadow++ def destroy(self, shadow: int) -> None:+ if self._managerVersion >= 2:+ marshal(self._wayland, shadow, SHADOW_DESTROY, [], flags=WL_MARSHAL_FLAG_DESTROY)+ else:+ self._wayland.wl_proxy_destroy(shadow)+ self._wayland.wl_display_flush(self._display)+++@cache+def createKwinShadow() -> KwinShadow | None:+ import shiboken6++ # Qt 没有公开取 wl_surface 的接口,只能按私有符号调用,见 ADR 0030+ try:+ wayland = CDLL("libwayland-client.so.0")+ resolveInterface = CDLL("libQt6Gui.so.6")["_ZNK7QWindow16resolveInterfaceEPKci"]+ wlSurface = CDLL("libQt6WaylandClient.so.6")["_ZNK15QtWaylandClient14QWaylandWindow9wlSurfaceEv"]+ wayland.wl_proxy_marshal_array_flags # noqa: B018 libwayland 1.20 起才有+ except (OSError, AttributeError) as e:+ logger.warning("无法加载窗口阴影所需的符号: {}", e)+ return None++ resolveInterface.restype, resolveInterface.argtypes = c_void_p, [c_void_p, c_char_p, c_int]+ wlSurface.restype, wlSurface.argtypes = c_void_p, [c_void_p]+ wayland.wl_proxy_marshal_array_flags.restype = c_void_p+ wayland.wl_proxy_marshal_array_flags.argtypes = [c_void_p, c_uint32, c_void_p, c_uint32, c_uint32, POINTER(WlArgument)]+ wayland.wl_proxy_create_wrapper.restype = c_void_p+ wayland.wl_display_create_queue.restype = c_void_p+ for name in ("wl_proxy_get_version", "wl_proxy_create_wrapper", "wl_proxy_wrapper_destroy",+ "wl_proxy_destroy", "wl_display_flush", "wl_display_create_queue"):+ getattr(wayland, name).argtypes = [c_void_p]+ for name in ("wl_proxy_set_queue", "wl_display_roundtrip_queue"):+ getattr(wayland, name).argtypes = [c_void_p, c_void_p]+ wayland.wl_proxy_add_listener.argtypes = [c_void_p, c_void_p, c_void_p]++ def surfaceByWindow(window: QWindow) -> int | None:+ # 私有接口 QWaylandWindow 是 QtWaylandClient::QWaylandWindow 的首个基类,指针即对象本身;+ # 接口名是 QT_DECLARE_NATIVE_INTERFACE 的短名,不带命名空间+ native = resolveInterface(shiboken6.getCppPointer(window)[0], b"QWaylandWindow", 1)+ return wlSurface(native) if native else None++ def interface(name: str) -> WlInterface:+ return WlInterface.in_dll(wayland, name)++ # 用独立事件队列枚举全局对象,不干扰 Qt 自己的队列+ display = QGuiApplication.instance().nativeInterface().display()+ advertised: dict[bytes, tuple[int, int]] = {}++ def onGlobal(data, registry, name, interfaceName, version):+ advertised[interfaceName] = (name, version)++ listener = RegistryListener(GlobalListener(onGlobal), GlobalRemoveListener(lambda *_: None))+ queue = wayland.wl_display_create_queue(display)+ wrapper = wayland.wl_proxy_create_wrapper(display)+ wayland.wl_proxy_set_queue(wrapper, queue)+ registry = marshal(wayland, wrapper, 1, [None], interface("wl_registry_interface"))+ wayland.wl_proxy_wrapper_destroy(wrapper)+ wayland.wl_proxy_add_listener(registry, addressof(listener), None)+ wayland.wl_display_roundtrip_queue(display, queue)++ if b"org_kde_kwin_shadow_manager" not in advertised or b"wl_shm" not in advertised:+ wayland.wl_proxy_destroy(registry)+ return None++ def bind(name: bytes, boundInterface: WlInterface, maxVersion: int) -> tuple[int, int]:+ globalName, version = advertised[name]+ version = min(version, maxVersion)+ return marshal(wayland, registry, 0, [globalName, name, version, None], boundInterface, version), version++ protocol = Protocol(wayland)+ manager, managerVersion = bind(b"org_kde_kwin_shadow_manager", protocol.manager, 2)+ shm, _ = bind(b"wl_shm", interface("wl_shm_interface"), 1)+ wayland.wl_proxy_destroy(registry)++ tiles = buildTiles()+ fd = os.memfd_create("ghost-downloader-shadow")+ try:+ for tile in tiles:+ os.write(fd, tile.pixels)+ pool = marshal(wayland, shm, 0, [None, fd, sum(len(tile.pixels) for tile in tiles)],+ interface("wl_shm_pool_interface"))+ finally:+ os.close(fd)+ buffers, offset = [], 0+ for tile in tiles:+ buffers.append(marshal(wayland, pool, 0, [None, offset, tile.width, tile.height, tile.width * 4,+ WL_SHM_FORMAT_ARGB8888], interface("wl_buffer_interface")))+ offset += len(tile.pixels)+ marshal(wayland, pool, 1, [], flags=WL_MARSHAL_FLAG_DESTROY)+ wayland.wl_display_flush(display)+ return KwinShadow(wayland, display, surfaceByWindow, protocol, manager, managerVersion, buffers)diff --git a/app/view/qfw_patch.py b/app/view/qfw_patch.pyindex 3043b475..ce616707 100644--- a/app/view/qfw_patch.py+++ b/app/view/qfw_patch.py@@ -78,13 +78,15 @@ def patchMaskDialogAnimation() -> None:MaskDialogBase.done = dialog_animation.done-def patchLinuxFramelessResize() -> None:+def patchLinuxFrameless() -> None:# Wayland 不提供窗口的全局位置,原实现用 globalPos - pos() 识别边框会整体偏移;# 改为在本窗口的 QWindow 上过滤事件,用窗口内坐标识别from PySide6.QtCore import QEvent, Qtfrom qframelesswindow import linuxfrom qframelesswindow.titlebar import TitleBar+ from app.platform import shadow+Edge = Qt.EdgeCURSORS = {Edge.LeftEdge | Edge.TopEdge: Qt.CursorShape.SizeFDiagCursor,@@ -105,6 +107,8 @@ def patchLinuxFramelessResize() -> None:self.updateFrameless()self.winId()self.windowHandle().installEventFilter(self)+ # 无边框窗口没有系统装饰,阴影要单独向合成器申请+ shadow.registerWindow(self.windowHandle())self.titleBar.raise_()self.resize(500, 500)diff --git a/docs/adr/0030-linux-window-shadow-via-kwin-protocol.md b/docs/adr/0030-linux-window-shadow-via-kwin-protocol.mdnew file mode 100644index 00000000..b2d0359d--- /dev/null+++ b/docs/adr/0030-linux-window-shadow-via-kwin-protocol.md@@ -0,0 +1,20 @@+# Linux 窗口阴影只走 KWin 的 org_kde_kwin_shadow 协议++Linux 上的窗口都是无边框窗口(qframelesswindow 设了 `FramelessWindowHint`),合成器不给它们画装饰,也就没有阴影。我们改用 KWin 专有的 `org_kde_kwin_shadow` 协议:把 8 块阴影贴图交给 KWin,由它画在 surface 外面。窗口几何不变,贴边、分屏、最大化都由合成器照常处理。这与 KDE 自己的 `KWindowShadow` 做法相同(Breeze 的菜单阴影就是这样实现的)。外观固定照搬 Breeze 默认的 Large 档,不读 `breezerc`。++只有注册表里存在 `org_kde_kwin_shadow_manager` 时才生效。GNOME、wlroots 系和 X11 都维持没有阴影。目前只有 KWin 实现了这个协议;以后有别的合成器实现,会自动生效。++PySide6 不提供取窗口 `wl_surface` 的接口,系统里的 KF6 `KWindowShadow` 又链接系统 Qt,与 PySide6 自带的 Qt 冲突,所以只能用 ctypes 调 Qt 私有符号(与 ADR 0019 同理):先用 `QWindow::resolveInterface("QWaylandWindow", 1)` 取得私有接口,它是 `QtWaylandClient::QWaylandWindow` 的首个基类,指针可以直接作为 `this` 调用 `QWaylandWindow::wlSurface()`。缺少符号时只记一条警告,不画阴影。++## Considered Options++- **自绘阴影**:开启透明背景,在窗口四周留出透明边距自己画阴影。Wayland 下必须调用 `xdg_surface.set_window_geometry` 告诉合成器窗口实际在哪,而 Qt 只在私有的 `setCustomMargins` 里调用它;不告诉的话,贴边和分屏会把透明边距算进窗口,留出一圈缝。GNOME 下也只能走这条路。+- **改用系统标题栏**:KDE 会画原生边框和阴影,但 Fluent 标题栏和挂在上面的搜索框都要放弃,与 Windows、macOS 的观感也不再一致。+- **Plasma 6.8 的"Window manager draws titlebar, frame, and shadows"窗口规则**:在 Wayland 上不会自动生效,需要用户手动配置,也没有让客户端主动申请的协议。+- **同时自绘圆角**:Linux 上没有让合成器裁圆角的协议,只能自绘,与上面放弃自绘阴影的理由相同。窗口保持直角。++## Consequences++- 升级 PySide6 后,如果 Linux 上的阴影消失,先查日志里有没有符号加载失败的警告。+- Qt 隐藏窗口时会回收 `wl_surface`,所以阴影在 `Hide` 时销毁,在下一次 `Expose` 时重建。+- 验证只能在 KDE Wayland 上手动做:主窗口和对话框都有阴影;隐藏后再显示,阴影还在;最大化、贴边、分屏时窗口不留缝;在 GNOME 或 X11 下启动不报错。