forked from trav/lintunes
578 lines
23 KiB
Python
578 lines
23 KiB
Python
"""The title bar LinTunes draws for itself on Wayland (Round 72).
|
||
|
||
GNOME's Mutter draws no title bars for Wayland clients, so Qt draws its own
|
||
through the ``adwaita`` decoration plugin — and that plugin builds its colors
|
||
from hardcoded constants: pure white in light mode, deaf to the palette and to
|
||
stylesheets. Against LinTunes' grey window body that white strip read as part
|
||
of the content. The only way to give it another color is to not have it: every
|
||
top-level window goes frameless and gets a ``TitleBar`` painted in the
|
||
palette's ``Window`` color, so it follows the Background slider too.
|
||
|
||
``install(app)`` does it for every window at once from an application event
|
||
filter, so no dialog has to know: the frameless flag is set at ``Polish``
|
||
(before the native window is mapped), and the bar is added at the first
|
||
``Show`` — after the dialog's own sizing has run, so its content area can be
|
||
grown by exactly the bar's height and comes out the size its author chose.
|
||
Moving, snapping and resizing are still the compositor's, through
|
||
``QWindow.startSystemMove`` / ``startSystemResize``.
|
||
|
||
A top-level window that must keep the system frame sets the Qt property
|
||
``OPT_OUT`` to ``True`` before it is first shown.
|
||
|
||
The window itself is the house's (shared-resources design.html#window,
|
||
after routine-widget): translucent, so its corners can be round
|
||
(``RADIUS``, square while maximized); its gray filled as that rounded
|
||
shape; no line under the bar; and a soft emboss round the whole edge — a
|
||
faint light rim along the top, a faint dark one along the bottom, then the
|
||
outline — painted by ``_Frame``, a mouse-transparent child on top of
|
||
everything that also cuts whatever a child painted outside the curve.
|
||
A window that must stay opaque (a GL child that writes alpha 0) sets
|
||
``SQUARE``. A window whose title is shown just below anyway sets ``BLANK_TITLE``: the
|
||
bar shows only its buttons, and the window keeps its title for the task
|
||
switcher.
|
||
"""
|
||
import subprocess
|
||
|
||
from PyQt6.QtCore import QEvent, QObject, QPoint, QRect, QRectF, QSize, Qt
|
||
from PyQt6.QtGui import (QBrush, QColor, QLinearGradient, QPainter,
|
||
QPainterPath, QPalette, QPen, QRegion)
|
||
from PyQt6.QtWidgets import QAbstractButton, QLayout, QWidget
|
||
|
||
OPT_OUT = "lintunes_system_frame"
|
||
BLANK_TITLE = "lintunes_blank_title"
|
||
SQUARE = "lintunes_square_corners" # stays opaque: square corners, same rim
|
||
_DONE = "_lintunes_titlebar"
|
||
|
||
RESIZE_MARGIN = 4 # the strip along each edge that resizes
|
||
CORNER = 14 # how far along an edge a corner reaches
|
||
BUTTON = 24 # the round button's diameter
|
||
SPACING = 8 # between buttons, and from the bar's ends
|
||
RADIUS = 10 # the window's corners
|
||
RIM_WIDTH = 2.5 # the soft emboss's light/dark rims, inside the outline
|
||
RIM = 4 # how far in from the edge the frame paints
|
||
|
||
_BUTTONS = ("close", "minimize", "maximize")
|
||
_FALLBACK_LAYOUT = ":minimize,close"
|
||
_layout_cache = None
|
||
|
||
|
||
def parse_button_layout(text: str) -> tuple[list[str], list[str]]:
|
||
"""GNOME's ``button-layout`` (``"close,minimize:appmenu"``) as the
|
||
buttons left of the title and those right of it. Anything LinTunes has
|
||
no button for (``appmenu``, ``icon``, ``spacer``) is dropped."""
|
||
left, _, right = text.strip().strip("'\"").partition(":")
|
||
|
||
def names(side):
|
||
return [n for n in (p.strip() for p in side.split(","))
|
||
if n in _BUTTONS]
|
||
return names(left), names(right)
|
||
|
||
|
||
def button_layout() -> tuple[list[str], list[str]]:
|
||
"""The desktop's button layout, read once; GNOME's default without one."""
|
||
global _layout_cache
|
||
if _layout_cache is None:
|
||
try:
|
||
text = subprocess.run(
|
||
["gsettings", "get", "org.gnome.desktop.wm.preferences",
|
||
"button-layout"],
|
||
capture_output=True, text=True, timeout=2).stdout
|
||
except (OSError, subprocess.SubprocessError):
|
||
text = ""
|
||
left, right = parse_button_layout(text)
|
||
if "close" not in left + right:
|
||
left, right = parse_button_layout(_FALLBACK_LAYOUT)
|
||
_layout_cache = (left, right)
|
||
return _layout_cache
|
||
|
||
|
||
def edges_at(pos: QPoint, size: QSize, margin: int = RESIZE_MARGIN,
|
||
corner: int = CORNER) -> Qt.Edge:
|
||
"""Which window edges a point (window coordinates) would resize. Within
|
||
``corner`` of a corner along an edge, that corner's other edge joins in,
|
||
so a corner is easy to catch without making the edges thick."""
|
||
x, y, w, h = pos.x(), pos.y(), size.width(), size.height()
|
||
near_left, near_right = x < margin, x >= w - margin
|
||
near_top, near_bottom = y < margin, y >= h - margin
|
||
if not (near_left or near_right or near_top or near_bottom):
|
||
return Qt.Edge(0)
|
||
edges = Qt.Edge(0)
|
||
if near_left or ((near_top or near_bottom) and x < corner):
|
||
edges |= Qt.Edge.LeftEdge
|
||
if near_right or ((near_top or near_bottom) and x >= w - corner):
|
||
edges |= Qt.Edge.RightEdge
|
||
if near_top or ((near_left or near_right) and y < corner):
|
||
edges |= Qt.Edge.TopEdge
|
||
if near_bottom or ((near_left or near_right) and y >= h - corner):
|
||
edges |= Qt.Edge.BottomEdge
|
||
return edges
|
||
|
||
|
||
def cursor_for(edges: Qt.Edge) -> Qt.CursorShape:
|
||
left, right = Qt.Edge.LeftEdge in edges, Qt.Edge.RightEdge in edges
|
||
top, bottom = Qt.Edge.TopEdge in edges, Qt.Edge.BottomEdge in edges
|
||
if (top and left) or (bottom and right):
|
||
return Qt.CursorShape.SizeFDiagCursor
|
||
if (top and right) or (bottom and left):
|
||
return Qt.CursorShape.SizeBDiagCursor
|
||
if left or right:
|
||
return Qt.CursorShape.SizeHorCursor
|
||
if top or bottom:
|
||
return Qt.CursorShape.SizeVerCursor
|
||
return Qt.CursorShape.ArrowCursor
|
||
|
||
|
||
def is_resizable(window: QWidget) -> bool:
|
||
if window.minimumSize() == window.maximumSize():
|
||
return False
|
||
layout = window.layout()
|
||
return not (layout is not None and layout.sizeConstraint()
|
||
== QLayout.SizeConstraint.SetFixedSize)
|
||
|
||
|
||
def _framed(window: QWidget) -> bool:
|
||
"""Whether the window shows edges at all (not maximized/fullscreen)."""
|
||
return not (window.windowState() & (Qt.WindowState.WindowMaximized
|
||
| Qt.WindowState.WindowFullScreen))
|
||
|
||
|
||
TILED_SLACK = 64 # a window this close to the screen's height is tiled
|
||
|
||
|
||
def tiled(window: QWidget) -> bool:
|
||
"""Snapped to half the screen (or any edge-to-edge height). Wayland
|
||
tells Qt the tiled state but Qt keeps it to itself, and its available
|
||
geometry still includes the top bar, so: as tall as the screen, give
|
||
or take the bar."""
|
||
screen = window.screen()
|
||
return (screen is not None and window.height()
|
||
>= screen.geometry().height() - TILED_SLACK)
|
||
|
||
|
||
def _radius(window: QWidget) -> int:
|
||
"""Round corners only on a free-floating, see-through window: maximized,
|
||
fullscreen or tiled windows meet the screen's edges or a neighbour."""
|
||
see_through = window.testAttribute(
|
||
Qt.WidgetAttribute.WA_TranslucentBackground)
|
||
if not see_through or not _framed(window) or tiled(window):
|
||
return 0
|
||
return RADIUS
|
||
|
||
|
||
def _outline(rect: QRect, radius: int) -> QPainterPath:
|
||
path = QPainterPath()
|
||
path.addRoundedRect(QRectF(rect).adjusted(0.5, 0.5, -0.5, -0.5),
|
||
radius, radius)
|
||
return path
|
||
|
||
|
||
def paint_window_background(window: QWidget):
|
||
"""The window's gray as a rounded tile (its corners stay see-through)."""
|
||
painter = QPainter(window)
|
||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||
painter.fillPath(_outline(window.rect(), _radius(window)),
|
||
window.palette().color(QPalette.ColorRole.Window))
|
||
painter.end()
|
||
|
||
|
||
def _rim_gradient(bg: QColor, height: int, strength: float) -> QLinearGradient:
|
||
"""The rims' light-from-above gradient, at `strength` (0–1) of full."""
|
||
light, dark = bg.lighter(112), bg.darker(112)
|
||
light.setAlphaF(strength)
|
||
dark.setAlphaF(strength)
|
||
rims = QLinearGradient(0, 0, 0, height)
|
||
rims.setColorAt(0, light)
|
||
rims.setColorAt(0.06, QColor(255, 255, 255, 0))
|
||
rims.setColorAt(0.94, QColor(0, 0, 0, 0))
|
||
rims.setColorAt(1, dark)
|
||
return rims
|
||
|
||
|
||
class _Frame(QWidget):
|
||
"""The window's edge, over everything in it: clears what lies outside
|
||
the rounded corners, then the soft emboss and the outline. Masked to a
|
||
ring along the edge, so an update inside the window never reaches it."""
|
||
|
||
def __init__(self, window: QWidget):
|
||
super().__init__(window)
|
||
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
|
||
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||
|
||
def place(self):
|
||
window = self.window()
|
||
rect = window.rect()
|
||
self.setGeometry(rect)
|
||
ring = QRegion(rect).subtracted(
|
||
QRegion(rect.adjusted(RIM, RIM, -RIM, -RIM)))
|
||
k = _radius(window) + 1
|
||
w, h = rect.width(), rect.height()
|
||
for x, y in ((0, 0), (w - k, 0), (0, h - k), (w - k, h - k)):
|
||
ring = ring.united(QRegion(x, y, k, k))
|
||
self.setMask(ring)
|
||
self.show()
|
||
self.update()
|
||
self.raise_()
|
||
|
||
def paintEvent(self, _event):
|
||
painter = QPainter(self)
|
||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||
r = _radius(self.window())
|
||
path = _outline(self.rect(), r)
|
||
outside = QPainterPath()
|
||
outside.addRect(QRectF(self.rect()))
|
||
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Clear)
|
||
painter.fillPath(outside.subtracted(path), Qt.GlobalColor.transparent)
|
||
painter.setCompositionMode(
|
||
QPainter.CompositionMode.CompositionMode_SourceOver)
|
||
bg = self.palette().color(QPalette.ColorRole.Window)
|
||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||
# The rims start just inside the outline and run RIM_WIDTH in, and
|
||
# fade across that band too: full strength in the pixel against the
|
||
# outline, each pixel further in fainter, so none of it is flat.
|
||
# One ring per whole pixel (the last one the leftover fraction):
|
||
# thinner rings blend at their seams and dim the brightest pixel.
|
||
offset = 0.0
|
||
while offset < RIM_WIDTH:
|
||
width = min(1.0, RIM_WIDTH - offset)
|
||
strength = 1 - offset / RIM_WIDTH
|
||
painter.setPen(QPen(QBrush(_rim_gradient(
|
||
bg, self.height(), strength)), width))
|
||
inset = 1 + offset + width / 2
|
||
ring = QPainterPath()
|
||
ring.addRoundedRect(
|
||
QRectF(self.rect()).adjusted(inset, inset, -inset, -inset),
|
||
max(0.0, r - inset + 0.5), max(0.0, r - inset + 0.5))
|
||
painter.drawPath(ring)
|
||
offset += width
|
||
painter.setPen(QPen(bg.darker(128), 1))
|
||
painter.drawPath(path)
|
||
|
||
|
||
class _Button(QAbstractButton):
|
||
"""A GNOME-style round title-bar button: a soft disc with a glyph."""
|
||
|
||
def __init__(self, kind: str, parent):
|
||
super().__init__(parent)
|
||
self.kind = kind
|
||
self.setFixedSize(BUTTON, BUTTON)
|
||
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||
self.setCursor(Qt.CursorShape.ArrowCursor)
|
||
self.setToolTip({"close": "Close", "minimize": "Minimize",
|
||
"maximize": "Maximize"}[kind])
|
||
|
||
def paintEvent(self, _event):
|
||
painter = QPainter(self)
|
||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||
base = self.palette().color(QPalette.ColorRole.Window)
|
||
if self.isDown():
|
||
disc = base.darker(135)
|
||
elif self.underMouse():
|
||
disc = base.darker(122)
|
||
else:
|
||
disc = base.darker(110)
|
||
painter.setPen(Qt.PenStyle.NoPen)
|
||
painter.setBrush(disc)
|
||
painter.drawEllipse(self.rect().adjusted(1, 1, -1, -1))
|
||
|
||
active = self.window().isActiveWindow()
|
||
ink = self.palette().color(QPalette.ColorRole.WindowText)
|
||
if not active:
|
||
ink.setAlpha(140)
|
||
pen = QPen(ink, 1.6)
|
||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||
painter.setPen(pen)
|
||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||
c = self.width() / 2
|
||
r = 4.0
|
||
if self.kind == "close":
|
||
painter.drawLine(int(c - r), int(c - r), int(c + r), int(c + r))
|
||
painter.drawLine(int(c - r), int(c + r), int(c + r), int(c - r))
|
||
elif self.kind == "minimize":
|
||
painter.drawLine(int(c - r), int(c + r), int(c + r), int(c + r))
|
||
elif _framed(self.window()):
|
||
painter.drawRect(int(c - r), int(c - r), int(2 * r), int(2 * r))
|
||
else: # restore: two overlapping squares
|
||
painter.drawRect(int(c - r), int(c - r + 2), int(2 * r - 2),
|
||
int(2 * r - 2))
|
||
painter.drawLine(int(c - r + 2), int(c - r), int(c + r),
|
||
int(c - r))
|
||
painter.drawLine(int(c + r), int(c - r), int(c + r),
|
||
int(c + r - 2))
|
||
|
||
|
||
class _Grip(QWidget):
|
||
"""A thin resize strip along the left, right or bottom edge (the top
|
||
edge is the bar's). The frame over it paints the edge."""
|
||
|
||
def __init__(self, side: str, window: QWidget):
|
||
super().__init__(window)
|
||
self.side = side
|
||
self.setMouseTracking(True)
|
||
|
||
def _edges(self, pos: QPoint) -> Qt.Edge:
|
||
window = self.window()
|
||
if not is_resizable(window):
|
||
return Qt.Edge(0)
|
||
return edges_at(self.mapTo(window, pos), window.size())
|
||
|
||
def mouseMoveEvent(self, event):
|
||
self.setCursor(cursor_for(self._edges(event.position().toPoint())))
|
||
|
||
def mousePressEvent(self, event):
|
||
edges = self._edges(event.position().toPoint())
|
||
handle = self.window().windowHandle()
|
||
if (event.button() == Qt.MouseButton.LeftButton and edges
|
||
and handle is not None):
|
||
handle.startSystemResize(edges)
|
||
event.accept()
|
||
return
|
||
event.ignore()
|
||
|
||
|
||
class TitleBar(QWidget):
|
||
"""The bar itself: a child of the window, placed by hand above the
|
||
window's contents (which make room through the top contents margin)."""
|
||
|
||
def __init__(self, window: QWidget):
|
||
super().__init__(window)
|
||
self.setObjectName("lintunesTitleBar")
|
||
self.setMouseTracking(True)
|
||
self._window = window
|
||
self._added = 0 # how much of the window's top margin is ours
|
||
left, right = button_layout()
|
||
self._left = [_Button(k, self) for k in left]
|
||
self._right = [_Button(k, self) for k in right]
|
||
for button in self._left + self._right:
|
||
button.clicked.connect(
|
||
lambda _=False, k=button.kind: self._on_button(k))
|
||
self._grips = [_Grip(side, window)
|
||
for side in ("left", "right", "bottom")]
|
||
self._frame = _Frame(window)
|
||
window.windowTitleChanged.connect(lambda _t: self.update())
|
||
self._apply_height()
|
||
self._place()
|
||
|
||
# -- geometry ------------------------------------------------------
|
||
|
||
def bar_height(self) -> int:
|
||
return max(BUTTON + 2 * 5, self.fontMetrics().height() + 18)
|
||
|
||
def _apply_height(self):
|
||
"""Make the window's top margin hold exactly this bar."""
|
||
height = self.bar_height()
|
||
if height == self._added:
|
||
return
|
||
m = self._window.contentsMargins()
|
||
self._window.setContentsMargins(
|
||
m.left(), m.top() - self._added + height, m.right(), m.bottom())
|
||
self._added = height
|
||
self._place()
|
||
|
||
def _place(self):
|
||
w, h = self._window.width(), self._window.height()
|
||
bar = self._added
|
||
self.setGeometry(0, 0, w, bar)
|
||
y = (bar - BUTTON) // 2
|
||
x = SPACING
|
||
for button in self._left:
|
||
button.move(x, y)
|
||
x += BUTTON + SPACING
|
||
x = w - SPACING - BUTTON
|
||
for button in reversed(self._right):
|
||
button.move(x, y)
|
||
x -= BUTTON + SPACING
|
||
resizable = is_resizable(self._window)
|
||
for button in self._left + self._right:
|
||
if button.kind == "maximize":
|
||
button.setVisible(resizable)
|
||
framed = _framed(self._window)
|
||
m = RESIZE_MARGIN
|
||
left, right, bottom = self._grips
|
||
left.setGeometry(0, bar, m, max(h - bar - m, 0))
|
||
right.setGeometry(w - m, bar, m, max(h - bar - m, 0))
|
||
bottom.setGeometry(0, h - m, w, m)
|
||
for grip in self._grips:
|
||
grip.setVisible(framed)
|
||
grip.raise_()
|
||
self.raise_()
|
||
self._frame.place()
|
||
|
||
# -- events --------------------------------------------------------
|
||
|
||
def window_event(self, kind):
|
||
"""The window's own events, relayed by ``TitleBarInstaller`` — not
|
||
an event filter on the window, which would still be called while the
|
||
window tears its children (this bar among them) down."""
|
||
if kind in (QEvent.Type.Resize, QEvent.Type.WindowStateChange):
|
||
self._place()
|
||
else:
|
||
self.update()
|
||
self._frame.update()
|
||
for button in self._left + self._right:
|
||
button.update()
|
||
|
||
def changeEvent(self, event):
|
||
if event.type() == QEvent.Type.FontChange:
|
||
self._apply_height()
|
||
super().changeEvent(event)
|
||
|
||
def _on_button(self, kind: str):
|
||
if kind == "close":
|
||
self._window.close()
|
||
elif kind == "minimize":
|
||
self._window.showMinimized()
|
||
else:
|
||
self.toggle_maximized()
|
||
|
||
def toggle_maximized(self):
|
||
if not is_resizable(self._window):
|
||
return
|
||
if self._window.isMaximized():
|
||
self._window.showNormal()
|
||
else:
|
||
self._window.showMaximized()
|
||
|
||
def _top_edges(self, pos: QPoint) -> Qt.Edge:
|
||
if not (_framed(self._window) and is_resizable(self._window)):
|
||
return Qt.Edge(0)
|
||
return edges_at(pos, self._window.size())
|
||
|
||
def mouseMoveEvent(self, event):
|
||
self.setCursor(cursor_for(self._top_edges(event.position().toPoint())))
|
||
|
||
def mousePressEvent(self, event):
|
||
if event.button() != Qt.MouseButton.LeftButton:
|
||
event.ignore()
|
||
return
|
||
handle = self._window.windowHandle()
|
||
if handle is not None:
|
||
edges = self._top_edges(event.position().toPoint())
|
||
if edges:
|
||
handle.startSystemResize(edges)
|
||
else:
|
||
handle.startSystemMove()
|
||
event.accept()
|
||
|
||
def mouseDoubleClickEvent(self, event):
|
||
if event.button() == Qt.MouseButton.LeftButton:
|
||
self.toggle_maximized()
|
||
event.accept()
|
||
|
||
def paintEvent(self, _event):
|
||
painter = QPainter(self)
|
||
palette = self.palette()
|
||
# No line under it: the bar is the top of the window, not a zone.
|
||
painter.fillRect(self.rect(), palette.color(QPalette.ColorRole.Window))
|
||
|
||
# The title is centered on the whole bar, kept clear of both button
|
||
# groups by the wider of the two.
|
||
reach = max(len(self._left), len(self._right)) * (BUTTON + SPACING)
|
||
room = QRect(reach + SPACING, 0,
|
||
max(self.width() - 2 * (reach + SPACING), 0),
|
||
self.height())
|
||
font = painter.font()
|
||
font.setBold(True)
|
||
painter.setFont(font)
|
||
ink = palette.color(QPalette.ColorRole.WindowText)
|
||
if not self._window.isActiveWindow():
|
||
ink.setAlpha(150)
|
||
painter.setPen(ink)
|
||
title = painter.fontMetrics().elidedText(
|
||
self.title(), Qt.TextElideMode.ElideRight, room.width())
|
||
painter.drawText(room, Qt.AlignmentFlag.AlignCenter, title)
|
||
|
||
def title(self) -> str:
|
||
if self._window.property(BLANK_TITLE):
|
||
return ""
|
||
# Qt's "[*]" modified placeholder, as the system bar would show it.
|
||
title = self._window.windowTitle()
|
||
return title.replace("[*]", "*" if self._window.isWindowModified()
|
||
else "")
|
||
|
||
|
||
def title_bar(window: QWidget) -> TitleBar | None:
|
||
return window.findChild(TitleBar, "lintunesTitleBar",
|
||
Qt.FindChildOption.FindDirectChildrenOnly)
|
||
|
||
|
||
def wants_bar(widget) -> bool:
|
||
if not isinstance(widget, QWidget) or not widget.isWindow():
|
||
return False
|
||
if widget.windowType() not in (Qt.WindowType.Window,
|
||
Qt.WindowType.Dialog):
|
||
return False
|
||
if widget.property(OPT_OUT):
|
||
return False
|
||
return True
|
||
|
||
|
||
_RELAYED = (QEvent.Type.Resize, QEvent.Type.WindowStateChange,
|
||
QEvent.Type.WindowActivate, QEvent.Type.WindowDeactivate)
|
||
|
||
|
||
class TitleBarInstaller(QObject):
|
||
"""The application event filter that gives each window its bar."""
|
||
|
||
def eventFilter(self, obj, event):
|
||
kind = event.type()
|
||
if kind in _RELAYED:
|
||
if (isinstance(obj, QWidget) and obj.isWindow()
|
||
and obj.property(_DONE) == "bar"):
|
||
bar = title_bar(obj)
|
||
if bar is not None:
|
||
bar.window_event(kind)
|
||
elif kind == QEvent.Type.Paint:
|
||
if (isinstance(obj, QWidget) and obj.isWindow()
|
||
and obj.property(_DONE)):
|
||
paint_window_background(obj)
|
||
elif kind == QEvent.Type.ParentChange:
|
||
# Polished while parentless (a style sheet set before it went
|
||
# into a layout), it looked like a window: undo it, or a
|
||
# see-through child paints no background of its own.
|
||
if (isinstance(obj, QWidget) and not obj.isWindow()
|
||
and obj.property(_DONE) == "frameless"):
|
||
obj.setProperty(_DONE, None)
|
||
obj.setAttribute(
|
||
Qt.WidgetAttribute.WA_TranslucentBackground, False)
|
||
obj.setAttribute(
|
||
Qt.WidgetAttribute.WA_NoSystemBackground, False)
|
||
elif kind == QEvent.Type.Polish:
|
||
if wants_bar(obj) and not obj.property(_DONE) and not (
|
||
obj.windowFlags() & Qt.WindowType.FramelessWindowHint):
|
||
self.make_frameless(obj)
|
||
elif kind == QEvent.Type.Show:
|
||
if obj.property(_DONE) == "frameless" and wants_bar(obj):
|
||
self.add_bar(obj)
|
||
return False
|
||
|
||
@staticmethod
|
||
def make_frameless(window: QWidget):
|
||
window.setProperty(_DONE, "frameless")
|
||
# Before the flag, which recreates the native window: an alpha
|
||
# channel is what lets the corners be round.
|
||
if not window.property(SQUARE):
|
||
window.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||
window.setWindowFlag(Qt.WindowType.FramelessWindowHint, True)
|
||
|
||
@staticmethod
|
||
def add_bar(window: QWidget) -> TitleBar:
|
||
"""Add the bar, growing the window so its contents keep the size
|
||
they had — the bar used to sit outside them."""
|
||
window.setProperty(_DONE, "bar")
|
||
bar = TitleBar(window)
|
||
grow = bar.bar_height()
|
||
if window.minimumSize() == window.maximumSize():
|
||
size = window.size()
|
||
window.setFixedSize(size.width(), size.height() + grow)
|
||
else:
|
||
window.resize(window.width(), window.height() + grow)
|
||
bar.show()
|
||
return bar
|
||
|
||
|
||
def install(app) -> TitleBarInstaller:
|
||
"""Give every LinTunes window an app-drawn title bar from now on."""
|
||
installer = TitleBarInstaller(app)
|
||
app.installEventFilter(installer)
|
||
return installer
|