diff --git a/.gitignore b/.gitignore index 8379206..ce84c10 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ /build/ /trials/ +/prompt/ +/.scratch/ +**/.hype-backups/ *.user __pycache__/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 95f5221..9cb85ef 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -24,6 +24,8 @@ endif() find_package(Qt6 6.9 REQUIRED COMPONENTS Core Gui Qml Quick QuickControls2 Multimedia Concurrent DBus Svg Widgets Test) +# qsb is a build-time tool: Qt Quick loads only baked shader packages. +find_package(Qt6 6.9 REQUIRED COMPONENTS ShaderToolsTools) find_package(PkgConfig REQUIRED) pkg_check_modules(WEBP REQUIRED IMPORTED_TARGET libwebp libwebpdemux) find_package(ZLIB REQUIRED) @@ -54,7 +56,37 @@ else() endif() endif() +# Slide transitions are one ES 1.00 body each, shared with the HTML exports. Qt +# Quick's ShaderEffect only loads baked shader packages in Qt 6, so every body is +# wrapped in modern GLSL and compiled by qsb here, then embedded as +# :/transitions/.frag.qsb for the QML to load. A new .glsl file is enough: +# the glob picks it up, as the registry picks up its name. +file(GLOB transition_bodies CONFIGURE_DEPENDS src/transitions/*.glsl) +list(REMOVE_ITEM transition_bodies "${CMAKE_SOURCE_DIR}/src/transitions/common.glsl") +set(transition_shaders "") +foreach(body IN LISTS transition_bodies) + get_filename_component(transition_name "${body}" NAME_WE) + set(transition_frag "${CMAKE_CURRENT_BINARY_DIR}/transitions/${transition_name}.frag") + set(transition_qsb "${transition_frag}.qsb") + add_custom_command(OUTPUT "${transition_frag}" + COMMAND ${CMAKE_COMMAND} + "-DCOMMON=${CMAKE_SOURCE_DIR}/src/transitions/common.glsl" + "-DBODY=${body}" + "-DOUTPUT=${transition_frag}" + -P "${CMAKE_SOURCE_DIR}/cmake/wrap-transition.cmake" + DEPENDS "${body}" "${CMAKE_SOURCE_DIR}/src/transitions/common.glsl" + "${CMAKE_SOURCE_DIR}/cmake/wrap-transition.cmake" + VERBATIM) + add_custom_command(OUTPUT "${transition_qsb}" + COMMAND $ --qt6 -o "${transition_qsb}" "${transition_frag}" + DEPENDS "${transition_frag}" + VERBATIM) + list(APPEND transition_shaders "${transition_qsb}") +endforeach() + add_executable(hype src/main.cpp src/resources.qrc) +qt_add_resources(hype "transition_shaders" PREFIX "/transitions" + BASE "${CMAKE_CURRENT_BINARY_DIR}/transitions" FILES ${transition_shaders}) target_link_libraries(hype PRIVATE hype_core) target_compile_definitions(hype PRIVATE HYPE_VERSION="${HYPE_VERSION}") set_target_properties(hype PROPERTIES INTERPROCEDURAL_OPTIMIZATION ON) @@ -67,6 +99,8 @@ find_package(Qt6 6.9 COMPONENTS Pdf) if(TARGET Qt6::Pdf) # The window-level tests load the same QML as the app, so they embed it too. add_executable(hype_tests tests/tests.cpp src/resources.qrc) + qt_add_resources(hype_tests "transition_shaders" PREFIX "/transitions" + BASE "${CMAKE_CURRENT_BINARY_DIR}/transitions" FILES ${transition_shaders}) target_link_libraries(hype_tests PRIVATE hype_core Qt6::Widgets Qt6::Pdf Qt6::Test) set_target_properties(hype_tests PROPERTIES INTERPROCEDURAL_OPTIMIZATION ON) add_test(NAME hype_tests COMMAND hype_tests) @@ -78,12 +112,14 @@ endif() set_tests_properties(hype_tests PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QPA_PLATFORMTHEME=generic;QT_STYLE_OVERRIDE=Fusion") -# The commands, exports and shutdown, driven through build/hype as an agent would. -# test_trials covers the trial import tools, which need their own Python packages. +# The commands, exports and shutdown through build/hype as an agent would, and +# the exported deck's navigation and rendering in a browser (skipped where +# chromium is absent). test_trials covers the trial import tools, which need +# their own Python packages. find_package(Python3 COMPONENTS Interpreter) if(Python3_FOUND) add_test(NAME hype_commands - COMMAND ${Python3_EXECUTABLE} -m unittest test_cli test_export test_shutdown + COMMAND ${Python3_EXECUTABLE} -m unittest test_cli test_export test_deck_navigation test_deck_render test_deck_svg test_deck_transitions test_shutdown WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/tests) else() add_test(NAME hype_commands COMMAND sh -c "echo 'hype_commands needs Python 3' >&2; exit 1") diff --git a/README.md b/README.md index 281be31..83a52e1 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Simple presentations, written in Markdown. Big headlines, images, video, and code—with a visual editor to put everything in order. -Hype is a native app for Omarchy. Your presentation is a Markdown file with its media alongside it. Choose an installed Omarchy theme, pick a font, and export to PDF or PowerPoint. +Hype is a native app for Omarchy. Your presentation is a Markdown file with its media alongside it. Choose an installed Omarchy theme, pick a font, and export to PDF, PowerPoint, or a self-contained HTML deck. ## Install @@ -167,7 +167,11 @@ Click **Present** or press **Ctrl+Space** (or **F5**) to toggle fullscreen prese Finished videos hold their last frame. Press Space again to replay from the beginning. -Choose **Export as PDF** or **Export as PowerPoint** from the file menu in the top bar, or press **Ctrl+E** for PDF and **Ctrl+Shift+E** for PowerPoint, to share your presentation. Both exports are built into Hype. PowerPoint renders slides and converted animations at 4K (3840 × 2160), storing slides as high-quality JPEG like the pictures in a PDF. Slides preserve the rendered appearance rather than exposing editable text and shapes; the receiving computer does not need your fonts installed. Videos are embedded, and animated WebP/GIF images are converted to MP4 automatically without changing the original files. PDF captures still slides. +Choose **Export as PDF**, **Export as PowerPoint**, **Export as HTML**, or **Export as HTML folder** from the file menu in the top bar, or press **Ctrl+E** for PDF, **Ctrl+Shift+E** for PowerPoint, **Ctrl+Alt+E** for HTML, and **Ctrl+Alt+Shift+E** for an HTML folder, to share your presentation. All exports are built into Hype. PowerPoint renders slides and converted animations at 4K (3840 × 2160), storing slides as high-quality JPEG like the pictures in a PDF. Slides preserve the rendered appearance rather than exposing editable text and shapes; the receiving computer does not need your fonts installed. Videos are embedded, and animated WebP/GIF images are converted to MP4 automatically without changing the original files. PDF captures still slides. + +**Export as HTML** writes one self-contained file: every slide rendered at 1920 pixels wide, inlined as WebP, wrapped in a page with arrow-key, click, swipe, and touch navigation, a slide counter, and `#N` deep links. It opens in any browser straight from a file manager or an email attachment — no fonts, no internet, no unzipping. The deck's Markdown rides inside the page as an inert block, so the file also carries its editable source wherever it goes. The Markdown file stays the source of truth; export again to refresh the deck. + +**Export as HTML folder** writes the same deck as an editable folder: the Markdown rides inside `index.html`, which renders it with `deck.js` and `deck.css` — mirroring Hype's layout, theme, and media directives — beside the deck's real images and videos. Edit the Markdown block in any text editor, refresh the browser, and the deck updates; no Hype needed. Pick a new or empty folder; export again to refresh it. Zip the folder to share the whole deck. Export runs in the background. The top bar shows progress through rendering, video conversion, and packaging under the presentation name, with a **Cancel export** button. You can keep editing; the export uses the presentation as it was when you started. Failed or cancelled exports leave an existing file intact. @@ -185,7 +189,8 @@ hype check talk/presentation.md # every problem, with its slid hype slides talk/presentation.md # an outline: number, lines, headline, media hype render talk/presentation.md --slide 3 -o slide.png hype render talk/presentation.md -o slides/ # every slide, plus slides.json -hype export talk/presentation.md talk.pdf # or talk.pptx +hype export talk/presentation.md talk.pdf # or talk.pptx, or talk.html for a web deck +hype export talk/presentation.md site/ # or a folder in /: an editable HTML deck hype themes ``` @@ -206,7 +211,7 @@ Slide navigation and selection shortcuts apply when the sidebar or preview has f | Ctrl+N / Ctrl+O | New presentation / open file | | Ctrl+S / Ctrl+Shift+S | Save / save as | | Ctrl+Q | Quit | -| Ctrl+E / Ctrl+Shift+E | Export as PDF / PowerPoint | +| Ctrl+E / Ctrl+Shift+E / Ctrl+Alt+E / Ctrl+Alt+Shift+E | Export as PDF / PowerPoint / HTML deck / HTML folder | | Ctrl+M | Overview on / off | | Ctrl+. | Markdown source on / off | | Ctrl+B / Ctrl+I / Ctrl+U | Bold / italic / underline | @@ -245,7 +250,7 @@ The mouse wheel over the sidebar selects the previous or next slide. Home/End ju ## Run from source -To build Hype yourself, install a C++17 compiler, CMake, Qt 6.9 or newer, FFmpeg, and GNU source-highlight; see [the package definition in omarchy-pkgs](https://github.com/omacom/omarchy-pkgs/blob/master/pkgbuilds/hype/PKGBUILD) for dependencies. Then: +To build Hype yourself, install a C++17 compiler, CMake, Qt 6.9 or newer (including Qt Shader Tools, which provides `qsb`), FFmpeg, and GNU source-highlight; see [the package definition in omarchy-pkgs](https://github.com/omacom/omarchy-pkgs/blob/master/pkgbuilds/hype/PKGBUILD) for dependencies. Then: ```sh ./bin/build diff --git a/cmake/wrap-transition.cmake b/cmake/wrap-transition.cmake new file mode 100644 index 0000000..f4f0121 --- /dev/null +++ b/cmake/wrap-transition.cmake @@ -0,0 +1,37 @@ +# Composes one transition into the modern GLSL that qsb bakes for Qt Quick's +# ShaderEffect. The ES 1.00 body stays the single source both renderers compile; +# only the wrapper differs from the HTML exports' WebGL one. +# +# cmake -DCOMMON= -DBODY=.glsl -DOUTPUT=.frag -P ... +# +# Qt Quick supplies the vertex shader, whose output is qt_TexCoord0. ShaderEffect +# packs the effect's properties into a std140 block bound at 0, while samplers +# keep their own binding points, so fromTex and toTex match the QML properties of +# those names and progress matches the QML progress property. + +foreach(input COMMON BODY) + if(NOT EXISTS "${${input}}") + message(FATAL_ERROR "wrap-transition: ${input} not found: ${${input}}") + endif() +endforeach() + +file(READ "${COMMON}" common) +file(READ "${BODY}" body) + +set(wrapper [=[#version 440 +layout(location = 0) in vec2 qt_TexCoord0; +layout(location = 0) out vec4 fragColor; +layout(std140, binding = 0) uniform buf { + mat4 qt_Matrix; + float qt_Opacity; + float progress; +}; +layout(binding = 1) uniform sampler2D fromTex; +layout(binding = 2) uniform sampler2D toTex; +#define varying in +#define texture2D texture +#define gl_FragColor fragColor +]=]) + +file(WRITE "${OUTPUT}" + "${wrapper}\n${common}\n${body}\n\nvoid main() { gl_FragColor = transition(qt_TexCoord0); }\n") diff --git a/examples/welcome.md b/examples/welcome.md index e04121d..6323d4c 100644 --- a/examples/welcome.md +++ b/examples/welcome.md @@ -4,21 +4,6 @@ font: JetBrains Mono theme: tokyo-night --- -# Your next idea - -Markdown in. A presentation out. - ---- - -# Keep it simple - -- Write in Markdown -- Drag slides to reorder -- Duplicate the good ones -- Pick an Omarchy theme - ---- - > A presentation is a sequence of ideas. > Give each one room to breathe. @@ -33,6 +18,15 @@ Sovereign --- +# Keep it simple + +- Write in Markdown +- Drag slides to reorder +- Duplicate the good ones +- Pick an Omarchy theme + +--- + # The source is the document ```ruby @@ -45,6 +39,12 @@ end --- +# Your next idea + +Markdown in. A presentation out. + +--- + # One folder | Directory | Contents | diff --git a/pkgbuild/hype-html.desktop b/pkgbuild/hype-html.desktop new file mode 100644 index 0000000..28d692c --- /dev/null +++ b/pkgbuild/hype-html.desktop @@ -0,0 +1,8 @@ +[Desktop Entry] +Type=Application +Name=Hype HTML +Comment=Markdown presentations, exported as self-contained HTML decks +Exec=hype-html open %f +Icon=hype-html +Terminal=false +Categories=Office;Presentation; diff --git a/pkgbuild/hype-html/.gitignore b/pkgbuild/hype-html/.gitignore new file mode 100644 index 0000000..e01fa87 --- /dev/null +++ b/pkgbuild/hype-html/.gitignore @@ -0,0 +1,6 @@ +# makepkg artifacts: the SRCDEST git mirror (named after pkgname), the build +# tree, the staging root, and built packages. +/hype-html/ +/src/ +/pkg/ +/*.pkg.tar.zst diff --git a/pkgbuild/hype-html/PKGBUILD b/pkgbuild/hype-html/PKGBUILD new file mode 100644 index 0000000..bb9e87d --- /dev/null +++ b/pkgbuild/hype-html/PKGBUILD @@ -0,0 +1,49 @@ +# Package this fork as hype-html, beside an installed hype: the same app with +# the HTML deck export, under its own name, icon, and desktop entry. The +# source is the checkout this PKGBUILD lives in, at the branch checked out +# there, so commit before building and re-run makepkg after pulling. +pkgname=hype-html +pkgver=0.7.1 +pkgrel=1 +pkgdesc='Simple Markdown presentations with a visual slide editor and self-contained HTML deck export' +arch=('x86_64') +url='https://github.com/razodin137/hype' +license=('MIT') +options=('!debug') +depends=( + 'ffmpeg' + 'hicolor-icon-theme' + 'qt6-base>=6.9' + 'qt6-declarative>=6.9' + 'qt6-multimedia>=6.9' + 'qt6-imageformats' + 'qt6-svg' + 'source-highlight' + 'zlib' + 'libwebp' + 'xdg-desktop-portal' + 'qt6-wayland' +) +makedepends=('cmake' 'gcc' 'make' 'pkgconf' 'git' 'qt6-shadertools') + +# This PKGBUILD sits at /pkgbuild/hype-html, so the checkout root is +# two levels up. Cloning from there lets any checkout build itself; git source +# means the package still tracks the committed branch, not the working tree. +_checkout="$(realpath -- "$(dirname -- "${BASH_SOURCE[0]}")/../..")" +source=("$pkgname::git+file://${_checkout}") +sha256sums=('SKIP') + +build() { + cd "$srcdir/$pkgname" + ./bin/build +} + +package() { + cd "$srcdir/$pkgname" + + install -Dm755 build/hype "$pkgdir/usr/bin/hype-html" + install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE" + install -Dm644 pkgbuild/hype.svg "$pkgdir/usr/share/icons/hicolor/scalable/apps/hype-html.svg" + install -Dm644 pkgbuild/hype-html.desktop "$pkgdir/usr/share/applications/hype-html.desktop" + install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md" +} diff --git a/scripts/split-serial.sh b/scripts/split-serial.sh new file mode 100755 index 0000000..825fdcb --- /dev/null +++ b/scripts/split-serial.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# Replay a prompt pack: one prompt per fresh session, stopping at the first +# failing gate. Run it in the repo the prompts change. +# +# ./scripts/split-serial.sh pack is ./prompt +# ./scripts/split-serial.sh ../packs/listmonk +# CHECK_ONLY=1 ./scripts/split-serial.sh print pack and gate, run nothing +# CHECK='make test' ./scripts/split-serial.sh +# COMMIT=0 ./scripts/split-serial.sh leave commits alone +# FROM=05-name ./scripts/split-serial.sh resume at a step +# +# Files run in filename order, so 01-, 02-, 03- sets the order. Logs land in +# .scratch/split/ and are never staged for commit. + +set -euo pipefail + +usage() { + awk 'NR > 1 { if ($0 !~ /^#/) exit; sub(/^# ?/, ""); print }' "$0" +} + +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then + usage + exit 0 +fi + +if ! [ -d prompt ] && [ "$(basename "$PWD")" = "scripts" ] && [ -d ../prompt ]; then + cd .. +fi + +PACK=${1:-${PACK:-prompt}} +MODEL=${MODEL:-ollama/deepseek-v4.1-flash:1017-cloud} +COMMIT=${COMMIT:-1} +FROM=${FROM:-} +LOGS=.scratch/split + +if [ ! -d "$PACK" ]; then + echo "no pack at $PACK; prompts live in /$PACK" >&2 + exit 1 +fi + +shopt -s nullglob +files=("$PACK"/*.md) +shopt -u nullglob + +if [ ${#files[@]} -eq 0 ]; then + echo "no prompts in $PACK" >&2 + exit 1 +fi + +CHECK=${CHECK:-} +if [ -z "$CHECK" ] && [ -f package.json ] && \ + node -e 'process.exit(require("./package.json").scripts?.check ? 0 : 1)' 2>/dev/null; then + CHECK="npm run check" +fi + +if [ "${CHECK_ONLY:-0}" = "1" ]; then + printf 'repo: %s\n' "$PWD" + printf 'pack: %s (%d prompts)\n' "$PACK" "${#files[@]}" + printf 'check: %s\n' "${CHECK:-none}" + exit 0 +fi + +if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then + COMMIT=0 +fi + +if [ "$COMMIT" = "1" ] && [ -n "$(git status --porcelain --untracked-files=normal -- . ':(exclude).scratch')" ]; then + echo "tree is dirty; commit it first, or run with COMMIT=0" >&2 + exit 1 +fi + +mkdir -p "$LOGS" + +for file in "${files[@]}"; do + name=$(basename "$file" .md) + if [ -n "$FROM" ] && [[ "$name" < "$FROM" ]]; then + continue + fi + + echo "== $name" + if ! opencode run -m "$MODEL" --auto --title "split $name" "$(cat "$file")" 2>&1 \ + | tee "$LOGS/$name.log"; then + echo "== $name: opencode failed, stopping" >&2 + exit 1 + fi + + if [ -n "$CHECK" ]; then + if ! eval "$CHECK" >"$LOGS/$name.check" 2>&1; then + echo "== $name: check failed: $CHECK" >&2 + echo "== see $LOGS/$name.check; fix, then resume with FROM=$name" >&2 + exit 1 + fi + fi + + if [ "$COMMIT" = "1" ]; then + git add -A -- . ':(exclude).scratch' + if git diff --cached --quiet; then + echo "== $name: nothing to commit" + else + git commit -q -m "split: $name" + fi + fi +done + +echo "== finished" diff --git a/src/AppIcon.qml b/src/AppIcon.qml index 9f36404..be313a4 100644 --- a/src/AppIcon.qml +++ b/src/AppIcon.qml @@ -5,7 +5,7 @@ Item { id: icon required property string name property color color: "black" - readonly property bool outlined: ["open", "save", "overview", "visual", "markdown", "code", "check", "file", "history", "export", "bold", "italic", "underline", "headline", "comment", "media-add", "adjust", "chevron-down"].indexOf(name) >= 0 + readonly property bool outlined: ["open", "save", "overview", "visual", "markdown", "code", "check", "file", "history", "export", "bold", "italic", "underline", "headline", "comment", "media-add", "adjust", "transition", "chevron-down"].indexOf(name) >= 0 readonly property real canvasSize: name === "open" || name === "save" ? 16 : 24 implicitWidth: 24; implicitHeight: 24 Shape { @@ -41,6 +41,7 @@ Item { : icon.name === "chevron-down" ? "M6 9L12 15L18 9" : icon.name === "chevron-right" ? "M9 6L15 12L9 18" : icon.name === "adjust" ? "M3 6H7 M11 6H21 M7 3V9H11V3Z M3 18H13 M17 18H21 M13 15V21H17V15Z" + : icon.name === "transition" ? "M4 8H17 M13 4L17 8L13 12 M20 16H7 M11 12L7 16L11 20" : icon.name === "save" ? "M2.5 2.5H10.5L13.5 5.5V13.5H2.5Z M5.5 2.5V6H10V2.5 M4.5 13.5V9.5H11.5V13.5" : "M2.5 13V3.5H6.5L8.5 5.5H13.5V13Z" } diff --git a/src/Main.qml b/src/Main.qml index c425c84..ebc1738 100644 --- a/src/Main.qml +++ b/src/Main.qml @@ -37,6 +37,18 @@ ApplicationWindow { if (text) flashTimer.restart() } Timer { id: flashTimer; onTriggered: win.flash = "" } + // Linear: the shaders shape their own timing, and a deck's duration is the + // span from the first frame to the last. + NumberAnimation { + id: transitionAnimation + target: win; property: "transitionProgress" + from: 0; to: 1; easing.type: Easing.Linear + duration: Math.max(1, Math.round(deck.transitionDuration * 1000)) + onFinished: win.finishSlideTransition() + } + // A frame that never finishes decoding must not leave the sources rendering + // forever; the slide itself has already swapped, so skipping is invisible. + Timer { id: transitionTimeout; interval: 2000; running: win.transitionPreparing; onTriggered: win.endSlideTransition() } Connections { target: deck function onStatusChanged() { if (!deck.exporting) win.flashStatus(deck.status, false) } @@ -57,6 +69,23 @@ ApplicationWindow { property var compressionReturnFocus: null property bool allowClose: false property int lastSelected: -1 + // A slide change plays a shader transition over the stage. The two frames are + // the outgoing and incoming renders; progress is the only animated value. + property string transitionFrom: "" + property string transitionTo: "" + property string transitionShaderName: "" + property real transitionProgress: 0 + // Both frames have to be decoded before the shader has anything to mix. + property bool transitionPreparing: false + property int transitionFromSlide: -1 + // Until the shader takes over, the stage keeps showing the outgoing slide + // rather than following the new selection. Otherwise the new preview can + // load first, flash, and then be replaced by the old slide mid-transition. + readonly property int previewSlide: transitionPreparing && transitionFromSlide >= 0 + ? transitionFromSlide : deck.selected + readonly property string previewSource: transitionPreparing && transitionFrom !== "" + ? "image://slides/" + transitionFrom + : "image://slides/" + (deck.revision, deck.renderId(deck.selected)) + (animation.active ? "/background" : "") // Qt Multimedia probes the GPU's video decoders when first used, which takes seconds on some // machines, so the player loads with the first video slide rather than with every window. property bool videoUsed: false @@ -282,6 +311,11 @@ ApplicationWindow { "left": qsTr("Left"), "center": qsTr("Center"), "right": qsTr("Right"), "bottom-left": qsTr("Bottom left"), "bottom": qsTr("Bottom"), "bottom-right": qsTr("Bottom right") })[id] || id } + // A slide transition's name, by the id the deck and its Markdown use. + function transitionName(id) { + return ({ "none": qsTr("None"), "crossfade": qsTr("Crossfade"), "dissolve": qsTr("Dissolve"), + "liquid": qsTr("Liquid"), "glitch": qsTr("Glitch") })[id] || id + } function changeMode(name, preserveEditing) { const switchingEditors = preserveEditing && !overview && name !== "overview" const editorFocused = sourceEditor.activeFocus || slideEditor.activeFocus @@ -405,6 +439,61 @@ ApplicationWindow { player.source = nextVideo if (presenting && deck.media.video && deck.media.autoplay) player.play() } + // What a slide change animates: the incoming slide's own directive, then the + // deck default. Its property reads the slide that is selected now. + function startSlideTransition(from, to) { + const name = deck.slideTransition + if (from < 0 || from >= deck.count || from === to || + to < 0 || to >= deck.count || + name === "" || name === "none" || !workspace.visible) { + endSlideTransition() + return + } + transitionAnimation.stop() + transitionFromSlide = from + transitionProgress = 0 + transitionFrom = deck.renderId(from) + transitionTo = deck.renderId(to) + transitionShaderName = name + // Record the outgoing slide as the one on screen; the source may already + // have followed the selection for a moment before this handler ran. + slidePreview.shownSlide = from + // Set this last, so the preview never reads a preparing state without a + // frame to hold on to. + transitionPreparing = true + // The frames may still be in the pixmap cache, but a new decode starts + // asynchronously; the Images' status handlers start the animation once + // both are ready, whichever finishes last. + Qt.callLater(startSlideTransitionIfReady) + } + function startSlideTransitionIfReady() { + if (!transitionPreparing) return + if (transitionFromFrame.status === Image.Error || transitionToFrame.status === Image.Error) { + endSlideTransition() + return + } + if (transitionFromFrame.status !== Image.Ready || transitionToFrame.status !== Image.Ready) return + transitionPreparing = false + transitionAnimation.restart() + } + function endSlideTransition() { + transitionAnimation.stop() + transitionPreparing = false + transitionProgress = 0 + transitionFrom = "" + transitionTo = "" + transitionShaderName = "" + transitionFromSlide = -1 + } + function finishSlideTransition() { + // At progress 1 the shader shows exactly the incoming slide, so dropping + // the frames here is invisible and returns their memory. + transitionProgress = 1 + transitionFrom = "" + transitionTo = "" + transitionShaderName = "" + transitionFromSlide = -1 + } Component.onCompleted: { syncSourceEditor(); syncEditors(); syncVideo(true); lastSelected = deck.selected; Qt.callLater(thumbnails.revealSelection); if (deck.path !== "") focusForDeck(true) } Connections { target: deck @@ -426,6 +515,7 @@ ApplicationWindow { win.syncEditors() if (win.dragIndex < 0 && win.lastSelected !== deck.selected) Qt.callLater(thumbnails.revealSelection) win.syncVideo(win.lastSelected !== deck.selected) + if (win.lastSelected !== deck.selected) win.startSlideTransition(win.lastSelected, deck.selected) win.lastSelected = deck.selected } function onModelAboutToBeReset() { @@ -434,7 +524,7 @@ ApplicationWindow { thumbnails.scrollBeforeReset = thumbnails.contentY - thumbnails.originY } function onModelReset() { Qt.callLater(thumbnails.revealSelection) } - function onOpened(existing) { win.sourceOnlyCursor = -1; Qt.callLater(function() { win.focusForDeck(existing) }) } + function onOpened(existing) { win.sourceOnlyCursor = -1; win.endSlideTransition(); Qt.callLater(function() { win.focusForDeck(existing) }) } } onPresentingChanged: { if (player && presenting && deck.media.video && deck.media.autoplay) player.play() } onClosing: function(close) { @@ -699,6 +789,8 @@ ApplicationWindow { Shortcut { enabled: !win.popupOpen && !deck.compressingImage; sequences: [StandardKey.Quit]; context: Qt.ApplicationShortcut; onActivated: win.close() } Shortcut { sequence: "Ctrl+E"; enabled: !win.popupOpen && !deck.compressingImage && !win.presenting && !deck.exporting; onActivated: deck.exportDialog("pdf") } Shortcut { sequence: "Ctrl+Shift+E"; enabled: !win.popupOpen && !deck.compressingImage && !win.presenting && !deck.exporting; onActivated: deck.exportDialog("pptx") } + Shortcut { sequence: "Ctrl+Alt+E"; enabled: !win.popupOpen && !deck.compressingImage && !win.presenting && !deck.exporting; onActivated: deck.exportDialog("html") } + Shortcut { sequence: "Ctrl+Alt+Shift+E"; enabled: !win.popupOpen && !deck.compressingImage && !win.presenting && !deck.exporting; onActivated: deck.exportDialog("html-folder") } Shortcut { sequences: ["?", "Shift+?"]; enabled: !win.popupOpen && !deck.compressingImage && !win.presenting && !slideEditor.activeFocus && !sourceEditor.activeFocus; onActivated: shortcutsOverlay.open() } Shortcut { sequence: "F1"; enabled: !win.popupOpen && !deck.compressingImage && !win.presenting; onActivated: shortcutsOverlay.open() } Shortcut { sequence: "Ctrl+M"; enabled: !win.popupOpen && !deck.compressingImage && (!win.presenting); onActivated: win.toggleOverview() } @@ -950,6 +1042,46 @@ ApplicationWindow { AppMenuItem { text: qsTr("Use theme color"); enabled: !mediaMenu.placed; checkable: true; checked: deck.media.background === "theme"; onTriggered: deck.matchImageBackground(false) } } } + EditorButton { + compact: editorBar.compact + objectName: editorBar.scope + "transitionButton"; iconName: "transition"; label: qsTr("Transition"); description: qsTr("Slide transition"); menu: true + dropdown: transitionMenu + AppMenu { + hasChecks: true + id: transitionMenu; objectName: editorBar.scope + "transitionMenu"; y: parent.height + 4 + AppMenuItem { + objectName: editorBar.scope + "useDeckTransitionItem" + text: qsTr("Use deck default"); checkable: true; checked: deck.slideTransitionOverride === "" + onTriggered: deck.setSlideTransition("") + } + Instantiator { + model: deck.transitionNames + delegate: AppMenuItem { + text: win.transitionName(modelData) + checkable: true; checked: deck.slideTransition === modelData + onTriggered: deck.setSlideTransition(modelData) + } + onObjectAdded: (index, item) => transitionMenu.insertItem(index + 1, item) + onObjectRemoved: (index, item) => transitionMenu.removeItem(item) + } + AppMenuSeparator {} + AppMenu { + id: deckTransitionMenu + objectName: editorBar.scope + "deckTransitionMenu" + title: qsTr("Deck default"); hasChecks: true + Instantiator { + model: deck.transitionNames + delegate: AppMenuItem { + text: win.transitionName(modelData) + checkable: true; checked: deck.transitionName === modelData + onTriggered: deck.chooseTransition(modelData) + } + onObjectAdded: (index, item) => deckTransitionMenu.insertItem(index, item) + onObjectRemoved: (index, item) => deckTransitionMenu.removeItem(item) + } + } + } + } } } header: ToolBar { @@ -1118,6 +1250,8 @@ ApplicationWindow { AppMenuSeparator {} AppMenuItem { text: qsTr("Export as PDF…"); hint: "Ctrl+E"; enabled: !deck.exporting; onTriggered: deck.exportDialog("pdf") } AppMenuItem { text: qsTr("Export as PowerPoint…"); hint: "Ctrl+Shift+E"; enabled: !deck.exporting; onTriggered: deck.exportDialog("pptx") } + AppMenuItem { text: qsTr("Export as HTML…"); hint: "Ctrl+Alt+E"; enabled: !deck.exporting; onTriggered: deck.exportDialog("html") } + AppMenuItem { text: qsTr("Export as HTML folder…"); hint: "Ctrl+Alt+Shift+E"; enabled: !deck.exporting; onTriggered: deck.exportDialog("html-folder") } AppMenuSeparator {} AppMenuItem { text: qsTr("Version history…"); onTriggered: historyDialog.open() } } @@ -1138,7 +1272,7 @@ ApplicationWindow { readonly property var groups: [ { title: qsTr("Presentation"), keys: [ ["Ctrl+N", qsTr("New presentation")], ["Ctrl+O", qsTr("Open")], ["Ctrl+S", qsTr("Save")], ["Ctrl+Shift+S", qsTr("Save as")], ["Ctrl+Q", qsTr("Quit")], - ["Ctrl+E", qsTr("Export as PDF")], ["Ctrl+Shift+E", qsTr("Export as PowerPoint")], ["Ctrl+Space / F5", qsTr("Present")], ["Shift+F5", qsTr("Present from first slide")], ["Esc", qsTr("Stop presenting")], + ["Ctrl+E", qsTr("Export as PDF")], ["Ctrl+Shift+E", qsTr("Export as PowerPoint")], ["Ctrl+Alt+E", qsTr("Export as HTML deck")], ["Ctrl+Alt+Shift+E", qsTr("Export as HTML folder")], ["Ctrl+Space / F5", qsTr("Present")], ["Shift+F5", qsTr("Present from first slide")], ["Esc", qsTr("Stop presenting")], ["Space", qsTr("Play or pause video while presenting")] ] }, { title: qsTr("View"), keys: [ ["Ctrl+M", qsTr("Overview on or off")], ["Ctrl+.", qsTr("Markdown source on or off")], @@ -1505,24 +1639,25 @@ ApplicationWindow { // briefly after loading, it cannot cover the sharp image once that is ready. Image { objectName: "slideQuickPreview"; anchors.fill: parent - visible: slidePreview.status === Image.Loading && slidePreview.shownSlide !== deck.selected && status === Image.Ready + visible: slidePreview.status === Image.Loading && slidePreview.shownSlide !== win.previewSlide && status === Image.Ready // The same URL and size as the sidebar thumbnail, so it comes from Qt's pixmap cache. - source: "image://slides/" + (deck.revision, deck.renderId(deck.selected)) + source: win.previewSource asynchronous: true; cache: true; sourceSize: Qt.size(340, 192) } Image { id: slidePreview; objectName: "slidePreview"; anchors.fill: parent - source: "image://slides/" + (deck.revision, deck.renderId(deck.selected)) + (animation.active ? "/background" : "") + source: win.previewSource asynchronous: true; retainWhileLoading: true; cache: true; sourceSize: Qt.size(1920, 1080) property int shownSlide: -1 // On a new slide, let its thumbnail show while this render loads. Edits to // the same slide retain the previous sharp frame until the new one is ready. - visible: status === Image.Ready || shownSlide === deck.selected - onStatusChanged: if (status === Image.Ready) shownSlide = deck.selected + visible: status === Image.Ready || shownSlide === win.previewSlide + onStatusChanged: if (status === Image.Ready) shownSlide = win.transitionPreparing && win.transitionFromSlide >= 0 + ? win.transitionFromSlide : deck.selected } Loader { id: animation; objectName: "animationLoader" - active: workspace.visible && !!deck.media.animated + active: workspace.visible && !!deck.media.animated && !win.transitionPreparing x: deck.media.rect.x * slideFrame.width / 1920 y: deck.media.rect.y * slideFrame.height / 1080 width: deck.media.rect.width * slideFrame.width / 1920 @@ -1563,14 +1698,46 @@ ApplicationWindow { sourceComponent: VideoOutput { id: video; objectName: "videoOutput" property alias player: player - visible: deck.media.video && (player.playbackState !== MediaPlayer.StoppedState || player.mediaStatus === MediaPlayer.EndOfMedia) + visible: deck.media.video && !win.transitionPreparing && (player.playbackState !== MediaPlayer.StoppedState || player.mediaStatus === MediaPlayer.EndOfMedia) endOfStreamPolicy: VideoOutput.KeepLastFrame fillMode: deck.media.span ? VideoOutput.PreserveAspectCrop : VideoOutput.PreserveAspectFit MediaPlayer { id: player; objectName: "player"; videoOutput: video; audioOutput: AudioOutput { muted: deck.media.muted } loops: deck.media.loop ? MediaPlayer.Infinite : 1; onErrorOccurred: function(error,message) { deck.setStatus(message) } } } } - Image { anchors.fill: parent; source: visible ? "image://slides/" + (deck.revision, deck.renderId(deck.selected)) + "/overlay" : ""; asynchronous: true; retainWhileLoading: true; sourceSize: Qt.size(1920,1080); visible: animation.active || (videoLoader.item && videoLoader.item.visible && deck.media.span) } - Button { visible: deck.media.video && !win.presenting; anchors.centerIn: parent; text: player && player.playbackState === MediaPlayer.PlayingState ? qsTr("Pause") : "▶ " + qsTr("Play"); onClicked: win.toggleVideo() } + Image { anchors.fill: parent; source: visible ? "image://slides/" + (deck.revision, deck.renderId(deck.selected)) + "/overlay" : ""; asynchronous: true; retainWhileLoading: true; sourceSize: Qt.size(1920,1080); visible: !win.transitionPreparing && (animation.active || (videoLoader.item && videoLoader.item.visible && deck.media.span)) } + Button { visible: deck.media.video && !win.presenting && !win.transitionPreparing; anchors.centerIn: parent; text: player && player.playbackState === MediaPlayer.PlayingState ? qsTr("Pause") : "▶ " + qsTr("Play"); onClicked: win.toggleVideo() } + // The transition draws last, over the slide and its media. Its two + // frames are full renders kept hidden: ShaderEffectSource turns + // them into the fromTex and toTex the shared shader samples. + Image { + id: transitionFromFrame; objectName: "transitionFromFrame" + anchors.fill: parent; visible: false + source: win.transitionFrom ? "image://slides/" + win.transitionFrom : "" + asynchronous: true; cache: true; sourceSize: Qt.size(1920, 1080) + onStatusChanged: win.startSlideTransitionIfReady() + } + Image { + id: transitionToFrame; objectName: "transitionToFrame" + anchors.fill: parent; visible: false + source: win.transitionTo ? "image://slides/" + win.transitionTo : "" + asynchronous: true; cache: true; sourceSize: Qt.size(1920, 1080) + onStatusChanged: win.startSlideTransitionIfReady() + } + ShaderEffectSource { id: transitionFromTexture; sourceItem: transitionFromFrame; hideSource: true; live: win.transitionPreparing || win.transitionShaderName !== "" } + ShaderEffectSource { id: transitionToTexture; sourceItem: transitionToFrame; hideSource: true; live: win.transitionPreparing || win.transitionShaderName !== "" } + ShaderEffect { + objectName: "slideTransition" + anchors.fill: parent + visible: win.transitionProgress > 0 && win.transitionProgress < 1 + property ShaderEffectSource fromTex: transitionFromTexture + property ShaderEffectSource toTex: transitionToTexture + property real progress: win.transitionProgress + // Keep a shader installed even while no transition runs: + // Qt's shaderless default samples a "source" texture this + // effect does not have, and warns about it on every reset. + fragmentShader: "qrc:/transitions/" + + (win.transitionShaderName || "crossfade") + ".frag.qsb" + } MouseArea { anchors.fill: parent enabled: win.presenting diff --git a/src/cli.cpp b/src/cli.cpp index 67b2b91..90b2064 100644 --- a/src/cli.cpp +++ b/src/cli.cpp @@ -107,29 +107,6 @@ QString toText(const QString &path, const Problem &problem) { .arg(problem.slide ? QString("slide %1 ").arg(problem.slide) : QString()) .arg(problem.error ? "error" : "warning", problem.message); } -// The headline, or else the first line of text, or else of code. Fences close as in parseDeck. -QString slideTitle(const QString &text) { - static const QRegularExpression fenceRe("^(`{3,}|~{3,})(.*)$"); - QString first, code, fence; - for (const auto &raw : text.split('\n')) { - const QString line = raw.trimmed(); - const auto match = fenceRe.match(line); - const QString run = match.captured(1); - if (match.hasMatch() && fence.isEmpty()) - fence = run; - else if (match.hasMatch() && run[0] == fence[0] && run.size() >= fence.size() && - match.captured(2).trimmed().isEmpty()) - fence.clear(); - else if (!fence.isEmpty() && code.isEmpty()) - code = line; - else if (fence.isEmpty() && line.startsWith('#')) - return line.mid(line.indexOf(' ') + 1).trimmed(); - else if (fence.isEmpty() && first.isEmpty()) - first = QString(line).remove(QRegularExpression(R"(^(>|[-*+]|\d+\.)\s+|\\$)")).trimmed(); - } - return first.isEmpty() ? code : first; -} - struct Command { QCommandLineParser parser; Command(const QString &name, const QString &description, bool presentation = true) { @@ -285,22 +262,37 @@ int render(const QStringList &arguments) { } int exportDeck(const QStringList &arguments) { - Command command("export", "Export a presentation as PDF or PowerPoint, chosen by the file extension."); - command.parser.addPositionalArgument("output", "File ending in .pdf or .pptx", ""); + Command command( + "export", + "Export a presentation as PDF, PowerPoint, or an HTML deck: one self-contained file, " + "or an editable folder for a path ending in /."); + command.parser.addPositionalArgument("output", + "File ending in .pdf, .pptx, or .html, or a new folder ending in /", + ""); command.json(); command.parser.process(arguments); const QString output = command.argument(2); - const QString format = QFileInfo(output).suffix().toLower(); - if (format != "pdf" && format != "pptx") - return fail("Name an output file ending in .pdf or .pptx."); + // A trailing slash, or a path that is already a directory, names the HTML folder export. + const QString directory = output.endsWith('/') ? output.left(output.size() - 1) : output; + const bool folder = output.endsWith('/') || + (QFileInfo(output).isDir() && QFileInfo(output).suffix().isEmpty()); + const QString format = folder ? QString("html-folder") : QFileInfo(output).suffix().toLower(); + if (format != "pdf" && format != "pptx" && format != "html" && format != "html-folder") + return fail("Name an output file ending in .pdf, .pptx, or .html, or a new folder ending in / " + "for an editable HTML deck."); Deck deck; if (!command.load(deck)) return 1; - QDir().mkpath(QFileInfo(output).absolutePath()); - if (!(format == "pdf" ? deck.exportPdf(output) : deck.exportPptx(output))) + QDir().mkpath(QFileInfo(directory).absolutePath()); + if (!(format == "pdf" ? deck.exportPdf(output) + : format == "pptx" ? deck.exportPptx(output) + : format == "html" ? deck.exportHtml(output) + : deck.exportHtmlFolder(directory))) return fail(deck.status()); if (command.parser.isSet("json")) - print({{"output", QFileInfo(output).absoluteFilePath()}, {"format", format}, {"slides", deck.count()}}); + print({{"output", QFileInfo(format == "html-folder" ? directory : output).absoluteFilePath()}, + {"format", format}, + {"slides", deck.count()}}); else print(stdout, deck.status()); return 0; @@ -418,7 +410,7 @@ QString cliSummary() { " check Report every problem, with slide and line\n" " slides Outline the slides\n" " render Render one slide or all of them to PNG\n" - " export Export PDF or PowerPoint\n" + " export Export PDF, PowerPoint, or an HTML deck or folder\n" " themes List installed themes\n" " help format How to write a presentation\n" " skill [install] Print the skill for coding agents, or install it"; diff --git a/src/deck.cpp b/src/deck.cpp index 4702a6e..ca306f9 100644 --- a/src/deck.cpp +++ b/src/deck.cpp @@ -6,6 +6,7 @@ #include "images.h" #include "pptx.h" #include "renderer.h" +#include "transitions.h" #include #include #include @@ -35,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -43,6 +45,7 @@ #include #include #include +#include // Hype's free functions translate like its classes do; the Translator ignores the context. static QString tr(const char *text) { return QCoreApplication::translate("Hype", text); } @@ -140,6 +143,28 @@ QString setScalar(QString header, const QString &key, const QString &value) { } return header; } +// The headline, or else the first line of text, or else of code. Fences close as in parseDeck. +QString slideTitle(const QString &text) { + static const QRegularExpression fenceRe("^(`{3,}|~{3,})(.*)$"); + QString first, code, fence; + for (const auto &raw : text.split('\n')) { + const QString line = raw.trimmed(); + const auto match = fenceRe.match(line); + const QString run = match.captured(1); + if (match.hasMatch() && fence.isEmpty()) + fence = run; + else if (match.hasMatch() && run[0] == fence[0] && run.size() >= fence.size() && + match.captured(2).trimmed().isEmpty()) + fence.clear(); + else if (!fence.isEmpty() && code.isEmpty()) + code = line; + else if (fence.isEmpty() && line.startsWith('#')) + return line.mid(line.indexOf(' ') + 1).trimmed(); + else if (fence.isEmpty() && first.isEmpty()) + first = QString(line).remove(QRegularExpression(R"(^(>|[-*+]|\d+\.)\s+|\\$)")).trimmed(); + } + return first.isEmpty() ? code : first; +} // The first slide's problem, for a structure whose boundaries are already known. static QString slidesError(const ParsedDeck &parsed) { for (const auto &slide : parsed.slides) { @@ -610,6 +635,38 @@ QColor Deck::accent() const { return QColor(palette()["accent"].toString()); } void Deck::chooseTheme(const QString &name) { replaceHeader(themedHeader(m_parsed.header, name, m_themes.value(name))); } +QStringList Deck::transitionNames() const { return ::transitionNames(); } +QString Deck::transitionName() const { + const QString name = scalar(m_parsed.header, "transition", "none"); + return ::transitionNames().contains(name) ? name : QStringLiteral("none"); +} +double Deck::transitionDuration() const { + bool ok = false; + const double seconds = scalar(m_parsed.header, "transition-duration", "0.6").toDouble(&ok); + return ok ? qBound(0.1, seconds, 4.0) : 0.6; +} +QString Deck::slideTransitionOverride() const { + return slideProperty(slideText(), "transition"); +} +QString Deck::slideTransition() const { + const QString override = slideTransitionOverride(); + return ::transitionNames().contains(override) ? override : transitionName(); +} +void Deck::chooseTransition(const QString &name) { + if (!::transitionNames().contains(name) || + scalar(m_parsed.header, "transition", "none") == name) + return; + replaceHeader(setScalar(m_parsed.header, "transition", name)); +} +void Deck::setSlideTransition(const QString &name) { + if (!name.isEmpty() && !::transitionNames().contains(name)) + return; + const QString source = slideText(); + const QString updated = withSlideProperty(source, "transition", name); + if (updated != source) + editSlide(updated); +} +QString Deck::transitionShader(const QString &name) const { return qtFragmentShader(name); } QStringList Deck::mediaPositions() const { return ::mediaPositions(); } QVariantMap Deck::media() const { const QString source = slideSource(), base = baseDir(); @@ -1298,11 +1355,14 @@ void Deck::exportDialog(const QString &format) { if (m_exporting) return; QString error; + // A folder export names a directory, not a file with an extension. + const bool folder = format == "html-folder"; + const QString name = QString(title()).replace(QRegularExpression(R"([/\\\x00-\x1f])"), "-"); const QString p = FileDialog::choose( true, - baseDir() + "/" + QString(title()).replace(QRegularExpression(R"([/\\\x00-\x1f])"), "-") + - "." + format, - format.toUpper(), {"*." + format}, &error); + folder ? baseDir() + "/" + name + "-html" : baseDir() + "/" + name + "." + format, + folder ? tr("HTML folder") : format.toUpper(), + folder ? QStringList{} : QStringList{"*." + format}, &error); if (!error.isEmpty()) setStatus(error); if (p.isEmpty()) return; @@ -1348,8 +1408,16 @@ bool Deck::loadExportSnapshot(const QString &path) { return validateStructure("export"); } void Deck::startExport(const QString &format, const QString &path) { - if (m_exporting || path.isEmpty() || !QStringList{"pdf", "pptx"}.contains(format)) + if (m_exporting || path.isEmpty() || !QStringList{"pdf", "pptx", "html", "html-folder"}.contains(format)) + return; + if (format == "html-folder" && QFileInfo::exists(path) && !QDir(path).isEmpty()) { + // A folder export moves a whole directory into place, so the destination must be free. + m_exportFailed = true; + m_exportStatus = tr("Choose a new or empty folder: %1 has files in it.").arg(path); + emit exportChanged(); + emit exportFinished(false); return; + } if (!validateStructure("export")) { m_exportFailed = true; m_exportStatus = m_status; @@ -1377,7 +1445,8 @@ void Deck::startExport(const QString &format, const QString &path) { m_exportCancelled = false; m_exportFailed = false; m_exportProgress = 0; - m_exportStatus = tr("Preparing %1 export…").arg(format.toUpper()); + m_exportStatus = tr("Preparing %1 export…") + .arg(format == "html-folder" ? QStringLiteral("HTML FOLDER") : format.toUpper()); emit exportChanged(); auto *process = new QProcess(this); m_exportProcess = process; @@ -1503,7 +1572,7 @@ static bool opaque(const QImage &image) { } return true; } -bool Deck::renderImages(const QString &directory, int width, bool powerPoint) { +bool Deck::renderImages(const QString &directory, int width, bool powerPoint, double portion) { if (!validateStructure("export")) return false; for (int i = 0; i < count(); ++i) { @@ -1558,7 +1627,6 @@ bool Deck::renderImages(const QString &directory, int width, bool powerPoint) { return still; }); if (!overlap) { - const double portion = 0.8; while (!stills.waitForDone(100)) { const auto done = std::count_if(rendered.cbegin(), rendered.cend(), [](const auto &f) { return f.isFinished(); }); emit exportAdvanced(portion * done / count(), tr("Exporting slide %1 of %2").arg(qMin(count(), done + 1)).arg(count())); @@ -1569,7 +1637,6 @@ bool Deck::renderImages(const QString &directory, int width, bool powerPoint) { QJsonArray slides; QHash convertedVideos; for (int i = 0; i < count(); ++i) { - const double portion = powerPoint ? 0.8 : 1.0; // `message` names the slide as %1 and the slide count as %2. auto progress = [this, i, portion](double fraction, const QString &message) { emit exportAdvanced(portion * (i + fraction) / count(), message.arg(i + 1).arg(count())); @@ -1661,7 +1728,7 @@ bool Deck::exportPptx(const QString &path) { setStatus(tr("Could not prepare the export: %1").arg(temp.errorString())); return false; } - if (!renderImages(temp.path(), 3840, true)) + if (!renderImages(temp.path(), 3840, true, 0.8)) return false; QString error; emit exportAdvanced(0.8, tr("Packaging PowerPoint…")); @@ -1673,3 +1740,280 @@ bool Deck::exportPptx(const QString &path) { setStatus(tr("Exported %1").arg(path)); return true; } +// WebP carries the same picture as PNG in a tenth of the bytes at 1920px, so a whole +// deck fits in one file that opens anywhere; alpha, and so a translucent background, +// survives. libwebp is linked directly rather than going through Qt's image plugins, +// whose WebP writer is only present when an extra package is installed. +static bool webp(const QImage &image, QByteArray *encoded, QString *error) { + const QImage rgba = image.convertToFormat(QImage::Format_RGBA8888); + uint8_t *output = nullptr; + const size_t size = WebPEncodeRGBA(rgba.constBits(), rgba.width(), rgba.height(), + rgba.bytesPerLine(), 85.0f, &output); + if (!size) { + *error = tr("Cannot encode image as WebP"); + return false; + } + *encoded = QByteArray(reinterpret_cast(output), qsizetype(size)); + WebPFree(output); + return true; +} +// Reads one of the bundled deck files, such as the page, the stylesheet, or the script. +static bool readResource(const QString &path, QString *content, QString *error) { + QFile file(path); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { + *error = Deck::tr("Could not read the deck template"); + return false; + } + *content = QString::fromUtf8(file.readAll()); + return true; +} + +// Fills the bundled deck page: shared chrome, plus the stylesheet, script, and slides +// the two HTML exports each supply in their own form. Both exports also pass the +// deck's Markdown source as inert script blocks, which the folder export renders, +// and the one-file export carries beside its slide pictures as the editable source. +QString Deck::htmlPage(const QString &stylesheet, const QString &script, const QString §ions, + const QString &source) const { + QString page, error; + if (!readResource(":/deck.html", &page, &error)) + return {}; + const QHash values = { + {"LANG", QLocale().name().split('_').value(0, "en")}, + {"TITLE", title().toHtmlEscaped()}, + {"PREVIOUS", tr("Previous slide").toHtmlEscaped()}, + {"NEXT", tr("Next slide").toHtmlEscaped()}, + {"STYLESHEET", stylesheet}, + {"SCRIPT", script}, + {"SOURCE", source}, + {"SLIDES", sections.trimmed()}, + }; + // Every slot is filled in one pass over the template, so a slot's value is never read + // as a slot itself: a deck titled "{{SCRIPT}}" keeps its title instead of pulling the + // whole script into the tab. + static const QRegularExpression slot("\\{\\{([A-Z]+)\\}\\}"); + QString filled; + qsizetype end = 0; + for (QRegularExpressionMatchIterator it = slot.globalMatch(page); it.hasNext();) { + const QRegularExpressionMatch match = it.next(); + filled += page.sliced(end, match.capturedStart() - end); + const auto value = values.constFind(match.captured(1)); + filled += value == values.cend() ? match.captured(0) : *value; + end = match.capturedEnd(); + } + return filled + page.sliced(end); +} + +// The deck's Markdown, resolved theme and transition shaders as inert script +// blocks, for both HTML exports. The Markdown is the deck's source of truth: +// anyone who receives an export can edit the block in any text editor and +// refresh the page (the folder export) or copy it back into a presentation. The +// folder export embeds the source as written; the one-file export strips +// speaker notes, since that file travels to readers. A \n" + "\n" + ""; +} + +// Encodes one rendered slide as WebP, named for a screen reader, and for search, as PDF bookmarks do. +static bool encodeSlide(const QString &rendered, int index, const QString &headline, + QByteArray *encoded, QString *altText, QString *error) { + QByteArray webpBytes; + if (!webp(QImage(rendered), &webpBytes, error)) + return false; + *encoded = webpBytes; + const QString title = headline.trimmed(); + const QString alt = title.isEmpty() + ? Deck::tr("Slide %1").arg(index) + : Deck::tr("Slide %1: %2").arg(index).arg(title); + *altText = alt.toHtmlEscaped(); + return true; +} + +bool Deck::exportHtml(const QString &path) { + // Render beside the destination, not in /tmp: /tmp is usually RAM-backed, and a deck's + // rendered slide images would otherwise sit in memory until inlined. + QTemporaryDir temp(QFileInfo(path).absoluteDir().filePath(".hype-render-XXXXXX")); + if (!temp.isValid()) { + setStatus(tr("Could not prepare the export: %1").arg(temp.errorString())); + return false; + } + if (!renderImages(temp.path(), 1920, false, 0.8)) + return false; + QString error, stylesheet, script; + if (!readResource(":/deck.css", &stylesheet, &error) || !readResource(":/deck.js", &script, &error)) { + setStatus(error); + return false; + } + QString sections; + for (int i = 0; i < count(); ++i) { + emit exportAdvanced(0.8 + 0.2 * (i + 1) / count(), tr("Inlining slide %1 of %2").arg(i + 1).arg(count())); + QByteArray webpBytes; + QString alt; + // The alt text is read by anyone who receives the file, so it is drawn from the + // visible slide: speaker notes, comments and media directives stay out of it. + if (!encodeSlide(temp.filePath(QString("slide-%1.png").arg(i + 1, 3, 10, QChar('0'))), + i + 1, slideTitle(parseMedia(slide(i), baseDir()).text), &webpBytes, &alt, + &error)) { + setStatus(tr("Slide %1: %2").arg(i + 1).arg(error)); + return false; + } + sections += QString("
\n\"%2\"\n
\n") + .arg(QString::fromLatin1(webpBytes.toBase64()), alt); + } + // One self-contained file: the stylesheet and script ride inside the page itself, + // and the Markdown rides with them as inert blocks, beside the slide pictures. + // Speaker notes stay out: this file is handed to readers. + const QString deck = htmlPage("", + "", sections, + sourceBlock(withoutSpeakerNotes(m_source))); + if (deck.isEmpty()) { + setStatus(tr("Could not read the deck template")); + return false; + } + QSaveFile file(path); + if (!file.open(QIODevice::WriteOnly | QIODevice::Text) || + file.write(deck.toUtf8()) < 0 || !file.commit()) { + setStatus(file.errorString()); + return false; + } + emit exportAdvanced(1.0, tr("Exported %1").arg(path)); + setStatus(tr("Exported %1").arg(path)); + return true; +} + +// The same deck in an editable shape: the Markdown rides inside index.html, with the +// theme's resolved colors beside it, and the page's script renders the slides in the +// browser, mirroring Hype's layout. Media ships as the real files, so videos play. +// The folder is built beside the destination and moved into place only after every +// write succeeds, so a failed export leaves nothing behind and can be retried. +bool Deck::exportHtmlFolder(const QString &path) { + const QFileInfo destination(path); + if (destination.exists() && !QDir(path).isEmpty()) { + setStatus(tr("Choose a new or empty folder: %1 has files in it.").arg(path)); + return false; + } + if (!validateStructure("export")) + return false; + QString error, stylesheet, script; + if (!readResource(":/deck.css", &stylesheet, &error) || !readResource(":/deck.js", &script, &error)) { + setStatus(error); + return false; + } + // Collect the media the slides name, at the paths the browser will resolve them. + struct Copy { QString from, to; }; + QList copies; + QSet seen; + // Where each copied file lands, so the Markdown names the copy rather than the + // path it came from: a deck shared on its own still finds its pictures. + QHash targets; + const QString base = baseDir(); + for (const auto &slide : m_parsed.slides) { + const auto media = parseMedia(slide.source, base); + for (const auto &item : {qMakePair(media.path, media.video), qMakePair(media.poster, false)}) { + // A missing file is not a failure: the browser draws Hype's missing-media + // notice in its place, as the editor does. + if (item.first.isEmpty() || !QFile::exists(item.first)) + continue; + QString target = QDir(base).relativeFilePath(QFileInfo(item.first).absoluteFilePath()); + if (target.startsWith("..")) + target = (item.second ? "videos/" : "images/") + QFileInfo(item.first).fileName(); + if (seen.contains(target)) + continue; + seen.insert(target); + copies.append({item.first, target}); + targets.insert(QFileInfo(item.first).absoluteFilePath(), target); + } + } + // Build beside the destination, not in /tmp: the finished folder then moves into + // place in one rename, which has to stay on one filesystem. A plain mkdir, not + // QTemporaryDir, so the folder keeps the permissions a new folder normally gets. + const QString parent = destination.absoluteDir().absolutePath(); + if (!QDir().mkpath(parent)) { + setStatus(tr("Could not create %1").arg(parent)); + return false; + } + QString temp; + for (int attempt = 0; attempt < 100 && temp.isEmpty(); ++attempt) { + const QString candidate = + parent + "/.hype-export-" + QUuid::createUuid().toString(QUuid::WithoutBraces).left(12); + if (QFileInfo::exists(candidate)) + continue; // A collision is vanishingly unlikely, but pick again. + if (!QDir().mkdir(candidate)) + break; // The parent is not writable. + temp = candidate; + } + if (temp.isEmpty()) { + setStatus(tr("Could not create %1").arg(path)); + return false; + } + // Every failed write below leaves the destination untouched and removes the draft. + auto discard = qScopeGuard([&] { QDir(temp).removeRecursively(); }); + for (int i = 0; i < copies.size(); ++i) { + emit exportAdvanced(0.2 + 0.6 * (i + 1) / copies.size(), + tr("Copying media %1 of %2").arg(i + 1).arg(copies.size())); + const QString target = temp + "/" + copies[i].to; + if (!QDir().mkpath(QFileInfo(target).absolutePath()) || !QFile::copy(copies[i].from, target)) { + setStatus(tr("Could not prepare the export: %1").arg(path + "/" + copies[i].to)); + return false; + } + } + const QList> chrome = {{QStringLiteral("deck.css"), stylesheet}, + {QStringLiteral("deck.js"), script}}; + for (const auto &[name, content] : chrome) { + QSaveFile chromeFile(temp + "/" + name); + if (!chromeFile.open(QIODevice::WriteOnly | QIODevice::Text) || + chromeFile.write(content.toUtf8()) < 0 || !chromeFile.commit()) { + setStatus(chromeFile.errorString()); + return false; + } + } + // The Markdown is the deck's source of truth: edit the block below in any text + // editor and refresh the page. A ", + "", {}, sourceBlock(markdown)); + if (page.isEmpty()) { + setStatus(tr("Could not read the deck template")); + return false; + } + QSaveFile file(temp + "/index.html"); + if (!file.open(QIODevice::WriteOnly | QIODevice::Text) || + file.write(page.toUtf8()) < 0 || !file.commit()) { + setStatus(file.errorString()); + return false; + } + // Every file is written: move the folder into place. An existing empty destination + // was allowed above, so clear it first; anything else is left untouched. + const QFileInfo finished(destination.absoluteFilePath()); + if (finished.exists() && !QDir().rmdir(finished.absoluteFilePath())) { + setStatus(tr("Could not create %1").arg(path)); + return false; + } + if (!QDir().rename(temp, destination.absoluteFilePath())) { + setStatus(tr("Could not create %1").arg(path)); + return false; + } + discard.dismiss(); + emit exportAdvanced(1.0, tr("Exported %1").arg(path)); + setStatus(tr("Exported %1").arg(path)); + return true; +} diff --git a/src/deck.css b/src/deck.css new file mode 100644 index 0000000..355e0d5 --- /dev/null +++ b/src/deck.css @@ -0,0 +1,197 @@ +:root { + color-scheme: dark; + /* The deck's theme, set by deck.js from the palette baked at export time. */ + --background: #1a1b26; + --foreground: #c0caf5; + --accent: #7aa2f7; + --green: #9ece6a; + --red: #f7768e; + --yellow: #e0af68; + --magenta: #bb9af7; + --cyan: #7dcfff; + --dark-foreground: #787c99; + --font: "JetBrains Mono"; +} +html, body { height: 100%; } +body { + margin: 0; + overflow: hidden; + background: #000; + display: flex; + align-items: center; + justify-content: center; + font-family: system-ui, sans-serif; +} +.stage { + position: relative; + aspect-ratio: 16 / 9; + width: min(100vw, 100vh * 16 / 9); + max-height: 100vh; + background: #000; +} +.slide { display: none; } +.slide.active { display: block; } +/* The shader transition's overlay, filled by deck.js while a slide changes. */ +.transition { + position: absolute; + left: 0; + top: 0; + width: 100%; + height: 100%; + pointer-events: none; +} +/* Laid out invisibly while a hidden slide's text is fitted; never painted. */ +.slide.measuring { display: block; visibility: hidden; } +.slide img { + width: 100%; + height: 100%; + object-fit: contain; + display: block; +} + +/* Slides rendered from the Markdown block in an editable folder export. Each + is laid out in Hype's 1080p coordinates and scaled to the window. */ +.canvas { + position: absolute; + left: 0; + top: 0; + width: 1920px; + height: 1080px; + transform-origin: 0 0; + overflow: hidden; +} +.media { + position: absolute; + object-fit: contain; +} +.media.cover { object-fit: cover; } +.media.soft { filter: blur(2px); } +.backdrop { + position: absolute; + left: 0; + top: 0; + width: 1920px; + height: 1080px; + overflow: hidden; +} +.backdrop img, .backdrop video { + position: absolute; + left: 50%; + top: 50%; + width: 110%; + height: 110%; + transform: translate(-50%, -50%); + object-fit: cover; + filter: blur(48px); +} +.overlay { + position: absolute; + left: 0; + top: 0; + width: 1920px; + height: 1080px; + pointer-events: none; +} +.svg-box { + position: absolute; + display: flex; + align-items: center; + justify-content: center; +} +.missing { + position: absolute; + display: flex; + align-items: center; + justify-content: center; + text-align: center; + white-space: pre-line; + color: var(--accent); + font-family: system-ui, sans-serif; + font-size: 32px; +} +.text { + position: absolute; + display: flex; + flex-direction: column; + justify-content: center; /* The fitted text centers vertically, as in Hype. */ +} +.text .content { + width: 100%; + font-family: var(--font), monospace; + line-height: 1.15; +} +.text.centered .content { text-align: center; } +.text .content > * { margin: 0 0 0.22em; } +.text .content > :last-child { margin-bottom: 0; } +.text h1, .text h2, .text h3, .text h4, .text h5, .text h6 { + font-weight: 700; + margin-top: 0.15em; + font-size: 1.25em; +} +.text h1 { font-size: 1.8em; } +.text strong { color: var(--accent); } +.text :is(h1, h2, h3, h4, h5, h6) strong { color: inherit; } +.text a { color: var(--accent); } +.text em { font-style: italic; } +.text blockquote { margin: 0; padding: 0 0 0 1em; } +.text blockquote p:last-child { margin-bottom: 0; } +.text .attribution { font-size: 0.7em; } +.text ul, .text ol { margin: 0 0 0.22em; padding: 0 0 0 1.4em; } +.text li { margin: 0; } +.text code { font-family: "JetBrains Mono", monospace; } +.text pre { + margin: 0; + font-family: "JetBrains Mono", monospace; + line-height: 1.2; + white-space: pre; +} +.text table { border-collapse: collapse; margin: 0 auto; } +.text:not(.centered) table { margin: 0; } +.text th, .text td { padding: 0.25em 0; } +.text th:not(:last-child), .text td:not(:last-child) { padding-right: 0.8em; } +.text th:not(:first-child), .text td:not(:first-child) { padding-left: 0.8em; } +.text thead tr { border-bottom: 0.06em solid var(--accent); } +.text tbody tr { border-bottom: 0.03em solid color-mix(in srgb, var(--foreground) 20%, transparent); } +.text tbody tr:last-child { border-bottom: none; } +.text .k { color: var(--magenta); } +.text .s { color: var(--green); } +.text .n { color: var(--red); } +.text .c { color: var(--dark-foreground); } +.text .f { color: var(--accent); } +.text .t { color: var(--yellow); } +.text .p { color: var(--cyan); } + +.nav { + position: absolute; + top: 50%; + transform: translateY(-50%); + padding: 14px 10px; + border: none; + border-radius: 6px; + background: rgba(255, 255, 255, 0.08); + color: #eee; + font-size: 28px; + line-height: 1; + cursor: pointer; + opacity: 0; + transition: opacity 0.2s; +} +.nav:hover { background: rgba(255, 255, 255, 0.2); opacity: 1; } +.nav:focus-visible { opacity: 0.7; } +.stage:hover .nav { opacity: 0.7; } +.prev { left: 10px; } +.next { right: 10px; } +.counter { + position: absolute; + right: 12px; + bottom: 10px; + padding: 2px 9px; + border-radius: 10px; + background: rgba(0, 0, 0, 0.4); + color: rgba(255, 255, 255, 0.6); + font-size: 13px; + pointer-events: none; +} +@media (hover: none) { + .nav { opacity: 0.5; } +} diff --git a/src/deck.h b/src/deck.h index 9510026..ef88e66 100644 --- a/src/deck.h +++ b/src/deck.h @@ -23,6 +23,8 @@ struct ParsedDeck { ParsedDeck parseDeck(const QString &source); QString scalar(const QString &header, const QString &key, const QString &fallback = {}); QString setScalar(QString header, const QString &key, const QString &value); +// The headline, or else the first line of text or code: what names a slide in an outline. +QString slideTitle(const QString &text); class Deck : public QAbstractListModel { Q_OBJECT @@ -49,6 +51,11 @@ class Deck : public QAbstractListModel { Q_PROPERTY(QStringList fontNames READ fontNames CONSTANT) Q_PROPERTY(QString fontName READ fontName NOTIFY fontChanged) Q_PROPERTY(QStringList themeNames READ themeNames NOTIFY themesChanged) + Q_PROPERTY(QStringList transitionNames READ transitionNames CONSTANT) + Q_PROPERTY(QString transitionName READ transitionName NOTIFY changed) + Q_PROPERTY(double transitionDuration READ transitionDuration NOTIFY changed) + Q_PROPERTY(QString slideTransition READ slideTransition NOTIFY selectionChanged) + Q_PROPERTY(QString slideTransitionOverride READ slideTransitionOverride NOTIFY selectionChanged) Q_PROPERTY(QStringList mediaPositions READ mediaPositions CONSTANT) Q_PROPERTY(QString themeName READ themeName NOTIFY changed) Q_PROPERTY(QColor background READ background NOTIFY changed) @@ -91,6 +98,12 @@ class Deck : public QAbstractListModel { Q_INVOKABLE void chooseFont(const QString &family); QStringList themeNames() const; QString themeName() const; + QStringList transitionNames() const; + QString transitionName() const; + double transitionDuration() const; + // What the selected slide plays: its own choice, or the deck's default. + QString slideTransition() const; + QString slideTransitionOverride() const; QColor background() const; QColor foreground() const; QColor accent() const; @@ -110,8 +123,17 @@ class Deck : public QAbstractListModel { Q_INVOKABLE bool restoreVersion(const QString &name); bool exportPdf(const QString &path); bool exportPptx(const QString &path); + // One self-contained file: every slide inlined as WebP, wrapped in a navigable page. + bool exportHtml(const QString &path); + // The same deck as an editable folder: the Markdown rides inside the page, + // and the script renders it in the browser, so edits in any text editor + // show on refresh. + bool exportHtmlFolder(const QString &path); // For PowerPoint, animations become videos and opaque slides are stored as JPEG. - bool renderImages(const QString &directory, int width = 1920, bool powerPoint = false); + // Portion is the share of the export progress bar rendering reports, so a caller + // that continues afterwards, like packaging or inlining, can take over from there. + bool renderImages(const QString &directory, int width = 1920, bool powerPoint = false, + double portion = 1.0); Q_INVOKABLE void select(int index); // After a language switch, so what the window shows is made again in the new language. void retranslate(); @@ -130,6 +152,9 @@ class Deck : public QAbstractListModel { Q_INVOKABLE void undo(); Q_INVOKABLE void redo(); Q_INVOKABLE void chooseTheme(const QString &name); + Q_INVOKABLE void chooseTransition(const QString &name); + Q_INVOKABLE void setSlideTransition(const QString &name); + Q_INVOKABLE QString transitionShader(const QString &name) const; Q_INVOKABLE void openDialog(); Q_INVOKABLE void save(); Q_INVOKABLE void saveAs(); @@ -211,6 +236,15 @@ class Deck : public QAbstractListModel { void apply(const QString &source, int selected, bool history = true, int anchor = -1, const ParsedDeck *structure = nullptr); void replaceHeader(const QString &header); + // Fills the bundled deck page: shared chrome plus the stylesheet, script, and slides + // the two HTML exports supply in their own form. Both also pass the Markdown as + // inert blocks: the folder export renders it in the browser, the one-file export + // carries it beside the slide pictures as the editable source. + QString htmlPage(const QString &stylesheet, const QString &script, const QString §ions, + const QString &source = {}) const; + // The deck's Markdown and theme as inert script blocks, shared by both exports; + // the one-file export passes the source without speaker notes. + QString sourceBlock(const QString &markdownSource) const; void replaceSlides(const QStringList &slides, int selected, int anchor = -1); bool confirmDiscard(); bool validateStructure(const QString &operation); diff --git a/src/deck.html b/src/deck.html new file mode 100644 index 0000000..d0867ed --- /dev/null +++ b/src/deck.html @@ -0,0 +1,19 @@ + + + + + + {{TITLE}} + {{STYLESHEET}} + + +
+ {{SLIDES}} + + +
+
+ {{SOURCE}} + {{SCRIPT}} + + diff --git a/src/deck.js b/src/deck.js new file mode 100644 index 0000000..8b2cc41 --- /dev/null +++ b/src/deck.js @@ -0,0 +1,1901 @@ +"use strict" + +// Navigation is shared by every deck: baked decks ship their slides as +//
markup, while an editable folder export ships its Markdown in a +// ', + text, re.DOTALL) + self.assertIsNotNone(block, page) + shaders = json.loads(block.group(1)) + self.assertIn('float mask = clamp(field * 0.62', shaders['liquid']) + self.assertIn('float band = floor(uv.y * 15.0)', shaders['glitch']) def test_flags_export_without_a_display_and_need_a_presentation(self): self.write(DECK) self.hype(self.deck, '--pdf', 'flag.pdf') self.assertEqual((self.root / 'flag.pdf').read_bytes()[:5], b'%PDF-') + self.hype(self.deck, '--html', 'flag.html') + self.assertIn('data:image/webp;base64,', (self.root / 'flag.html').read_text()) self.assertIn('Name a Markdown presentation', self.hype('--pdf', 'none.pdf', code=1).stderr) + self.assertIn('Name a Markdown presentation', self.hype('--html', 'none.html', code=1).stderr) self.assertFalse((self.root / 'config/hype/hype.ini').exists()) def test_themes_and_help(self): diff --git a/tests/test_deck_navigation.py b/tests/test_deck_navigation.py new file mode 100644 index 0000000..8e17ba8 --- /dev/null +++ b/tests/test_deck_navigation.py @@ -0,0 +1,91 @@ +"""Drive the exported deck's navigation in a browser: a swipe moves one slide.""" +import html +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +CHROMIUM = shutil.which('chromium') or shutil.which('chromium-browser') or shutil.which('google-chrome') + +PAGE = """ + + + + deck navigation + + + +
+ + +
+
+ + + + + + +""" + + +def page(stylesheet, script): + return PAGE.replace('__STYLESHEET__', stylesheet).replace('__SCRIPT__', script) + + +@unittest.skipUnless(CHROMIUM, 'chromium is not installed') +class DeckNavigationTests(unittest.TestCase): + def test_swipe_and_tap_each_move_one_slide(self): + with tempfile.TemporaryDirectory() as directory: + document = Path(directory) / 'index.html' + document.write_text(page((ROOT / 'src/deck.css').as_uri(), (ROOT / 'src/deck.js').as_uri())) + result = subprocess.run([CHROMIUM, '--headless=new', '--disable-gpu', '--no-sandbox', + '--dump-dom', document.as_uri()], + capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stderr) + match = re.search(r'
(.*?)
', result.stdout, re.S) + self.assertIsNotNone(match, result.stdout + result.stderr) + report = html.unescape(match.group(1)) + self.assertNotIn('FAIL', report, report) + self.assertEqual(report.count('PASS'), 4, report) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_deck_render.py b/tests/test_deck_render.py new file mode 100644 index 0000000..0431c4b --- /dev/null +++ b/tests/test_deck_render.py @@ -0,0 +1,206 @@ +"""Render the exported deck's slides in a browser: fitted text stays inside the +slide, and lists render as lists. Both were broken when slides were fitted while +still display: none, which measures zero and lets every font size "fit".""" +import html +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +CHROMIUM = shutil.which('chromium') or shutil.which('chromium-browser') or shutil.which('google-chrome') + +PAGE = """ + + + + deck rendering + + + +
+ + +
+
+ + + + + + +""" + + +@unittest.skipUnless(CHROMIUM, 'chromium is not installed') +class DeckRenderTests(unittest.TestCase): + def test_fitted_text_and_lists_render(self): + with tempfile.TemporaryDirectory() as directory: + document = Path(directory) / 'index.html' + document.write_text(PAGE + .replace('__STYLESHEET__', (ROOT / 'src/deck.css').as_uri()) + .replace('__SCRIPT__', (ROOT / 'src/deck.js').as_uri())) + result = subprocess.run([CHROMIUM, '--headless=new', '--disable-gpu', '--no-sandbox', + '--virtual-time-budget=2000', '--dump-dom', document.as_uri()], + capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stderr) + match = re.search(r'
(.*?)
', result.stdout, re.S) + self.assertIsNotNone(match, result.stdout + result.stderr) + report = html.unescape(match.group(1)) + self.assertNotIn('FAIL', report, report) + # Every slide fits and is measured: one fit line per slide, plus the + # list, table, overlay, blur, line-break, code-backslash, and + # rendered-slide checks. + self.assertEqual(report.count('PASS'), 21, report) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_deck_svg.py b/tests/test_deck_svg.py new file mode 100644 index 0000000..f106f58 --- /dev/null +++ b/tests/test_deck_svg.py @@ -0,0 +1,105 @@ +"""Draw an exported deck's svg blocks in a browser: the drawing appears, but it +is an image rather than page markup, so a shared deck cannot run script or +restyle the page from inside a drawing.""" +import html +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +CHROMIUM = shutil.which('chromium') or shutil.which('chromium-browser') or shutil.which('google-chrome') + +PAGE = """ + + + + deck svg + + + +
+ + +
+
+ + + + + + +""" + + +@unittest.skipUnless(CHROMIUM, 'chromium is not installed') +class DeckSvgTests(unittest.TestCase): + def test_svg_blocks_render_as_images_not_markup(self): + with tempfile.TemporaryDirectory() as directory: + document = Path(directory) / 'index.html' + document.write_text(PAGE + .replace('__STYLESHEET__', (ROOT / 'src/deck.css').as_uri()) + .replace('__SCRIPT__', (ROOT / 'src/deck.js').as_uri())) + result = subprocess.run([CHROMIUM, '--headless=new', '--disable-gpu', '--no-sandbox', + '--virtual-time-budget=3000', '--dump-dom', document.as_uri()], + capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stderr) + match = re.search(r'
(.*?)
', result.stdout, re.S) + self.assertIsNotNone(match, result.stdout + result.stderr) + report = html.unescape(match.group(1)) + self.assertNotIn('FAIL', report, report) + self.assertEqual(report.count('PASS'), 6, report) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_deck_transitions.py b/tests/test_deck_transitions.py new file mode 100644 index 0000000..b69a7cc --- /dev/null +++ b/tests/test_deck_transitions.py @@ -0,0 +1,721 @@ +"""Drive an exported deck's transitions in a browser. + +The page's HypeDeck hook resolves a slide's transition (its own directive, then +the deck default, then none) and rasterizes any slide into a 1920 × 1080 canvas +for the WebGL overlay. The overlay itself needs a WebGL context; a headless +browser without one skips that check instead of failing the suite. +""" +import base64 +import html +import re +import shutil +import struct +import subprocess +import tempfile +import unittest +import zlib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +CHROMIUM = shutil.which('chromium') or shutil.which('chromium-browser') or shutil.which('google-chrome') + + +def png_data_uri(rgb): + """A 2 × 2 opaque picture of one color, as a data URI.""" + def chunk(kind, data): + return (struct.pack('>I', len(data)) + kind + data + + struct.pack('>I', zlib.crc32(kind + data) & 0xffffffff)) + raw = (b'\0' + bytes(rgb) * 2) * 2 + data = (b'\x89PNG\r\n\x1a\n' + + chunk(b'IHDR', struct.pack('>IIBBBBB', 2, 2, 8, 2, 0, 0, 0)) + + chunk(b'IDAT', zlib.compress(raw)) + + chunk(b'IEND', b'')) + return 'data:image/png;base64,' + base64.b64encode(data).decode() + + +# A folder-export deck: four Markdown slides, the last a spanning picture. +FOLDER_PAGE = """ + + + + deck transitions + + + +
+ + +
+
+ + + + + + + +""" + +# An unknown transition name and an oversized duration: the hook must report +# "none" and clamp the seconds to the presenter-friendly range. +CLAMP_PAGE = """ + + + + deck transition clamp + + + +
+ + +
+
+ + + + + + + +""" + +# A deck whose first slide is an animated picture. Leaving it must repaint the +# cached texture, because the picture has moved past the frame it was painted +# with; a slide of text keeps its cache. +MOVING_PAGE = """ + + + + deck moving media + + + +
+ + +
+
+ + + + + + + +""" + +# A baked deck (the one-file export): the slides are pictures already, so the +# transition engine reads them into WebGL textures. A null context is a skip. +BAKED_PAGE = """ + + + + deck transition overlay + + + +
+ + +
+
+
+
+ + + + + + + + +""" + + +# A deck longer than the texture cache's limit. Visiting every slide must leave +# only the last few textures behind: a transition needs two, and the rest would +# hold pixel memory for slides the viewer has left. +BOUNDED_PAGE = """ + + + + deck texture cache + + + +
+ + +
+
+ + + + + + + +""" + + +# A picture that arrives after the transition asked for it. The overlay must not +# upload an empty canvas: the transition waits for the repaint, or skips. +READINESS_PAGE = """ + + + + deck media readiness + + + +
+ + +
+
+ + + + + + + + +""" + + +@unittest.skipUnless(CHROMIUM, 'chromium is not installed') +class DeckTransitionTests(unittest.TestCase): + def render(self, page, files=None): + with tempfile.TemporaryDirectory() as directory: + for name, content in (files or {}).items(): + target = Path(directory) / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + document = Path(directory) / 'index.html' + document.write_text(page + .replace('__STYLESHEET__', (ROOT / 'src/deck.css').as_uri()) + .replace('__SCRIPT__', (ROOT / 'src/deck.js').as_uri())) + result = subprocess.run([CHROMIUM, '--headless=new', '--disable-gpu', '--no-sandbox', + '--virtual-time-budget=5000', '--dump-dom', document.as_uri()], + capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stderr) + match = re.search(r'
(.*?)
', result.stdout, re.S) + self.assertIsNotNone(match, result.stdout + result.stderr) + return html.unescape(match.group(1)) + + def test_resolver_and_rasterizer(self): + report = self.render(FOLDER_PAGE.replace('__RED__', png_data_uri((255, 0, 0)))) + self.assertNotIn('FAIL', report, report) + # Hook, six resolver checks, and the rasterizer's size, pixels, and fit. + self.assertGreaterEqual(report.count('PASS'), 14, report) + + def test_unknown_transition_and_duration_clamp(self): + report = self.render(CLAMP_PAGE) + self.assertNotIn('FAIL', report, report) + self.assertEqual(report.count('PASS'), 3, report) + + def test_overlay_runs_or_skips_without_webgl(self): + report = self.render(BAKED_PAGE + .replace('__RED__', png_data_uri((255, 0, 0))) + .replace('__BLUE__', png_data_uri((0, 0, 255)))) + self.assertNotIn('FAIL', report, report) + # The hook, resolver, and baked texture checks do not need WebGL. + self.assertGreaterEqual(report.count('PASS'), 6, report) + self.assertTrue('PASS transition drew frames' in report or 'SKIP webgl' in report + or 'SKIP engine webgl' in report, report) + + def test_moving_media_texture_repaints_at_transition(self): + animated = (ROOT / 'tests/fixtures/animated.gif').read_bytes() + report = self.render(MOVING_PAGE, {'images/anim.gif': animated}) + self.assertNotIn('FAIL', report, report) + # Hook, instrumentation, both textures, and the direct refresh checks. + self.assertGreaterEqual(report.count('PASS'), 7, report) + self.assertIn('PASS refresh repaints moving media', report) + self.assertTrue('PASS departing moving texture repainted' in report + or 'SKIP webgl' in report, report) + + def test_texture_cache_stays_bounded(self): + report = self.render(BOUNDED_PAGE) + self.assertNotIn('FAIL', report, report) + self.assertIn('PASS every slide rasterizes', report) + self.assertIn('PASS texture cache bounded', report) + self.assertIn('PASS cache smaller than the deck', report) + self.assertIn('PASS evicted slide repaints on demand', report) + self.assertIn('PASS repaint stays within the limit', report) + + def test_incomplete_media_waits_for_repaint(self): + page = (READINESS_PAGE + .replace('__RED__', png_data_uri((255, 0, 0))) + .replace('__BLUE__', png_data_uri((0, 0, 255)))) + report = self.render(page) + self.assertNotIn('FAIL', report, report) + self.assertIn('PASS undecoded slide not ready', report) + self.assertTrue('PASS outgoing slide held while preparing' in report + or 'SKIP webgl' in report, report) + self.assertIn('PASS new slide shown when the wait ends', report) + self.assertIn('PASS no upload without ready media', report) + self.assertIn('PASS no animation without ready media', report) + self.assertIn('PASS late picture becomes ready', report) + self.assertIn('PASS incoming slide not ready', report) + self.assertTrue('PASS second slide held while preparing' in report + or 'SKIP webgl' in report, report) + self.assertIn('PASS new slide shown when the transition starts', report) + self.assertTrue('PASS deferred transition drew frames' in report or 'SKIP webgl' in report, + report) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/tests.cpp b/tests/tests.cpp index ca7f6a2..f21fb3d 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -5,6 +5,7 @@ #include "renderer.h" #include "images.h" #include "syntax.h" +#include "transitions.h" #include "translator.h" #include #include @@ -1188,6 +1189,139 @@ static void write(const QString &path, const QString &content) { d.selectAt(parsed.slides[1].start); QCOMPARE(d.selected(), 1); } + void transitionRegistryIsShared() { + const QStringList names = transitionNames(); + QVERIFY(names.contains("none")); + for (const char *name : {"crossfade", "dissolve", "liquid", "glitch"}) { + QVERIFY2(names.contains(name), name); + const QString body = transitionBody(name); + QVERIFY2(!body.isEmpty(), name); + // The shared helpers ride in every body, and every body defines the + // contract both renderers call. + QVERIFY2(body.contains("float snoise(vec2"), name); + QVERIFY2(body.contains("vec4 transition(vec2 uv)"), name); + QVERIFY2(body.contains("texture2D(fromTex"), name); + QVERIFY2(body.contains("texture2D(toTex"), name); + + const QString shader = qtFragmentShader(name); + QVERIFY2(shader.contains("uniform sampler2D fromTex;"), name); + QVERIFY2(shader.contains("uniform sampler2D toTex;"), name); + QVERIFY2(shader.contains("uniform float progress;"), name); + QVERIFY2(shader.contains("varying vec2 qt_TexCoord0;"), name); + QVERIFY2(shader.contains("transition(qt_TexCoord0)"), name); + } + QVERIFY(transitionBody("none").isEmpty()); + QVERIFY(qtFragmentShader("none").isEmpty()); + QVERIFY(transitionBody("missing").isEmpty()); + + // The export gets every real body, keyed by name, and none for "none". + const QByteArray json = transitionsJson(); + QVERIFY(!json.contains("")); + QVERIFY(!deck.slide(0).contains("hype:")); + deck.undo(); + QVERIFY(deck.slideTransitionOverride().isEmpty()); + deck.redo(); + QCOMPARE(deck.slideTransitionOverride(), "glitch"); + deck.setSlideTransition(""); + QVERIFY(deck.slideTransitionOverride().isEmpty()); + QVERIFY(!deck.slide(1).contains("transition=")); + + QCOMPARE(deck.transitionShader("liquid"), qtFragmentShader("liquid")); + QVERIFY(deck.transitionShader("liquid").contains("vec4 transition(vec2 uv)")); + QVERIFY(deck.transitionShader("none").isEmpty()); + } + void slidePropertyWritesIntoDirectives() { + // An existing directive gains the attribute and keeps the others. + QCOMPARE(withSlideProperty("\n# Title\n", + "transition", "glitch"), + QString("\n# Title\n")); + // Replacing leaves one entry, not two. + QCOMPARE(withSlideProperty("\n", + "transition", "glitch"), + QString("\n")); + // Without a directive one is appended at the slide's end. + QCOMPARE(withSlideProperty("# Title\n\n", "transition", "glitch"), + QString("# Title\n\n\n")); + QCOMPARE(withSlideProperty("", "transition", "glitch"), + QString("")); + // Clearing removes the attribute; the directive goes when nothing is left. + QCOMPARE(withSlideProperty("\n", + "transition", ""), + QString("\n")); + QCOMPARE(withSlideProperty("\n# Title\n", + "transition", ""), + QString("# Title\n")); + QCOMPARE(withSlideProperty("# Title\n", + "transition", ""), + QString("# Title")); + // A directive in a code fence is code, not a property. + const QString fenced = "```html\n\n```\n# Title\n"; + QCOMPARE(withSlideProperty(fenced, "transition", ""), fenced); + QCOMPARE(withSlideProperty(fenced, "transition", "liquid"), + fenced + "\n"); + } + void slidePropertyReadsOutsideCode() { + // A directive in a fence is code, not a property. The reader agrees with + // the writer, so a slide's own choice is still the one that applies. + const QString fenced = "```html\n\n```\n# Title\n"; + QVERIFY(slideProperty(fenced, "transition").isEmpty()); + QVERIFY(slideProperty("``\n", "transition").isEmpty()); + // A real directive elsewhere in the slide still wins. + QCOMPARE(slideProperty(fenced + "\n", "transition"), + QString("liquid")); + + Deck deck; + deck.editSource("---\ntransition: crossfade\n---\n\n# One\n\n---\n\n" + fenced + + "\n---\n\n\n# Three\n"); + deck.select(1); + QVERIFY(deck.slideTransitionOverride().isEmpty()); + QCOMPARE(deck.slideTransition(), QString("crossfade")); + deck.select(2); + QCOMPARE(deck.slideTransitionOverride(), QString("none")); + } void newDeckTitleFollowsFileName() { QTemporaryDir tmp; Deck d; @@ -3326,6 +3460,7 @@ static void write(const QString &path, const QString &content) { write(output, "keep me"); QVERIFY(!d.exportPdf(output)); QVERIFY(!d.exportPptx(tmp.filePath("out.pptx"))); + QVERIFY(!d.exportHtml(tmp.filePath("out.html"))); QVERIFY(!d.renderImages(tmp.filePath("rendered"))); QSignalSpy finished(&d, &Deck::exportFinished); d.startExport("pdf", output); @@ -3346,6 +3481,194 @@ static void write(const QString &path, const QString &content) { QCOMPARE(pdf.load(tmp.filePath("complete.pdf")), QPdfDocument::Error::None); QCOMPARE(pdf.pageCount(), 3); } + void exportHtmlProducesASelfContainedDeck() { + QTemporaryDir tmp; + write(tmp.path() + "/talk.md", "---\ntitle: \"A idea\"\n---\n\n# One\n\n---\n\n# Two\n\n- a\n"); + Deck d; + QVERIFY(d.loadPath(tmp.path() + "/talk.md")); + QVERIFY(d.exportHtml(tmp.path() + "/talk.html")); + QFile file(tmp.path() + "/talk.html"); + QVERIFY(file.open(QIODevice::ReadOnly)); + const QString page = QString::fromUtf8(file.readAll()); + // Every slide inlined as WebP, named for a screen reader and search. + QCOMPARE(page.count("data:image/webp;base64,"), 2); + QCOMPARE(page.count("
"), 2); + QVERIFY(page.contains("A <big> idea")); + QVERIFY(page.contains("alt=\"Slide 1: One\"")); + QVERIFY(page.contains("alt=\"Slide 2: Two\"")); + // The Markdown rides inside the file as inert blocks: the editable source + // travels with the deck it produced. + QVERIFY(page.contains("\"\n---\n\n# One\n"); + Deck d; + QVERIFY(d.loadPath(tmp.path() + "/talk.md")); + QVERIFY(d.exportHtml(tmp.path() + "/talk.html")); + QFile file(tmp.path() + "/talk.html"); + QVERIFY(file.open(QIODevice::ReadOnly)); + const QString page = QString::fromUtf8(file.readAll()); + // The font reaches the page through the palette JSON, so that copy needs the + // same protection as the Markdown block: a closing script tag in the header + // must not close the block early. + const QString open = "", start); + QVERIFY(end > start); + const QString json = page.mid(start + open.size(), end - start - open.size()); + QVERIFY(!json.contains("")); + } + void exportHtmlAltTextLeavesSpeakerNotesOut() { + QTemporaryDir tmp; + write(tmp.path() + "/talk.md", + "---\ntitle: Notes\n---\n\n\n\n" + "\n\nVisible line\n"); + Deck d; + QVERIFY(d.loadPath(tmp.path() + "/talk.md")); + QVERIFY(d.exportHtml(tmp.path() + "/talk.html")); + QFile file(tmp.path() + "/talk.html"); + QVERIFY(file.open(QIODevice::ReadOnly)); + const QString page = QString::fromUtf8(file.readAll()); + // The alt text names the visible slide for anyone who receives the file, so a hidden + // speaker note on a slide without a headline never becomes part of it. The editable + // Markdown rides along too, with the same rule: notes stay out, directives stay in. + QVERIFY(page.contains("alt=\"Slide 1: Visible line\"")); + QVERIFY(page.contains("Visible line")); + QVERIFY(page.contains("hype: background")); + QVERIFY(!page.contains("Private speaker note")); + } + void htmlTitleIsNotASlot() { + QTemporaryDir tmp; + write(tmp.path() + "/talk.md", "---\ntitle: \"{{SCRIPT}}\"\n---\n\n# One\n"); + Deck d; + QVERIFY(d.loadPath(tmp.path() + "/talk.md")); + QVERIFY(d.exportHtml(tmp.path() + "/talk.html")); + QFile file(tmp.path() + "/talk.html"); + QVERIFY(file.open(QIODevice::ReadOnly)); + const QString page = QString::fromUtf8(file.readAll()); + // A title that reads like a slot stays the title: filled slots are never rescanned, + // so the script does not land in the tab. + QVERIFY(page.contains("{{SCRIPT}}")); + QVERIFY(page.contains("\n```\n"); + write(tmp.path() + "/images/city.jpg", "city"); + Deck d; + QVERIFY(d.loadPath(tmp.path() + "/talk.md")); + const QString folder = tmp.path() + "/deck-html"; + QVERIFY(d.exportHtmlFolder(folder)); + // The editable shape: the Markdown rides inside the page, which renders it, + // beside the stylesheet, the script, and the deck's real media. + QVERIFY(QFile::exists(folder + "/index.html")); + QVERIFY(QFile::exists(folder + "/deck.css")); + QVERIFY(QFile::exists(folder + "/deck.js")); + QVERIFY(QFile::exists(folder + "/images/city.jpg")); + QCOMPARE(QDir(folder + "/slides").exists(), false); // Slides render, not bake. + QFile city(folder + "/images/city.jpg"); + QVERIFY(city.open(QIODevice::ReadOnly)); + QCOMPARE(city.readAll(), QByteArray("city")); + QFile file(folder + "/index.html"); + QVERIFY(file.open(QIODevice::ReadOnly)); + const QString page = QString::fromUtf8(file.readAll()); + QVERIFY(page.contains("A <big> idea")); + QVERIFY(page.contains("")); + QVERIFY(page.contains("")); + QVERIFY(page.contains("