Files
xieyi-weixin-/desktop_window.py
T
2026-12-02 11:30:59 +08:00

167 lines
7.1 KiB
Python

"""Native actions for the console's fixed HTML title bar and resize gestures."""
import json
from PySide6.QtCore import QEvent, QPoint, QRectF, Qt, Signal
from PySide6.QtGui import QPainterPath, QRegion
from PySide6.QtWidgets import QApplication, QMenuBar, QWidget
class _ResizeHandle(QWidget):
def __init__(self, window, edges, cursor):
super().__init__(window)
self.setProperty("uiScaleLocked", True)
self.edges = edges
self.setCursor(cursor)
self.setStyleSheet("background: transparent; border: none;")
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
handle = self.window().windowHandle()
if handle and handle.startSystemResize(self.edges):
event.accept()
return
super().mousePressEvent(event)
class DesktopWindowBar(QMenuBar):
"""Own the native account menu/actions; render chrome inside WebEngine."""
RESIZE_MARGIN = 5
CORNER_RADIUS = 32
BAR_HEIGHT = 32
BUTTON_WIDTH = 42
CONTROLS_RIGHT = 32
frameChanged = Signal()
def __init__(self, window):
super().__init__(window)
# Only monitor DPI scales window chrome; page zoom must not move it.
self.setProperty("uiScaleLocked", True)
self.host = window
self._frame_key = None
self._flat = False
window.setWindowFlag(Qt.FramelessWindowHint, True)
# A native region has only binary coverage, producing stair-stepped
# corners (especially after DPI scaling). Let Chromium paint the
# rounded shell with fractional alpha onto a translucent window.
window.setAttribute(Qt.WA_TranslucentBackground, True)
window.setStyleSheet("QMainWindow { background: transparent; }")
window.setContentsMargins(0, 0, 0, 0)
self.setNativeMenuBar(False)
self.setFixedHeight(self.BAR_HEIGHT)
# Native QWidget overlays can disappear behind Chromium's compositor
# after its surface is restored. Keep only the popup menu native.
self.hide()
left, right, top, bottom = Qt.LeftEdge, Qt.RightEdge, Qt.TopEdge, Qt.BottomEdge
self._resize_handles = {
edges: _ResizeHandle(window, edges, cursor)
for edges, cursor in (
(left, Qt.SizeHorCursor), (right, Qt.SizeHorCursor),
(top, Qt.SizeVerCursor), (bottom, Qt.SizeVerCursor),
(top | left, Qt.SizeFDiagCursor), (bottom | right, Qt.SizeFDiagCursor),
(top | right, Qt.SizeBDiagCursor), (bottom | left, Qt.SizeBDiagCursor),
)
}
window.installEventFilter(self)
def addMenu(self, *args):
menu = super().addMenu(*args)
menu.menuAction().changed.connect(self.frameChanged.emit)
return menu
def web_frame_script(self):
"""Share the native contour with CSS, including maximize/restore state."""
flat = self.host.isMaximized() or self.host.isFullScreen()
payload = json.dumps({
"account": self.actions()[0].text() if self.actions() else "账号",
"maximized": self.host.isMaximized(),
"flat": flat,
})
return (
"document.documentElement.classList.add('embedded','desktop-frame');"
f"document.documentElement.classList.toggle('window-flat',{str(flat).lower()});"
f"document.documentElement.style.setProperty('--window-radius','{self.CORNER_RADIUS}px');"
f"document.documentElement.style.setProperty('--window-bar-height','{self.BAR_HEIGHT}px');"
f"if(window.updateDesktopChrome)window.updateDesktopChrome({payload});"
"if(window.fit)fit();"
)
def perform_action(self, action):
if action == "minimize":
self.host.showMinimized()
elif action == "maximize":
self.toggle_maximized()
elif action == "close":
self.host.close() # Preserve the app's tray/background close policy.
elif action == "move" and QApplication.mouseButtons() & Qt.LeftButton:
handle = self.host.windowHandle()
if handle:
handle.startSystemMove()
def show_account_menu(self, x, y):
if self.actions() and self.actions()[0].menu():
point = QPoint(max(0, min(int(x), self.host.width() - 1)),
max(0, min(int(y), self.host.height() - 1)))
self.actions()[0].menu().popup(self.host.mapToGlobal(point))
def toggle_maximized(self):
if self.host.isMaximized():
self.host.showNormal()
else:
self.host.showMaximized()
def eventFilter(self, watched, event):
if watched is self.host and event.type() in (
QEvent.Resize, QEvent.Show, QEvent.WindowStateChange,
):
self._update_frame()
return super().eventFilter(watched, event)
@staticmethod
def _rounded_region(rect, radius):
path = QPainterPath()
path.addRoundedRect(QRectF(rect), radius, radius)
return QRegion(path.toFillPolygon().toPolygon())
def _update_frame(self):
flat = self.host.isMaximized() or self.host.isFullScreen()
key = (self.host.width(), self.host.height(), flat)
if key != self._frame_key:
changed = flat != self._flat
self._flat = flat
self._frame_key = key
# Masks remain useful only for the invisible resize hit areas.
# Never clip the rendered window back to a jagged binary region.
if not self.host.mask().isEmpty():
self.host.clearMask()
self._update_handles()
if changed:
self.frameChanged.emit()
def _update_handles(self):
margin = self.RESIZE_MARGIN
width, height = self.host.width(), self.host.height()
radius = self.CORNER_RADIUS
outer = self._rounded_region(self.host.rect(), radius)
inner = self._rounded_region(self.host.rect().adjusted(margin, margin, -margin, -margin), radius - margin)
border = outer.subtracted(inner)
for edges, handle in self._resize_handles.items():
horizontal = bool(edges & (Qt.LeftEdge | Qt.RightEdge))
vertical = bool(edges & (Qt.TopEdge | Qt.BottomEdge))
if horizontal and vertical:
x = width - radius if edges & Qt.RightEdge else 0
y = height - radius if edges & Qt.BottomEdge else 0
handle.setGeometry(x, y, radius, radius)
# Only the arc receives resize gestures; nearby controls stay clickable.
handle.setMask(border.intersected(QRegion(handle.geometry())).translated(-x, -y))
elif horizontal:
handle.setGeometry(width - margin if edges & Qt.RightEdge else 0, radius,
margin, max(0, height - 2 * radius))
else:
handle.setGeometry(radius, height - margin if edges & Qt.BottomEdge else 0,
max(0, width - 2 * radius), margin)
handle.setVisible(not self._flat)
handle.raise_()