Files
SageTube/ytsage/gui/ytsage_smooth_tab_widget.py
T
Homer 5ae2817eea Stop the player freeing a render context libmpv still uses
The segfault: Qt destroys and recreates a widget's QOpenGLContext whenever it
moves to another top-level window, then calls initializeGL() again. libmpv
permits one render context per handle, so the second creation failed with
"There is already a mpv_render_context set" -- and the except branch assigned
self._render_ctx = None, dropping the last Python reference to the first
context, which libmpv was still holding a function pointer into. python-mpv's
MpvRenderContext has no __del__ and free() does not unregister the callback,
so the ctypes trampoline was collected while registered and the next frame
notification jumped into freed memory.

Two invariants fix it. initializeGL() now tears down any existing render
context first, so a second call is an ordinary recreation. Teardown clears
update_cb, calls free() with the GL context current, and only then drops the
reference -- and it is connected to QOpenGLContext.aboutToBeDestroyed, so it
runs before the GL context dies instead of never. The local reference during
teardown is load-bearing: it is what keeps the trampoline alive until free()
returns.

Three things were destroying that context. Fullscreen reparented the panel
into a new top-level window (twice per toggle) and put it back at the end of
the splitter, losing the pane layout; it now fullscreens the main window and
hides the chrome, reparenting nothing. The tab cross-fade and the dialog blur
both grab() the widget tree, which on an OpenGL surface forces a framebuffer
readback and returns black -- the fade is skipped for pages holding the video,
and dialogs dim rather than blur.

Verified on a real Wayland GL context: ten forced context destroy/recreate
cycles re-establish the render context every time, and the full app survives
tab switching, six fullscreen toggles and resizes with no render-context
error and a clean exit. Before this, the same startup dumped core.

Also here because they are one-line consequences of touching _create_mpv: an
explicit per-platform hwdec list ending in software decoding, and the restored
volume actually reaching mpv -- the slider set its value before connecting its
signal, so playback always started at 100.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 00:48:18 +02:00

141 lines
4.7 KiB
Python

from PySide6.QtCore import QEasingCurve, QPropertyAnimation, Qt
from PySide6.QtGui import QPixmap
from PySide6.QtOpenGLWidgets import QOpenGLWidget
from PySide6.QtWidgets import (
QFrame,
QGraphicsOpacityEffect,
QLabel,
QStackedWidget,
QTabBar,
QVBoxLayout,
QWidget,
)
class FadingStackedWidget(QStackedWidget):
"""
A QStackedWidget that cross-fades between widgets.
"""
def __init__(self, parent=None):
super().__init__(parent)
self.fade_duration = 300
self.fade_easing = QEasingCurve.Type.OutQuad
@staticmethod
def _contains_gl(widget):
"""Whether an OpenGL surface lives anywhere under this page."""
if widget is None:
return False
return isinstance(widget, QOpenGLWidget) or widget.findChild(QOpenGLWidget) is not None
def setCurrentIndex(self, index):
curr_index = self.currentIndex()
if index == curr_index:
return
widget = self.widget(index)
curr_widget = self.widget(curr_index)
# If widget isn't visible or valid, just swap
if not self.isVisible() or not curr_widget:
super().setCurrentIndex(index)
return
# Never fade a page containing an OpenGL surface. grab() on one
# returns a black rectangle -- so the "fade" was a black slab sliding
# over the new tab -- and forcing a framebuffer readback plus a
# QGraphicsEffect over that subtree is a way to lose the GL context,
# which for the embedded mpv player means a crash.
if self._contains_gl(widget) or self._contains_gl(curr_widget):
super().setCurrentIndex(index)
return
# 1. Capture the current view (the "old" tab)
# Use grab() for simplicity and reliability in PySide6
pixmap = self.grab()
# 2. Create an overlay label to hold this "old" view
overlay = QLabel(self)
overlay.setPixmap(pixmap)
overlay.setGeometry(0, 0, self.width(), self.height())
overlay.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents) # Don't block clicks
overlay.show()
# 3. Switch the actual stack to the "new" view
super().setCurrentIndex(index)
# CRITICAL: Ensure overlay stays on top of the new widget
overlay.raise_()
# 4. Fade OUT the overlay, revealing the new view
effect = QGraphicsOpacityEffect(overlay)
overlay.setGraphicsEffect(effect)
anim = QPropertyAnimation(effect, b"opacity", overlay)
anim.setDuration(self.fade_duration)
anim.setStartValue(1.0)
anim.setEndValue(0.0)
anim.setEasingCurve(self.fade_easing)
# Cleanup when done
anim.finished.connect(lambda: self._cleanup(overlay))
# Keep reference to prevent GC
self._active_anim = anim
anim.start(QPropertyAnimation.DeletionPolicy.DeleteWhenStopped)
def _cleanup(self, overlay):
overlay.hide()
overlay.deleteLater()
class SmoothTabWidget(QWidget):
"""
A unified Widget that behaves like a QTabWidget but uses smooth fading transitions.
Includes a QTabBar and a FadingStackedWidget.
"""
def __init__(self, parent=None):
super().__init__(parent)
# Main Layout
self.layout = QVBoxLayout(self)
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setSpacing(0)
# Tab Bar
self.tab_bar = QTabBar(self)
self.tab_bar.setDrawBase(False) # We draw border on content instead
self.tab_bar.currentChanged.connect(self.set_current_index)
self.layout.addWidget(self.tab_bar)
# Content Area (Frame) - Mimics QTabWidget::pane
self.content_frame = QFrame(self)
self.content_frame.setObjectName("tabContent")
# Layout inside the content frame
self.content_layout = QVBoxLayout(self.content_frame)
self.content_layout.setContentsMargins(0, 0, 0, 0)
self.content_layout.setSpacing(0)
# The Stack
self.stack = FadingStackedWidget(self.content_frame)
self.content_layout.addWidget(self.stack)
self.layout.addWidget(self.content_frame)
def addTab(self, widget, label):
"""Add a tab with the given widget and label."""
self.stack.addWidget(widget)
self.tab_bar.addTab(label)
def set_current_index(self, index):
"""Slot to handle tab bar clicks."""
self.tab_bar.setCurrentIndex(index)
self.stack.setCurrentIndex(index)
def currentWidget(self):
return self.stack.currentWidget()
def currentIndex(self):
return self.stack.currentIndex()