diff --git a/docs/files.md b/docs/files.md index 861e8a95..64ec51dd 100644 --- a/docs/files.md +++ b/docs/files.md @@ -27,6 +27,9 @@ double-click to open, right-click for the menu, `Ctrl`/`Shift`+click to mark. | folder | its contents, with sizes and dates; the header adds the folder's total size | | image | the image, with its pixel size | | video | plays muted; `Space` pauses (`Shift+Space` types a space), `Alt+M` toggles sound, the fullsize button opens mpv | +| audio (mp3, flac, wav, ogg, oga, opus, m4a, aac) | its cover, title and artist over its waveform, which fills in as it plays; `Space` plays and pauses, a click on the waveform seeks | +| PDF | every page, drawn as it scrolls into view; `Shift+↑` `Shift+↓` scroll | +| 3D model (glb, gltf, obj, stl, ply, fbx) | turns with a drag or `Shift`+arrows, zooms with the wheel; needs the optional `qt6-quick3d` and `assimp`. Converted outside the shell: past 8 MB that takes a moment, which the preview says. Past 128 MB, or for a point cloud such as a Gaussian splat (points, no faces), there is no preview, and it says why | | Markdown | rendered | | other text | syntax highlighted, with line numbers | | anything else | its size | diff --git a/docs/wheel.md b/docs/wheel.md index 151a8eb7..7c9d9ed9 100644 --- a/docs/wheel.md +++ b/docs/wheel.md @@ -34,7 +34,7 @@ A row with a keybinding shows its keys last; on the selected row, keys that do n |---|---| | anything | everything above | | `workspace` | every open window; `workspace 2` the ones on 2 | -| `/` | files and folders under home and any folders you add | +| `/` | files and folders under home and any folders you add; a pasted full path that exists, however deep | | `=` | a calculation; `Enter` copies the answer | | `help` | the manual; `Enter` shows it on one screen | | `wheely settings` | the wheel's settings | diff --git a/plugins/xpo.files/Files.qml b/plugins/xpo.files/Files.qml index 89525405..3dfcddda 100644 --- a/plugins/xpo.files/Files.qml +++ b/plugins/xpo.files/Files.qml @@ -115,14 +115,20 @@ Item { readonly property int lineHeight: Math.round(Style.font.subtitle * 1.75) readonly property int previewLimit: 262144 - // What an entry previews as: "image", "video" or "". A handler of settledSel asks it of the entry, - // since it runs before the bindings below and would see the last entry's answer. + // What an entry previews as: "image", "video", "audio", "pdf", "model" or "". A handler of settledSel + // asks it of the entry, since it runs before the bindings below and would see the last entry's answer. function media(e) { return !e || e.isDir || e.missing ? "" - : FilesIndex.isImage(e.name) ? "image" : FilesIndex.isVideo(e.name) ? "video" : "" + : FilesIndex.isImage(e.name) ? "image" : FilesIndex.isVideo(e.name) ? "video" + : FilesIndex.isAudio(e.name) ? "audio" : FilesIndex.isPdf(e.name) ? "pdf" : FilesIndex.isModel(e.name) ? "model" : "" } readonly property bool showsImage: root.media(root.settledSel) === "image" readonly property bool showsVideo: root.media(root.settledSel) === "video" + readonly property bool showsAudio: root.media(root.settledSel) === "audio" + // balsam converts a model in its own process, but the shell still loads what it makes, in a time + // that grows with its size: past 128 MB, no preview. + readonly property bool showsModel: root.media(root.settledSel) === "model" && root.settledSel.size <= 134217728 + readonly property bool showsPdf: root.media(root.settledSel) === "pdf" property string imageDims: "" FilesProcess { id: measurer @@ -148,7 +154,7 @@ Item { readonly property bool showsMarkdown: !root.showsDiff && !!root.settledSel && !root.settledSel.isDir && !root.settledSel.missing && FilesIndex.isMarkdown(root.settledSel.name) readonly property string previewPath: - (root.settledSel && !root.settledSel.isDir && !root.settledSel.missing && !root.showsImage && !root.showsVideo + (root.settledSel && !root.settledSel.isDir && !root.settledSel.missing && !root.media(root.settledSel) && root.settledSel.size <= root.previewLimit) ? root.settledSel.path : "" // Keep the full file for safe editing. The preview lays out three screens of folder rows, over two of code, // and twice as many whenever scrolling nears their end. @@ -258,7 +264,7 @@ Item { } } // Read whether shown or not, so the heading can count its lines. Only changed files have - // a diff; the rest, images and videos, keep their usual preview. + // a diff; the rest, and media of every kind, keep their usual preview. function readDiff() { differ.cancel() var e = root.settledSel @@ -346,8 +352,17 @@ Item { : root.showsCode || root.previewBody || root.showsDiff ? "" : root.settledSel.missing ? "Deleted · Ctrl+D shows changes" : (root.showsVideo && preview.videoStatus !== Loader.Error) ? "" + : (root.showsAudio && preview.audioStatus !== Loader.Error) ? "" + // Past 8 MB, converting a model takes long enough to say so until it shows. + : (root.showsModel && !preview.modelFailed && !(preview.modelLoading && root.settledSel.size > 8388608)) ? "" : (root.showsImage && preview.imageStatus !== Image.Error) ? "" + : (root.showsPdf && !preview.pdfFailed) ? "" : FilesIndex.humanSize(root.settledSel.size) + " · no preview" + + (root.media(root.settledSel) !== "model" ? "" + : !root.showsModel ? "\nOver 128 MB, too large to preview" + : preview.modelLoading ? "\nLarge model, it takes a moment to load" + : preview.modelNeeds ? "\nInstall " + preview.modelNeeds + " to preview 3D models" + : preview.modelPoints ? "\nA point cloud, not a mesh" : "") // Payloads may choose a start; otherwise use the stable home directory. // A popped-out window is raised instead, and keeps its place unless sent elsewhere. diff --git a/plugins/xpo.files/FilesAudio.qml b/plugins/xpo.files/FilesAudio.qml new file mode 100644 index 00000000..d95fd97e --- /dev/null +++ b/plugins/xpo.files/FilesAudio.qml @@ -0,0 +1,94 @@ +import QtQuick +import QtMultimedia +import qs.Commons +import qs.Commons as Commons +import "FilesIndex.js" as FilesIndex + +// A song: its cover, title and artist over its waveform, which fills in as it plays. Space plays it; +// it never starts on its own, so stepping through a folder of music stays quiet. +Item { + id: root + property string path: "" + property string cover: "" + property string wave: "" + + function toggle() { if (player.playing) player.pause(); else player.play() } + + MediaPlayer { + id: player + source: root.path ? FilesIndex.fileUrl(root.path) : "" + audioOutput: AudioOutput { volume: 0.7 } + } + Component.onDestruction: player.stop() + + // ffmpeg draws both as PNG data URLs: the embedded cover, if any, and the waveform in the accent. + FilesProcess { id: coverer; onFinished: output => root.cover = output ? "data:image/png;base64," + output : "" } + FilesProcess { id: waver; onFinished: output => root.wave = output ? "data:image/png;base64," + output : "" } + Component.onCompleted: { + coverer.start(["sh", "-c", 'ffmpeg -v error -i "$1" -an -frames:v 1 -c:v png -f image2pipe - | base64 -w0', "sh", root.path]) + waver.start(["sh", "-c", 'ffmpeg -v error -i "$1" -filter_complex "aformat=channel_layouts=mono,showwavespic=s=1600x240:scale=sqrt:colors=$2"' + + ' -frames:v 1 -c:v png -f image2pipe - | base64 -w0', "sh", root.path, String(Commons.Color.accent)]) + } + + Column { + anchors.centerIn: parent + width: parent.width * 0.8 + spacing: Style.spacing.md + + Image { + anchors.horizontalCenter: parent.horizontalCenter + visible: !!root.cover + source: root.cover + width: Math.min(parent.width, root.height * 0.45) + height: width + fillMode: Image.PreserveAspectCrop + } + Text { + width: parent.width + horizontalAlignment: Text.AlignHCenter + elide: Text.ElideRight + text: player.metaData.stringValue(MediaMetaData.Title) || root.path.slice(root.path.lastIndexOf("/") + 1) + color: Commons.Color.menu.text + font.family: Style.font.menuFamily + font.pixelSize: Style.font.subtitle + } + Text { + width: parent.width + horizontalAlignment: Text.AlignHCenter + elide: Text.ElideRight + text: player.error !== MediaPlayer.NoError ? "Cannot play this file" + : player.metaData.stringValue(MediaMetaData.ContributingArtist) || player.metaData.stringValue(MediaMetaData.AlbumArtist) + color: Commons.Color.menu.text + opacity: 0.6 + font.family: Style.font.menuFamily + font.pixelSize: Style.font.bodySmall + } + + // The waveform dim, and again in full up to where it plays; a click seeks there. + Item { + width: parent.width + height: Style.space(120) + Image { anchors.fill: parent; source: root.wave; opacity: 0.3 } + Item { + width: parent.width * player.position / Math.max(1, player.duration) + height: parent.height + clip: true + Image { width: parent.parent.width; height: parent.height; source: root.wave } + } + MouseArea { + anchors.fill: parent + enabled: player.seekable + cursorShape: Qt.PointingHandCursor + onClicked: mouse => player.position = mouse.x / width * player.duration + } + } + Text { + anchors.horizontalCenter: parent.horizontalCenter + text: (player.playing ? "󰏤 " : "󰐊 ") + FilesIndex.clock(player.position) + " / " + FilesIndex.clock(player.duration) + color: Commons.Color.menu.text + opacity: 0.6 + font.family: Style.font.menuFamily + font.pixelSize: Style.font.caption + } + } +} diff --git a/plugins/xpo.files/FilesHints.qml b/plugins/xpo.files/FilesHints.qml index 396592a7..1b363ce3 100644 --- a/plugins/xpo.files/FilesHints.qml +++ b/plugins/xpo.files/FilesHints.qml @@ -23,6 +23,7 @@ Item { ? [["↑↓", "select"], ["enter", "open"], ["←", "up"], ["shift+↑↓", "scroll"]] : [["↑↓", "scroll"], ["enter", "open"], ["←", "list"]]) .concat(panel && root.panel.showsVideo ? [["space", "play/pause"], ["alt+m", "mute"]] : []) + .concat(panel && root.panel.showsAudio ? [["space", "play/pause"]] : []) readonly property var paste: !panel || !root.panel.held ? [] : ["ctrl+v", (root.panel.held.move ? "move " : "copy ") + root.panel.held.name + " here"] // A window closes like any other, so only the overlay offers esc. diff --git a/plugins/xpo.files/FilesIndex.js b/plugins/xpo.files/FilesIndex.js index c3a0130c..a0cc985d 100644 --- a/plugins/xpo.files/FilesIndex.js +++ b/plugins/xpo.files/FilesIndex.js @@ -149,6 +149,13 @@ function humanSize(bytes) { return (u === 0 ? n : n.toFixed(n < 10 ? 1 : 0)) + units[u] } +// A player's position: m:ss, or h:mm:ss from the first hour. +function clock(ms) { + var s = Math.floor(ms / 1000), m = Math.floor(s / 60), h = Math.floor(m / 60) + return (h ? h + ":" + String(m % 60).padStart(2, "0") : String(m)) + + ":" + String(s % 60).padStart(2, "0") +} + // Only formats available through this Qt installation. var IMAGE = { png: 1, jpg: 1, jpeg: 1, gif: 1, webp: 1, bmp: 1, svg: 1, ico: 1, icns: 1, tif: 1, tiff: 1, tga: 1 } @@ -156,6 +163,10 @@ var IMAGE = { png: 1, jpg: 1, jpeg: 1, gif: 1, webp: 1, bmp: 1, var VIDEO = { mp4: 1, m4v: 1, mkv: 1, webm: 1, mov: 1, avi: 1, mpg: 1, mpeg: 1, ogv: 1, wmv: 1, flv: 1, "3gp": 1, "3g2": 1, m2ts: 1, vob: 1 } +var AUDIO = { mp3: 1, flac: 1, wav: 1, ogg: 1, oga: 1, opus: 1, m4a: 1, aac: 1 } + +var MODEL = { glb: 1, gltf: 1, obj: 1, stl: 1, ply: 1, fbx: 1 } + // StyledText lays code out an order of magnitude faster than rich text. Drop the // last newline, break lines as drawnText() does, and keep other whitespace as written, // through entities StyledText cannot collapse. highlight.py applies the same rules. @@ -382,15 +393,17 @@ function isMarkdown(name) { return /\.(md|markdown|mdown|mkd)$/.test(n) } -function isImage(name) { +// Whether a name, with more than its extension, ends in one of the table's extensions. +function hasExt(name, table) { var cut = String(name).lastIndexOf(".") - return cut > 0 && IMAGE[String(name).slice(cut + 1).toLowerCase()] === 1 + return cut > 0 && table[String(name).slice(cut + 1).toLowerCase()] === 1 } -function isVideo(name) { - var cut = String(name).lastIndexOf(".") - return cut > 0 && VIDEO[String(name).slice(cut + 1).toLowerCase()] === 1 -} +function isImage(name) { return hasExt(name, IMAGE) } +function isVideo(name) { return hasExt(name, VIDEO) } +function isAudio(name) { return hasExt(name, AUDIO) } +function isPdf(name) { return hasExt(name, { pdf: 1 }) } +function isModel(name) { return hasExt(name, MODEL) } // Normalize text files to a trailing newline on save. function endLine(t) { diff --git a/plugins/xpo.files/FilesKeys.js b/plugins/xpo.files/FilesKeys.js index 78196534..d1c7f657 100644 --- a/plugins/xpo.files/FilesKeys.js +++ b/plugins/xpo.files/FilesKeys.js @@ -65,8 +65,8 @@ function onKey(panel, ops, preview, event) { if (menu && (event.key === Qt.Key_Menu || (event.key === Qt.Key_F10 && (event.modifiers & Qt.ShiftModifier)))) { menu.openHere(); event.accepted = true; return } - if (event.key === Qt.Key_Space && panel.showsVideo && !event.modifiers) { - if (!event.isAutoRepeat) preview.toggleVideo() + if (event.key === Qt.Key_Space && (panel.showsVideo || panel.showsAudio) && !event.modifiers) { + if (!event.isAutoRepeat) preview.togglePlay() event.accepted = true return } diff --git a/plugins/xpo.files/FilesModel.qml b/plugins/xpo.files/FilesModel.qml new file mode 100644 index 00000000..c419f640 --- /dev/null +++ b/plugins/xpo.files/FilesModel.qml @@ -0,0 +1,86 @@ +import QtQuick +import QtQuick3D +import QtQuick3D.Helpers +import "FilesIndex.js" as FilesIndex + +// A 3D model, scaled to a fixed size about its centre, turned by dragging and zoomed by scrolling. +// An import blocks its process until done, so Qt's balsam converts the model in a process of its own +// as assimp reads its bounds, and the shell only loads balsam's meshes. Loaded on its own so a shell +// without Qt Quick 3D only loses this preview. +View3D { + id: root + property string path: "" + property bool loading: true + // Without assimp, Qt has no importer for any model. + property bool noImporter: false + // Points with no faces, as a Gaussian splat: nothing for Qt Quick 3D to draw. + property bool pointCloud: false + property string scene: "" + property vector3d low + property vector3d high + readonly property bool failed: !root.loading && (!root.scene || model.status === Loader3D.Error) + + function turn(dx, dy) { + origin.eulerRotation = Qt.vector3d(origin.eulerRotation.x + dx, origin.eulerRotation.y + dy, 0) + } + + // Each conversion clears the last one's files. Its children die with it, as when the preview moves on. + // balsam's complaint, if any, is read with the rest. The shell decodes textures as it shows them, a + // 2048 px one in tens of milliseconds, so past 1024 px, more than a preview needs, they shrink here. + FilesProcess { + id: converter + onFinished: (output, code) => { + var qml = output.match(/^.*\.qml$/m) + var lo = output.match(/^Minimum point\s+\((\S+) (\S+) (\S+)\)/m), hi = output.match(/^Maximum point\s+\((\S+) (\S+) (\S+)\)/m) + root.noImporter = code === 127 + root.pointCloud = output.indexOf("No meshes remaining") >= 0 + if (!code && qml && lo && hi) { + root.low = Qt.vector3d(+lo[1], +lo[2], +lo[3]) + root.high = Qt.vector3d(+hi[1], +hi[2], +hi[3]) + root.scene = FilesIndex.fileUrl(qml[0]) + } + root.loading = false + } + } + Component.onCompleted: converter.start(["sh", "-c", 'command -v assimp >/dev/null || exit 127; ' + + 'm=${XDG_CACHE_HOME:-$HOME/.cache}/wheely/models; rm -rf "$m" && mkdir -p "$m" && d=$(mktemp -d -p "$m") || exit 1; ' + + 'setpriv --pdeathsig TERM assimp info "$1" > "$d/info" & ' + + 'setpriv --pdeathsig TERM /usr/lib/qt6/bin/balsam -o "$d" "$1" 2>&1 >/dev/null || exit 1; ' + + '[ ! -d "$d/maps" ] || setpriv --pdeathsig TERM magick mogrify -resize "1024x1024>" -define png:compression-level=1 "$d"/maps/* 2>/dev/null; ' + + 'wait $! && ls "$d"/*.qml && cat "$d/info"', + "files", root.path]) + + environment: SceneEnvironment { + backgroundMode: SceneEnvironment.Color + clearColor: "black" + antialiasingMode: SceneEnvironment.MSAA + } + + // Seen from a little above and to the side, close enough that the model fills most of the pane. + Node { + id: origin + eulerRotation: Qt.vector3d(-20, 30, 0) + PerspectiveCamera { + id: camera + z: 170 + DirectionalLight { ambientColor: Qt.rgba(0.35, 0.35, 0.35, 1) } + } + } + + // Made over several frames, so a scene of many parts doesn't hold up the shell either. + Loader3D { + id: model + source: root.scene + asynchronous: true + readonly property vector3d size: root.high.minus(root.low) + readonly property real fit: 100 / Math.max(size.x, size.y, size.z, 1e-6) + scale: Qt.vector3d(fit, fit, fit) + position: root.high.plus(root.low).times(-fit / 2) + } + + OrbitCameraController { + anchors.fill: parent + origin: origin + camera: camera + } +} diff --git a/plugins/xpo.files/FilesPdf.qml b/plugins/xpo.files/FilesPdf.qml new file mode 100644 index 00000000..c0864005 --- /dev/null +++ b/plugins/xpo.files/FilesPdf.qml @@ -0,0 +1,49 @@ +import QtQuick +import qs.Commons + +// A PDF's pages in a column, each drawn by pdftoppm only once it scrolls near the view. +// Every page takes the first page's shape; a page of another shape is fitted inside it. +ListView { + id: root + property string path: "" + property int pages: 0 + property real aspect: 1.414 + property bool failed: false + + clip: true + spacing: Style.spacing.md + boundsBehavior: Flickable.StopAtBounds + model: root.pages + + function scrollBy(dy) { + root.contentY = Math.max(root.originY, Math.min(root.contentY + dy, + root.originY + root.contentHeight - root.height)) + } + + FilesProcess { + id: info + onFinished: output => { + var pages = output.match(/^Pages:\s+(\d+)/m), size = output.match(/^Page size:\s+([\d.]+) x ([\d.]+)/m) + if (size) root.aspect = size[2] / size[1] + root.pages = pages ? +pages[1] : 0 + root.failed = !root.pages + } + } + Component.onCompleted: info.start(["pdfinfo", root.path]) + + delegate: Image { + id: page + required property int index + width: ListView.view.width + height: width * root.aspect + fillMode: Image.PreserveAspectFit + asynchronous: true + FilesProcess { + id: render + onFinished: output => page.source = output ? "data:image/png;base64," + output : "" + } + Component.onCompleted: render.start(["sh", "-c", + 'pdftoppm -png -singlefile -f "$3" -l "$3" -scale-to-x "$2" -scale-to-y -1 "$1" | base64 -w0', "sh", + root.path, String(Math.ceil(width * Screen.devicePixelRatio)), String(index + 1)]) + } +} diff --git a/plugins/xpo.files/FilesPreview.qml b/plugins/xpo.files/FilesPreview.qml index 3de4a4e4..6bfd985c 100644 --- a/plugins/xpo.files/FilesPreview.qml +++ b/plugins/xpo.files/FilesPreview.qml @@ -18,6 +18,14 @@ Item { readonly property real paneHeight: scroller.height readonly property int imageStatus: scrollerImage.status readonly property int videoStatus: video.status + readonly property int audioStatus: audio.status + readonly property bool pdfFailed: !!pdf.item && pdf.item.failed + readonly property bool modelFailed: model.status === Loader.Error || !!model.item && model.item.failed + readonly property bool modelLoading: !!model.item && model.item.loading + readonly property bool modelPoints: !!model.item && model.item.pointCloud + // Both optional; what a failed model preview still needs, if anything. + readonly property string modelNeeds: model.status === Loader.Error ? "qt6-quick3d and assimp" + : !!model.item && model.item.noImporter ? "assimp" : "" property alias editorText: editor.text readonly property string lineNumbers: root.panel.editing ? FilesIndex.numbers(editor.text) @@ -115,22 +123,27 @@ Item { gutter.forceLayout() } + // A PDF scrolls its pages; a model turns, Up and Down tilting it, Left and Right spinning it. function scrollBy(dy) { + if (pdf.item) return pdf.item.scrollBy(dy) + if (model.item) return model.item.turn(dy > 0 ? 15 : -15, 0) scroller.contentY = Util.clamp(scroller.contentY + dy, 0, Math.max(0, scroller.contentHeight - scroller.height)) } function scrollAcross(dx) { + if (model.item) return model.item.turn(0, dx > 0 ? -15 : 15) scroller.contentX = Util.clamp(scroller.contentX + dx, 0, Math.max(0, scroller.contentWidth - scroller.width)) } function resetScroll() { scroller.contentY = 0; scroller.contentX = 0 } - function toggleVideo() { const player = video.item as FilesVideo; if (player) player.toggle() } + function togglePlay() { const player = (video.item as FilesVideo) || audio.item; if (player) player.toggle() } function toggleMute() { const player = video.item as FilesVideo; if (player) player.muted = !player.muted } function scrollTo(fraction) { + if (pdf.item) return fraction ? pdf.item.positionViewAtEnd() : pdf.item.positionViewAtBeginning() // The end of a partly laid out file waits for the rest. if (fraction === 1 && root.panel.previewCut) { root.pendingAt = 1 @@ -518,10 +531,33 @@ Item { onLoaded: (item as FilesVideo).fullsize.connect(function(path, position) { root.panel.openVideo(path, position) }) } + Loader { + id: audio + anchors.fill: parent + readonly property string path: root.panel.showsAudio ? root.panel.settledSel.path : "" + onPathChanged: setSource(path ? "FilesAudio.qml" : "", { path: path }) + } + + Loader { + id: pdf + anchors.fill: parent + readonly property string path: root.panel.showsPdf ? root.panel.settledSel.path : "" + onPathChanged: setSource(path ? "FilesPdf.qml" : "", { path: path }) + } + + // Untyped, so a shell without Qt Quick 3D fails only this Loader. + Loader { + id: model + anchors.fill: parent + readonly property string path: root.panel.showsModel ? root.panel.settledSel.path : "" + onPathChanged: setSource(path ? "FilesModel.qml" : "", { path: path }) + } + Text { anchors.centerIn: parent visible: !!root.panel.previewNote text: root.panel.previewNote + horizontalAlignment: Text.AlignHCenter color: Commons.Color.menu.text opacity: 0.45 font.family: Style.font.menuFamily @@ -558,7 +594,8 @@ Item { id: pointer readonly property bool overText: root.panel.showsCode || root.panel.showsMarkdown anchors.fill: scroller - enabled: !root.panel.editing && !root.panel.showsVideo + enabled: !root.panel.editing && !root.panel.showsVideo && !root.panel.showsModel && !root.panel.showsPdf + && !root.panel.showsAudio hoverEnabled: true cursorShape: overText ? Qt.IBeamCursor : Qt.ArrowCursor onPressed: mouse => { if (overText) root.pickAt(mouse.x, mouse.y, mouse.modifiers & Qt.ShiftModifier) } diff --git a/plugins/xpo.files/FilesVideo.qml b/plugins/xpo.files/FilesVideo.qml index 8429b3c7..46cccab7 100644 --- a/plugins/xpo.files/FilesVideo.qml +++ b/plugins/xpo.files/FilesVideo.qml @@ -20,12 +20,6 @@ Rectangle { && player.mediaStatus !== MediaPlayer.LoadingMedia && player.mediaStatus !== MediaPlayer.NoMedia - function clock(ms) { - var s = Math.floor(ms / 1000), m = Math.floor(s / 60), h = Math.floor(m / 60) - return (h ? h + ":" + String(m % 60).padStart(2, "0") : String(m)) - + ":" + String(s % 60).padStart(2, "0") - } - function toggle() { if (!root.ready) return if (player.playing) player.pause() @@ -114,7 +108,7 @@ Rectangle { } Text { - text: root.clock(seek.dragging ? seek.liveValue : player.position) + " / " + root.clock(player.duration) + text: FilesIndex.clock(seek.dragging ? seek.liveValue : player.position) + " / " + FilesIndex.clock(player.duration) color: Commons.Color.menu.text font.family: Style.font.menuFamily font.pixelSize: Style.font.caption diff --git a/plugins/xpo.files/manifest.json b/plugins/xpo.files/manifest.json index e3683e93..1dde04f0 100644 --- a/plugins/xpo.files/manifest.json +++ b/plugins/xpo.files/manifest.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "id": "xpo.files", "name": "Files", - "version": "0.1.0", + "version": "0.2.0", "author": "Xpond", "description": "Keyboard-driven directory browser", "kinds": ["overlay"], diff --git a/plugins/xpo.wheel/MenuIndex.js b/plugins/xpo.wheel/MenuIndex.js index f646594e..f1644384 100644 --- a/plugins/xpo.wheel/MenuIndex.js +++ b/plugins/xpo.wheel/MenuIndex.js @@ -837,6 +837,18 @@ function fileRow(path, home) { } } +// A pasted absolute path, its doubled and closing slashes dropped, or "" for a search term. `/` then +// a paste doubles the first. +function pastedPath(query) { + var q = String(query || "").trim().replace(/\/+/g, "/") + return q.charAt(0) === "/" && q.indexOf("/", 1) > 0 ? q.replace(/(.)\/$/, "$1") : "" +} + +// The pasted path's row leads the results, which the scan may rank lower, and is not repeated. +function pastedFirst(row, rows) { + return row ? [row].concat(rows.filter(function (r) { return r.path !== row.path })) : rows +} + // A directory's own path, or the directory holding a file. function dirOf(path) { var p = String(path) diff --git a/plugins/xpo.wheel/Wheel.qml b/plugins/xpo.wheel/Wheel.qml index f2c3759c..b6ea9309 100644 --- a/plugins/xpo.wheel/Wheel.qml +++ b/plugins/xpo.wheel/Wheel.qml @@ -180,7 +180,7 @@ Item { : root.listing ? MenuIndex.subfolderRows(root.subfolderPaths, root.query, root.home) // A bare `/` lists the files picked before, latest first, while the scan runs. : root.mode === "file" && !root.term ? MenuIndex.historyRows([], root.uses, root.home) - : root.mode === "file" ? root.fileResults + : root.mode === "file" ? MenuIndex.pastedFirst(root.pastedRow, root.fileResults) : root.mode === "calc" ? Calc.rows(root.term) : MenuIndex.search(root.editingRing ? root.index.filter(MenuIndex.pinnable) : root.index, root.term, root.resultLimit, root.uses) @@ -793,6 +793,20 @@ Item { // Scan lazily per open; cap depth to avoid large cache and SDK trees. Home and the added folders // scan apart, so a slow folder, such as a share still mounting, holds back only its own paths. property var fileResults: [] + // A pasted path that exists leads the results, though the scan stops six folders down. + readonly property string pastedPath: root.mode === "file" ? MenuIndex.pastedPath(root.query) : "" + property var pastedRow: null + onPastedPathChanged: { root.pastedRow = null; pasted.running = false; Qt.callLater(root.checkPasted) } + function checkPasted() { if (root.pastedPath) pasted.running = true } + Process { + id: pasted + command: ["stat", "-c", "%F\t%n", "--", root.pastedPath] + stdout: StdioCollector { onStreamFinished: { + var cut = text.indexOf("\t"), path = text.slice(cut + 1).replace(/\n$/, "") + if (cut > 0 && path === root.pastedPath) + root.pastedRow = MenuIndex.fileRow(path + (text.slice(0, cut) === "directory" ? "/" : ""), root.home) + } } + } property var fileQueue: [] property bool fileBusy: false property int fileRequest: 0 diff --git a/plugins/xpo.wheel/manifest.json b/plugins/xpo.wheel/manifest.json index 555fa2d0..c3f80429 100644 --- a/plugins/xpo.wheel/manifest.json +++ b/plugins/xpo.wheel/manifest.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "id": "xpo.wheel", "name": "Wheel", - "version": "0.3.0", + "version": "0.4.0", "author": "Xpond", "description": "Radial control center: panels on a ring, and one search for everything else", "kinds": ["overlay", "menu"], diff --git a/plugins/xpo.wheel/manual.md b/plugins/xpo.wheel/manual.md index b99761d8..9b2e9222 100644 --- a/plugins/xpo.wheel/manual.md +++ b/plugins/xpo.wheel/manual.md @@ -52,8 +52,8 @@ a window, and Esc goes back. Backspace also goes back when the filter is empty. | `Enter` | open folder or file | | `→` `←` | into or out of a folder | | `Backspace` | delete, then up a folder | -| Shift + move keys | scroll the preview | -| `Space` | play or pause a video | +| Shift + move keys | scroll the preview, or turn a 3D model | +| `Space` | play or pause a video or song | | `Alt+M` | mute or unmute a video | | `Ctrl+X` `Ctrl+C` | take to move, or to copy; or copy dragged text | | `Ctrl+V` | put it here | diff --git a/tests/files-index.js b/tests/files-index.js index d0e05b11..979ed6b2 100644 --- a/tests/files-index.js +++ b/tests/files-index.js @@ -9,6 +9,22 @@ for (const name of ["app.ts", "module.mts", "photo.gif", "clip.mp4.txt", "mp4", assert.equal(F.isVideo(name), false, name) console.log("ok: video formats preserve text and image previews") +for (const name of ["doc.pdf", "DOC.PDF", "a.b.pdf"]) assert.equal(F.isPdf(name), true, name) +for (const name of [".pdf", "pdf", "doc.pdf.txt", "doc.pdfx"]) assert.equal(F.isPdf(name), false, name) +console.log("ok: pdf names") + +for (const name of ["song.mp3", "SONG.FLAC", "a.b.opus", "voice.m4a"]) assert.equal(F.isAudio(name), true, name) +for (const name of [".mp3", "mp3", "song.mp3.txt", "clip.mp4"]) assert.equal(F.isAudio(name), false, name) +console.log("ok: audio names") + +for (const name of ["duck.glb", "PART.STL", "a.b.fbx"]) assert.equal(F.isModel(name), true, name) +for (const name of [".glb", "glb", "duck.glb.txt", "duck.blend"]) assert.equal(F.isModel(name), false, name) +console.log("ok: model names") + +for (const [ms, shown] of [[0, "0:00"], [65400, "1:05"], [3599999, "59:59"], [4500000, "1:15:00"]]) + assert.equal(F.clock(ms), shown, String(ms)) +console.log("ok: a player's clock counts hours past the first") + const buffer = bytes => Uint8Array.from(bytes).buffer const valid = [[], [0], [0x7f], [0xc2, 0x80], [0xdf, 0xbf], [0xe0, 0xa0, 0x80], [0xed, 0x9f, 0xbf], [0xef, 0xbb, 0xbf], [0xef, 0xbf, 0xbd], [0xf0, 0x90, 0x80, 0x80], diff --git a/tests/files-navigation.js b/tests/files-navigation.js index 8ffe9d9c..913501db 100644 --- a/tests/files-navigation.js +++ b/tests/files-navigation.js @@ -293,12 +293,16 @@ console.log("ok: typing during a landing cancels it") // Space plays a selected video; Shift+Space still types. let toggles = 0, mutes = 0 const viewer = { filter: "movie", index: 7, editing: false, naming: "", listShown: true, showsVideo: true } -const viewKey = keymap("plugins/xpo.files/FilesKeys.js", viewer, { doomed: "" }, { toggleVideo() { toggles++ }, toggleMute() { mutes++ } }) +const viewKey = keymap("plugins/xpo.files/FilesKeys.js", viewer, { doomed: "" }, { togglePlay() { toggles++ }, toggleMute() { mutes++ } }) viewKey("Key_Space", 0, " ") assert.deepEqual([toggles, viewer.filter, viewer.index], [1, "movie", 7], "Space did not toggle the video") viewKey("Key_Space", 1 << 25, " ") assert.deepEqual([toggles, viewer.filter], [1, "movie "], "Shift+Space did not type a space") -console.log("ok: Space plays a selected video, Shift+Space types") +viewer.showsVideo = false; viewer.showsAudio = true +viewKey("Key_Space", 0, " ") +assert.deepEqual([toggles, viewer.filter], [2, "movie "], "Space did not toggle the song") +viewer.showsVideo = true; viewer.showsAudio = false +console.log("ok: Space plays a selected video or song, Shift+Space types") viewKey("Key_M", 1 << 27, "m") assert.deepEqual([mutes, viewer.filter], [1, "movie "], "Alt+M did not toggle the sound") viewKey("Key_M", 0, "m") diff --git a/tests/files_model.py b/tests/files_model.py new file mode 100644 index 00000000..28cf16e6 --- /dev/null +++ b/tests/files_model.py @@ -0,0 +1,93 @@ +"""A 3D model converts outside the shell: what Files shows while it does, once it has, and when it can't.""" +import glob +import re +import shutil +import subprocess + +POLL = ''' + Timer { interval: 20; repeat: true; running: true; onTriggered: { + if (model.loading) return + var got = [model.failed, model.noImporter, %s] + if (JSON.stringify(got) !== JSON.stringify(%s)) { console.error("FAIL", JSON.stringify(got)); Qt.exit(1) } + else { console.log("PASS"); Qt.quit() } + } } +''' + + +def check(files, base, run, block): + # balsam's scene and assimp's bounds arrive together, in the cache; a damaged file fails without + # blaming assimp or calling itself a point cloud, points with no faces fail as one, and without + # assimp the preview names it. + (base / "box.obj").write_text("v 0 0 0\nv 2 0 0\nv 0 4 0\nv 0 0 6\nf 1 2 3\nf 1 2 4\nf 1 3 4\nf 2 3 4\n") + (base / "broken.glb").write_bytes(b"glTF" + bytes(60)) + (base / "splat.ply").write_text("ply\nformat ascii 1.0\nelement vertex 3\nproperty float x\nproperty float y\n" + "property float z\nend_header\n0 0 0\n1 0 0\n0 1 0\n") + cache = f"file://{base}/cache/wheely/models/" + run("files-model-converts", f' FilesModel {{ id: model; path: "{base}/box.obj" }}' + POLL % ( + f'model.scene.startsWith("{cache}") && model.scene.endsWith("/Box.qml"), model.low.x, model.high.y, model.high.z', + '[false, false, true, 0, 4, 6]')) + run("files-model-fails", f' FilesModel {{ id: model; path: "{base}/broken.glb" }}' + + POLL % ('model.pointCloud, model.scene', '[true, false, false, ""]')) + run("files-model-point-cloud", f' FilesModel {{ id: model; path: "{base}/splat.ply" }}' + + POLL % ('model.pointCloud, model.scene', '[true, false, true, ""]')) + + # A texture past 1024 px shrinks before the shell decodes it. + (base / "skin.png").write_bytes(subprocess.run(["magick", "-size", "2048x1024", "xc:red", "png:-"], + capture_output=True, check=True).stdout) + (base / "skinned.mtl").write_text("newmtl skin\nmap_Kd skin.png\n") + (base / "skinned.obj").write_text("mtllib skinned.mtl\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\n" + "usemtl skin\nf 1/1 2/2 3/3\n") + run("files-model-textures", f' FilesModel {{ id: model; path: "{base}/skinned.obj" }}' + + POLL % ('!!model.scene', '[false, false, true]')) + shrunk = subprocess.run(["identify", "-format", "%wx%h"] + glob.glob(f"{base}/cache/wheely/models/*/maps/skin.png"), + capture_output=True, text=True, check=True).stdout + assert shrunk == "1024x512", shrunk + print("ok: a model's texture shrinks to 1024 px, keeping its shape") + bare = base / "bare" + bare.mkdir() + for tool in ["quickshell", "sh"]: + (bare / tool).symlink_to(shutil.which(tool)) + run("files-model-needs-assimp", f' FilesModel {{ id: model; path: "{base}/box.obj" }}' + POLL % ('model.scene', '[true, true, ""]'), + extra={"PATH": str(bare)}) + + # Past 8 MB the note asks for a moment while the model converts; past 128 MB, or for a point cloud, + # there is no preview, and the note says why. + note = files[files.index(" readonly property string previewNote:"):files.index(" // Payloads may choose")] + run("files-model-note", ''' + property bool editing: false + property var settledSel: ({ name: "a.stl", size: 9437184 }) + property bool showsCode: false + property string previewBody: "" + property bool showsDiff: false + property bool showsVideo: false + property bool showsAudio: false + property bool showsImage: false + property bool showsPdf: false + QtObject { + id: preview + property bool modelFailed: false + property bool modelLoading: true + property string modelNeeds: "" + property bool modelPoints: false + } +''' + block(files, r"^ function media\(") + "\n" + re.search(r"^ readonly property bool showsModel:.*$", files, re.M).group() + + "\n" + note + ''' + Timer { interval: 0; running: true; onTriggered: { + var seen = [previewNote] + settledSel = { name: "a.stl", size: 1048576 } + seen.push(previewNote) + preview.modelLoading = false + seen.push(previewNote) + preview.modelFailed = true; preview.modelNeeds = "assimp" + seen.push(previewNote) + preview.modelNeeds = ""; preview.modelPoints = true + seen.push(previewNote) + settledSel = { name: "a.stl", size: 209715200 } + seen.push(previewNote) + var want = ["9.0M · no preview\\nLarge model, it takes a moment to load", "", "", + "1.0M · no preview\\nInstall assimp to preview 3D models", "1.0M · no preview\\nA point cloud, not a mesh", + "200M · no preview\\nOver 128 MB, too large to preview"] + if (JSON.stringify(seen) !== JSON.stringify(want)) { console.error("FAIL", JSON.stringify(seen)); Qt.exit(1) } + else { console.log("PASS"); Qt.quit() } + } } +''') diff --git a/tests/runtime.py b/tests/runtime.py index ca43d75e..e50cf2be 100644 --- a/tests/runtime.py +++ b/tests/runtime.py @@ -12,6 +12,7 @@ from wheel_menu import check as check_wheel_menu from file_runtime import check as check_file_runtime from files_info import check as check_files_info +from files_model import check as check_files_model from files_lifecycle import check as check_files_lifecycle from files_git_runtime import check as check_files_git from wheel_settings import check as check_wheel_settings @@ -52,7 +53,7 @@ def line(source, pattern): assert not Path(f"/proc/{pidfile.read_text()}").exists(), "scanner was not reaped" print("ok: closed scan reader stays quiet and reaps its child") - for path in ["xpo.files/FilesIndex.js", "xpo.files/FilesProcess.qml", "xpo.files/FilesList.qml", "xpo.files/FilesPreview.qml", "xpo.files/FilesHeader.qml", "xpo.files/FilesHints.qml", "xpo.files/FilesProps.qml", "xpo.files/FilesTip.qml", + for path in ["xpo.files/FilesIndex.js", "xpo.files/FilesProcess.qml", "xpo.files/FilesModel.qml", "xpo.files/FilesList.qml", "xpo.files/FilesPreview.qml", "xpo.files/FilesHeader.qml", "xpo.files/FilesHints.qml", "xpo.files/FilesProps.qml", "xpo.files/FilesTip.qml", "xpo.files/FilesMenu.qml", "xpo.files/FilesMenuCard.qml", "xpo.files/FilesActions.js", "xpo.wheel/MenuIndex.js", "xpo.wheel/scan.py", "xpo.wheel/MenuKeys.js", "xpo.wheel/WheelResults.qml", "xpo.wheel/ClickShield.qml", "xpo.wheel/PanelIcon.qml"]: @@ -105,6 +106,7 @@ def run(name, body, extra=None, expected=(), imports=""): check_wheel_menu(wheel, base, run, block, line) check_file_runtime(files, ops, base, run, block) check_files_info(files, base, run, block) + check_files_model(files, base, run, block) check_files_lifecycle(files, run, block, line) check_files_git(repo, files, base, run, block, line) diff --git a/tests/wheel-files.js b/tests/wheel-files.js index 07191509..bbb2c4b3 100644 --- a/tests/wheel-files.js +++ b/tests/wheel-files.js @@ -23,3 +23,19 @@ assert.equal(M.pathPayload(`${home}/a/`), JSON.stringify({ dir: `${home}/a` }), assert.equal(M.keyOf(M.fileRow(`${home}/a.txt`, home)), `file:${home}/a.txt`, "a file is not counted by its path") console.log("ok: sigils strip once, file rows name themselves and their folder, payloads and use keys follow the path") + +for (const [query, path] of [["/home/u/a/b.glb", "/home/u/a/b.glb"], [" /home/u/models/ ", "/home/u/models"], + ["/home/u//", "/home/u"], ["//home/u/a", "/home/u/a"], ["/home//u/", "/home/u"], + ["/notes", ""], ["/", ""], ["//", ""], ["notes/a", ""]]) + assert.equal(M.pastedPath(query), path, query) +console.log("ok: a pasted absolute path is taken as written, a search term is not") + +// The scan ranks a folder below children with shorter names; pasted, it leads. +const ranked = M.fileRows(M.parseFiles(["/u/projects/", "/u/projects/a.md", "/u/projects/web/"].join("\0")), + "u/projects", 40, "/u") +const pasted = M.fileRow("/u/projects/", "/u") +assert.notEqual(ranked[0].path, pasted.path, "the scan no longer ranks the folder below its children") +assert.equal(M.pastedFirst(pasted, ranked).map(r => r.path).join(" "), + "/u/projects/ /u/projects/web/ /u/projects/a.md") +assert.equal(M.pastedFirst(null, ranked), ranked, "without a pasted path the results were not kept") +console.log("ok: a pasted path's row leads the results once")