Skip to content

The only downloader you need. 下载器的集大成者。

fix(task): 详情抽屉长文件名不再撑出横向滚动,文字可选中

XiaoYouChR87825e4dd1f8
diff --git a/app/view/dialogs/task_drawer.py b/app/view/dialogs/task_drawer.py
index 645b21de..9d6757d6 100644
--- a/app/view/dialogs/task_drawer.py
+++ b/app/view/dialogs/task_drawer.py
@@ -1,15 +1,16 @@
from __future__ import annotations
from datetime import datetime
+from math import ceil
from typing import TYPE_CHECKING
from PySide6.QtCore import (
- QEasingCurve, QFileInfo, QParallelAnimationGroup, QPoint, QPointF, QPropertyAnimation, QSize, Qt, QTimer,
+ QEasingCurve, QFileInfo, QParallelAnimationGroup, QPoint, QPointF, QPropertyAnimation, Qt, QTimer,
)
-from PySide6.QtGui import QColor, QPainter, QTextLayout, QTextOption
+from PySide6.QtGui import QColor, QFont, QTextOption
from PySide6.QtWidgets import (
- QAbstractItemView, QApplication, QDialog, QFileIconProvider, QGraphicsOpacityEffect, QHBoxLayout,
- QHeaderView, QTableWidgetItem, QVBoxLayout, QWidget,
+ QAbstractItemView, QApplication, QDialog, QFileIconProvider, QFrame, QGraphicsOpacityEffect, QHBoxLayout,
+ QHeaderView, QSizePolicy, QTableWidgetItem, QTextEdit, QVBoxLayout, QWidget,
)
from qfluentwidgets import (
CaptionLabel, FluentIcon, ImageLabel, InfoBar, InfoBarIcon, InfoBarPosition, LineEdit, ProgressBar, ScrollArea,
@@ -17,6 +18,7 @@ from qfluentwidgets import (
TransparentToolButton, isDarkTheme, setFont,
)
from qfluentwidgets.components.dialog_box.mask_dialog_base import MaskDialogBase
+from qfluentwidgets.components.widgets.menu import TextEditMenu
from app.config.cfg import cfg
from app.format import toReadableSize, toReadableTime
@@ -55,62 +57,45 @@ def toCaptionStyle(label: CaptionLabel) -> None:
label.setTextColor(QColor(96, 96, 96), QColor(206, 206, 206))
-class WrapLabel(QWidget):
+class SelectableText(QTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
- self._text = ""
+ self.setReadOnly(True)
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+ self.setFrameShape(QFrame.Shape.NoFrame)
+ self.setWordWrapMode(QTextOption.WrapMode.WrapAnywhere)
+ self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
+ self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
+ self.setStyleSheet(f"background: transparent; color: {'white' if isDarkTheme() else 'black'}")
+ self.document().setDocumentMargin(0)
+ self.document().documentLayout().documentSizeChanged.connect(
+ lambda size: self.setFixedHeight(ceil(size.height())))
setFont(self, 14)
- sizePolicy = self.sizePolicy()
- sizePolicy.setHeightForWidth(True)
- self.setSizePolicy(sizePolicy)
def text(self) -> str:
- return self._text
+ return self.toPlainText()
def setText(self, text: str) -> None:
- if text == self._text:
+ if text != self.toPlainText():
+ self.setPlainText(text)
+
+ def contextMenuEvent(self, e) -> None:
+ TextEditMenu(self).exec(e.globalPos())
+
+ def focusOutEvent(self, e) -> None:
+ super().focusOutEvent(e)
+ if e.reason() in (Qt.FocusReason.ActiveWindowFocusReason, Qt.FocusReason.PopupFocusReason):
return
- self._text = text
- self.updateGeometry()
- self.update()
-
- def _buildLayout(self, width: int) -> QTextLayout:
- layout = QTextLayout(self._text, self.font())
- option = QTextOption()
- option.setWrapMode(QTextOption.WrapMode.WrapAnywhere)
- layout.setTextOption(option)
- layout.beginLayout()
- y = 0.0
- while (line := layout.createLine()).isValid():
- line.setLineWidth(width)
- line.setPosition(QPointF(0, y))
- y += line.height()
- layout.endLayout()
- return layout
-
- def hasHeightForWidth(self) -> bool:
- return True
-
- def heightForWidth(self, width: int) -> int:
- return int(self._buildLayout(max(width, 1)).boundingRect().height()) + 1
-
- def sizeHint(self) -> QSize:
- return QSize(self.fontMetrics().horizontalAdvance(self._text), self.heightForWidth(self.width()))
-
- def minimumSizeHint(self) -> QSize:
- return QSize(0, self.fontMetrics().height())
-
- def paintEvent(self, e) -> None:
- painter = QPainter(self)
- painter.setPen(QColor(255, 255, 255) if isDarkTheme() else QColor(0, 0, 0))
- self._buildLayout(self.width()).draw(painter, QPointF(0, 0))
+ cursor = self.textCursor()
+ cursor.clearSelection()
+ self.setTextCursor(cursor)
class InfoRow(QWidget):
def __init__(self, caption: str, parent=None):
super().__init__(parent)
self.captionLabel = CaptionLabel(caption, self)
- self.valueLabel = WrapLabel(self)
+ self.valueText = SelectableText(self)
self.buttonLayout = QHBoxLayout()
self._initWidget()
self._initLayout()
@@ -123,12 +108,12 @@ class InfoRow(QWidget):
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(12)
layout.addWidget(self.captionLabel, 0, Qt.AlignmentFlag.AlignTop)
- layout.addWidget(self.valueLabel, 1)
+ layout.addWidget(self.valueText, 1)
layout.addLayout(self.buttonLayout)
self.buttonLayout.setSpacing(2)
def setValue(self, text: str) -> None:
- self.valueLabel.setText(text)
+ self.valueText.setText(text)
def addButton(self, icon, tooltip: str, onClick) -> None:
button = TransparentToolButton(icon, self)
@@ -140,7 +125,7 @@ class InfoRow(QWidget):
def addCopyButton(self) -> None:
self.addButton(FluentIcon.COPY, self.tr("复制"),
- lambda: QApplication.clipboard().setText(self.valueLabel.text()))
+ lambda: QApplication.clipboard().setText(self.valueText.text()))
class DetailCard(QWidget):
@@ -169,20 +154,19 @@ class HeaderCard(QWidget):
super().__init__(parent)
self._task = task
self.iconLabel = ImageLabel(self)
- self.nameLabel = SubtitleLabel(task.name, self)
+ self.nameText = SelectableText(self)
self.statusLabel = CaptionLabel(self)
self.progressBar = ProgressBar(self)
self._initWidget()
self._initLayout()
def _initWidget(self) -> None:
- self.nameLabel.setWordWrap(True)
- self.nameLabel.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
+ setFont(self.nameText, 20, QFont.Weight.DemiBold)
def _initLayout(self) -> None:
textLayout = QVBoxLayout()
textLayout.setSpacing(4)
- textLayout.addWidget(self.nameLabel)
+ textLayout.addWidget(self.nameText)
textLayout.addWidget(self.statusLabel)
textLayout.addWidget(self.progressBar)
@@ -194,7 +178,7 @@ class HeaderCard(QWidget):
def refresh(self) -> None:
task = self._task
- self.nameLabel.setText(task.name)
+ self.nameText.setText(task.name)
self.iconLabel.setPixmap(QFileIconProvider().icon(QFileInfo(task.outputPath)).pixmap(48, 48))
self.iconLabel.setFixedSize(48, 48)
progress, speed, received = task.currentSnapshot()
@@ -460,6 +444,7 @@ class TaskDrawer(MaskDialogBase):
self.setMaskColor(QColor(0, 0, 0, 128) if isDarkTheme() else QColor(0, 0, 0, 102))
self.setShadowEffect(64, (0, 0), QColor(0, 0, 0, 61))
self._hBoxLayout.removeWidget(self.widget)
+ self.widget.setFocusPolicy(Qt.FocusPolicy.ClickFocus)
background = "rgb(41, 41, 41)" if isDarkTheme() else "rgb(255, 255, 255)"
self.widget.setStyleSheet(f"#centerWidget {{ background-color: {background}; border: none; }}")
self.scrollArea.setWidget(self.scrollWidget)
diff --git a/features/bittorrent_pack/detail_cards.py b/features/bittorrent_pack/detail_cards.py
index 803ae532..f3d38161 100644
--- a/features/bittorrent_pack/detail_cards.py
+++ b/features/bittorrent_pack/detail_cards.py
@@ -60,7 +60,7 @@ class TorrentCard(DetailCard):
self.piecesRow.setValue(f"{meta.pieceCount} × {toReadableSize(meta.pieceSize)}"
+ (self.tr("(私有)") if meta.isPrivate else "") if meta else "")
for row in (self.hashV1Row, self.hashV2Row, self.commentRow, self.creatorRow, self.createdRow, self.piecesRow):
- row.setVisible(bool(row.valueLabel.text()))
+ row.setVisible(bool(row.valueText.text()))
self._setSwarm(None)
def _initLayout(self) -> None:
diff --git a/tests/test_task_card_links.py b/tests/test_task_card_links.py
deleted file mode 100644
index d7b5d005..00000000
--- a/tests/test_task_card_links.py
+++ /dev/null
@@ -1,117 +0,0 @@
-"""TaskCard 的名称和信息行热区。
-
-Seam: TaskCard 鼠标事件(qtbot 真实点击)
-"""
-from __future__ import annotations
-
-import pytest
-from PySide6.QtCore import QPoint, Qt
-
-from app.models.task import TaskStatus
-from app.signal import Signal
-from tests.test_task_service import makeTask
-
-
-class FakeTaskService:
- def checksumProgress(self, task):
- return None
-
-
-class FakeCategoryService:
- categoriesChanged = Signal()
-
- def categoryById(self, categoryId):
- return None
-
-
-def card(qtbot, monkeypatch, tmp_path):
- from app.view.cards import task_cards
- opened: list[str] = []
- monkeypatch.setattr(task_cards, "openFile", opened.append)
- task = makeTask(name="movie.mp4")
- task.outputFolder = tmp_path
- (tmp_path / "movie.mp4").write_bytes(b"x")
- task.steps[0].progress = 100
- task.setStatus(TaskStatus.COMPLETED)
- widget = task_cards.TaskCard(task, FakeTaskService(), None, FakeCategoryService())
- widget.drawers = []
- monkeypatch.setattr(widget, "_openDrawer", lambda: widget.drawers.append(task.taskId))
- widget.opened = opened
- qtbot.addWidget(widget)
- widget.resize(800, widget.ROW_HEIGHT)
- widget.show()
- widget.refresh(force=True)
- qtbot.waitExposed(widget)
- return widget
-
-
-def namePos(card) -> QPoint:
- return card.nameLabel.geometry().topLeft() + QPoint(card.nameLabel.indent() + 5, card.nameLabel.height() // 2)
-
-
-def blankNamePos(card) -> QPoint:
- return card.nameLabel.geometry().topRight() + QPoint(-5, card.nameLabel.height() // 2)
-
-
-def infoPos(card) -> QPoint:
- return card.statusLabel.geometry().center()
-
-
-def test_click_name_text_opens_file(card, qtbot):
- qtbot.mouseClick(card, Qt.MouseButton.LeftButton, pos=namePos(card))
-
- assert card.opened == [card.task.outputPath]
-
-
-def test_click_blank_after_name_selects_instead(card, qtbot):
- with qtbot.waitSignal(card.selectionChanged, timeout=1000):
- qtbot.mouseClick(card, Qt.MouseButton.LeftButton, pos=blankNamePos(card))
-
- assert card.opened == []
-
-
-def test_click_info_opens_drawer_without_selecting(card, qtbot):
- with qtbot.assertNotEmitted(card.selectionChanged):
- qtbot.mouseClick(card, Qt.MouseButton.LeftButton, pos=infoPos(card))
-
- assert card.drawers == [card.task.taskId]
-
-
-def test_shift_click_on_name_extends_selection(card, qtbot):
- with qtbot.waitSignal(card.selectionChanged, timeout=1000) as blocker:
- qtbot.mouseClick(card, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.ShiftModifier, pos=namePos(card))
-
- assert blocker.args == [True, True]
- assert card.opened == []
-
-
-def test_selection_mode_turns_links_into_plain_area(card, qtbot):
- card.setSelectionMode(True)
-
- with qtbot.waitSignal(card.selectionChanged, timeout=1000):
- qtbot.mouseClick(card, Qt.MouseButton.LeftButton, pos=namePos(card))
- with qtbot.waitSignal(card.selectionChanged, timeout=1000):
- qtbot.mouseClick(card, Qt.MouseButton.LeftButton, pos=infoPos(card))
-
- assert card.opened == []
- assert card.drawers == []
-
-
-def test_name_of_unfinished_task_is_not_a_link(card, qtbot):
- card.task.steps[0].status = TaskStatus.PAUSED
- card.task.updateStatus()
- card.refresh(force=True)
-
- with qtbot.waitSignal(card.selectionChanged, timeout=1000):
- qtbot.mouseClick(card, Qt.MouseButton.LeftButton, pos=namePos(card))
-
- assert card.opened == []
-
-
-def test_hover_shows_hand_only_over_links(card, qtbot):
- qtbot.mouseMove(card, namePos(card))
- assert card.cursor().shape() == Qt.CursorShape.PointingHandCursor
-
- qtbot.mouseMove(card, blankNamePos(card))
- assert card.cursor().shape() == Qt.CursorShape.ArrowCursor
diff --git a/tests/test_task_drawer.py b/tests/test_task_drawer.py
deleted file mode 100644
index ef922f10..00000000
--- a/tests/test_task_drawer.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""TaskDrawer 的关闭路径。
-
-Seam: TaskDrawer(qtbot,真实动画)
-"""
-from __future__ import annotations
-
-import pytest
-from PySide6.QtWidgets import QWidget
-from shiboken6 import isValid
-
-from app.signal import Signal
-from tests.test_task_service import makeTask
-
-
-class FakeTaskService:
- taskRemoved = Signal(str)
-
-
-class FakeFeatureService:
- def detailCards(self, task, parent=None):
- return []
-
-
-class FakeCategoryService:
- def categoryById(self, categoryId):
- return None
-
-
-def opened(qtbot):
- from app.view.dialogs.task_drawer import TaskDrawer
- window = QWidget()
- qtbot.addWidget(window)
- window.resize(1000, 700)
- window.show()
- taskService = FakeTaskService()
- task = makeTask()
- drawer = TaskDrawer(task, taskService, FakeFeatureService(), FakeCategoryService(), window)
- drawer.show()
- qtbot.waitExposed(drawer)
- yield drawer, taskService, task
- window.close()
-
-
-def test_close_slides_out_then_destroys(opened, qtbot):
- drawer, _, _ = opened
-
- drawer.reject()
-
- assert isValid(drawer) and drawer.isVisible()
- qtbot.waitUntil(lambda: not isValid(drawer), timeout=2000)
-
-
-def test_removing_the_task_closes_drawer(opened, qtbot):
- drawer, taskService, task = opened
-
- taskService.taskRemoved.emit(task.taskId)
-
- qtbot.waitUntil(lambda: not isValid(drawer), timeout=2000)
-
-
-def test_other_task_removed_keeps_drawer(opened, qtbot):
- drawer, taskService, _ = opened
-
- taskService.taskRemoved.emit("tsk_other")
- qtbot.wait(500)
-
- assert isValid(drawer) and drawer.isVisible()