Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

feat(ui): add persistent folder playlists and floating controls

Veyra Goal Agente6ead9f10957
diff --git a/AGENTS.md b/AGENTS.md
index c0f7be1c..39e322f6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra 项目 Agent 执行规则
+> **2026-10-09 PR31 与播放列表授权**:用户要求处理 PR31 / issue21,播放列表采用文件夹导入、极简底栏按钮、可移动缩放浮窗、拖动排序/单项移除/名称排序/追加拖入/正在播放标记。按 docs/PR31_PLAYLIST_PLAN_2026-10-09.md 在 codex/pr31-playlist-20261009 隔离接入 PR31 的采集音频输出切换修复及必要 UI 模型/bridge/QML/构建/翻译/定向验收;这些具体接点覆盖旧冻结。基于已验字幕分支27cf4b4;独立 start/bundle 保护40既有工作树/495脏文件。产物全E盘、不制作测试包、不派Agent、不改驱动/用户配置/运行库原件。只做本次局部修改,不推进其它增强算法;本轮不发布、关机。每项测试≤300秒,构建≤900秒,当前主线及其它工作树不动。
+
> **2026-10-09 字幕格式修复授权**:用户要求修复PGS/SUP不显示并检查其它字幕格式,确认多位其他用户的内嵌PGS轨道显示不可用。按docs/SUBTITLE_FORMATS_PLAN_2026-10-09.md从main 0e7018ad在E盘codex/subtitle-formats-20261009隔离排查/修复共享字幕解码/加载/字幕层和必要bridge/菜单/翻译及定向验收,这些具体接点覆盖历史冻结。独立start/bundle保护39既有工作树/495脏文件;main与其它工作树保持,不改旧guard。所有产物E盘;原runtime/模型/SDK字节不变、不进Git;允许针对已复现的Matroska压缩PGS缺口,在E盘另行构建同版本patched FFmpeg,仅启用现有静态zlib、保留PS5 slices256/dav1d/原解码能力并记录对应源码/许可证/实际配置,不覆盖原件。此为字幕修复必要接点,不改proprietary运行库。不派Agent/造压,不改用户配置/驱动,无新merge/push/Release/版本更新/关机授权。现场视频未提供,不以公开样本冒充反馈者全部通过。
> **2026-10-09 HDR 补帧开关与 main 整合授权**:用户先要求将目前修复合入 main,再明确 HDR 补帧兼容必须改为设置页开关、默认关闭。按 docs/HDR_FG_COMPAT_TOGGLE_PLAN_2026-10-09.md 在当前 FG 隔离工作树修改必要呈现设置/bridge/QML/翻译及定向验收,覆盖这些接点的历史冻结。通过后允许本地 commit/checkpoint/main 合并 BMD、HDR 开关和对应诊断脚本/记录;不 push/Release/更新版本/关机,不派 Agent、不造压、不改运行库/模型/驱动/用户配置。39 工作树、495 脏文件按 archives/hdr-fg-toggle-20261009/start.json 保护,旧 guard/start 不改,产物全 E 盘;测试≤300秒、构建≤900秒。HDR 现场根因、5090 复测及 BMD 实卡/延迟仍未确认,不把兼容候选或开关测试冒充根治。
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 28e5842f..8122092d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -883,6 +883,7 @@ endif()
# never depend on Qt being installed.
if(VEYRA_BUILD_QML_UI AND Qt6_FOUND)
add_library(veyra_qml_bridge STATIC src/ui/QmlExportQueueModel.cpp include/veyra/ui/QmlExportQueueModel.h src/ui/QmlPlayerBridge.cpp src/ui/ThumbnailProvider.cpp
+ src/ui/PlaylistModel.cpp include/veyra/ui/PlaylistModel.h
include/veyra/ui/QmlPlayerBridge.h include/veyra/ui/ThumbnailProvider.h
# P4-c: the existing subtitle renderer, reused as-is (no second renderer).
apps/veyra/ui/SubtitleOverlay.cpp)
@@ -936,6 +937,21 @@ if(VEYRA_BUILD_QML_UI AND Qt6_FOUND)
# piece of the old shell worth keeping, and its own dialog is what users
# expect from a desktop app. No QWidget UI is created.
target_link_libraries(veyra_qml_bridge PUBLIC veyra_engine Qt6::Core Qt6::Gui Qt6::Qml Qt6::Quick Qt6::QuickControls2 Qt6::Widgets)
+ add_executable(veyra_playlist_tests tests/unit/PlaylistModelTests.cpp src/ui/PlaylistModel.cpp include/veyra/ui/PlaylistModel.h)
+ set_target_properties(veyra_playlist_tests PROPERTIES AUTOMOC ON)
+ target_compile_features(veyra_playlist_tests PRIVATE cxx_std_20)
+ target_compile_options(veyra_playlist_tests PRIVATE /utf-8)
+ target_include_directories(veyra_playlist_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
+ target_link_libraries(veyra_playlist_tests PRIVATE Qt6::Core)
+ find_package(Qt6 COMPONENTS Test)
+ if(TARGET Qt6::Test)
+ add_executable(veyra_playlist_window_tests tests/qml/PlaylistWindowTests.cpp)
+ target_compile_features(veyra_playlist_window_tests PRIVATE cxx_std_20)
+ target_compile_options(veyra_playlist_window_tests PRIVATE /utf-8)
+ target_include_directories(veyra_playlist_window_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
+ target_compile_definitions(veyra_playlist_window_tests PRIVATE VEYRA_QML_DIR="${CMAKE_CURRENT_SOURCE_DIR}/qml")
+ target_link_libraries(veyra_playlist_window_tests PRIVATE veyra_qml_bridge Qt6::Test)
+ endif()
# VEYRA_DISPLAY_VERSION is the human-readable version the app reports; it is
# the same value the resource file uses, so the UI cannot drift from it.
target_compile_definitions(veyra_qml_bridge PRIVATE VEYRA_DISPLAY_VERSION="${VEYRA_DISPLAY_VERSION}")
diff --git a/docs/PR31_PLAYLIST_PLAN_2026-10-09.md b/docs/PR31_PLAYLIST_PLAN_2026-10-09.md
new file mode 100644
index 00000000..34b91b54
--- /dev/null
+++ b/docs/PR31_PLAYLIST_PLAN_2026-10-09.md
@@ -0,0 +1,24 @@
+# PR31 / issue21 实施与验收
+
+用户要求:采集音频输出切换修复;播放列表支持文件夹导入、极简模式底栏入口、独立可移动/缩放窗口、拖动顺序、单项移除、名称排序、继续拖入其它目录文件和真实正在播放标记。issue21 另外涉及200部以上文件的时间/大小排序。
+
+## 范围与基线
+
+- 隔离工作树 E:/项目/Veyra/worktrees/pr31-playlist-20261009,分支 codex/pr31-playlist-20261009;起点27cf4b4包含未合并主线的已验字幕修复。
+- PR31 来源 Likely7/Veyra-NRVideo,作者GeT-LeFt,固定提交a0a3c098d72bb24bb46ffbadaa86fa8c5258e684,本地cherry-pick为51591bc。仅WORKLOG追加冲突,保留双方记录。上游报告不作为本机验收证据。
+- 开工不可变证据 E:/项目/Veyra/archives/pr31-playlist-20261009/start.json / source-before.bundle;保护40个原工作树和495个原脏文件。执行 scripts/acceptance/pr31-playlist-control.py 检查。
+- 新构建/测试/日志/临时文件分别在E:/项目/Veyra/{build,tests,logs,tmp,reports}/pr31-playlist-20261009。不制作测试包,不改用户真实配置或Windows默认设备,不修改SDK/runtime/模型原件。
+
+## 实现
+
+1. 保留PR31音频线程观察端点generation失效、沿原恢复流程重开;实际WASAPI静音PCM验证端点切换、重试及原回归。无实体采集卡结果时明确限制。
+2. UI层独立QAbstractListModel负责元数据、稳定路径身份、自然名称/时间/大小排序、重排、移除、去重和原子持久化。后台只扫描目录/文件信息,单工作线程、有界任务及列表,不逐文件探测媒体或解码。清空使旧导入结果失效,析构停止线程。符号链接/重解析目录不递归。
+3. 共享现有openPath及引擎运输状态,不新增解码循环。列表追加不切源;双击播放、上一项/下一项;只有当前文件真实Ended才顺序播放下一项,手动停止/失败/图片/直播不触发。排序、移除、晚到快照不误标当前项。
+4. 原生Qt独立工具窗口避开视频HWND覆盖,标题栏系统移动、八方向系统缩放;ListView虚拟化,拖动手柄重排、删除仅移除条目,文件/文件夹拖入追加。极简/全屏共享底栏加播放列表按钮,无片源时也能从载入入口导入文件夹。
+
+## 验证与交付
+
+- 编译当前GUI及生产模型/采集音频测试,重新生成修改过的Qt meta-object;沿用已验字幕FFmpeg与当前主线所有ABI相关对象,旧缓存只读核验。
+- 模型测试覆盖200+条目、后台返回/事件循环、嵌套/多文件夹/去重、自然/时间/大小排序、重排/当前项身份、仅移除不删磁盘、持久化、损坏配置、取消/销毁、缺失文件。
+- QML实际窗口交互及真实bridge回归验证按钮、尺寸、重排、追加不打断、播放/暂停标记、自然结束下一项和关闭行为;测试能证明什么就报告什么,不用伪模型替代真实播放证据。
+- 记录本机命令、结果、耗时、日志路径、失败修复及未验事项到报告和WORKLOG;最终审查diff/范围/原件哈希。用户已要求不用打测试包,本轮只交付代码及验收结果,不创建Release。
diff --git a/docs/PR31_PLAYLIST_REPORT_2026-10-09.md b/docs/PR31_PLAYLIST_REPORT_2026-10-09.md
new file mode 100644
index 00000000..64a6fbf3
--- /dev/null
+++ b/docs/PR31_PLAYLIST_REPORT_2026-10-09.md
@@ -0,0 +1,58 @@
+# PR31 与 issue21 本机实施结果
+
+## 结果
+
+已在 `codex/pr31-playlist-20261009` 完成代码接入、当前GUI构建和定向回归。本轮没有制作测试包,没有推送或发布,也没有改动main/其它工作树。起点27cf4b4已包含上一轮已验字幕修复,不能把本分支误当成只包含播放列表的主线补丁。
+
+PR31:https://github.com/Likely7/Veyra-NRVideo/pull/31 。作者GeT-LeFt,原提交a0a3c098d72bb24bb46ffbadaa86fa8c5258e684,本地接入51591bc,保留原作者。它属于本项目GPLv3源码贡献,未引入外部运行库。仅WORKLOG追加冲突,保留双方完整记录。
+
+issue21:https://github.com/Likely7/Veyra-NRVideo/issues/21 。本次实现用户追加的极简底栏入口、独立浮窗、拖入追加及播放标记,不止原issue的目录清单。
+
+## PR31适配
+
+原先选择新音频输出后,WASAPI端点generation失效不会必然让事件等待或填充缓冲报错,采集音频线程因此继续使用旧输出。补充检查 `renderer.lastError()`,沿原恢复函数在音频所属线程重开端点,文件播放已有类似检查。
+
+本机真实静音PCM/WASAPI会话验证A→B→A→系统默认,选择相同设备不重新初始化;输入持续增加,恢复后的缓冲有界。端点丢失、慢启动、瞬态转换与Xbox float/RTP原点回归通过。不改变Windows系统默认设备,不添加视频排队,不修改采集画面、NR、补帧或驱动。本机测试是合成PCM进入真实输出,不等于全部实体采集卡、USB扬声器或硬件端到端延迟验收。上游WORKLOG的硬件/耗时是作者的历史证据,未冒充本机结果。
+
+## 播放列表
+
+- 首页与极简/全屏共用底栏均有入口,未打开视频也可打开列表。
+- 独立Qt工具窗口由主播放器拥有,标题栏调用系统移动,四边/四角调用系统缩放;关闭列表仅隐藏,重新打开保留本次运行的位置/尺寸。
+- 导入文件夹包含子文件夹;添加文件或拖入文件/多文件/文件夹均追加。单个文件拖到主视频区域仍沿原拖放打开行为,多文件/文件夹放到主窗口进入列表。
+- `ListView`虚拟化;双击播放,左侧手柄拖动顺序并支持边缘自动滚动,单项移除/清空只改清单;上/下一项和定位当前文件按钮。
+- 自然名称顺序(2在10前)及逆序、修改时间、文件大小双向排序。路径身份不会因排序/移除其它行而变化。
+- 状态来自真实引擎会话,区分正在打开/正在播放/暂停/已播完/失败/图片查看;移除正在播放的条目不停止视频,也不把下一行误标正在播放。
+- 播完自动下一项可关闭,默认开启,只响应当前文件的真实Ended;手动停止、失败、图片和直播不触发。旧会话快照不跳过下一部,列表末尾不自动循环。
+- `playlist.v1.json`在现有应用数据目录原子保存顺序、元数据和续播选项;重启恢复列表,不伪造正在播放状态;缺失文件保留条目并明确提示。
+- 一个可取消后台线程只读取目录/文件元数据,最多10000条目、16个导入任务、单任务100000次目录项检查。跳过重解析/链接目录,清空会使旧结果失效。没有逐文件媒体解码/封面探测,没有新增播放器循环。
+- 补充简中/繁中/英文/日文文案。
+
+## 当前构建与本机证据
+
+所有产物均在 `E:/项目/Veyra/`,命令在当前隔离工作树执行。
+
+| 命令 | 结果与证据 |
+| --- | --- |
+| `py -3.11 -B scripts/acceptance/pr31-playlist-build.py` | GUI、音频测试、生产模型与窗口测试均编译/链接成功;28.406秒。重生成两个Q_OBJECT的meta-object;保留当前HDR/BMD与字幕全部必要对象,原缓存只读哈希核验。 |
+| `py -3.11 -B scripts/acceptance/pr31-playlist-test.py` | 7项均exit0:model/window/endpoint-switch/endpoint-loss/slow-start/transient/xbox-float-rtp。 |
+| `py -3.11 -B scripts/acceptance/pr31-playlist-gui-test.py all` | functional/next/english/empty四个实际播放器用例均exit0,36项检查,无QML/引擎错误。 |
+| `py -3.11 -B scripts/i18n/extract.py --check` | 新增41个来源键全部有三种翻译、占位符无错误;全项目遗留30个未翻译键与27cf4b4基线一致,未扩改。 |
+| `py -3.11 -B scripts/acceptance/pr31-playlist-control.py …` | 40既有工作树、495脏文件不变,本轮变更在白名单内;最终复核见reports目录。 |
+
+当前GUI SHA256:`5155C55D52B33BC445F5B61F2D872EEA9D41A57614B5DB9CAC1DC26E43123810`。
+
+- 构建回执:`E:/项目/Veyra/logs/pr31-playlist-20261009/build-20261009-143504/receipt.json`。
+- 本机测试回执:`E:/项目/Veyra/logs/pr31-playlist-20261009/tests-20261009-143640/receipt.json`。
+- 模型1642个断言通过,包含fixture生成、321条目逐行检查、元数据排序、持久化逐行一致、删除不删文件、取消/销毁/去重/缺失/损坏配置等;不是1642个独立功能场景。提交导入调用0毫秒,后台扫描321文件11毫秒,导入期间UI计时器继续运行。仅代表本机热缓存目录元数据测试,不是媒体解码或所有硬盘性能。
+- 窗口23个检查通过,使用真实生产模型、Qt鼠标事件与原生URL拖放事件,覆盖重排、双击、删除、文件夹/多文件/单文件拖入、尺寸适配、关闭再开和所属窗口关闭。
+- GUI证据:`gui-functional-20261009-143727`、`gui-next-20261009-143733`、`gui-english-20261009-143740`、`gui-empty-20261009-143746`,均在同一logs目录。输入为既有20秒测试影片的硬链接,使用私有配置与私有app;原便携包1614文件每次前后哈希不变。
+
+## 排查中修正与边界
+
+1. 新工作树的Git CRLF转换导致旧构建来源字节哈希不同。构建脚本只允许原件回执哈希匹配且逐字节规范化换行后内容完全相等的复用,没有绕过源代码身份校验。
+2. 初版窗口测试把原生C++ QQuickWindow传给QML Window属性,类型不匹配。测试宿主改为真实QML Window,随后验证实际窗口交互;该次失败没有当通过处理。
+3. 原生URL拖入的QML→C++转换用QVariantList时没有添加条目;改为明确的QList<QUrl>,文件夹/多文件/单文件原生事件均通过。主窗口也使用相同明确类型。
+4. 移除后旧导入摘要中的总数会过期,现移除时清除该摘要;JSON数值改用安全整数读取,避免异常数值转换。
+5. 尚未实测实体采集卡换输出、操作系统标题栏持续拖动/四角拖拽、多显示器/DPI组合与全部媒体格式。已验证系统API接线、程序调整尺寸后的布局和本机GUI,不扩大为全设备通过。
+
+GUI/测试/脚本源文件及对应回执已保留;没有SDK、DLL、模型、用户配置或私有媒体进入源码Git。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index f3a48b9f..112cd014 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -8914,3 +8914,17 @@ documented user-data was migrated, with a separate rollback copy; the
complete official application remains available. Public contribution is
source/test/documentation only, with no user data, endpoint IDs, logs,
media, SDK files or runtime binaries.
+
+## 2026-10-09 PR31 / issue21 播放列表(本机后续实施)
+
+用户要求处理PR31与issue21,追加文件夹导入、极简底栏入口、自由移动缩放浮窗、拖动排序/移除/名称排序/继续拖入与正在播放标记;沿用此前“不用打测试包”。本段是本机执行结果,上面的PR作者历史记录不作为本机硬件证据。
+
+- 工作树 `E:/项目/Veyra/worktrees/pr31-playlist-20261009`,分支 `codex/pr31-playlist-20261009`,基线27cf4b4(含上一轮已验字幕修复)。不可变存档 `E:/项目/Veyra/archives/pr31-playlist-20261009/start.json` 与 `source-before.bundle`,保护40原工作树/495脏文件;main保留0e7018ad。计划与报告:`docs/PR31_PLAYLIST_PLAN_2026-10-09.md` / `docs/PR31_PLAYLIST_REPORT_2026-10-09.md`。
+- PR31原提交a0a3c098d72bb24bb46ffbadaa86fa8c5258e684,保留作者接入为51591bc。WORKLOG仅追加冲突,双方记录均保留。代码观察采集音频renderer端点generation失效并沿原音频线程恢复流程重开。
+- 新生产PlaylistModel负责后台元数据导入、自然名称/时间/大小排序、稳定路径身份、重排/去重/仅移除清单、原子持久化及有界取消。PlaylistWindow为原生owned工具窗口,ListView虚拟化,系统移动/八方向缩放API、双击播放、上/下一项/定位、拖放追加、自动续播开关;首页与极简/全屏底栏接入。共享原openPath与真实TransportState/sessionId,未改解码/NR/补帧/导出算法。
+- `py -3.11 -B scripts/acceptance/pr31-playlist-build.py`:当前GUI与3个测试程序构建成功,28.406秒;回执 `E:/项目/Veyra/logs/pr31-playlist-20261009/build-20261009-143504/receipt.json`。两个Q_OBJECT重新生成;保留全部当前HDR/BMD/字幕对象及已验zlib版同版本FFmpeg,不写旧缓存。GUI SHA256 `5155C55D52B33BC445F5B61F2D872EEA9D41A57614B5DB9CAC1DC26E43123810`。
+- `py -3.11 -B scripts/acceptance/pr31-playlist-test.py`:7项全部exit0;回执 `E:/项目/Veyra/logs/pr31-playlist-20261009/tests-20261009-143640/receipt.json`。生产模型1642断言(含fixture与逐行一致检查),321文件导入提交0ms、后台扫描11ms、导入期间UI计时器继续运行;Qt窗口23检查,包括真实鼠标重排/双击/移除及原生URL文件夹/多文件/单文件追加。真实静音WASAPI A→B→A→默认/重复同设备、端点丢失、慢启动、瞬态及Xbox float/RTP回归均通过;未改Windows默认端点。
+- `py -3.11 -B scripts/acceptance/pr31-playlist-gui-test.py all`:当前GUI actual bridge四用例通过,36项检查。回执在同一logs目录的 `gui-functional-20261009-143727` / `gui-next-20261009-143733` / `gui-english-20261009-143740` / `gui-empty-20261009-143746`。验证追加不改视频/进度/暂停、重排/移除不误标、真实结束只推进一次、手动停止不续播、空片源入口与英文;私有配置/硬链接app,原便携包1614文件每次前后SHA不变。
+- 翻译 `py -3.11 -B scripts/i18n/extract.py --check`:placeholder问题0。新增41个来源键全部有繁中/英文/日文;全项目30个遗留缺译与基线相同,未顺手扩改。
+- 排查修正:Git autocrlf来源只允许在原件回执SHA匹配且规范换行内容完全相等时复用;测试宿主C++/QML Window类型不匹配改为真实QML宿主;拖放QVariantList没有添加条目改为明确QList<QUrl>并原生事件回归;移除后的过期总数摘要清除,异常JSON数值安全读取。初次失败日志保留,均未当成通过。
+- 产物:`E:/项目/Veyra/{build,tests,logs,tmp,reports,archives}/pr31-playlist-20261009`;同名受控目录,无测试包/整工程备份,无运行库字节改动或二进制入Git。实体采集卡换输出、OS持续拖动/多显示器/DPI与全部媒体未实测;不宣称全设备通过。本轮未修改main、推送、关闭远端PR/issue、发布、关机或派Agent。
diff --git a/i18n/catalog.json b/i18n/catalog.json
index 180c650f..4e47e8f9 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -14456,6 +14456,293 @@
"zh-TW": "文字字幕超過 16 MiB 上限",
"en": "Text subtitles exceed the 16 MiB limit",
"ja": "テキスト字幕が 16 MiB の上限を超えています"
+ },
+ {
+ "zh": "%1 项",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "%1 項",
+ "en": "%1 items",
+ "ja": "%1 件"
+ },
+ {
+ "zh": "上一项",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "上一項",
+ "en": "Previous item",
+ "ja": "前の項目"
+ },
+ {
+ "zh": "下一项",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "下一項",
+ "en": "Next item",
+ "ja": "次の項目"
+ },
+ {
+ "zh": "仅清空列表,不删除硬盘文件",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "僅清空清單,不刪除硬碟檔案",
+ "en": "Clear playlist; keep files on disk",
+ "ja": "リストのみクリア。ファイルは削除しません"
+ },
+ {
+ "zh": "从列表移除,不删除文件",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "從清單移除,不刪除檔案",
+ "en": "Remove from playlist; keep file",
+ "ja": "リストから削除。ファイルは保持します"
+ },
+ {
+ "zh": "修改时间:新 → 旧",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "修改時間:新 → 舊",
+ "en": "Modified: newest first",
+ "ja": "更新日時:新しい順"
+ },
+ {
+ "zh": "修改时间:旧 → 新",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "修改時間:舊 → 新",
+ "en": "Modified: oldest first",
+ "ja": "更新日時:古い順"
+ },
+ {
+ "zh": "列表或导入任务已达上限,请稍后重试或移除部分条目",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "清單或匯入工作已達上限,請稍後重試或移除部分項目",
+ "en": "Playlist or import queue is full. Try later or remove some items.",
+ "ja": "リストまたは追加待ちが上限に達しました。後で再試行するか、項目を削除してください。"
+ },
+ {
+ "zh": "名称 A → Z",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "名稱 A → Z",
+ "en": "Name A → Z",
+ "ja": "名前 A → Z"
+ },
+ {
+ "zh": "名称 Z → A",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "名稱 Z → A",
+ "en": "Name Z → A",
+ "ja": "名前 Z → A"
+ },
+ {
+ "zh": "媒体文件 (*.mp4 *.mkv *.mov *.avi *.webm *.ts *.m2ts *.mts *.m4v *.wmv *.mpg *.mpeg *.vob *.flv *.ogv *.asf *.3gp *.jpg *.jpeg *.png *.bmp *.webp);;所有文件 (*)",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "媒體檔案 (*.mp4 *.mkv *.mov *.avi *.webm *.ts *.m2ts *.mts *.m4v *.wmv *.mpg *.mpeg *.vob *.flv *.ogv *.asf *.3gp *.jpg *.jpeg *.png *.bmp *.webp);;所有檔案 (*)",
+ "en": "Media files (*.mp4 *.mkv *.mov *.avi *.webm *.ts *.m2ts *.mts *.m4v *.wmv *.mpg *.mpeg *.vob *.flv *.ogv *.asf *.3gp *.jpg *.jpeg *.png *.bmp *.webp);;All files (*)",
+ "ja": "メディアファイル (*.mp4 *.mkv *.mov *.avi *.webm *.ts *.m2ts *.mts *.m4v *.wmv *.mpg *.mpeg *.vob *.flv *.ogv *.asf *.3gp *.jpg *.jpeg *.png *.bmp *.webp);;すべてのファイル (*)"
+ },
+ {
+ "zh": "定位正在播放的文件",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "定位正在播放的檔案",
+ "en": "Show current file",
+ "ja": "再生中のファイルを表示"
+ },
+ {
+ "zh": "导入文件夹",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "匯入資料夾",
+ "en": "Import folder",
+ "ja": "フォルダーを追加"
+ },
+ {
+ "zh": "导入文件夹到播放列表",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "匯入資料夾至播放清單",
+ "en": "Import folder into playlist",
+ "ja": "プレイリストにフォルダーを追加"
+ },
+ {
+ "zh": "导入文件夹,或将文件 / 文件夹拖到这里\n支持子文件夹 · 双击播放 · 拖动左侧手柄调整顺序",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "匯入資料夾,或將檔案 / 資料夾拖到這裡\n支援子資料夾 · 按兩下播放 · 拖曳左側把手調整順序",
+ "en": "Import a folder, or drop files / folders here\nIncludes subfolders · Double-click to play · Drag the left handle to reorder",
+ "ja": "フォルダーを追加するか、ファイル / フォルダーをドロップ\nサブフォルダー対応 · ダブルクリックで再生 · 左のハンドルで並べ替え"
+ },
+ {
+ "zh": "已停止",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "已停止",
+ "en": "Stopped",
+ "ja": "停止中"
+ },
+ {
+ "zh": "已播完",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "已播完",
+ "en": "Finished",
+ "ja": "再生終了"
+ },
+ {
+ "zh": "已添加 %1 项 · 列表共 %2 项",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "已新增 %1 項 · 清單共 %2 項",
+ "en": "Added %1 items · %2 total",
+ "ja": "%1 件追加 · 合計 %2 件"
+ },
+ {
+ "zh": "已达到导入上限(最多10000项),其余文件未添加",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "已達到匯入上限(最多10000項),其餘檔案未新增",
+ "en": "Import limit reached (10,000 items). Remaining files were not added.",
+ "ja": "追加の上限(10,000 件)に達しました。残りのファイルは追加されていません。"
+ },
+ {
+ "zh": "手动顺序",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "手動順序",
+ "en": "Custom order",
+ "ja": "手動の順序"
+ },
+ {
+ "zh": "拖入只追加列表,不打断当前播放",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "拖入僅追加清單,不中斷目前播放",
+ "en": "Drops append without interrupting playback",
+ "ja": "追加しても現在の再生は中断しません"
+ },
+ {
+ "zh": "播完后播放下一项",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "播完後播放下一項",
+ "en": "Play next when finished",
+ "ja": "終了後に次の項目を再生"
+ },
+ {
+ "zh": "播放列表",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "播放清單",
+ "en": "Playlist",
+ "ja": "プレイリスト"
+ },
+ {
+ "zh": "播放列表 · 导入文件夹",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "播放清單 · 匯入資料夾",
+ "en": "Playlist · Import folder",
+ "ja": "プレイリスト · フォルダーを追加"
+ },
+ {
+ "zh": "播放列表保存失败:%1",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "播放清單儲存失敗:%1",
+ "en": "Could not save playlist: %1",
+ "ja": "プレイリストを保存できません:%1"
+ },
+ {
+ "zh": "播放列表文件损坏,已使用空列表",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "播放清單檔案損壞,已使用空清單",
+ "en": "Playlist file is damaged; using an empty list.",
+ "ja": "プレイリストが破損しているため、空のリストを使用します。"
+ },
+ {
+ "zh": "播放列表文件无法读取,已使用空列表",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "播放清單檔案無法讀取,已使用空清單",
+ "en": "Could not read playlist; using an empty list.",
+ "ja": "プレイリストを読み込めないため、空のリストを使用します。"
+ },
+ {
+ "zh": "播放失败",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "播放失敗",
+ "en": "Playback failed",
+ "ja": "再生に失敗"
+ },
+ {
+ "zh": "文件不存在或已移动:%1",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "檔案不存在或已移動:%1",
+ "en": "File missing or moved: %1",
+ "ja": "ファイルが見つからないか移動されています:%1"
+ },
+ {
+ "zh": "文件大小:大 → 小",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "檔案大小:大 → 小",
+ "en": "Size: largest first",
+ "ja": "サイズ:大きい順"
+ },
+ {
+ "zh": "文件大小:小 → 大",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "檔案大小:小 → 大",
+ "en": "Size: smallest first",
+ "ja": "サイズ:小さい順"
+ },
+ {
+ "zh": "未添加新条目:文件已在列表中,或没有支持的媒体文件",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "未新增項目:檔案已在清單中,或沒有支援的媒體檔案",
+ "en": "No new items: files are already listed or no supported media was found.",
+ "ja": "新しい項目はありません。登録済みか、対応するメディアが見つかりませんでした。"
+ },
+ {
+ "zh": "松开以追加到播放列表",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "放開以追加至播放清單",
+ "en": "Drop to append to playlist",
+ "ja": "ドロップしてプレイリストに追加"
+ },
+ {
+ "zh": "正在打开",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "正在開啟",
+ "en": "Opening",
+ "ja": "読み込み中"
+ },
+ {
+ "zh": "正在扫描文件夹…",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "正在掃描資料夾…",
+ "en": "Scanning folders…",
+ "ja": "フォルダーをスキャン中…"
+ },
+ {
+ "zh": "正在播放",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "正在播放",
+ "en": "Playing",
+ "ja": "再生中"
+ },
+ {
+ "zh": "正在查看",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "正在檢視",
+ "en": "Viewing",
+ "ja": "表示中"
+ },
+ {
+ "zh": "添加文件",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "新增檔案",
+ "en": "Add files",
+ "ja": "ファイルを追加"
+ },
+ {
+ "zh": "添加文件到播放列表",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "新增檔案至播放清單",
+ "en": "Add files to playlist",
+ "ja": "プレイリストにファイルを追加"
+ },
+ {
+ "zh": "排序",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "排序",
+ "en": "Sort",
+ "ja": "並べ替え"
+ },
+ {
+ "zh": "关闭窗口",
+ "src": "qml/Veyra/PlaylistWindow.qml; src/ui/PlaylistModel.cpp",
+ "zh-TW": "關閉視窗",
+ "en": "Close window",
+ "ja": "ウィンドウを閉じる"
}
]
}
diff --git a/include/veyra/ui/PlaylistModel.h b/include/veyra/ui/PlaylistModel.h
new file mode 100644
index 00000000..ef0a3da1
--- /dev/null
+++ b/include/veyra/ui/PlaylistModel.h
@@ -0,0 +1,94 @@
+#pragma once
+#include <QAbstractListModel>
+#include <QSet>
+#include <QStringList>
+#include <QTimer>
+#include <QVariantList>
+#include <QUrl>
+#include <atomic>
+#include <condition_variable>
+#include <deque>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+namespace veyra::ui {
+// UI-owned metadata only. Directory enumeration runs on one cancellable worker;
+// playback continues through QmlPlayerBridge's existing openPath/transport.
+class PlaylistModel final : public QAbstractListModel {
+ Q_OBJECT
+ Q_PROPERTY(int count READ count NOTIFY countChanged)
+ Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)
+ Q_PROPERTY(QString status READ status NOTIFY statusChanged)
+ Q_PROPERTY(int currentIndex READ currentIndex NOTIFY currentChanged)
+ Q_PROPERTY(int sortMode READ sortMode NOTIFY sortModeChanged)
+ Q_PROPERTY(bool autoAdvance READ autoAdvance WRITE setAutoAdvance NOTIFY autoAdvanceChanged)
+public:
+ enum Role { NameRole = Qt::UserRole + 1, PathRole, SizeRole, ModifiedRole, CurrentRole, StateRole };
+ enum Sort { Manual, NameAscending, NameDescending, NewestFirst, OldestFirst, LargestFirst, SmallestFirst };
+ Q_ENUM(Sort)
+ explicit PlaylistModel(QString storageFile = {}, QObject* parent = nullptr);
+ ~PlaylistModel() override;
+ int rowCount(const QModelIndex& parent = {}) const override;
+ QVariant data(const QModelIndex& index, int role) const override;
+ QHash<int, QByteArray> roleNames() const override;
+ int count() const { return int(entries_.size()); }
+ bool busy() const { return pending_ > 0; }
+ QString status() const { return status_; }
+ int currentIndex() const;
+ int sortMode() const { return sort_; }
+ bool autoAdvance() const { return autoAdvance_; }
+ void setAutoAdvance(bool enabled);
+ static bool supported(const QString& path);
+ static QString normalizedPath(const QString& path);
+ bool containsPath(const QString& path) const { return keys_.contains(keyOf(path)); }
+ void setPlayback(const QString& path, const QString& state);
+ // Returns false at the ends: never silently wraps or restarts the same file.
+ bool advanceAfterEnd();
+ Q_INVOKABLE void addPaths(const QStringList& paths);
+ Q_INVOKABLE void addUrls(const QList<QUrl>& urls);
+ Q_INVOKABLE QString pathAt(int row) const;
+ Q_INVOKABLE int indexOfPath(const QString& path) const;
+ Q_INVOKABLE bool play(int row);
+ Q_INVOKABLE bool next();
+ Q_INVOKABLE bool previous();
+ Q_INVOKABLE bool move(int from, int to);
+ Q_INVOKABLE bool remove(int row);
+ Q_INVOKABLE void clear();
+ Q_INVOKABLE void sortBy(int mode);
+ Q_INVOKABLE bool save();
+signals:
+ void countChanged();
+ void busyChanged();
+ void statusChanged();
+ void currentChanged();
+ void sortModeChanged();
+ void autoAdvanceChanged();
+ void playRequested(const QString& path);
+ void error(const QString& text);
+private:
+ struct Entry { QString path, name, key; qint64 size = 0, modified = 0; };
+ struct Job { QStringList paths; uint64_t generation = 0; };
+ struct Result { std::vector<Entry> entries; int skipped = 0; bool limited = false; };
+ static QString keyOf(const QString& path);
+ static void order(std::vector<Entry>& entries, int mode);
+ Result scan(const Job& job, std::stop_token stop) const;
+ void workerLoop(std::stop_token stop);
+ void accept(Result result, uint64_t generation);
+ void setStatus(QString text);
+ void load();
+ bool playFrom(int row, int direction);
+ QString storage_, status_, currentKey_, state_;
+ std::vector<Entry> entries_;
+ QSet<QString> keys_;
+ QTimer saveTimer_;
+ int pending_ = 0, sort_ = Manual;
+ bool autoAdvance_ = true;
+ std::atomic<uint64_t> generation_{1};
+ std::mutex mutex_;
+ std::condition_variable_any wake_;
+ std::deque<Job> jobs_;
+ // Declared last; destructor explicitly joins before QObject destruction.
+ std::jthread worker_;
+};
+}
diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.h
index 0f029e3f..0dfb0907 100644
--- a/include/veyra/ui/QmlPlayerBridge.h
+++ b/include/veyra/ui/QmlPlayerBridge.h
@@ -399,6 +399,7 @@ class QmlPlayerBridge : public QObject {
// --- dialogs the UI opens ----------------------------------------------
Q_PROPERTY(QVariantList recentFiles READ recentFiles NOTIFY recentFilesChanged)
+ Q_PROPERTY(QObject* playlist READ playlist CONSTANT)
Q_PROPERTY(QVariantList presets READ presets NOTIFY presetsChanged)
// The name of the preset currently in effect, or "自定义" when the
// settings no longer match any stored preset. Derived, never guessed.
@@ -475,6 +476,11 @@ class QmlPlayerBridge : public QObject {
Q_PROPERTY(QVariantList colourLooks READ colourLooks NOTIFY colourLibraryChanged)
public:
+ QObject* playlist() const;
+ Q_INVOKABLE void showPlaylist();
+ Q_INVOKABLE void addPlaylistFilesDialog();
+ Q_INVOKABLE void addPlaylistFolderDialog();
+ Q_INVOKABLE void openDroppedUrls(const QList<QUrl>& urls);
bool amdNrGpu() const;
QVariantMap effectCapabilities() const;
QVariantList nrRuntimeChoices() const;
@@ -1078,6 +1084,7 @@ public:
Q_INVOKABLE void copyDiagnostics();
signals:
+ void playlistRequested();
void nodeAnchorsChanged();
void ps5Changed();
void moonlightUiChanged();
@@ -1148,6 +1155,7 @@ private:
void tickPs5();
void tickMoonlight();
void tickXbox();
+ void tickPlaylist();
#ifdef VEYRA_ENABLE_XBOX
void setupXbox();
#endif
diff --git a/qml/Veyra/CineBar.qml b/qml/Veyra/CineBar.qml
index 77575af1..2b5a2478 100644
--- a/qml/Veyra/CineBar.qml
+++ b/qml/Veyra/CineBar.qml
@@ -20,6 +20,7 @@ Rectangle {
// Windowed 极简: a drag on the pill's empty space moves the window, like a title bar.
signal requestMove()
signal requestHide()
+ signal requestPlaylist()
// Set on the fullscreen bar: shows the lock button.
property bool fullscreen: false
// Set by FullscreenBar so upward menus stop above the playback pill.
@@ -114,6 +115,12 @@ Rectangle {
elide: Text.ElideRight
}
}
+ VButton {
+ objectName: "cine-playlist"
+ icon: true; iconName: "list"; tip: qsTr("播放列表")
+ implicitWidth: 32; implicitHeight: 32
+ onClicked: bar.requestPlaylist()
+ }
}
// --- middle: transport + seek --------------------------------
diff --git a/qml/Veyra/FullscreenBar.qml b/qml/Veyra/FullscreenBar.qml
index 6aec96be..735a0eeb 100644
--- a/qml/Veyra/FullscreenBar.qml
+++ b/qml/Veyra/FullscreenBar.qml
@@ -24,6 +24,7 @@ Window {
signal requestLock()
signal requestMove()
signal requestHide()
+ signal requestPlaylist()
// Pointer movement over the bar keeps the controls up (the main window cannot
// see it here).
signal activity()
@@ -116,6 +117,7 @@ Window {
onRequestLock: win.requestLock()
onRequestMove: win.requestMove()
onRequestHide: win.requestHide()
+ onRequestPlaylist: win.requestPlaylist()
HoverHandler {
// Real movement only: hover repeats while the bar animates.
property point last: Qt.point(-1, -1)
diff --git a/qml/Veyra/HomePage.qml b/qml/Veyra/HomePage.qml
index 67918bdf..76a284b7 100644
--- a/qml/Veyra/HomePage.qml
+++ b/qml/Veyra/HomePage.qml
@@ -85,6 +85,13 @@ VPage {
}
}
+ VButton {
+ objectName: "home-playlist"
+ Layout.alignment: Qt.AlignHCenter
+ text: qsTr("播放列表 · 导入文件夹"); iconName: "list"
+ onClicked: veyra.showPlaylist()
+ }
+
// .srcgrid: 164px cards, gap 12. Six cards since PC and Xbox streaming (1044 wide,
// fits a 1280 window); a narrower window wraps them onto a second row.
Flow {
diff --git a/qml/Veyra/Main.qml b/qml/Veyra/Main.qml
index f006c9ff..442ff0b9 100644
--- a/qml/Veyra/Main.qml
+++ b/qml/Veyra/Main.qml
@@ -363,7 +363,7 @@ Window {
onDropped: drop => {
if (!drop.hasUrls || drop.urls.length === 0) return
drop.accept(Qt.CopyAction)
- veyra.openUrl(drop.urls[0])
+ veyra.openDroppedUrls(drop.urls)
}
}
@@ -551,6 +551,13 @@ Window {
y: root.fullscreen ? 16 : 52
z: 90
}
+ PlaylistWindow {
+ id: playlistWindow
+ owner: root
+ playlist: veyra.playlist
+ onAddFiles: veyra.addPlaylistFilesDialog()
+ onAddFolder: veyra.addPlaylistFolderDialog()
+ }
FullscreenBar {
id: fullBar
owner: root
@@ -567,6 +574,7 @@ Window {
onRequestFullscreen: root.toggleFullscreen()
onRequestLock: root.toggleLock()
onRequestHide: root.setPillHidden(true)
+ onRequestPlaylist: playlistWindow.toggle()
onRequestMove: if (!root.fullscreen && !root.maximized) root.startSystemMove()
onActivity: root.pointerActivity()
}
@@ -685,6 +693,7 @@ Window {
Connections {
target: veyra
+ function onPlaylistRequested() { playlistWindow.open() }
function onNotice(text, isError) { toast.show(text, isError) }
function onOverlayRestartSuggested() { overlayRestart.open() }
function onNavigate(p) {
diff --git a/qml/Veyra/PlaylistWindow.qml b/qml/Veyra/PlaylistWindow.qml
new file mode 100644
index 00000000..c82fd396
--- /dev/null
+++ b/qml/Veyra/PlaylistWindow.qml
@@ -0,0 +1,304 @@
+// Native owned window: the D3D12 video HWND cannot cover the playlist.
+import QtQuick
+import QtQuick.Window
+import QtQuick.Controls
+import QtQuick.Layouts
+
+Window {
+ id: win
+ objectName: "playlistWindow"
+ required property Window owner
+ required property var playlist
+ signal addFiles()
+ signal addFolder()
+ transientParent: owner
+ flags: Qt.Tool | Qt.FramelessWindowHint
+ color: "transparent"
+ width: 500; height: 600
+ minimumWidth: 420; minimumHeight: 320
+ property bool positioned: false
+ property string selectedPath: ""
+ property string dragPath: ""
+ property real dragY: 0
+ property bool dragging: false
+ property string failure: ""
+ readonly property var sortOptions: [
+ { id: "0", label: qsTr("手动顺序") },
+ { id: "1", label: qsTr("名称 A → Z") }, { id: "2", label: qsTr("名称 Z → A") },
+ { id: "3", label: qsTr("修改时间:新 → 旧") }, { id: "4", label: qsTr("修改时间:旧 → 新") },
+ { id: "5", label: qsTr("文件大小:大 → 小") }, { id: "6", label: qsTr("文件大小:小 → 大") }
+ ]
+ function open() {
+ if (!positioned) {
+ const s = owner.screen
+ const right = s ? s.virtualX + s.width : owner.x + owner.width
+ const bottom = s ? s.virtualY + s.height : owner.y + owner.height
+ x = Math.max(s ? s.virtualX : 0, Math.min(owner.x + owner.width - width - 24, right - width))
+ y = Math.max(s ? s.virtualY : 0, Math.min(owner.y + 60, bottom - height))
+ positioned = true
+ }
+ show(); raise(); requestActivate()
+ }
+ function toggle() { if (visible) hide(); else open() }
+ function removeSelected() {
+ const row = playlist.indexOfPath(selectedPath)
+ if (row >= 0) playlist.remove(row)
+ }
+ function finishDrag(commit) {
+ if (dragging && commit) {
+ let target = list.indexAt(list.width / 2, dragY + list.contentY)
+ if (target < 0) target = dragY < list.height / 2 ? 0 : playlist.count - 1
+ playlist.move(playlist.indexOfPath(dragPath), target)
+ }
+ dragging = false; dragPath = ""
+ }
+ onClosing: event => { event.accepted = false; hide() }
+ onVisibleChanged: if (!visible) finishDrag(false)
+ Connections {
+ target: win.playlist
+ function onError(text) { win.failure = text; errorTimer.restart() }
+ }
+ Connections {
+ target: win.owner
+ function onClosing(event) { win.hide() }
+ }
+ Timer { id: errorTimer; interval: 6000; onTriggered: win.failure = "" }
+ Shortcut { sequence: "Escape"; onActivated: win.hide() }
+ Shortcut { sequence: "Delete"; onActivated: win.removeSelected() }
+ Shortcut {
+ sequence: "Return"
+ onActivated: win.playlist.play(win.playlist.indexOfPath(win.selectedPath))
+ }
+
+ Rectangle {
+ anchors.fill: parent
+ radius: Theme.rWindow
+ color: Theme.dialog
+ border.width: 1; border.color: Theme.stroke2
+ ColumnLayout {
+ anchors.fill: parent; anchors.margins: 14
+ spacing: 10
+ Item {
+ Layout.fillWidth: true; implicitHeight: 34
+ MouseArea {
+ objectName: "playlist-title-drag"
+ anchors.fill: parent
+ onPressed: win.startSystemMove()
+ }
+ RowLayout {
+ anchors.fill: parent; spacing: 8
+ VIcon { name: "list"; size: 19; color: Theme.accent }
+ Text {
+ text: qsTr("播放列表")
+ font.family: Theme.fontUi; font.pixelSize: 16; font.weight: Font.DemiBold
+ color: Theme.t1
+ }
+ Text { text: qsTr("%1 项").arg(win.playlist.count); font.pixelSize: 11; color: Theme.t3 }
+ Item { Layout.fillWidth: true }
+ VButton {
+ objectName: "playlist-close"
+ icon: true; iconName: "x"; ghost: true; tip: qsTr("关闭窗口")
+ onClicked: win.hide()
+ }
+ }
+ }
+ RowLayout {
+ Layout.fillWidth: true; spacing: 8
+ VButton { objectName: "playlist-add-folder"; text: qsTr("导入文件夹"); iconName: "folder"; primary: true; onClicked: win.addFolder() }
+ VButton { objectName: "playlist-add-files"; text: qsTr("添加文件"); iconName: "plus"; onClicked: win.addFiles() }
+ Item { Layout.fillWidth: true }
+ VButton {
+ objectName: "playlist-clear"
+ text: qsTr("清空"); ghost: true; enabled: win.playlist.count > 0 || win.playlist.busy
+ tip: qsTr("仅清空列表,不删除硬盘文件")
+ onClicked: { win.playlist.clear(); win.selectedPath = ""; win.finishDrag(false) }
+ }
+ }
+ RowLayout {
+ Layout.fillWidth: true; spacing: 8
+ VSelect {
+ objectName: "playlist-sort"
+ Layout.fillWidth: true
+ title: qsTr("排序")
+ options: win.sortOptions
+ value: win.sortOptions[win.playlist.sortMode].label
+ enabled: !win.dragging
+ onPicked: id => win.playlist.sortBy(Number(id))
+ }
+ VButton { objectName: "playlist-previous"; icon: true; iconName: "left"; tip: qsTr("上一项"); enabled: win.playlist.count > 0; onClicked: win.playlist.previous() }
+ VButton { objectName: "playlist-next"; icon: true; iconName: "right"; tip: qsTr("下一项"); enabled: win.playlist.count > 0; onClicked: win.playlist.next() }
+ VButton {
+ objectName: "playlist-locate"
+ icon: true; iconName: "play"; tip: qsTr("定位正在播放的文件")
+ enabled: win.playlist.currentIndex >= 0
+ onClicked: list.positionViewAtIndex(win.playlist.currentIndex, ListView.Contain)
+ }
+ }
+ Item {
+ Layout.fillWidth: true; Layout.fillHeight: true; Layout.minimumHeight: 80
+ ListView {
+ id: list
+ objectName: "playlist-list"
+ anchors.fill: parent; clip: true; spacing: 4
+ model: win.playlist
+ boundsBehavior: Flickable.StopAtBounds
+ ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded }
+ delegate: Rectangle {
+ id: row
+ required property int index
+ required property string entryName
+ required property string entryPath
+ required property string entrySize
+ required property string entryModified
+ required property bool entryCurrent
+ required property string entryState
+ objectName: "playlist-row-" + index
+ width: list.width - 10; height: 64; radius: 9
+ color: win.selectedPath === entryPath ? Theme.card3 : entryCurrent ? Theme.accentSoft : rowMouse.containsMouse ? Theme.card2 : "transparent"
+ border.width: 1
+ border.color: win.dragging && win.dragPath === entryPath ? Theme.accent : "transparent"
+ MouseArea {
+ id: rowMouse
+ objectName: "playlist-select-" + row.index
+ anchors.fill: parent; anchors.leftMargin: 32; anchors.rightMargin: 40
+ hoverEnabled: true
+ onClicked: win.selectedPath = row.entryPath
+ onDoubleClicked: win.playlist.play(row.index)
+ ToolTip.visible: containsMouse && !win.dragging
+ ToolTip.delay: 900
+ ToolTip.text: row.entryPath
+ }
+ Item {
+ width: 32; height: parent.height
+ VIcon { anchors.centerIn: parent; name: "grip"; size: 16; color: Theme.t3 }
+ MouseArea {
+ objectName: "playlist-grip-" + row.index
+ anchors.fill: parent; cursorShape: pressed ? Qt.ClosedHandCursor : Qt.OpenHandCursor
+ preventStealing: true
+ property real startY: 0
+ onPressed: mouse => {
+ win.selectedPath = row.entryPath; win.dragPath = row.entryPath
+ startY = mapToItem(list, mouse.x, mouse.y).y; win.dragY = startY
+ }
+ onPositionChanged: mouse => {
+ if (!pressed) return
+ win.dragY = mapToItem(list, mouse.x, mouse.y).y
+ if (Math.abs(win.dragY - startY) > 5) win.dragging = true
+ }
+ onReleased: win.finishDrag(true)
+ onCanceled: win.finishDrag(false)
+ }
+ }
+ ColumnLayout {
+ anchors.left: parent.left; anchors.leftMargin: 36
+ anchors.right: parent.right; anchors.rightMargin: 42
+ anchors.verticalCenter: parent.verticalCenter; spacing: 4
+ RowLayout {
+ Layout.fillWidth: true; spacing: 6
+ Text {
+ Layout.fillWidth: true
+ text: row.entryName; elide: Text.ElideRight; color: row.entryCurrent ? Theme.accent : Theme.t1
+ font.family: Theme.fontUi; font.pixelSize: 12
+ }
+ Text {
+ objectName: "playlist-state-" + row.index
+ visible: row.entryCurrent
+ text: {
+ switch (row.entryState) {
+ case "playing": return qsTr("正在播放")
+ case "paused": return qsTr("已暂停")
+ case "opening": return qsTr("正在打开")
+ case "image": return qsTr("正在查看")
+ case "ended": return qsTr("已播完")
+ case "failed": return qsTr("播放失败")
+ default: return qsTr("已停止")
+ }
+ }
+ color: row.entryState === "failed" ? Theme.err : Theme.accent
+ font.pixelSize: 10
+ }
+ }
+ Text { Layout.fillWidth: true; text: row.entrySize + " · " + row.entryModified; color: Theme.t3; elide: Text.ElideRight; font.pixelSize: 10 }
+ }
+ VButton {
+ objectName: "playlist-remove-" + row.index
+ anchors.right: parent.right; anchors.rightMargin: 4; anchors.verticalCenter: parent.verticalCenter
+ icon: true; ghost: true; iconName: "x"; tip: qsTr("从列表移除,不删除文件")
+ onClicked: win.playlist.remove(row.index)
+ }
+ }
+ }
+ Text {
+ anchors.centerIn: parent; width: parent.width - 32
+ visible: win.playlist.count === 0
+ text: win.playlist.busy ? qsTr("正在扫描文件夹…") : qsTr("导入文件夹,或将文件 / 文件夹拖到这里\n支持子文件夹 · 双击播放 · 拖动左侧手柄调整顺序")
+ color: Theme.t3; wrapMode: Text.WordWrap; horizontalAlignment: Text.AlignHCenter
+ font.family: Theme.fontUi; font.pixelSize: 12; lineHeight: 1.5
+ }
+ Rectangle {
+ visible: win.dragging; x: 0; y: Math.max(0, Math.min(list.height - 2, win.dragY))
+ width: list.width; height: 2; color: Theme.accent
+ }
+ Timer {
+ interval: 40; repeat: true; running: win.dragging
+ onTriggered: {
+ const step = win.dragY < 28 ? -12 : win.dragY > list.height - 28 ? 12 : 0
+ list.contentY = Math.max(0, Math.min(Math.max(0, list.contentHeight - list.height), list.contentY + step))
+ }
+ }
+ }
+ RowLayout {
+ Layout.fillWidth: true; spacing: 8
+ Text { text: qsTr("播完后播放下一项"); color: Theme.t2; font.pixelSize: 11 }
+ VSwitch { objectName: "playlist-auto-advance"; checked: win.playlist.autoAdvance; onToggled: checked => win.playlist.autoAdvance = checked }
+ Item { Layout.fillWidth: true }
+ }
+ Text {
+ objectName: "playlist-status"
+ Layout.fillWidth: true
+ text: win.failure || win.playlist.status || qsTr("拖入只追加列表,不打断当前播放")
+ color: win.failure ? Theme.err : Theme.t3; elide: Text.ElideRight; font.pixelSize: 10
+ }
+ }
+ }
+ DropArea {
+ id: filesDrop
+ objectName: "playlist-drop"
+ anchors.fill: parent
+ onDropped: drop => {
+ console.log("playlist-drop", "hasUrls=" + drop.hasUrls, "count=" + drop.urls.length)
+ if (!drop.hasUrls || !drop.urls.length) return
+ drop.accept(Qt.CopyAction); win.playlist.addUrls(drop.urls)
+ }
+ Rectangle {
+ anchors.fill: parent; anchors.margins: 2; radius: Theme.rWindow
+ visible: filesDrop.containsDrag; color: Theme.accentSoft
+ border.width: 2; border.color: Theme.accent
+ Text { anchors.centerIn: parent; text: qsTr("松开以追加到播放列表"); color: Theme.t1; font.pixelSize: 16 }
+ }
+ }
+ Repeater {
+ model: [
+ { e: Qt.LeftEdge, c: Qt.SizeHorCursor }, { e: Qt.RightEdge, c: Qt.SizeHorCursor },
+ { e: Qt.TopEdge, c: Qt.SizeVerCursor }, { e: Qt.BottomEdge, c: Qt.SizeVerCursor },
+ { e: Qt.LeftEdge | Qt.TopEdge, c: Qt.SizeFDiagCursor }, { e: Qt.RightEdge | Qt.BottomEdge, c: Qt.SizeFDiagCursor },
+ { e: Qt.RightEdge | Qt.TopEdge, c: Qt.SizeBDiagCursor }, { e: Qt.LeftEdge | Qt.BottomEdge, c: Qt.SizeBDiagCursor }
+ ]
+ delegate: MouseArea {
+ required property var modelData
+ readonly property bool l: (modelData.e & Qt.LeftEdge) !== 0
+ readonly property bool r: (modelData.e & Qt.RightEdge) !== 0
+ readonly property bool t: (modelData.e & Qt.TopEdge) !== 0
+ readonly property bool b: (modelData.e & Qt.BottomEdge) !== 0
+ readonly property bool corner: (l || r) && (t || b)
+ objectName: "playlist-resize-" + modelData.e
+ z: 130
+ width: corner ? 12 : (l || r) ? 6 : win.width - 24
+ height: corner ? 12 : (t || b) ? 6 : win.height - 24
+ x: l ? 0 : r ? win.width - width : 12
+ y: t ? 0 : b ? win.height - height : 12
+ cursorShape: modelData.c
+ onPressed: win.startSystemResize(modelData.e)
+ }
+ }
+}
diff --git a/qml/Veyra/qmldir b/qml/Veyra/qmldir
index 647bf76e..b1c15c58 100644
--- a/qml/Veyra/qmldir
+++ b/qml/Veyra/qmldir
@@ -1,4 +1,5 @@
module Veyra
+PlaylistWindow 1.0 PlaylistWindow.qml
PlaybackRateButton 1.0 PlaybackRateButton.qml
PlaybackRateDialog 1.0 PlaybackRateDialog.qml
singleton Theme 1.0 Theme.qml
diff --git a/scripts/acceptance/pr31-playlist-build.py b/scripts/acceptance/pr31-playlist-build.py
new file mode 100644
index 00000000..667d8eac
--- /dev/null
+++ b/scripts/acceptance/pr31-playlist-build.py
@@ -0,0 +1,136 @@
+"""Scoped PR31/playlist build. Old objects/runtime remain read-only and hashed."""
+from pathlib import Path
+import ctypes
+import hashlib
+import json
+import os
+import re
+import subprocess
+import time
+
+ROOT=Path(__file__).resolve().parents[2]
+BASE=Path('E:/项目/Veyra');TASK='pr31-playlist-20261009'
+CACHE=BASE/'build/vfg-next-20261007';OUT=BASE/'build'/TASK
+LOG=BASE/'logs'/TASK/('build-'+time.strftime('%Y%m%d-%H%M%S'));TMP=BASE/'tmp'/TASK/'build'
+for p in (OUT,LOG,TMP):p.mkdir(parents=True,exist_ok=True)
+def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
+shell=ctypes.WinDLL('shell32');shell.CommandLineToArgvW.argtypes=[ctypes.c_wchar_p,ctypes.POINTER(ctypes.c_int)]
+shell.CommandLineToArgvW.restype=ctypes.POINTER(ctypes.c_wchar_p);ctypes.windll.kernel32.LocalFree.argtypes=[ctypes.c_void_p]
+def args(s):
+ n=ctypes.c_int();p=shell.CommandLineToArgvW(s,ctypes.byref(n));a=[p[i] for i in range(n.value)];ctypes.windll.kernel32.LocalFree(p);return a
+def unescape(s):return s.replace('$ ',' ').replace('$:',':').replace('$$','$')
+tool=re.search(r'^CMAKE_MAKE_PROGRAM:FILEPATH=(.*)$',(CACHE/'CMakeCache.txt').read_text(encoding='utf8'),re.M).group(1)
+ninja=(CACHE/'build.ninja').read_text(encoding='utf8');inputs={};sources={};commands=[];start=time.monotonic()
+def protect(p):
+ p=Path(p);p=p if p.is_absolute() else CACHE/p
+ assert p.is_file(),p
+ if str(p) not in inputs:inputs[str(p)]=sha(p)
+ return p
+def rule(name,objectsRequired=True):
+ lines=re.search(r'^build '+re.escape(name)+r': .*?(?=\n\n)',ninja,re.M|re.S).group().splitlines()
+ var=dict(re.match(r' ([A-Z_]+) = (.*)',l).groups() for l in lines[1:] if re.match(r' ([A-Z_]+) = (.*)',l))
+ objects=[unescape(n).replace('\\','/') for n in lines[0].split('Release ',1)[1].split(' | ',1)[0].split(' ')]
+ if objectsRequired:
+ for p in objects:protect(p)
+ for value in args(unescape(var.get('LINK_LIBRARIES',''))):
+ if value.lower().endswith('.lib') and (Path(value).is_file() or (CACHE/value).is_file()):protect(value)
+ return objects,var
+def compiler(name):
+ return args(subprocess.check_output([tool,'-t','commands',name],cwd=CACHE,text=True,encoding='utf8').splitlines()[-1])
+env=dict(os.environ);env.update(TEMP=str(TMP),TMP=str(TMP))
+setup=subprocess.run(['cmd.exe','/u','/d','/c',r'call C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Auxiliary\Build\vcvars64.bat >nul && set'],capture_output=True,text=True,encoding='utf-16-le',env=env,check=True)
+for line in setup.stdout.splitlines():
+ if '=' in line:
+ key,value=line.split('=',1)
+ if key and not key.startswith('='):env[key]=value
+env.update(TEMP=str(TMP),TMP=str(TMP))
+def run(command,name):
+ commands.append(command);remaining=890-(time.monotonic()-start);assert remaining>0
+ with (LOG/(name+'.log')).open('wb') as stream:r=subprocess.run(command,cwd=CACHE,env=env,stdout=stream,stderr=subprocess.STDOUT,timeout=min(300,remaining))
+ print(name,'exit',r.returncode,flush=True)
+ if r.returncode:print((LOG/(name+'.log')).read_text(encoding='utf8',errors='replace')[-5000:]);raise SystemExit(r.returncode)
+def compile(source,name,a):
+ sources[str(source)]=sha(source);target=OUT/(name+'.obj')
+ command=a[:1]+['/utf-8','/I'+str(ROOT/'include'),'/I'+str(ROOT/'src')]+[v for v in a[1:-1] if not v.startswith(('/Fo','/Fd')) and v!='/showIncludes']
+ run(command+['/Fo'+str(target),'/Fd'+str(OUT/(name+'.pdb')),str(source)],'compile-'+name)
+ return target
+
+# The cached CMake build predates HDR compatibility and the BMD follow-up.
+# Retain ALL current-main overrides, verifying sources and immutable objects.
+previous=json.loads((BASE/'logs/subtitle-formats-20261009/build-20261009-133206/receipt.json').read_text(encoding='utf8'))
+overrides={}
+for name,row in previous['overrides'].items():
+ if name.endswith(('QmlPlayerBridge.cpp.obj','qrc_veyra_i18n.cpp.obj')):continue
+ source=name.split('.dir/',1)[1][:-4]
+ if source.startswith(('src/','apps/')):
+ original=next((p for p in previous['sources'] if p.replace('\\','/').endswith('/'+source) and
+ Path(p).is_file() and sha(Path(p))==previous['sources'][p] and
+ Path(p).read_bytes().replace(b'\r\n',b'\n')==(ROOT/source).read_bytes().replace(b'\r\n',b'\n')),None)
+ assert original,source # Git autocrlf may change bytes, never source content.
+ protect(original)
+ sources[str(ROOT/source)]=sha(ROOT/source)
+ assert sha(Path(row['path']))==row['sha256'],name
+ overrides[name]=protect(row['path'])
+for relative,group in (('src/ui/QmlPlayerBridge.cpp','veyra_qml_bridge'),('src/sink/CaptureAudioSession.cpp','veyra_sinks')):
+ name=f'CMakeFiles/{group}.dir/{relative}.obj'
+ overrides[name]=compile(ROOT/relative,Path(relative).stem,compiler(name))
+sources[str(ROOT/'include/veyra/engine/Subtitles.h')]=sha(ROOT/'include/veyra/engine/Subtitles.h')
+
+# Both Q_OBJECT headers changed/new: rebuild the bridge's complete meta-object
+# group, retaining the other two unmodified objects from immutable generation.
+autogen=json.loads(protect(CACHE/'CMakeFiles/veyra_qml_bridge_autogen.dir/AutogenInfo.json').read_text(encoding='utf8'))
+mocArgs=[autogen['QT_MOC_EXECUTABLE']]+['-D'+d for d in autogen['MOC_DEFINITIONS']]+['-I'+str(ROOT/'include')]+['-I'+d for d in autogen['MOC_INCLUDES']]
+for stem in ('QmlPlayerBridge','PlaylistModel'):
+ header=ROOT/f'include/veyra/ui/{stem}.h';sources[str(header)]=sha(header)
+ run(mocArgs+['-o',str(OUT/f'moc_{stem}.cpp'),str(header)],'moc-'+stem)
+mocs=OUT/'mocs_compilation.cpp'
+retained=[protect(CACHE/f'veyra_qml_bridge_autogen/EC3QK4C7QJ/moc_{name}.cpp') for name in ('MoonlightInputCapture','QmlExportQueueModel')]
+mocs.write_text(''.join('#include "'+p.as_posix()+'"\n' for p in retained)+'#include "moc_QmlPlayerBridge.cpp"\n',encoding='utf8')
+bridgeCompiler=compiler('CMakeFiles/veyra_qml_bridge.dir/src/ui/QmlPlayerBridge.cpp.obj')
+overrides['CMakeFiles/veyra_qml_bridge.dir/veyra_qml_bridge_autogen/mocs_compilation.cpp.obj']=compile(mocs,'bridge-mocs',bridgeCompiler)
+playlistObject=compile(ROOT/'src/ui/PlaylistModel.cpp','PlaylistModel',bridgeCompiler)
+playlistMoc=compile(OUT/'moc_PlaylistModel.cpp','playlist-moc',bridgeCompiler)
+
+gui=rule('veyra_qml_ui.exe')
+resource=next(p for p in gui[0] if p.endswith('/qrc_veyra_i18n.cpp.obj'))
+lines=subprocess.check_output([tool,'-t','commands',resource],cwd=CACHE,text=True,encoding='utf8').splitlines()
+rccLine=next(l for l in lines if 'rcc.exe' in l.lower() and 'veyra_i18n' in l)
+rcc=next(a for part in args(rccLine) for a in args(part) if a.lower().endswith('rcc.exe'))
+qrc=OUT/'i18n.qrc';qrc.write_text('<RCC><qresource prefix="/i18n"><file alias="catalog.json">'+(ROOT/'i18n/catalog.json').as_posix()+'</file></qresource></RCC>',encoding='utf8')
+generated=OUT/'qrc_veyra_i18n.cpp';run([rcc,'--name','veyra_i18n','--no-zstd','-o',str(generated),str(qrc)],'generate-i18n')
+sources[str(ROOT/'i18n/catalog.json')]=sha(ROOT/'i18n/catalog.json')
+overrides[resource]=compile(generated,'qrc_veyra_i18n',compiler(resource))
+core=[p for name,p in overrides.items() if name.startswith(('CMakeFiles/veyra_engine.','CMakeFiles/veyra_sources.'))]
+assert any(p.name=='Subtitles.obj' for p in core) and len(core)==11
+
+cmake=r'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe'
+link=r'C:\PROGRA~2\MICROS~3\2022\BUILDT~1\VC\Tools\MSVC\1444~1.352\bin\Hostx64\x64\link.exe'
+executables=[]
+def linkTarget(name,objects,variables):
+ rsp=OUT/(name+'.rsp')
+ rsp.write_text('\n'.join(subprocess.list2cmdline([str(p)]) for p in objects)+'\n'+unescape(variables.get('LINK_PATH',''))+'\n'+unescape(variables['LINK_LIBRARIES']),encoding='utf8')
+ directory=OUT/('manifest-'+name);directory.mkdir(exist_ok=True)
+ flags=[('/MANIFESTINPUT:'+str(CACHE/'veyra-qml.manifest')) if a.startswith('/MANIFESTINPUT:') else a for a in args(unescape(variables.get('LINK_FLAGS','')))]
+ protect(CACHE/'veyra-qml.manifest')
+ command=[cmake,'-E','vs_link_exe','--msvc-ver=1944','--intdir='+str(directory),r'--rc=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\rc.exe',r'--mt=C:\PROGRA~2\WI3CF2~1\10\bin\100261~1.0\x64\mt.exe','--manifests','--',link,'/nologo','@'+str(rsp),'/out:'+str(OUT/(name+'.exe')),'/implib:'+str(OUT/(name+'.lib')),'/pdb:'+str(OUT/(name+'.pdb')),'/version:0.0']+flags
+ run(command,'link-'+name);executables.append(OUT/(name+'.exe'))
+linkTarget('veyra_qml_ui',list(overrides.values())+[playlistObject,playlistMoc]+[CACHE/p for p in gui[0] if p not in overrides],gui[1])
+objects,var=rule('veyra_capture_audio_tests.exe',False)
+obj=compile(ROOT/'tests/integration/CaptureAudioTests.cpp','test-audio',compiler(objects[0]))
+linkTarget('capture-audio-tests',[overrides['CMakeFiles/veyra_sinks.dir/src/sink/CaptureAudioSession.cpp.obj'],obj],var)
+objects,var=rule('veyra_qml_easing_tests.exe',False)
+# These tests exercise the production model, not a reimplementation. Qt GUI
+# link libraries are reused; no engine singleton/worker is started in unit UI.
+obj=compile(ROOT/'tests/unit/PlaylistModelTests.cpp','test-playlist',bridgeCompiler)
+linkTarget('playlist-tests',[playlistObject,playlistMoc,obj],var)
+qtRoot=Path(autogen['QT_MOC_EXECUTABLE']).parent.parent
+testCompiler=bridgeCompiler[:-1]+['/I'+str(qtRoot/'include/QtTest'),'/DVEYRA_QML_DIR="'+ROOT.joinpath('qml').as_posix()+'"',bridgeCompiler[-1]]
+obj=compile(ROOT/'tests/qml/PlaylistWindowTests.cpp','test-playlist-window',testCompiler)
+testVar=dict(var);testVar['LINK_LIBRARIES']+=' '+subprocess.list2cmdline([str(protect(qtRoot/'lib/Qt6Test.lib'))])
+linkTarget('playlist-window-tests',[playlistObject,playlistMoc,obj],testVar)
+for p,d in inputs.items():assert sha(Path(p))==d,p
+for relative in ('CMakeLists.txt','qml/Veyra/DialogHost.qml','qml/Veyra/Main.qml','qml/Veyra/CineBar.qml','qml/Veyra/FullscreenBar.qml','qml/Veyra/HomePage.qml','qml/Veyra/PlaylistWindow.qml','qml/Veyra/qmldir'):sources[str(ROOT/relative)]=sha(ROOT/relative)
+receipt={'commands':commands,'sources':sources,'overrides':{n:{'path':str(p),'sha256':sha(p)} for n,p in overrides.items()},'inputsUnchanged':inputs,'seconds':time.monotonic()-start,'executables':{p.name:sha(p) for p in executables}}
+(LOG/'receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2),encoding='utf8')
+(BASE/'reports'/TASK/'build-current.json').write_text(json.dumps({'receipt':str(LOG/'receipt.json')},indent=2),encoding='utf8')
+print('Built current GUI, PR31 audio and playlist tests; original inputs unchanged;',LOG,flush=True)
diff --git a/scripts/acceptance/pr31-playlist-control.py b/scripts/acceptance/pr31-playlist-control.py
new file mode 100644
index 00000000..ebe562ac
--- /dev/null
+++ b/scripts/acceptance/pr31-playlist-control.py
@@ -0,0 +1,53 @@
+"""Audit immutable pre-task worktrees and this task's narrow source scope."""
+from pathlib import Path
+import hashlib
+import json
+import re
+import subprocess
+import sys
+
+ROOT = Path(__file__).resolve().parents[2]
+BASE = Path('E:/项目/Veyra')
+TASK = 'pr31-playlist-20261009'
+start = json.loads((BASE/'archives'/TASK/'start.json').read_text(encoding='utf8'))
+
+def git(*args, cwd=ROOT):
+ return subprocess.check_output(['git', *args], cwd=cwd)
+
+def sha(path):
+ with path.open('rb') as stream:
+ return hashlib.file_digest(stream, 'sha256').hexdigest()
+
+for name, row in start['worktrees'].items():
+ path = Path(name)
+ assert git('rev-parse', 'HEAD', cwd=path).decode().strip() == row['head'], name
+ assert hashlib.sha256(git('status', '--porcelain=v1', '-z', cwd=path)).hexdigest() == row['statusSha256'], name
+ for relative, digest in row['dirtyFiles'].items():
+ file = path/relative
+ assert (sha(file) if file.is_file() else None) == digest, str(file)
+assert git('branch', '--show-current').decode().strip() == 'codex/'+TASK
+allowed = {
+ 'AGENTS.md', 'CMakeLists.txt', 'docs/WORKLOG.md', 'i18n/catalog.json',
+ 'docs/CAPTURE_AUDIO_ENDPOINT_SWITCH_PLAN_2026-10-09.md',
+ 'docs/PR31_PLAYLIST_PLAN_2026-10-09.md', 'docs/PR31_PLAYLIST_REPORT_2026-10-09.md',
+ 'src/sink/CaptureAudioSession.cpp', 'tests/integration/CaptureAudioTests.cpp',
+ 'include/veyra/ui/PlaylistModel.h', 'src/ui/PlaylistModel.cpp',
+ 'include/veyra/ui/QmlPlayerBridge.h', 'src/ui/QmlPlayerBridge.cpp',
+ 'qml/Veyra/Main.qml', 'qml/Veyra/CineBar.qml', 'qml/Veyra/FullscreenBar.qml',
+ 'qml/Veyra/PlaylistWindow.qml', 'qml/Veyra/qmldir', 'qml/Veyra/HomePage.qml',
+ 'tests/unit/PlaylistModelTests.cpp', 'tests/qml/PlaylistWindowTests.cpp',
+ 'scripts/acceptance/pr31-playlist-control.py', 'scripts/acceptance/pr31-playlist-build.py',
+ 'scripts/acceptance/pr31-playlist-test.py', 'scripts/acceptance/pr31-playlist-gui-test.py',
+}
+dirty = {p.decode('utf8') for p in git('ls-files', '-m', '-d', '--others', '--exclude-standard', '-z').split(b'\0') if p}
+changed = {p.decode('utf8') for p in git('diff', '--name-only', start['base']).splitlines() if p}
+assert (changed | dirty) <= allowed, (changed | dirty) - allowed
+git('diff', '--check')
+git('diff', '--cached', '--check')
+label = sys.argv[1] if len(sys.argv) > 1 else 'audit'
+assert re.fullmatch('[a-z0-9-]+', label)
+report = {'baselineWorktreesUnchanged': len(start['worktrees']),
+ 'dirtyFilesUnchanged': sum(len(v['dirtyFiles']) for v in start['worktrees'].values()),
+ 'scopePass': True, 'changed': sorted(changed | dirty), 'mainHead': start['main'], 'base': start['base']}
+(BASE/'reports'/TASK/(label+'.json')).write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8')
+print(json.dumps(report, ensure_ascii=False), flush=True)
diff --git a/scripts/acceptance/pr31-playlist-gui-test.py b/scripts/acceptance/pr31-playlist-gui-test.py
new file mode 100644
index 00000000..02beaf55
--- /dev/null
+++ b/scripts/acceptance/pr31-playlist-gui-test.py
@@ -0,0 +1,208 @@
+"""Actual player/bridge playlist checks, with a private app and profile only."""
+from pathlib import Path
+import hashlib
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import time
+import psutil
+
+if len(sys.argv) == 2 and sys.argv[1] == 'all':
+ outcomes = [subprocess.run([sys.executable, '-B', __file__, case], timeout=120).returncode
+ for case in ('functional', 'next', 'english', 'empty')]
+ raise SystemExit(any(outcomes))
+
+ROOT = Path(__file__).resolve().parents[2]
+BASE = Path('E:/项目/Veyra'); TASK = 'pr31-playlist-20261009'
+DONOR = BASE/'test-packages/vfg-next-20261007/Veyra-2.0.6-VFG-next-NVIDIA-win64-portable'
+APP = BASE/'tests'/TASK/'app'; BUILD = BASE/'build'/TASK
+FFMPEG = BASE/'deps/ffmpeg-subtitle-formats-20261009/installed/bin'
+case = sys.argv[1]; assert case in ('functional', 'next', 'english', 'empty')
+stamp = time.strftime('%Y%m%d-%H%M%S')
+LOG = BASE/'logs'/TASK/('gui-'+case+'-'+stamp)
+TMP = BASE/'tmp'/TASK/LOG.name
+for path in (LOG, TMP): path.mkdir(parents=True, exist_ok=False)
+
+def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest()
+manifest = json.loads((DONOR/'package-manifest.json').read_text(encoding='utf8'))
+
+def verify():
+ for row in manifest['files']: assert sha(DONOR/row['path']) == row['sha256'], row['path']
+
+verify()
+for proc in psutil.process_iter(['pid', 'name']):
+ name = (proc.info['name'] or '').lower()
+ assert not name.startswith(('veyra', 'fg-presentation', 'flash-pixel')), f'Player already running: {name} {proc.pid}'
+if not APP.exists():
+ APP.mkdir(parents=True)
+ for row in manifest['files']:
+ relative = Path(row['path'])
+ if relative.parts[0] in ('runtime_local', 'logs') or relative.name == 'veyra_qml_ui.exe': continue
+ target = APP/relative; target.parent.mkdir(parents=True, exist_ok=True)
+ os.link(DONOR/relative, target)
+ (APP/'runtime_local').mkdir(exist_ok=True)
+
+def replace(source, target):
+ target.parent.mkdir(parents=True, exist_ok=True)
+ swap = target.with_name(target.name+'.swap'); shutil.copy2(source, swap); os.replace(swap, target)
+
+replace(BUILD/'veyra_qml_ui.exe', APP/'veyra_qml_ui.exe')
+for source in (ROOT/'qml').rglob('*'):
+ if source.is_file() and (source.suffix in ('.qml', '.js') or source.name == 'qmldir'):
+ replace(source, APP/'qml'/source.relative_to(ROOT/'qml'))
+for source in FFMPEG.glob('*.dll'): replace(source, APP/source.name)
+profile = BASE/'tests'/TASK/'profiles'/LOG.name; profile.mkdir(parents=True, exist_ok=False)
+(profile/'qml-preferences.v1.json').write_text(json.dumps({'language': 'en' if case == 'english' else 'zh-CN',
+ 'gpuPriority': 'normal', 'autoResume': False, 'rememberPosition': False, 'prewarmEnhancement': False,
+ 'subtitleEnabled': False, 'sentinel': 'preserved'}), encoding='utf8')
+clips = BASE/'tests'/TASK/'playback-clips'; clips.mkdir(exist_ok=True)
+other = clips/'other'; other.mkdir(exist_ok=True)
+original = BASE/'tests/playback-smoothness-20261004/fixtures/golden.mkv'
+for target in (clips/'Movie1.mkv', other/'Movie2.mkv', other/'Movie10.mkv'):
+ if not target.exists(): os.link(original, target)
+
+env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('VEYRA_', 'QT_', 'QSG_'))}
+env.update(PATH=str(APP)+os.pathsep+env['PATH'], TEMP=str(TMP), TMP=str(TMP),
+ CUDA_CACHE_PATH=str(TMP/'cuda-cache'), QML_DISK_CACHE_PATH=str(TMP/'qml-cache'),
+ QT_FORCE_STDERR_LOGGING='1', VEYRA_LOG_FILE=str(LOG/'engine.log'))
+timer = r'''
+ property int playlistTestStep: 0
+ property int playlistTestTicks: 0
+ property int playlistTestAt: 0
+ property real playlistTestPosition: 0
+ function playlistTestFail(text) { console.error("PLAYGUI_FAIL", text); playlistTestTimer.stop() }
+ function playlistTestCheck(ok, text) {
+ if (!ok) { playlistTestFail(text); return false }
+ console.log("PLAYGUI_CHECK", text); return true
+ }
+ function playlistTestFind(item, name) {
+ if (item.objectName === name) return item
+ if (item.children) for (let i=0;i<item.children.length;++i) {
+ const found=playlistTestFind(item.children[i],name); if(found)return found
+ }
+ return null
+ }
+ function playlistTestDone() {
+ playlistWindow.contentItem.grabToImage(result=>result.saveToFile(SCREENSHOT))
+ console.log("PLAYGUI_PASS", MODE); playlistTestTimer.stop()
+ playlistTestClose.start()
+ }
+ Timer { id: playlistTestClose; interval: 500; onTriggered: veyra.quit() }
+ Timer {
+ id: playlistTestTimer; interval: 150; repeat: true; running: true
+ onTriggered: {
+ ++root.playlistTestTicks
+ if(root.playlistTestTicks>150) { root.playlistTestFail("timeout step="+root.playlistTestStep); return }
+ const p=veyra.playlist
+ if(MODE==="empty") {
+ if(root.playlistTestStep===0) {
+ if(!root.playlistTestCheck(!veyra.running && p.count===0,"starts without a source or fabricated entries"))return
+ veyra.showPlaylist(); root.playlistTestStep=1; return
+ }
+ if(root.playlistTestStep===1) {
+ if(!root.playlistTestCheck(playlistWindow.visible,"home playlist opens before a video"))return
+ veyra.openDroppedUrls([FOLDER]); root.playlistTestStep=2; return
+ }
+ if(p.busy)return
+ if(!root.playlistTestCheck(p.count===2 && !veyra.running,"folder drop imports without starting playback"))return
+ root.playlistTestDone(); return
+ }
+ if(root.playlistTestStep===0) {
+ if(!veyra.running || p.busy || !p.count || veyra.duration<2)return
+ if(!root.playlistTestCheck(p.count===1 && p.currentIndex===0,"actual open is in the playlist"))return
+ if(!root.playlistTestCheck(veyra.preferences.hdrFgCompatibility!==true,"HDR compatibility remains default-off"))return
+ p.autoAdvance=false
+ if(!veyra.paused)veyra.togglePlayPause()
+ root.playlistTestStep=1; return
+ }
+ if(root.playlistTestStep===1) {
+ if(!veyra.paused)return
+ root.playlistTestPosition=veyra.position
+ const button=root.playlistTestFind(fullBar.contentItem,"cine-playlist")
+ if(!root.playlistTestCheck(button!==null,"minimal bottom bar contains playlist button"))return
+ button.clicked()
+ veyra.openDroppedUrls([FOLDER])
+ root.playlistTestStep=2; return
+ }
+ if(root.playlistTestStep===2) {
+ if(p.busy)return
+ if(!root.playlistTestCheck(playlistWindow.visible && p.count===3,"folder appends and owned floating playlist opens"))return
+ if(!root.playlistTestCheck(veyra.sourceName==="Movie1.mkv" && veyra.paused && Math.abs(veyra.position-root.playlistTestPosition)<0.2,"append does not change source/position/pause state"))return
+ p.sortBy(1)
+ if(MODE==="next") {
+ p.autoAdvance=true; veyra.seekTo(veyra.duration-0.6)
+ root.playlistTestStep=20; return
+ }
+ p.move(0,2); root.playlistTestStep=3; return
+ }
+ if(root.playlistTestStep===3) {
+ const badge=root.playlistTestFind(playlistWindow.contentItem,"playlist-state-2")
+ if(!root.playlistTestCheck(p.currentIndex===2 && badge && badge.text===(MODE==="english"?"Paused":"已暂停"),"reorder keeps actual paused file marker"))return
+ p.remove(0)
+ if(!root.playlistTestCheck(p.currentIndex===1 && veyra.sourceName==="Movie1.mkv","removing another row keeps playback"))return
+ p.remove(1)
+ if(!root.playlistTestCheck(p.currentIndex===-1 && veyra.paused && veyra.sourceName==="Movie1.mkv","removing active row does not stop or mislabel playback"))return
+ p.play(0); root.playlistTestStep=4; return
+ }
+ if(root.playlistTestStep===4) {
+ if(!veyra.running || veyra.paused || veyra.openingSource)return
+ if(!root.playlistTestCheck(veyra.sourceName==="Movie10.mkv" && p.currentIndex===0,"playlist selection opens the chosen real video"))return
+ const badge=root.playlistTestFind(playlistWindow.contentItem,"playlist-state-0")
+ if(!root.playlistTestCheck(badge && badge.text===(MODE==="english"?"Playing":"正在播放"),"playing marker follows confirmed engine state"))return
+ playlistWindow.width=620; playlistWindow.height=480; playlistWindow.hide(); playlistWindow.open()
+ if(!root.playlistTestCheck(playlistWindow.width===620 && playlistWindow.height===480,"playlist reopen preserves resized geometry"))return
+ p.autoAdvance=true; veyra.stopPlayback(); root.playlistTestAt=root.playlistTestTicks
+ root.playlistTestStep=5; return
+ }
+ if(root.playlistTestStep===5) {
+ if(root.playlistTestTicks-root.playlistTestAt<5)return
+ if(!root.playlistTestCheck(!veyra.running && veyra.sourceName==="Movie10.mkv","manual stop does not trigger another file"))return
+ if(!root.playlistTestCheck(p.save(),"actual playlist persisted"))return
+ root.playlistTestDone(); return
+ }
+ if(root.playlistTestStep===20) {
+ if(veyra.position<veyra.duration-1)return
+ veyra.togglePlayPause(); root.playlistTestStep=21; return
+ }
+ if(root.playlistTestStep===21) {
+ if(veyra.sourceName!=="Movie2.mkv" || !veyra.running || veyra.openingSource)return
+ if(!root.playlistTestCheck(p.currentIndex===1,"actual end advances once to the next sorted file"))return
+ if(!veyra.paused)veyra.togglePlayPause()
+ root.playlistTestAt=root.playlistTestTicks; root.playlistTestStep=22; return
+ }
+ if(root.playlistTestStep===22) {
+ if(root.playlistTestTicks-root.playlistTestAt<4)return
+ if(!root.playlistTestCheck(veyra.paused && veyra.sourceName==="Movie2.mkv" && p.currentIndex===1,"stale Ended snapshots do not skip another file"))return
+ root.playlistTestDone(); return
+ }
+ }
+ }
+'''
+for token, value in {'MODE': case, 'FOLDER': other.as_uri(), 'SCREENSHOT': str(LOG/'playlist.png')}.items():
+ timer = timer.replace(token, json.dumps(value.replace('\\', '/'), ensure_ascii=False))
+main = APP/'qml/Veyra/Main.qml'; saved = main.read_bytes()
+assert saved.decode('utf8').count(' id: root') == 1
+swap = main.with_suffix('.swap'); swap.write_text(saved.decode('utf8').replace(' id: root', ' id: root'+timer, 1), encoding='utf8'); os.replace(swap, main)
+command = [str(APP/'veyra_qml_ui.exe'), '--data-dir', str(profile), '--page', 'home' if case == 'empty' else 'min',
+ '--size', '1280x800', '--exit-after', '24000']
+if case != 'empty': command.append(str(clips/'Movie1.mkv'))
+start = time.monotonic()
+try:
+ with (LOG/'console.log').open('wb') as stream:
+ run = subprocess.run(command, cwd=APP, env=env, stdout=stream, stderr=subprocess.STDOUT, timeout=45)
+finally:
+ swap = main.with_suffix('.swap'); swap.write_bytes(saved); os.replace(swap, main)
+verify()
+text = (LOG/'console.log').read_text(encoding='utf8', errors='replace')
+errors = [line for line in text.splitlines() if re.search(r'PLAYGUI_FAIL|ReferenceError:|TypeError:|\[ERROR\s*\]|\[FATAL\s*\]|D3D12 ERROR|D3D12 CORRUPTION|Cannot assign|Binding loop', line)]
+receipt = {'case': case, 'command': command, 'exit': run.returncode, 'seconds': time.monotonic()-start,
+ 'errors': errors, 'passed': 'PLAYGUI_PASS' in text and not errors and run.returncode == 0,
+ 'events': [line for line in text.splitlines() if 'PLAYGUI_' in line],
+ 'exeSha256': sha(APP/'veyra_qml_ui.exe'), 'donorUnchanged': len(manifest['files']), 'profile': str(profile)}
+(LOG/'receipt.json').write_text(json.dumps(receipt, ensure_ascii=False, indent=2), encoding='utf8')
+(BASE/'reports'/TASK/('gui-'+case+'-current.json')).write_text(json.dumps({'receipt': str(LOG/'receipt.json')}, indent=2), encoding='utf8')
+print(json.dumps(receipt, ensure_ascii=False, indent=2), flush=True)
+raise SystemExit(not receipt['passed'])
diff --git a/scripts/acceptance/pr31-playlist-test.py b/scripts/acceptance/pr31-playlist-test.py
new file mode 100644
index 00000000..74619f43
--- /dev/null
+++ b/scripts/acceptance/pr31-playlist-test.py
@@ -0,0 +1,51 @@
+"""Bounded real playlist/window and WASAPI tests; no user profile changes."""
+from pathlib import Path
+import hashlib
+import json
+import os
+import subprocess
+import sys
+import time
+
+BASE = Path('E:/项目/Veyra')
+TASK = 'pr31-playlist-20261009'
+BUILD = BASE/'build'/TASK
+DONOR = BASE/'test-packages/vfg-next-20261007/Veyra-2.0.6-VFG-next-NVIDIA-win64-portable'
+FFMPEG = BASE/'deps/ffmpeg-subtitle-formats-20261009/installed/bin'
+QT = Path('C:/veyra-deps/qt-veyra/6.8.3/msvc2022_64')
+stamp = time.strftime('%Y%m%d-%H%M%S')
+LOG = BASE/'logs'/TASK/('tests-'+stamp)
+TMP = BASE/'tmp'/TASK/('tests-'+stamp)
+FIX = BASE/'tests'/TASK/('fixtures-'+stamp)
+for path in (LOG, TMP, FIX): path.mkdir(parents=True, exist_ok=False)
+env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('VEYRA_', 'QT_', 'QSG_'))}
+env.update(PATH=os.pathsep.join(map(str, (FFMPEG, QT/'bin', DONOR)))+os.pathsep+env['PATH'],
+ TEMP=str(TMP), TMP=str(TMP), QML_DISK_CACHE_PATH=str(TMP/'qml'),
+ QT_PLUGIN_PATH=str(QT/'plugins'), QT_FORCE_STDERR_LOGGING='1',
+ CUDA_CACHE_PATH=str(TMP/'cuda'))
+commands = [('model', [BUILD/'playlist-tests.exe', FIX/'model']),
+ ('window', [BUILD/'playlist-window-tests.exe', FIX/'window'])]
+commands += [(mode, [BUILD/'capture-audio-tests.exe', '--'+mode]) for mode in
+ ('endpoint-switch', 'endpoint-loss', 'slow-start', 'transient', 'xbox-float-rtp')]
+selected = sys.argv[1:]
+if selected:
+ assert set(selected) <= {name for name, _ in commands}
+ commands = [(name, values) for name, values in commands if name in selected]
+results = []
+for name, values in commands:
+ command = list(map(str, values)); env['VEYRA_LOG_FILE'] = str(LOG/(name+'-engine.log'))
+ start = time.monotonic()
+ with (LOG/(name+'.log')).open('wb') as output:
+ run = subprocess.run(command, cwd=TMP, env=env, stdout=output, stderr=subprocess.STDOUT, timeout=180)
+ text = (LOG/(name+'.log')).read_text(encoding='utf8', errors='replace')
+ failed = [line for line in text.splitlines() if line.startswith('FAIL') or 'ReferenceError' in line or 'TypeError' in line]
+ result = {'name': name, 'command': command, 'exit': run.returncode, 'seconds': time.monotonic()-start,
+ 'failures': failed, 'checks': [line for line in text.splitlines() if line.startswith(('PASS', 'FAIL', 'SKIP'))],
+ 'exeSha256': hashlib.sha256(Path(command[0]).read_bytes()).hexdigest(),
+ 'skipped': name == 'endpoint-switch' and run.returncode == 77}
+ results.append(result)
+ (LOG/'receipt.json').write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding='utf8')
+ print(name, 'exit', run.returncode, 'seconds', round(result['seconds'], 2), 'failures', failed, flush=True)
+(BASE/'reports'/TASK/('tests-'+('-'.join(selected) if selected else 'all')+'-current.json')).write_text(json.dumps({'receipt': str(LOG/'receipt.json'), 'fixtures': str(FIX)}, indent=2), encoding='utf8')
+print(LOG, flush=True)
+raise SystemExit(any((r['exit'] and not r['skipped']) or r['failures'] for r in results))
diff --git a/src/ui/PlaylistModel.cpp b/src/ui/PlaylistModel.cpp
new file mode 100644
index 00000000..109ef1c2
--- /dev/null
+++ b/src/ui/PlaylistModel.cpp
@@ -0,0 +1,323 @@
+#include "veyra/ui/PlaylistModel.h"
+#include <QCollator>
+#include <QDateTime>
+#include <QDir>
+#include <QDirIterator>
+#include <QFile>
+#include <QFileInfo>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QLocale>
+#include <QSaveFile>
+#include <QUrl>
+#include <algorithm>
+#include <utility>
+#ifdef Q_OS_WIN
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <windows.h>
+#endif
+
+namespace veyra::ui {
+namespace {
+constexpr int maxEntries = 10000, maxJobs = 16, maxVisited = 100000;
+bool reparse(const QFileInfo& info) {
+ if (info.isSymLink()) return true;
+#ifdef Q_OS_WIN
+ const auto attributes = GetFileAttributesW(reinterpret_cast<LPCWSTR>(info.absoluteFilePath().utf16()));
+ return attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
+#else
+ return false;
+#endif
+}
+}
+
+PlaylistModel::PlaylistModel(QString storage, QObject* parent)
+ : QAbstractListModel(parent), storage_(std::move(storage)) {
+ saveTimer_.setSingleShot(true);
+ saveTimer_.setInterval(350);
+ connect(&saveTimer_, &QTimer::timeout, this, [this] { save(); });
+ load();
+ worker_ = std::jthread([this](std::stop_token stop) { workerLoop(stop); });
+}
+PlaylistModel::~PlaylistModel() {
+ worker_.request_stop();
+ wake_.notify_all();
+ if (worker_.joinable()) worker_.join();
+ if (saveTimer_.isActive()) save();
+}
+int PlaylistModel::rowCount(const QModelIndex& parent) const { return parent.isValid() ? 0 : count(); }
+QString PlaylistModel::normalizedPath(const QString& path) {
+ return QDir::cleanPath(QFileInfo(QDir::fromNativeSeparators(path)).absoluteFilePath());
+}
+QString PlaylistModel::keyOf(const QString& path) {
+ auto value = normalizedPath(path);
+#ifdef Q_OS_WIN
+ value = value.toCaseFolded();
+#endif
+ return value;
+}
+bool PlaylistModel::supported(const QString& path) {
+ static const QSet<QString> suffixes{
+ "mp4", "mkv", "mov", "avi", "webm", "ts", "m2ts", "mts", "m4v", "wmv",
+ "mpg", "mpeg", "vob", "flv", "ogv", "asf", "3gp", "jpg", "jpeg", "png", "bmp", "webp"
+ };
+ return suffixes.contains(QFileInfo(path).suffix().toLower());
+}
+QVariant PlaylistModel::data(const QModelIndex& index, int role) const {
+ if (!index.isValid() || index.row() < 0 || index.row() >= count()) return {};
+ const auto& entry = entries_[index.row()];
+ switch (role) {
+ case Qt::DisplayRole: case NameRole: return entry.name;
+ case PathRole: return QDir::toNativeSeparators(entry.path);
+ case SizeRole: return QLocale().formattedDataSize(entry.size);
+ case ModifiedRole: return QDateTime::fromMSecsSinceEpoch(entry.modified).toString("yyyy-MM-dd HH:mm");
+ case CurrentRole: return entry.key == currentKey_;
+ case StateRole: return entry.key == currentKey_ ? state_ : QString();
+ default: return {};
+ }
+}
+QHash<int, QByteArray> PlaylistModel::roleNames() const {
+ return {{NameRole, "entryName"}, {PathRole, "entryPath"}, {SizeRole, "entrySize"},
+ {ModifiedRole, "entryModified"}, {CurrentRole, "entryCurrent"}, {StateRole, "entryState"}};
+}
+int PlaylistModel::currentIndex() const {
+ if (!currentKey_.isEmpty())
+ for (int i = 0; i < count(); ++i) if (entries_[i].key == currentKey_) return i;
+ return -1;
+}
+void PlaylistModel::setPlayback(const QString& path, const QString& state) {
+ const QString key = path.isEmpty() ? QString() : keyOf(path);
+ if (key == currentKey_ && state == state_) return;
+ const int before = currentIndex();
+ currentKey_ = key; state_ = state;
+ const int after = currentIndex();
+ if (before >= 0) emit dataChanged(index(before), index(before), {CurrentRole, StateRole});
+ if (after >= 0 && after != before) emit dataChanged(index(after), index(after), {CurrentRole, StateRole});
+ emit currentChanged();
+}
+void PlaylistModel::setAutoAdvance(bool enabled) {
+ if (autoAdvance_ == enabled) return;
+ autoAdvance_ = enabled; emit autoAdvanceChanged(); saveTimer_.start();
+}
+void PlaylistModel::setStatus(QString text) {
+ if (status_ == text) return;
+ status_ = std::move(text); emit statusChanged();
+}
+void PlaylistModel::addUrls(const QList<QUrl>& urls) {
+ QStringList paths;
+ for (const auto& url : urls) {
+ if (url.isLocalFile()) paths << url.toLocalFile();
+ }
+ addPaths(paths);
+}
+void PlaylistModel::addPaths(const QStringList& paths) {
+ if (paths.isEmpty()) return;
+ if (pending_ >= maxJobs || count() >= maxEntries) {
+ emit error(tr("列表或导入任务已达上限,请稍后重试或移除部分条目")); return;
+ }
+ // No directory/file existence checks here: a network folder can be slow.
+ Job job; job.generation = generation_.load();
+ for (const auto& path : paths) {
+ if (!path.trimmed().isEmpty() && job.paths.size() < maxEntries) job.paths << normalizedPath(path);
+ }
+ if (job.paths.isEmpty()) return;
+ const bool wasBusy = busy(); ++pending_;
+ { std::lock_guard lock(mutex_); jobs_.push_back(std::move(job)); }
+ if (!wasBusy) emit busyChanged();
+ setStatus(tr("正在扫描文件夹…"));
+ wake_.notify_one();
+}
+void PlaylistModel::order(std::vector<Entry>& entries, int mode) {
+ QCollator collator; collator.setNumericMode(true); collator.setCaseSensitivity(Qt::CaseInsensitive);
+ std::stable_sort(entries.begin(), entries.end(), [&](const Entry& a, const Entry& b) {
+ if ((mode == NewestFirst || mode == OldestFirst) && a.modified != b.modified)
+ return mode == NewestFirst ? a.modified > b.modified : a.modified < b.modified;
+ if ((mode == LargestFirst || mode == SmallestFirst) && a.size != b.size)
+ return mode == LargestFirst ? a.size > b.size : a.size < b.size;
+ const int compared = collator.compare(a.name, b.name);
+ if (compared) return mode == NameDescending ? compared > 0 : compared < 0;
+ return a.key < b.key;
+ });
+}
+PlaylistModel::Result PlaylistModel::scan(const Job& job, std::stop_token stop) const {
+ Result result;
+ QSet<QString> visited, found;
+ QStringList directories;
+ int examined = 0;
+ auto cancelled = [&] { return stop.stop_requested() || job.generation != generation_.load(); };
+ auto file = [&](const QFileInfo& info) {
+ if (!info.isFile() || !supported(info.filePath()) || reparse(info)) { ++result.skipped; return; }
+ const auto path = normalizedPath(info.absoluteFilePath()), key = keyOf(path);
+ if (found.contains(key)) return;
+ found.insert(key);
+ result.entries.push_back({path, info.fileName(), key, info.size(), info.lastModified().toMSecsSinceEpoch()});
+ };
+ for (const auto& path : job.paths) {
+ if (cancelled()) return {};
+ const QFileInfo info(path);
+ if (info.isDir() && !reparse(info)) directories << path;
+ else file(info);
+ if (int(result.entries.size()) >= maxEntries) { result.limited = true; break; }
+ }
+ while (!directories.isEmpty() && !result.limited && !cancelled()) {
+ const auto path = directories.takeLast(), key = keyOf(path);
+ if (visited.contains(key)) continue;
+ visited.insert(key);
+ QDirIterator it(path, QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden, QDirIterator::NoIteratorFlags);
+ while (it.hasNext() && !cancelled()) {
+ it.next(); const QFileInfo info = it.fileInfo();
+ if (++examined > maxVisited) { result.limited = true; break; }
+ if (info.isDir()) {
+ if (!reparse(info) && directories.size() < maxEntries) directories << info.absoluteFilePath();
+ } else file(info);
+ if (int(result.entries.size()) >= maxEntries) { result.limited = true; break; }
+ }
+ }
+ if (!cancelled()) order(result.entries, NameAscending);
+ return result;
+}
+void PlaylistModel::workerLoop(std::stop_token stop) {
+ while (!stop.stop_requested()) {
+ Job job;
+ {
+ std::unique_lock lock(mutex_);
+ if (!wake_.wait(lock, stop, [this] { return !jobs_.empty(); })) return;
+ job = std::move(jobs_.front()); jobs_.pop_front();
+ }
+ auto result = scan(job, stop);
+ if (stop.stop_requested()) return;
+ QMetaObject::invokeMethod(this, [this, result = std::move(result), generation = job.generation]() mutable {
+ accept(std::move(result), generation);
+ }, Qt::QueuedConnection);
+ }
+}
+void PlaylistModel::accept(Result result, uint64_t generation) {
+ if (generation != generation_.load()) return;
+ --pending_;
+ std::vector<Entry> added;
+ for (auto& entry : result.entries) {
+ if (keys_.contains(entry.key)) continue;
+ if (count() + int(added.size()) >= maxEntries) { result.limited = true; break; }
+ keys_.insert(entry.key); added.push_back(std::move(entry));
+ }
+ if (!added.empty()) {
+ beginInsertRows({}, count(), count() + int(added.size()) - 1);
+ for (auto& entry : added) entries_.push_back(std::move(entry));
+ endInsertRows(); emit countChanged(); emit currentChanged();
+ if (sort_ != Manual) sortBy(sort_);
+ saveTimer_.start();
+ }
+ if (!busy()) emit busyChanged();
+ setStatus(busy() ? tr("正在扫描文件夹…")
+ : tr("已添加 %1 项 · 列表共 %2 项").arg(added.size()).arg(count()));
+ if (result.limited) emit error(tr("已达到导入上限(最多10000项),其余文件未添加"));
+ else if (added.empty() && !busy()) setStatus(tr("未添加新条目:文件已在列表中,或没有支持的媒体文件"));
+}
+QString PlaylistModel::pathAt(int row) const { return row >= 0 && row < count() ? entries_[row].path : QString(); }
+int PlaylistModel::indexOfPath(const QString& path) const {
+ const auto key = keyOf(path);
+ for (int i = 0; i < count(); ++i) if (entries_[i].key == key) return i;
+ return -1;
+}
+bool PlaylistModel::play(int row) {
+ if (row < 0 || row >= count()) return false;
+ const QString path = entries_[row].path;
+ if (!QFileInfo(path).isFile()) { emit error(tr("文件不存在或已移动:%1").arg(QDir::toNativeSeparators(path))); return false; }
+ emit playRequested(QDir::toNativeSeparators(path)); return true;
+}
+bool PlaylistModel::playFrom(int row, int direction) {
+ for (; row >= 0 && row < count(); row += direction) {
+ // Skip missing entries without opening a failed engine session for each.
+ if (QFileInfo(entries_[row].path).isFile()) return play(row);
+ }
+ return false;
+}
+bool PlaylistModel::next() { const int at = currentIndex(); return playFrom(at < 0 ? 0 : at + 1, 1); }
+bool PlaylistModel::previous() { const int at = currentIndex(); return playFrom(at < 0 ? count() - 1 : at - 1, -1); }
+bool PlaylistModel::advanceAfterEnd() { return autoAdvance_ && currentIndex() >= 0 && next(); }
+bool PlaylistModel::move(int from, int to) {
+ if (from < 0 || to < 0 || from >= count() || to >= count() || from == to) return false;
+ beginMoveRows({}, from, from, {}, to > from ? to + 1 : to);
+ auto entry = std::move(entries_[from]); entries_.erase(entries_.begin() + from);
+ entries_.insert(entries_.begin() + to, std::move(entry)); endMoveRows();
+ if (sort_ != Manual) { sort_ = Manual; emit sortModeChanged(); }
+ emit currentChanged(); saveTimer_.start(); return true;
+}
+bool PlaylistModel::remove(int row) {
+ if (row < 0 || row >= count()) return false;
+ beginRemoveRows({}, row, row); keys_.remove(entries_[row].key); entries_.erase(entries_.begin() + row); endRemoveRows();
+ emit countChanged(); emit currentChanged(); setStatus({}); saveTimer_.start(); return true;
+}
+void PlaylistModel::clear() {
+ ++generation_;
+ { std::lock_guard lock(mutex_); jobs_.clear(); }
+ const bool wasBusy = busy(); pending_ = 0;
+ beginResetModel(); entries_.clear(); keys_.clear(); endResetModel();
+ if (wasBusy) emit busyChanged();
+ emit countChanged(); emit currentChanged();
+ setStatus({}); saveTimer_.start();
+}
+void PlaylistModel::sortBy(int mode) {
+ if (mode < Manual || mode > SmallestFirst) return;
+ if (mode != Manual && count() > 1) {
+ // A layout change keeps the identity of any persistent model indices.
+ emit layoutAboutToBeChanged();
+ const auto indices = persistentIndexList(); QStringList paths;
+ for (const auto& item : indices) paths << entries_[item.row()].key;
+ order(entries_, mode);
+ QModelIndexList replacements;
+ for (const auto& key : paths) {
+ const auto it = std::find_if(entries_.begin(), entries_.end(), [&](const auto& e) { return e.key == key; });
+ replacements << index(int(it - entries_.begin()));
+ }
+ changePersistentIndexList(indices, replacements); emit layoutChanged(); emit currentChanged();
+ }
+ if (sort_ != mode) { sort_ = mode; emit sortModeChanged(); }
+ saveTimer_.start();
+}
+bool PlaylistModel::save() {
+ saveTimer_.stop();
+ if (storage_.isEmpty()) return true;
+ QJsonArray array;
+ for (const auto& entry : entries_) array.append(QJsonObject{{"path", entry.path}, {"size", double(entry.size)}, {"modified", double(entry.modified)}});
+ QSaveFile file(storage_);
+ const auto bytes = QJsonDocument(QJsonObject{{"version", 1}, {"sort", sort_}, {"autoAdvance", autoAdvance_}, {"entries", array}}).toJson(QJsonDocument::Compact);
+ if (!file.open(QIODevice::WriteOnly) || file.write(bytes) != bytes.size() || !file.commit()) {
+ emit error(tr("播放列表保存失败:%1").arg(file.errorString())); return false;
+ }
+ return true;
+}
+void PlaylistModel::load() {
+ if (storage_.isEmpty()) return;
+ QFile file(storage_);
+ if (!file.exists()) return;
+ if (!file.open(QIODevice::ReadOnly) || file.size() > 16 * 1024 * 1024) {
+ status_ = tr("播放列表文件无法读取,已使用空列表"); return;
+ }
+ QJsonParseError error;
+ const auto doc = QJsonDocument::fromJson(file.readAll(), &error);
+ const auto object = doc.object();
+ if (error.error != QJsonParseError::NoError || object.value("version").toInt() != 1 || !object.value("entries").isArray()) {
+ status_ = tr("播放列表文件损坏,已使用空列表"); return;
+ }
+ sort_ = std::clamp(object.value("sort").toInt(), int(Manual), int(SmallestFirst));
+ autoAdvance_ = object.value("autoAdvance").toBool(true);
+ for (const auto& value : object.value("entries").toArray()) {
+ const auto entry = value.toObject(); const auto path = entry.value("path").toString();
+ if (path.isEmpty() || !QDir::isAbsolutePath(path) || !supported(path)) continue;
+ const auto normalized = normalizedPath(path), key = keyOf(normalized);
+ if (keys_.contains(key)) continue;
+ keys_.insert(key);
+ entries_.push_back({normalized, QFileInfo(normalized).fileName(), key,
+ std::max(qint64(0), entry.value("size").toInteger()),
+ entry.value("modified").toInteger()});
+ if (count() >= maxEntries) break;
+ }
+}
+}
diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cpp
index b147f0d3..f6ede25e 100644
--- a/src/ui/QmlPlayerBridge.cpp
+++ b/src/ui/QmlPlayerBridge.cpp
@@ -4,6 +4,7 @@
#include "veyra/ui/EffectAvailability.h"
#include "veyra/engine/FrameGenerationSelection.h"
#include "veyra/ui/QmlExportQueueModel.h"
+#include "veyra/ui/PlaylistModel.h"
#include "veyra/ui/UiLanguage.h"
#include <QQmlEngine>
#include <QMetaMethod>
@@ -295,6 +296,9 @@ struct QmlPlayerBridge::Impl {
QVariantMap anchors;
// Where the user's own files live (the facade resolves the same default).
std::filesystem::path dataDir;
+ PlaylistModel* playlist = nullptr;
+ QString playlistPath;
+ uint64_t playlistSession = 0, playlistCompletedSession = 0;
// --- subtitles (ported from the Win32 shell, same semantics) ---
std::unique_ptr<engine::SubtitleLoader> subLoader;
std::unique_ptr<engine::SubtitleLoader> subFileLoader;
@@ -1014,6 +1018,16 @@ QVariantList QmlPlayerBridge::srBackendChoices() const {
QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesystem::path dataDirectory,
QObject* parent)
: QObject(parent), impl_(std::make_unique<Impl>(engine, std::move(dataDirectory))) {
+ impl_->playlist = new PlaylistModel(utf8Of((impl_->dataDir / L"playlist.v1.json").wstring()), this);
+ connect(impl_->playlist, &PlaylistModel::playRequested, this, [this](const QString& path) {
+ openPath(path);
+ // Explicit playlist selection starts at the beginning; opening from
+ // recent files retains the existing resume-position preference.
+ impl_->resumeSession = 0;
+ });
+ connect(impl_->playlist, &PlaylistModel::error, this, [this](const QString& text) {
+ veyra::log::warn("playlist", text.toStdString()); emit notice(text, true);
+ });
connect(this,&QmlPlayerBridge::snapshotChanged,this,
[this,ceiling=fgMaxMultiplier(),text=fgProviderText()]() mutable {
const auto nextCeiling=fgMaxMultiplier();const auto nextText=fgProviderText();
@@ -1296,6 +1310,7 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst
// An export in flight needs its own poll; it is a separate job and its
// snapshot is not part of the player snapshot.
if (impl_->exportQueue.queue().needsTick()) pollExport();
+ tickPlaylist();
});
impl_->timer->start(16);
startGpuSampler();
@@ -4823,8 +4838,67 @@ void QmlPlayerBridge::openFileDialog() {
}
int QmlPlayerBridge::thumbnailGeneration() const { return impl_->thumbnailGeneration; }
+QObject* QmlPlayerBridge::playlist() const { return impl_->playlist; }
+void QmlPlayerBridge::showPlaylist() { emit playlistRequested(); }
+void QmlPlayerBridge::addPlaylistFilesDialog() {
+ const auto paths = QFileDialog::getOpenFileNames(nullptr, tr("添加文件到播放列表"), {},
+ tr("媒体文件 (*.mp4 *.mkv *.mov *.avi *.webm *.ts *.m2ts *.mts *.m4v *.wmv *.mpg *.mpeg *.vob *.flv *.ogv *.asf *.3gp *.jpg *.jpeg *.png *.bmp *.webp);;所有文件 (*)"));
+ if (!paths.isEmpty()) { impl_->playlist->addPaths(paths); emit playlistRequested(); }
+}
+void QmlPlayerBridge::addPlaylistFolderDialog() {
+ const auto path = QFileDialog::getExistingDirectory(nullptr, tr("导入文件夹到播放列表"));
+ if (!path.isEmpty()) { impl_->playlist->addPaths({path}); emit playlistRequested(); }
+}
+void QmlPlayerBridge::openDroppedUrls(const QList<QUrl>& urls) {
+ // A single file on the video retains drag-to-open. Folder/multi-file drops
+ // append to the playlist; dropping inside PlaylistWindow always appends.
+ if (urls.size() == 1) {
+ const QUrl url = urls.front();
+ if (url.isLocalFile() && !QFileInfo(url.toLocalFile()).isDir()) { openUrl(url); return; }
+ }
+ impl_->playlist->addUrls(urls);
+ emit playlistRequested();
+}
+void QmlPlayerBridge::tickPlaylist() {
+ const auto& s = impl_->snapshot;
+ using T = engine::TransportState;
+ if (!impl_->playlistSession) return;
+ if (!impl_->liveKind.isEmpty() || utf8Of(impl_->sourceLabel) != impl_->playlistPath) {
+ impl_->playlistSession = 0; impl_->playlist->setPlayback({}, {}); return;
+ }
+ if (s.sessionId != impl_->playlistSession) return; // Ignore old session snapshots after open.
+ if (s.capture || s.remotePlay) { impl_->playlistSession = 0; impl_->playlist->setPlayback({}, {}); return; }
+ QString state = QStringLiteral("stopped");
+ switch (s.transport) {
+ case T::Opening: state = QStringLiteral("opening"); break;
+ case T::Playing: state = s.image ? QStringLiteral("image") : QStringLiteral("playing"); break;
+ case T::Paused: state = QStringLiteral("paused"); break;
+ case T::Ended: state = QStringLiteral("ended"); break;
+ case T::Failed: state = QStringLiteral("failed"); break;
+ default: break;
+ }
+ impl_->playlist->setPlayback(impl_->playlistPath, state);
+ if (s.transport != T::Ended || s.failed || s.image || impl_->openingSource ||
+ impl_->playlistCompletedSession == s.sessionId) return;
+ impl_->playlistCompletedSession = s.sessionId;
+ // Wait for this GUI tick to finish, then recheck the engine session. A stop,
+ // new file, or live source selected in between must cancel auto-advance.
+ QTimer::singleShot(0, this, [this, session = s.sessionId] {
+ const auto latest = impl_->engine.snapshot();
+ if (impl_->playlistSession == session && latest.sessionId == session &&
+ latest.transport == T::Ended && !latest.failed && !latest.image && impl_->liveKind.isEmpty())
+ impl_->playlist->advanceAfterEnd();
+ });
+}
+
void QmlPlayerBridge::openPath(const QString& path) {
if (path.isEmpty()) return;
+ if (QFileInfo(path).isDir()) {
+ impl_->playlist->addPaths({path}); emit playlistRequested(); return;
+ }
+ if (PlaylistModel::supported(path) && !impl_->playlist->containsPath(path)) impl_->playlist->addPaths({path});
+ impl_->playlistPath = path;
+ impl_->playlist->setPlayback(path, QStringLiteral("opening"));
rememberPosition(true);
impl_->exportQueue.setSelectedId(0);
++impl_->liveOpenGen; impl_->pendingLiveText.clear(); // a waiting live open is dropped
@@ -4858,6 +4932,7 @@ void QmlPlayerBridge::openPath(const QString& path) {
options.hardwareDecodeOnly = impl_->prefString("decode") == QLatin1String("hardware");
impl_->engine.open(impl_->videoWindow, wide, options);
impl_->openingSessionId = impl_->engine.snapshot().sessionId;
+ impl_->playlistSession = impl_->openingSessionId;
impl_->resumeSession = 0;
if ((impl_->prefBool("rememberPosition", true)||impl_->prefBool("autoResume",false))) {
const auto saved = impl_->prefs.value("positions").toMap().value(path).toMap();
@@ -4893,6 +4968,8 @@ void QmlPlayerBridge::togglePlayPause() {
veyra::log::info("ui-transport", pause ? "pause" : "resume");
}
void QmlPlayerBridge::stopPlayback() {
+ impl_->playlistSession = 0;
+ impl_->playlist->setPlayback(impl_->playlistPath, QStringLiteral("stopped"));
rememberPosition(true);
++impl_->liveOpenGen; impl_->pendingLiveText.clear();
impl_->openingSource = false;
diff --git a/tests/qml/PlaylistWindowTests.cpp b/tests/qml/PlaylistWindowTests.cpp
new file mode 100644
index 00000000..5f2c2d70
--- /dev/null
+++ b/tests/qml/PlaylistWindowTests.cpp
@@ -0,0 +1,137 @@
+#include "veyra/ui/PlaylistModel.h"
+#include <QDir>
+#include <QDragEnterEvent>
+#include <QDropEvent>
+#include <QDragMoveEvent>
+#include <QFile>
+#include <QFileInfo>
+#include <QGuiApplication>
+#include <QMimeData>
+#include <QQmlComponent>
+#include <QQmlEngine>
+#include <QQmlContext>
+#include <QQuickItem>
+#include <QQuickWindow>
+#include <QTest>
+#include <QUrl>
+#include <cstdio>
+#include <memory>
+
+namespace {
+int assertions = 0, failures = 0;
+QStringList warnings;
+void messages(QtMsgType type, const QMessageLogContext&, const QString& message) {
+ if (type == QtWarningMsg || type == QtCriticalMsg || type == QtFatalMsg) warnings << message;
+ std::fprintf(stderr, "%s\n", message.toUtf8().constData());
+}
+void check(bool condition, const char* message) {
+ ++assertions; std::printf("%s %s\n", condition ? "PASS" : "FAIL", message);
+ if (!condition) ++failures;
+}
+QQuickItem* find(QQuickItem* item, const QString& name) {
+ if (item->objectName() == name) return item;
+ for (auto* child : item->childItems()) if (auto* found = find(child, name)) return found;
+ return nullptr;
+}
+QPoint point(QQuickItem* item) { return item->mapToScene(QPointF(item->width()/2, item->height()/2)).toPoint(); }
+bool click(QQuickWindow* win, const char* name, bool twice = false) {
+ auto* item = find(win->contentItem(), QString::fromUtf8(name));
+ if (!item) { check(false, name); return false; }
+ if (twice) QTest::mouseDClick(win, Qt::LeftButton, Qt::NoModifier, point(item));
+ else QTest::mouseClick(win, Qt::LeftButton, Qt::NoModifier, point(item));
+ QTest::qWait(80); return true;
+}
+void dropUrls(QQuickWindow* win, const QList<QUrl>& urls) {
+ QMimeData mime; mime.setUrls(urls);
+ QDragEnterEvent enter(QPoint(180, 240), Qt::CopyAction, &mime, Qt::LeftButton, Qt::NoModifier);
+ QCoreApplication::sendEvent(win, &enter);
+ check(enter.isAccepted(), "native URL drag accepted");
+ QDragMoveEvent move(QPoint(180, 240), Qt::CopyAction, &mime, Qt::LeftButton, Qt::NoModifier);
+ QCoreApplication::sendEvent(win, &move);
+ QDropEvent event(QPointF(180, 240), Qt::CopyAction, &mime, Qt::LeftButton, Qt::NoModifier);
+ QCoreApplication::sendEvent(win, &event);
+ check(event.isAccepted(), "native URL drop accepted");
+}
+void drop(QQuickWindow* win, const QString& path) { dropUrls(win, {QUrl::fromLocalFile(path)}); }
+}
+int main(int argc, char** argv) {
+ QGuiApplication app(argc, argv);
+ qInstallMessageHandler(messages);
+ if (argc != 2) return 2;
+ const auto path = QString::fromLocal8Bit(argv[1]);
+ if (!QDir::isAbsolutePath(path) || QFileInfo::exists(path)) return 2;
+ QDir().mkpath(path);
+ for (int i = 1; i <= 12; ++i) { QFile f(path + QString("/file%1.mp4").arg(i)); f.open(QIODevice::WriteOnly); f.write("metadata fixture"); }
+ veyra::ui::PlaylistModel model;
+ model.addPaths({path});
+ for (int i = 0; i < 200 && model.busy(); ++i) QTest::qWait(10);
+ check(model.count() == 12 && !model.busy(), "production model ready");
+ const QString playing = model.pathAt(0);
+ model.setPlayback(playing, "playing");
+ QString requested;
+ QObject::connect(&model, &veyra::ui::PlaylistModel::playRequested, [&](const auto& selected) { requested = selected; });
+ QQmlEngine engine;
+ engine.addImportPath(QString::fromUtf8(VEYRA_QML_DIR));
+ engine.rootContext()->setContextProperty("testPlaylist", &model);
+ QQmlComponent component(&engine);
+ component.setData("import QtQuick\nimport Veyra\nWindow { id: owner; x: 40; y: 40; width: 800; height: 500; visible: true; PlaylistWindow { owner: owner; playlist: testPlaylist } }", QUrl());
+ std::unique_ptr<QObject> object(component.create());
+ if (!object) { std::fprintf(stderr, "%s\n", component.errorString().toUtf8().constData()); return 1; }
+ auto* owner = qobject_cast<QQuickWindow*>(object.get());
+ auto* win = object->findChild<QQuickWindow*>("playlistWindow");
+ check(win && owner && win->transientParent() == owner, "independent window belongs to player");
+ if (!win) return 1;
+ QMetaObject::invokeMethod(win, "open");
+ check(QTest::qWaitForWindowExposed(win), "playlist window opens");
+ QTest::qWait(250);
+ auto* badge = find(win->contentItem(), "playlist-state-0");
+ check(badge && badge->property("text").toString() == QString::fromUtf8("正在播放"), "real model state shown in row");
+ auto* grip = find(win->contentItem(), "playlist-grip-0");
+ auto* row2 = find(win->contentItem(), "playlist-row-2");
+ if (grip && row2) {
+ const auto first = point(grip), destination = QPoint(first.x(), point(row2).y());
+ QTest::mousePress(win, Qt::LeftButton, Qt::NoModifier, first);
+ QTest::mouseMove(win, destination, 100);
+ QTest::mouseRelease(win, Qt::LeftButton, Qt::NoModifier, destination);
+ QTest::qWait(100);
+ check(model.currentIndex() == 2 && model.pathAt(2) == playing, "mouse drag reorders while current file follows");
+ } else check(false, "visible drag handles");
+ model.setPlayback(playing, "paused"); QTest::qWait(50);
+ badge = find(win->contentItem(), "playlist-state-2");
+ check(badge && badge->property("text").toString() == QString::fromUtf8("已暂停"), "paused badge changes without replacing playlist");
+ click(win, "playlist-select-1", true);
+ check(veyra::ui::PlaylistModel::normalizedPath(requested) == model.pathAt(1), "double click emits playback request");
+ const auto removed = model.pathAt(1); click(win, "playlist-remove-1");
+ check(model.count() == 11 && QFileInfo::exists(removed), "remove button only removes list item");
+ requested.clear();
+ QDir().mkpath(path + "/追加"); QFile extra(path + "/追加/added.mkv"); extra.open(QIODevice::WriteOnly); extra.write("new"); extra.close();
+ drop(win, path + "/追加");
+ QTest::qWait(20);
+ for (int i = 0; i < 200 && model.busy(); ++i) QTest::qWait(10);
+ std::printf("DROP count=%d current=%d requested=%s status=%s\n", model.count(), model.currentIndex(), requested.toUtf8().constData(), model.status().toUtf8().constData());
+ check(model.count() == 12 && requested.isEmpty() && model.pathAt(model.currentIndex()) == playing, "folder drop appends while playback selection stays");
+ QDir().mkpath(path + "/outside");
+ for (const auto& name : {"one.mp4", "two.mkv", "three.mp4"}) {
+ QFile file(path + "/outside/" + name); file.open(QIODevice::WriteOnly); file.write("file drop fixture");
+ }
+ dropUrls(win, {QUrl::fromLocalFile(path + "/outside/one.mp4"), QUrl::fromLocalFile(path + "/outside/two.mkv")});
+ QTest::qWait(20); for (int i = 0; i < 200 && model.busy(); ++i) QTest::qWait(10);
+ check(model.count() == 14 && requested.isEmpty(), "multiple files from another folder append without playback");
+ drop(win, path + "/outside/three.mp4");
+ QTest::qWait(20); for (int i = 0; i < 200 && model.busy(); ++i) QTest::qWait(10);
+ check(model.count() == 15 && requested.isEmpty(), "single file drop in playlist appends instead of switching video");
+ auto* list = find(win->contentItem(), "playlist-list");
+ win->resize(620, 480); win->setPosition(win->x() + 25, win->y() + 30); QTest::qWait(100);
+ check(win->width() == 620 && win->height() == 480 && list && list->width() > 560, "resized layout adapts without clipping controls");
+ check(find(win->contentItem(), "playlist-title-drag") && find(win->contentItem(), "playlist-resize-10"), "system move and corner resize input handles exist");
+ click(win, "playlist-close");
+ check(!win->isVisible() && owner->isVisible(), "close hides playlist without closing player");
+ QMetaObject::invokeMethod(win, "open"); QTest::qWait(100);
+ check(win->isVisible() && win->width() == 620 && win->height() == 480, "reopen preserves window size");
+ check(warnings.isEmpty(), "no QML binding/import/runtime warnings");
+ win->grabWindow().save(path + "/playlist.png");
+ owner->close(); QTest::qWait(100);
+ check(!win->isVisible(), "closing owner also hides playlist");
+ std::printf("%s playlist window assertions=%d\n", failures ? "FAIL" : "PASS", assertions);
+ return failures ? 1 : 0;
+}
diff --git a/tests/unit/PlaylistModelTests.cpp b/tests/unit/PlaylistModelTests.cpp
new file mode 100644
index 00000000..8011c90a
--- /dev/null
+++ b/tests/unit/PlaylistModelTests.cpp
@@ -0,0 +1,125 @@
+#include "veyra/ui/PlaylistModel.h"
+#include <QCoreApplication>
+#include <QDateTime>
+#include <QDir>
+#include <QElapsedTimer>
+#include <QFile>
+#include <QFileInfo>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QPersistentModelIndex>
+#include <QThread>
+#include <QUrl>
+#include <cstdio>
+#include <functional>
+
+using veyra::ui::PlaylistModel;
+namespace {
+int assertions = 0, failures = 0;
+void check(bool condition, const char* message) {
+ ++assertions;
+ if (!condition) { ++failures; std::fprintf(stderr, "FAIL %s\n", message); }
+}
+bool wait(const std::function<bool()>& ready) {
+ QElapsedTimer timer; timer.start();
+ do { QCoreApplication::processEvents(); if (ready()) return true; QThread::msleep(1); } while (timer.elapsed() < 15000);
+ return false;
+}
+void make(const QString& path, int size, qint64 modified) {
+ QDir().mkpath(QFileInfo(path).path());
+ QFile file(path); check(file.open(QIODevice::WriteOnly), "fixture create");
+ check(file.write(QByteArray(size, 'x')) == size, "fixture bytes");
+ check(file.setFileTime(QDateTime::fromMSecsSinceEpoch(modified), QFileDevice::FileModificationTime), "fixture date");
+}
+QString name(PlaylistModel& model, int row) { return model.data(model.index(row), PlaylistModel::NameRole).toString(); }
+}
+int main(int argc, char** argv) {
+ QCoreApplication app(argc, argv);
+ if (argc != 2) return 2;
+ const QString root = QString::fromLocal8Bit(argv[1]);
+ if (!QDir::isAbsolutePath(root) || QFileInfo(root).exists()) { std::fprintf(stderr, "Use a fresh absolute fixture directory\n"); return 2; }
+ QDir().mkpath(root);
+ const auto folder = root + "/影片 α";
+ const qint64 time = 1700000000000LL;
+ for (int i = 320; i >= 1; --i) make(folder + QString("/movie%1.MKV").arg(i), i, time + i * 2000);
+ make(folder + "/子文件夹/中文片名.mp4", 900, time + 900000);
+ make(folder + "/notes.txt", 12, time);
+ const QString storage = root + "/playlist.json";
+ QString playing, error;
+ PlaylistModel model(storage);
+ QObject::connect(&model, &PlaylistModel::playRequested, &app, [&](const auto& path) { playing = path; });
+ QObject::connect(&model, &PlaylistModel::error, &app, [&](const auto& text) { error = text; });
+ QElapsedTimer elapsed; elapsed.start(); model.addPaths({folder});
+ const auto submitted = elapsed.elapsed();
+ check(submitted < 50, "folder import returns to GUI within 50ms");
+ check(model.busy() && model.count() == 0, "enumeration is queued off GUI thread");
+ int heartbeats = 0; QTimer pulse; pulse.setInterval(1); QObject::connect(&pulse, &QTimer::timeout, [&] { ++heartbeats; }); pulse.start();
+ check(wait([&] { return !model.busy(); }), "321 entries imported");
+ const auto scanned = elapsed.elapsed();
+ check(model.count() == 321 && heartbeats > 0, "200+ import includes nested media while UI timer runs");
+ check(name(model, 0) == "movie1.MKV" && name(model, 1) == "movie2.MKV", "natural names keep 2 before 10");
+ check(playing.isEmpty(), "import never starts playback");
+ for (int i = 0; i < 320; ++i) check(name(model, i) == QString("movie%1.MKV").arg(i + 1), "all naturally ordered files present once");
+ model.addPaths({folder, folder + "/movie2.MKV"});
+ check(wait([&] { return !model.busy(); }) && model.count() == 321, "overlapping folder/file drops deduplicate");
+ const QString chosen = model.pathAt(9);
+ model.setPlayback(chosen, "playing");
+ check(model.currentIndex() == 9 && model.data(model.index(9), PlaylistModel::StateRole) == "playing", "actual playback marker");
+ QPersistentModelIndex persistent(model.index(9));
+ check(model.move(9, 0) && model.currentIndex() == 0 && persistent.row() == 0, "drag reorder preserves current and persistent index");
+ model.sortBy(PlaylistModel::LargestFirst);
+ check(name(model, 0) == QString::fromUtf8("中文片名.mp4") && model.pathAt(persistent.row()) == chosen, "size sort preserves file identity");
+ model.sortBy(PlaylistModel::SmallestFirst); check(name(model, 0) == "movie1.MKV", "smallest first");
+ model.sortBy(PlaylistModel::NewestFirst); check(name(model, 0) == QString::fromUtf8("中文片名.mp4"), "newest first");
+ model.sortBy(PlaylistModel::OldestFirst); check(name(model, 0) == "movie1.MKV", "oldest first");
+ model.sortBy(PlaylistModel::NameDescending); check(name(model, model.count() - 1) == "movie1.MKV", "descending names");
+ model.sortBy(PlaylistModel::NameAscending); check(name(model, 1) == "movie2.MKV", "ascending names");
+ model.setPlayback(chosen, "paused"); check(model.data(model.index(model.currentIndex()), PlaylistModel::StateRole) == "paused", "paused is not falsely playing");
+ const auto kept = model.pathAt(3);
+ check(model.remove(3) && QFileInfo::exists(kept) && model.count() == 320, "remove never deletes disk file");
+ check(model.pathAt(model.currentIndex()) == chosen, "removing another row preserves playing file");
+ make(root + "/other/extra.mp4", 44, time);
+ model.addUrls({QUrl::fromLocalFile(root + "/other"), QUrl("https://invalid.example/test.mkv")});
+ check(wait([&] { return !model.busy(); }) && model.count() == 321 && playing.isEmpty(), "another folder appends without play and remote URLs ignored");
+ check(model.pathAt(model.currentIndex()) == chosen, "append plus sort preserves current path");
+ check(model.play(model.currentIndex()) && PlaylistModel::normalizedPath(playing) == chosen, "selection invokes shared playback command");
+ playing.clear(); model.setAutoAdvance(false);
+ check(!model.advanceAfterEnd() && playing.isEmpty(), "auto advance toggle off");
+ model.setAutoAdvance(true); model.sortBy(PlaylistModel::NameAscending);
+ model.setPlayback(model.pathAt(0), "ended");
+ check(model.advanceAfterEnd() && playing.endsWith("movie1.MKV"), "next follows current list order");
+ model.setPlayback(model.pathAt(model.count() - 1), "ended"); playing.clear();
+ check(!model.advanceAfterEnd() && playing.isEmpty(), "last item does not wrap");
+ model.setPlayback(chosen, "playing");
+ const int before = model.count(); model.remove(model.currentIndex());
+ check(model.currentIndex() == -1 && model.count() == before - 1 && !model.advanceAfterEnd(), "removing active item does not mislabel its successor");
+ model.setAutoAdvance(false);
+ check(model.save(), "atomic JSON save");
+ {
+ PlaylistModel restored(storage);
+ check(restored.count() == model.count() && !restored.autoAdvance() && restored.currentIndex() == -1, "restore order/options without fake playing marker");
+ for (int i = 0; i < model.count(); ++i) check(restored.pathAt(i) == model.pathAt(i), "persistent list order exact");
+ }
+ // Missing files remain visible after restart; playing one gives an error,
+ // rather than silently deleting the user's list or opening a dead session.
+ const QString missing = root + "/missing.json";
+ QFile out(missing); out.open(QIODevice::WriteOnly);
+ out.write(QJsonDocument(QJsonObject{{"version", 1}, {"entries", QJsonArray{QJsonObject{{"path", root + "/gone.mp4"}}}}}).toJson()); out.close();
+ PlaylistModel absent(missing);
+ QObject::connect(&absent, &PlaylistModel::error, [&](const auto& text) { error = text; });
+ check(absent.count() == 1 && !absent.play(0) && !error.isEmpty(), "missing media is explicit, retained, and never played");
+ QFile damaged(root + "/bad.json"); damaged.open(QIODevice::WriteOnly); damaged.write("{broken"); damaged.close();
+ PlaylistModel invalid(root + "/bad.json"); check(invalid.count() == 0 && !invalid.status().isEmpty(), "invalid JSON handled");
+ model.clear(); check(model.count() == 0 && !model.busy(), "clear leaves no list or scan state");
+ model.addPaths({folder}); model.clear(); model.addPaths({root + "/other"});
+ check(wait([&] { return !model.busy(); }) && model.count() == 1 && name(model, 0) == "extra.mp4", "clear cancels stale queued scan results");
+ model.clear(); model.addPaths({folder}); model.addPaths({root + "/other"});
+ check(wait([&] { return !model.busy(); }) && model.count() == 322, "queued folder jobs both append");
+ { PlaylistModel closing; closing.addPaths({folder}); } // joins without use-after-free callbacks
+ QCoreApplication::processEvents();
+ check(!model.move(-1, 1) && !model.remove(9000) && !model.play(-1), "invalid selections safely rejected");
+ std::printf("%s playlist assertions=%d importReturnMs=%lld scan321Ms=%lld uiHeartbeats=%d\n",
+ failures ? "FAIL" : "PASS", assertions, submitted, scanned, heartbeats);
+ return failures ? 1 : 0;
+}