diff --git a/.forgejo/workflows/dev-release.yml b/.forgejo/workflows/dev-release.yml index 4398649..2ffbe57 100644 --- a/.forgejo/workflows/dev-release.yml +++ b/.forgejo/workflows/dev-release.yml @@ -56,6 +56,7 @@ jobs: sha256sum "${PKG_DIR}/breadpaper-x86_64" | awk '{print $1}' \ > "${PKG_DIR}/breadpaper-x86_64.sha256" cp src/LICENSE "${PKG_DIR}/" + cp src/packaging/breadpaper.desktop "${PKG_DIR}/" cp src/bakery.toml "${PKG_DIR}/bakery.toml" ln -sfn "${VERSION}" "/srv/breadway-dl/dev/breadpaper/latest" diff --git a/.forgejo/workflows/rc-release.yml b/.forgejo/workflows/rc-release.yml index 3c1646b..6a588e1 100644 --- a/.forgejo/workflows/rc-release.yml +++ b/.forgejo/workflows/rc-release.yml @@ -37,6 +37,7 @@ jobs: sha256sum "${PKG_DIR}/breadpaper-x86_64" | awk '{print $1}' \ > "${PKG_DIR}/breadpaper-x86_64.sha256" cp src/LICENSE "${PKG_DIR}/" + cp src/packaging/breadpaper.desktop "${PKG_DIR}/" cp src/bakery.toml "${PKG_DIR}/bakery.toml" ln -sfn "${VERSION}" "/srv/breadway-dl/beta/breadpaper/latest" diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index 96877ef..0d5451e 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -4,52 +4,57 @@ on: push: tags: ["v*"] -env: - DL_DIR: /srv/breadway-dl - ECOSYSTEM_DIR: /tmp/bread-ecosystem-ci - PATH: /home/breadway/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin - jobs: build: if: ${{ !contains(github.ref_name, '-rc.') }} - runs-on: hestia - defaults: - run: - working-directory: /tmp/breadpaper-build - + runs-on: [self-hosted, hestia] steps: - name: checkout - working-directory: /tmp run: | - rm -rf /tmp/breadpaper-build + set -euo pipefail + rm -rf src && mkdir src git clone --branch "${GITHUB_REF_NAME}" --depth 1 \ - "https://git.breadway.dev/${GITHUB_REPOSITORY}.git" /tmp/breadpaper-build + "https://git.breadway.dev/${GITHUB_REPOSITORY}.git" src - name: build - run: bash ci/build.sh cargo build --release --locked + run: | + set -euo pipefail + if [ ! -f src/ci/build.sh ]; then + echo "::error::ci/build.sh is missing — bakery release builds must go through the shared CI wrapper" + exit 1 + fi + cd src && bash ci/build.sh cargo build --release --locked || { + echo "::error::cargo build --release --locked failed. If Cargo.lock drifted, update and commit it; do not drop --locked." + exit 1 + } - name: test - run: bash ci/build.sh cargo test --release --locked + run: cd src && bash ci/build.sh cargo test --release --locked - name: prepare artifacts run: | + set -euo pipefail VERSION="${GITHUB_REF_NAME#v}" - PKG_DIR="${DL_DIR}/breadpaper/${VERSION}" + PKG_DIR="/srv/breadway-dl/breadpaper/${VERSION}" mkdir -p "${PKG_DIR}" - cp target/release/breadpaper "${PKG_DIR}/breadpaper-x86_64" + cp src/target/release/breadpaper "${PKG_DIR}/breadpaper-x86_64" strip "${PKG_DIR}/breadpaper-x86_64" sha256sum "${PKG_DIR}/breadpaper-x86_64" | awk '{print $1}' \ > "${PKG_DIR}/breadpaper-x86_64.sha256" - cp LICENSE "${PKG_DIR}/" - cp bakery.toml "${PKG_DIR}/bakery.toml" - ln -sfn "${VERSION}" "${DL_DIR}/breadpaper/latest" - - - name: ensure bread-ecosystem - working-directory: /tmp - run: | - rm -rf "${ECOSYSTEM_DIR}" - git clone https://github.com/Breadway/bread-ecosystem.git "${ECOSYSTEM_DIR}" + cp src/LICENSE "${PKG_DIR}/" + cp src/packaging/breadpaper.desktop "${PKG_DIR}/" + cp src/bakery.toml "${PKG_DIR}/bakery.toml" + ln -sfn "${VERSION}" "/srv/breadway-dl/breadpaper/latest" - name: regenerate index.json - working-directory: /tmp - run: bash "${ECOSYSTEM_DIR}/scripts/gen-index.sh" + env: + MINISIGN_SEC_KEY: ${{ secrets.BAKERY_MINISIGN_SEC_KEY_PATH }} + run: | + set -euo pipefail + if [ -z "${MINISIGN_SEC_KEY:-}" ]; then + echo "::error::BAKERY_MINISIGN_SEC_KEY_PATH secret not set — refusing to regenerate index.json unsigned (would leave a stale signature mismatched against fresh content and break bakery for everyone)" + exit 1 + fi + rm -rf /tmp/bread-ecosystem-ci + git clone https://git.breadway.dev/Breadway/bread-ecosystem.git /tmp/bread-ecosystem-ci + bash /tmp/bread-ecosystem-ci/scripts/gen-index.sh diff --git a/Cargo.lock b/Cargo.lock index 837cd66..cf5aeb6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -58,6 +58,18 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + [[package]] name = "bread-shared" version = "0.7.0" @@ -66,7 +78,18 @@ dependencies = [ "dirs", "serde", "serde_json", - "toml", + "toml 0.8.23", +] + +[[package]] +name = "bread-theme" +version = "0.7.4" +source = "git+https://git.breadway.dev/Breadway/bread-ecosystem?tag=v0.7.4#fcba3760387e2523edb71350f8efea3bc851b21e" +dependencies = [ + "dirs", + "gtk4", + "serde", + "serde_json", ] [[package]] @@ -82,12 +105,49 @@ dependencies = [ [[package]] name = "breadpaper" -version = "0.1.12" +version = "0.1.14" dependencies = [ "anyhow", + "bread-theme", "bread-utils", "clap", + "gtk4", + "serde", "serde_json", + "toml 0.8.23", +] + +[[package]] +name = "cairo-rs" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc8d9aa793480744cd9a0524fef1a2e197d9eaa0f739cde19d16aba530dcb95" +dependencies = [ + "bitflags", + "cairo-sys-rs", + "glib", + "libc", +] + +[[package]] +name = "cairo-sys-rs" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8b4985713047f5faee02b8db6a6ef32bbb50269ff53c1aee716d1d195b76d54" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "cfg-expr" +version = "0.20.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb693542bcafa528e198be0ebd9d3632ca5b7c93dbe7237460e199910835997c" +dependencies = [ + "smallvec", + "target-lexicon", ] [[package]] @@ -169,6 +229,135 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gdk-pixbuf" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25f420376dbee041b2db374ce4573892a36222bb3f6c0c43e24f0d67eae9b646" +dependencies = [ + "gdk-pixbuf-sys", + "gio", + "glib", + "libc", +] + +[[package]] +name = "gdk-pixbuf-sys" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48f31b37b1fc4b48b54f6b91b7ef04c18e00b4585d98359dd7b998774bbd91fb" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gdk4" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d81e2a6c6ecba2aab60633a98df1868b03fa0bfdce8105edc27c1bccf71f0e39" +dependencies = [ + "cairo-rs", + "gdk-pixbuf", + "gdk4-sys", + "gio", + "glib", + "libc", + "pango", +] + +[[package]] +name = "gdk4-sys" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d8f608d8d7d229975c4d0d026f5d3071598c4ddab3c5262b0a31840fec78d13" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "pkg-config", + "system-deps", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -180,6 +369,194 @@ dependencies = [ "wasi", ] +[[package]] +name = "gio" +version = "0.22.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b3e1f669909c326b9413bde5a742097b8c90a7d78f45326db13668984769ded" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "gio-sys", + "glib", + "libc", + "pin-project-lite", + "smallvec", +] + +[[package]] +name = "gio-sys" +version = "0.22.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353fdc7da7cd16da916104b1e0e4e7de380ec9c8aaa20d4d742d66310ab4b0d5" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "windows-sys 0.61.2", +] + +[[package]] +name = "glib" +version = "0.22.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddbcf514bd1881fc1b960e4e52b4e82873f4da3bceddbd58d42827b508888100" +dependencies = [ + "bitflags", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "smallvec", +] + +[[package]] +name = "glib-macros" +version = "0.22.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "506d23499707c7142898429757e8d9a3871d965239a2cb66dfa05052be6d6f19" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "glib-sys" +version = "0.22.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "030967459f9f676851872c6304adea7825c6d462ec9b72554c733cf0c5952233" +dependencies = [ + "libc", + "system-deps", +] + +[[package]] +name = "gobject-sys" +version = "0.22.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22a861859b887a79cf461359c192c97a57d8fb0229dd291232e57aa11f6fa72c" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "graphene-rs" +version = "0.22.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb856b9c558971c3f13ab692358926da710b046932a4e087aedcc35b040d7dff" +dependencies = [ + "glib", + "graphene-sys", +] + +[[package]] +name = "graphene-sys" +version = "0.22.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7ffdfde88f3570d3705e0d8a2433e036d387a1f2930bbf47eafcb5f569fd04" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gsk4" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b867be1c5f14dcb8f552c0eff6e9a9b1da5f8b43943e8efc3a63c889d84952ff" +dependencies = [ + "cairo-rs", + "gdk4", + "glib", + "graphene-rs", + "gsk4-sys", + "libc", + "pango", +] + +[[package]] +name = "gsk4-sys" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b7c7eb2e681ee896646cfb8872b431f24d09f53ba9283289d9b10caa6707088" +dependencies = [ + "cairo-sys-rs", + "gdk4-sys", + "glib-sys", + "gobject-sys", + "graphene-sys", + "libc", + "pango-sys", + "system-deps", +] + +[[package]] +name = "gtk4" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98a0a0466484f64b07b5b8184d43fa46be78eb0b8e04ae4e179af31d770b76d9" +dependencies = [ + "cairo-rs", + "field-offset", + "futures-channel", + "gdk-pixbuf", + "gdk4", + "gio", + "glib", + "graphene-rs", + "gsk4", + "gtk4-macros", + "gtk4-sys", + "libc", + "pango", +] + +[[package]] +name = "gtk4-macros" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ac7179400a36a04de039c24206bb841c5596992b907b43b23ee8d5bdc40d00e" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "gtk4-sys" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82b8f954786af0b1984425c4446b77f5ff6594346181316be3f850caab1c6f01" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk4-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "graphene-sys", + "gsk4-sys", + "libc", + "pango-sys", + "system-deps", +] + [[package]] name = "hashbrown" version = "0.17.1" @@ -235,6 +612,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "once_cell_polyfill" version = "1.70.2" @@ -247,6 +633,50 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "pango" +version = "0.22.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d800d8d0de2ad5d0fb046f5344dbaba14a003cf3dd27cc21d85893d35ea316c" +dependencies = [ + "gio", + "glib", + "pango-sys", +] + +[[package]] +name = "pango-sys" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd111a20ca90fedf03e09c59783c679c00900f1d8491cca5399f5e33609d5d6" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.13+spec-1.1.0", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -276,6 +706,21 @@ dependencies = [ "thiserror", ] +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -328,6 +773,27 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + [[package]] name = "strsim" version = "0.11.1" @@ -356,6 +822,25 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "system-deps" +version = "7.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +dependencies = [ + "cfg-expr", + "heck", + "pkg-config", + "toml 1.1.4+spec-1.1.0", + "version-compare", +] + +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "thiserror" version = "1.0.69" @@ -383,9 +868,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" dependencies = [ "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + +[[package]] +name = "toml" +version = "1.1.4+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aace63f4bbcdfc2c965b059de67119c89c4017a70d633be6c104910f67056f5" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned 1.1.1", + "toml_datetime 1.1.1+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.4", ] [[package]] @@ -397,6 +897,15 @@ dependencies = [ "serde", ] +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + [[package]] name = "toml_edit" version = "0.22.27" @@ -405,10 +914,31 @@ checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ "indexmap", "serde", - "serde_spanned", - "toml_datetime", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", "toml_write", - "winnow", + "winnow 0.7.15", +] + +[[package]] +name = "toml_edit" +version = "0.25.13+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b" +dependencies = [ + "indexmap", + "toml_datetime 1.1.1+spec-1.1.0", + "toml_parser", + "winnow 1.0.4", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow 1.0.4", ] [[package]] @@ -417,6 +947,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -429,6 +965,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -525,6 +1067,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 1efe23d..b2bea93 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "breadpaper" -version = "0.1.12" +version = "0.1.14" edition = "2024" description = "Wallpaper manager for the bread desktop" license = "MIT" @@ -8,5 +8,9 @@ license = "MIT" [dependencies] clap = { version = "4", features = ["derive"] } anyhow = "1" +serde = { version = "1", features = ["derive"] } serde_json = "1" +toml = "0.8" +gtk4 = { version = "0.11", features = ["v4_12"] } +bread-theme = { git = "https://git.breadway.dev/Breadway/bread-ecosystem", tag = "v0.7.4", features = ["gtk"] } bread-utils = { git = "https://git.breadway.dev/Breadway/bread-ecosystem", tag = "v0.7.2", features = ["bread-client"] } diff --git a/EVENTS.md b/EVENTS.md index b4cd0f1..37260ba 100644 --- a/EVENTS.md +++ b/EVENTS.md @@ -4,7 +4,7 @@ breadpaper is a wallpaper setter: it works exactly the same with or without `breadd` running. When breadd *is* present, a successful `breadpaper set` (or the bare-path shorthand) publishes `bread.paper.changed` into the shared bread automation fabric, and `breadpaper listen` honors -`bread.command.paper.set`. See the parent `bread` repo's +`bread.command.paper.set` and `bread.command.paper.library`. See the parent `bread` repo's `Documentation.md` — specifically its "Namespaces" and "Integrating a bread\* app" sections — for the general convention this follows. @@ -15,9 +15,10 @@ long-running `listen` subcommand holds a `subscribe` open. `breadpaper listen` is fail-silent if breadd is down: `subscribe` reconnects with backoff and simply delivers nothing until the daemon -comes back. The one-shot `set`/`get` path does not require `listen`. -Modules that want to change the wallpaper without a listener can still -shell out: +comes back. It also honors `bread.monitor.connected` by re-applying +`~/.config/breadpaper/current.json`. The one-shot `set`/`get`/`library` +/`apply` path does not require `listen`. Modules that want to change +the wallpaper without a listener can still shell out: ```lua bread.exec("breadpaper set /path/to/image.png") @@ -35,9 +36,11 @@ bread.wait("bread.paper.set.done", { timeout = 10000 }) | Event | Data | When | |-------|------|------| -| `bread.paper.changed` | `{ "path": "" }` | After a successful `set` (awww + wal + `bread-theme reload`), including when `listen` honors `bread.command.paper.set`. `path` is the canonical absolute path that was applied. Not emitted on `get`, and not emitted if any of the three steps fail. | -| `bread.paper.set.done` | `{ "path": "" }` | `bread.command.paper.set` was received and `set()` succeeded. `path` is the canonical absolute path that was applied. Not emitted by the one-shot CLI `set` — that path only publishes `changed`. | -| `bread.paper.set.failed` | `{ "error": "", "path"?: "" }` | `bread.command.paper.set` was received but `set()` failed, or `data.path` was missing/not a string. `path` is the requested (not canonical) path when one was supplied. | +| `bread.paper.changed` | `{ "path": "", "output"?: "" }` | After a successful `set` / `set --output` (awww + palette + theme write), including when `listen` honors `bread.command.paper.set` or restores `current.json` after `bread.monitor.connected`. `path` is the canonical absolute path that was applied. `output` is the compositor output name when only one monitor was targeted; omit (or `null`) means every output. Not emitted on `get`, and not emitted if the set fails. | +| `bread.paper.set.done` | `{ "path": "", "output"?: "" }` | `bread.command.paper.set` was received and `set()` / `set_on()` succeeded. `path` is the canonical absolute path that was applied. `output` is present when the command targeted one monitor. Not emitted by the one-shot CLI `set` — that path only publishes `changed`. | +| `bread.paper.set.failed` | `{ "error": "", "path"?: "", "output"?: "" }` | `bread.command.paper.set` was received but `set()` / `set_on()` failed, or `data.path` was missing/not a string. `path` is the requested (not canonical) path when one was supplied. `output` is echoed when the command included one. | +| `bread.paper.library.done` | `{}` | `bread.command.paper.library` was received and a `breadpaper library` process was started. Not emitted by the one-shot CLI `library` / `browse`. | +| `bread.paper.library.failed` | `{ "error": "" }` | `bread.command.paper.library` was received but the library process could not be spawned. | ## Commands honored (`bread.command.paper.*`) @@ -47,14 +50,14 @@ Honored only while `breadpaper listen` is running. A | Verb | Data | Effect | |------|------|--------| -| `set` | `{ "path": "..." }` | Calls the existing `set()` (awww + wal + `bread-theme reload`). Emits `bread.paper.set.done` / `.failed`. A successful set also emits `bread.paper.changed`. | +| `set` | `{ "path": "...", "output"?: "..." }` | Missing `output` calls `set()` (all live outputs, global `wal -i`, `bread-theme reload`). A string `output` calls `set_on()` (that monitor only; no global wal unless it is the focused Hyprland monitor). Emits `bread.paper.set.done` / `.failed`. A successful set also emits `bread.paper.changed`. | +| `library` | `{}` | Spawns `breadpaper library` (GTK picker). Emits `bread.paper.library.done` once the process is started, or `bread.paper.library.failed` if the spawn fails. Clicking a thumbnail in that window applies to the picker's output and publishes `bread.paper.changed`. | -### Not implemented: slideshow / library / random / next +### Not implemented: slideshow / random / next -breadpaper is not a wallpaper library, a slideshow daemon, or a picker. -Browsing `~/Pictures/Backgrounds` lives in bos-settings. Do not invent +`breadpaper library` / `browse` is the in-app picker. Do not invent `bread.command.paper.next` / `.random` / `.cycle` (or matching events) -ahead of a real product feature. Unrecognized verbs are ignored. +ahead of a real slideshow feature. Unrecognized verbs are ignored. ## Fail-safe behavior diff --git a/README.md b/README.md index d0ae2de..f49b156 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,13 @@ Wallpaper setter for the bread desktop. One command sets the wallpaper via [awww](https://github.com/heywoodlh/awww), generates a palette with [pywal](https://github.com/dylanaraps/pywal) (`wal`), and runs -`bread-theme reload`. +`bread-theme reload`. Two monitors can keep different wallpapers (and +per-output bread-theme files); the last path per output is stored in +`~/.config/breadpaper/current.json`. -It is not a wallpaper library, a slideshow daemon, or a GUI. Browsing -`~/Pictures/Backgrounds` and picking an image lives in -[bos-settings](https://git.breadway.dev/Breadway/bos-settings). +`set` / `get` / `apply` stay one-shot CLI. `breadpaper library` (alias +`browse`) opens a GTK picker over the wallpaper directories. It is not +a slideshow daemon. ## Dependencies @@ -17,7 +19,10 @@ Must be on `$PATH` for `set`: - `wal` — palette generation (`python-pywal`) - `bread-theme` — theme reload (bakery package, not `breadd`) -`get` only reads the path pywal stored at `~/.cache/wal/wal`. +`library` also needs GTK4 (the window loads `bread-theme`'s shared +stylesheet and follows the monitor it sits on). `get` without +`--output` still reads the path pywal stored at `~/.cache/wal/wal`. +`get --output NAME` reads `~/.config/breadpaper/current.json`. ## Install @@ -35,21 +40,49 @@ install -Dm755 target/release/breadpaper ~/.local/bin/breadpaper ## Usage ``` -breadpaper # shorthand for `set` -breadpaper set # awww + wal + bread-theme reload -breadpaper get # print the current wallpaper path -breadpaper listen # honor bread.command.paper.set (fail-silent if breadd is down) +breadpaper # shorthand for `set` (all outputs) +breadpaper --output NAME # one output +breadpaper set # awww + wal + bread-theme reload (all) +breadpaper set --output NAME +breadpaper get # print ~/.cache/wal/wal +breadpaper get --output NAME # path from current.json +breadpaper apply # restore current.json +breadpaper library # GTK picker (alias: browse) +breadpaper library --dir PATH # also scan PATH (repeatable) +breadpaper listen # honor bread.command.paper.set / .library ``` Supported formats: `png`, `jpg`, `jpeg`, `webp`, `gif`, `bmp`. +## Library + +`breadpaper library` scans these directories (missing ones are skipped): + +1. `~/Pictures/Wallpapers` +2. `/usr/share/backgrounds/bos` + +Override the list in `~/.config/breadpaper/config.toml`: + +```toml +library_dirs = [ + "~/Pictures/Wallpapers", + "/usr/share/backgrounds/bos", +] +``` + +`BREADPAPER_LIBRARY_DIRS` (colon-separated) overrides the file. `--dir` +appends extra roots for that invocation. Clicking a thumbnail applies +to the monitor the picker is on (`set --output`); if the output cannot +be resolved it falls back to all outputs. + ## Bread events After a successful `set`, breadpaper emits `bread.paper.changed` if `breadd` is running (silent no-op if it isn't). `breadpaper listen` is -the optional long-running subscriber for `bread.command.paper.set`; it -does not start by itself. Lua modules can still -`bread.exec("breadpaper set …")`. See [EVENTS.md](EVENTS.md). +the optional long-running subscriber for `bread.command.paper.set` and +`bread.command.paper.library`; it does not start by itself. Lua modules +can still `bread.exec("breadpaper set …")` or +`bread.exec("breadpaper library")`. See [EVENTS.md](EVENTS.md). ## License diff --git a/bakery.toml b/bakery.toml index c946a46..d003e38 100644 --- a/bakery.toml +++ b/bakery.toml @@ -1,10 +1,11 @@ name = "breadpaper" description = "Wallpaper manager for the bread desktop — sets awww wallpaper, generates pywal palette, reloads bread themes" binaries = ["breadpaper"] -system_deps = ["awww", "python-pywal"] +system_deps = ["awww", "python-pywal", "gtk4"] optional_system_deps = [] bread_deps = ["bread-theme"] license_file = "LICENSE" +desktop_file = "breadpaper.desktop" [install] post_install = [] diff --git a/config.example.toml b/config.example.toml new file mode 100644 index 0000000..a447d7c --- /dev/null +++ b/config.example.toml @@ -0,0 +1,6 @@ +# ~/.config/breadpaper/config.toml +# Missing directories are skipped. An empty list uses the built-in defaults. +library_dirs = [ + "~/Pictures/Wallpapers", + "/usr/share/backgrounds/bos", +] diff --git a/packaging/breadpaper.desktop b/packaging/breadpaper.desktop new file mode 100644 index 0000000..86ccccd --- /dev/null +++ b/packaging/breadpaper.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Name=Wallpapers +Comment=Browse and apply wallpapers on the Bread desktop +Exec=breadpaper library +Icon=preferences-desktop-wallpaper +Terminal=false +Type=Application +Categories=Settings;DesktopSettings; +StartupWMClass=com.breadway.breadpaper diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..b89bd08 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,252 @@ +use std::path::{Path, PathBuf}; + +use serde::Deserialize; + +/// User library directory used when no config file is present. +pub const DEFAULT_USER_LIBRARY: &str = "Pictures/Wallpapers"; + +/// Packaged BOS backgrounds, scanned when the directory exists. +pub const DEFAULT_SYSTEM_LIBRARY: &str = "/usr/share/backgrounds/bos"; + +/// Colon-separated override of [`Config::library_dirs`]. Empty means "use +/// the config file / defaults". +pub const LIBRARY_DIRS_ENV: &str = "BREADPAPER_LIBRARY_DIRS"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Config { + pub library_dirs: Vec, +} + +#[derive(Debug, Default, Deserialize)] +struct ConfigFile { + #[serde(default)] + library_dirs: Vec, +} + +impl Default for Config { + fn default() -> Self { + Self { + library_dirs: default_library_dirs(), + } + } +} + +impl Config { + pub fn path() -> PathBuf { + bread_utils::xdg::config_dir("breadpaper").join("config.toml") + } + + pub fn load() -> Self { + Self::load_from(&Self::path()) + } + + pub fn load_from(path: &Path) -> Self { + let mut cfg = match std::fs::read_to_string(path) { + Ok(text) => match toml::from_str::(&text) { + Ok(parsed) if !parsed.library_dirs.is_empty() => Self { + library_dirs: parsed.library_dirs, + }, + Ok(_) => Self::default(), + Err(e) => { + eprintln!( + "breadpaper: {} failed to parse ({e}); using defaults", + path.display() + ); + Self::default() + } + }, + Err(_) => Self::default(), + }; + + if let Some(dirs) = env_library_dirs() { + cfg.library_dirs = dirs; + } + + cfg.library_dirs = cfg + .library_dirs + .into_iter() + .map(expand_tilde) + .filter(|p| !p.as_os_str().is_empty()) + .collect(); + cfg + } + + pub fn with_extra_dirs(mut self, extra: impl IntoIterator) -> Self { + self.library_dirs + .extend(extra.into_iter().map(expand_tilde)); + self + } +} + +pub fn default_library_dirs() -> Vec { + vec![ + bread_utils::xdg::home_dir().join(DEFAULT_USER_LIBRARY), + PathBuf::from(DEFAULT_SYSTEM_LIBRARY), + ] +} + +pub fn expand_tilde(path: PathBuf) -> PathBuf { + let Some(s) = path.to_str() else { + return path; + }; + if s == "~" { + return bread_utils::xdg::home_dir(); + } + if let Some(rest) = s.strip_prefix("~/") { + return bread_utils::xdg::home_dir().join(rest); + } + path +} + +fn env_library_dirs() -> Option> { + let raw = std::env::var(LIBRARY_DIRS_ENV).ok()?; + if raw.is_empty() { + return None; + } + let dirs: Vec = raw + .split(':') + .filter(|s| !s.is_empty()) + .map(PathBuf::from) + .collect(); + if dirs.is_empty() { None } else { Some(dirs) } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Mutex, OnceLock}; + + fn env_lock() -> std::sync::MutexGuard<'static, ()> { + static LOCK: OnceLock> = OnceLock::new(); + LOCK.get_or_init(|| Mutex::new(())) + .lock() + .unwrap_or_else(|e| e.into_inner()) + } + + fn tmp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "breadpaper-config-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn default_dirs_are_pictures_wallpapers_and_bos_backgrounds() { + let dirs = Config::default().library_dirs; + assert!( + dirs.iter().any(|d| d.ends_with(DEFAULT_USER_LIBRARY)), + "missing ~/{DEFAULT_USER_LIBRARY} in {dirs:?}" + ); + assert!( + dirs.iter().any(|d| d == Path::new(DEFAULT_SYSTEM_LIBRARY)), + "missing {DEFAULT_SYSTEM_LIBRARY} in {dirs:?}" + ); + } + + #[test] + fn expand_tilde_prefix() { + let home = bread_utils::xdg::home_dir(); + assert_eq!( + expand_tilde(PathBuf::from("~/Pictures/Wallpapers")), + home.join("Pictures/Wallpapers") + ); + assert_eq!(expand_tilde(PathBuf::from("~")), home); + let abs = PathBuf::from("/usr/share/backgrounds/bos"); + assert_eq!(expand_tilde(abs.clone()), abs); + } + + #[test] + fn load_from_missing_file_uses_defaults() { + let _lock = env_lock(); + let prev = std::env::var_os(LIBRARY_DIRS_ENV); + unsafe { std::env::remove_var(LIBRARY_DIRS_ENV) }; + let cfg = Config::load_from(&PathBuf::from("/no/such/breadpaper-config.toml")); + if let Some(v) = prev { + unsafe { std::env::set_var(LIBRARY_DIRS_ENV, v) }; + } + assert_eq!(cfg.library_dirs, default_library_dirs()); + } + + #[test] + fn load_from_parses_library_dirs_and_expands_tilde() { + let _lock = env_lock(); + let prev = std::env::var_os(LIBRARY_DIRS_ENV); + unsafe { std::env::remove_var(LIBRARY_DIRS_ENV) }; + + let dir = tmp_dir("parse"); + let path = dir.join("config.toml"); + std::fs::write( + &path, + "library_dirs = [\"~/custom/walls\", \"/opt/walls\"]\n", + ) + .unwrap(); + let cfg = Config::load_from(&path); + if let Some(v) = prev { + unsafe { std::env::set_var(LIBRARY_DIRS_ENV, v) }; + } + let _ = std::fs::remove_dir_all(&dir); + assert_eq!( + cfg.library_dirs, + vec![ + bread_utils::xdg::home_dir().join("custom/walls"), + PathBuf::from("/opt/walls"), + ] + ); + } + + #[test] + fn empty_library_dirs_key_falls_back_to_defaults() { + let _lock = env_lock(); + let prev = std::env::var_os(LIBRARY_DIRS_ENV); + unsafe { std::env::remove_var(LIBRARY_DIRS_ENV) }; + + let dir = tmp_dir("empty"); + let path = dir.join("config.toml"); + std::fs::write(&path, "library_dirs = []\n").unwrap(); + let cfg = Config::load_from(&path); + if let Some(v) = prev { + unsafe { std::env::set_var(LIBRARY_DIRS_ENV, v) }; + } + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(cfg.library_dirs, default_library_dirs()); + } + + #[test] + fn env_overrides_config_file() { + let _lock = env_lock(); + let prev = std::env::var_os(LIBRARY_DIRS_ENV); + unsafe { std::env::set_var(LIBRARY_DIRS_ENV, "/tmp/a:/tmp/b") }; + + let dir = tmp_dir("env"); + let path = dir.join("config.toml"); + std::fs::write(&path, "library_dirs = [\"/from/file\"]\n").unwrap(); + let cfg = Config::load_from(&path); + match prev { + Some(v) => unsafe { std::env::set_var(LIBRARY_DIRS_ENV, v) }, + None => unsafe { std::env::remove_var(LIBRARY_DIRS_ENV) }, + } + let _ = std::fs::remove_dir_all(&dir); + assert_eq!( + cfg.library_dirs, + vec![PathBuf::from("/tmp/a"), PathBuf::from("/tmp/b")] + ); + } + + #[test] + fn with_extra_dirs_appends() { + let cfg = Config { + library_dirs: vec![PathBuf::from("/a")], + } + .with_extra_dirs([PathBuf::from("/b")]); + assert_eq!( + cfg.library_dirs, + vec![PathBuf::from("/a"), PathBuf::from("/b")] + ); + } +} diff --git a/src/current.rs b/src/current.rs new file mode 100644 index 0000000..f39d680 --- /dev/null +++ b/src/current.rs @@ -0,0 +1,126 @@ +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; + +/// Persisted wallpaper path per output (`~/.config/breadpaper/current.json`). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Current { + #[serde(default)] + outputs: BTreeMap, +} + +impl Current { + pub fn path() -> PathBuf { + bread_utils::xdg::config_dir("breadpaper").join("current.json") + } + + pub fn load() -> Self { + Self::load_from(&Self::path()) + } + + /// Missing or unreadable file => empty map. + pub fn load_from(path: &Path) -> Self { + let Ok(text) = std::fs::read_to_string(path) else { + return Self::default(); + }; + serde_json::from_str(&text).unwrap_or_default() + } + + pub fn save(&self) -> Result<()> { + self.save_to(&Self::path()) + } + + pub fn save_to(&self, path: &Path) -> Result<()> { + let text = serde_json::to_string_pretty(self).context("serialize current.json")?; + let text = format!("{text}\n"); + bread_utils::atomic::write_atomic(path, &text, None) + .with_context(|| format!("write {}", path.display())) + } + + pub fn set_output(&mut self, output: impl Into, path: impl Into) { + self.outputs.insert(output.into(), path.into()); + } + + pub fn get_output(&self, output: &str) -> Option<&Path> { + self.outputs.get(output).map(PathBuf::as_path) + } + + pub fn all(&self) -> &BTreeMap { + &self.outputs + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tmp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "breadpaper-current-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn missing_file_is_empty_map() { + let dir = tmp_dir("missing"); + let path = dir.join("current.json"); + let cur = Current::load_from(&path); + assert!(cur.all().is_empty()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn roundtrip_pretty_json() { + let dir = tmp_dir("roundtrip"); + let path = dir.join("nested").join("current.json"); + let mut cur = Current::default(); + cur.set_output("eDP-1", "/abs/path/a.png"); + cur.set_output("HDMI-A-1", "/abs/path/b.png"); + cur.save_to(&path).unwrap(); + + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("\n \"outputs\"")); + assert!(text.contains("\n \"HDMI-A-1\"")); + assert!(text.contains("\n \"eDP-1\"")); + + let loaded = Current::load_from(&path); + assert_eq!( + loaded.get_output("eDP-1"), + Some(Path::new("/abs/path/a.png")) + ); + assert_eq!( + loaded.get_output("HDMI-A-1"), + Some(Path::new("/abs/path/b.png")) + ); + assert_eq!(loaded.all().len(), 2); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn set_one_output_does_not_drop_others() { + let dir = tmp_dir("keep"); + let path = dir.join("current.json"); + let mut cur = Current::default(); + cur.set_output("eDP-1", "/abs/a.png"); + cur.set_output("HDMI-A-1", "/abs/b.png"); + cur.save_to(&path).unwrap(); + + let mut cur = Current::load_from(&path); + cur.set_output("eDP-1", "/abs/c.png"); + cur.save_to(&path).unwrap(); + + let loaded = Current::load_from(&path); + assert_eq!(loaded.get_output("eDP-1"), Some(Path::new("/abs/c.png"))); + assert_eq!(loaded.get_output("HDMI-A-1"), Some(Path::new("/abs/b.png"))); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src/lib.rs b/src/lib.rs index f846d67..60d1c9b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,13 +1,22 @@ +mod config; +mod current; +mod library; mod pywal; mod theme; +mod ui; mod wallpaper; use std::path::{Path, PathBuf}; +#[cfg(not(test))] +use std::process::{Command, Stdio}; use std::thread; -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; use bread_utils::bread_client::{BreadClient, BreadEvent}; -use serde_json::{json, Value}; +use serde_json::{Value, json}; + +pub use config::{Config, DEFAULT_SYSTEM_LIBRARY, DEFAULT_USER_LIBRARY}; +pub use library::{Wallpaper, scan}; /// App id in bread's sibling-app registry (`KNOWN_APPS`). Events publish as /// `bread.paper.*`. See `EVENTS.md`. @@ -15,12 +24,108 @@ const APP_ID: &str = "paper"; const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "webp", "gif", "bmp"]; +/// Open the GTK wallpaper library. Extra dirs are appended to the configured +/// scan list (`~/.config/breadpaper/config.toml`, then defaults). +pub fn library(extra_dirs: impl IntoIterator) -> Result<()> { + let cfg = Config::load().with_extra_dirs(extra_dirs); + ui::run(cfg.library_dirs) +} + +/// Set wallpaper + global pywal palette on every live output. pub fn set(path: &Path) -> Result<()> { let path = validate(path)?; apply_wallpaper(&path)?; generate_palette(&path)?; reload_theme()?; - emit_changed(&path); + + let mut cur = current::Current::load(); + if cur.all().is_empty() { + let live = live_outputs(); + if live.is_empty() { + cur.set_output("*", path.clone()); + } else { + for output in live { + cur.set_output(output, path.clone()); + } + } + } else { + let keys: Vec = cur.all().keys().cloned().collect(); + for output in keys { + cur.set_output(output, path.clone()); + } + } + cur.save()?; + + for output in cur.all().keys() { + if output != "*" { + theme::generate_for_output(output, &path)?; + } + } + + emit_changed(&path, None); + Ok(()) +} + +/// Set wallpaper + per-output theme on a single compositor output. +/// +/// Does not run global `wal -i`. If `output` is the focused Hyprland +/// monitor, the shared stylesheet is updated from that output's palette +/// so unbound apps match the focused screen. +pub fn set_on(path: &Path, output: &str) -> Result<()> { + if output.is_empty() { + bail!("output name is empty"); + } + let path = validate(path)?; + wallpaper::apply_on(&path, output)?; + let palette = theme::generate_for_output(output, &path)?; + + let mut cur = current::Current::load(); + cur.set_output(output, path.clone()); + cur.save()?; + + if is_focused_output(output) { + theme::write_shared_from(&palette)?; + } + + emit_changed(&path, Some(output)); + Ok(()) +} + +/// Re-apply every wallpaper + per-output theme stored in current.json. +pub fn apply_saved() -> Result<()> { + let cur = current::Current::load(); + let mut first_err = None; + for (output, path) in cur.all() { + let result = restore_one(output, path); + match result { + Ok(()) => { + let name = (output != "*").then_some(output.as_str()); + emit_changed(path, name); + } + Err(e) => { + eprintln!("breadpaper: apply {output}: {e:#}"); + if first_err.is_none() { + first_err = Some(e); + } + } + } + } + match first_err { + Some(e) => Err(e), + None => Ok(()), + } +} + +fn restore_one(output: &str, path: &Path) -> Result<()> { + if output == "*" { + wallpaper::apply(path)?; + return Ok(()); + } + wallpaper::apply_on(path, output)?; + let palette = theme::generate_for_output(output, path)?; + if is_focused_output(output) { + theme::write_shared_from(&palette)?; + } Ok(()) } @@ -29,6 +134,11 @@ pub fn set(path: &Path) -> Result<()> { pub fn listen() -> Result<()> { let client = BreadClient::connect(APP_ID); let _subscription = client.subscribe("bread.command.paper.**", handle_command); + let _monitors = client.subscribe("bread.monitor.connected", |_| { + if let Err(e) = apply_saved() { + eprintln!("breadpaper: apply_saved on monitor connect failed: {e:#}"); + } + }); loop { thread::park(); } @@ -36,11 +146,14 @@ pub fn listen() -> Result<()> { /// Fire-and-forget `bread.paper.changed`. Silent no-op if breadd is down /// (`BreadClient::emit` never blocks or errors the caller). -fn emit_changed(path: &Path) { - BreadClient::connect(APP_ID).emit( - "bread.paper.changed", - json!({ "path": path.to_string_lossy() }), - ); +/// +/// `output` is `None` when the wallpaper was applied to every output. +fn emit_changed(path: &Path, output: Option<&str>) { + let mut data = json!({ "path": path.to_string_lossy() }); + if let Some(name) = output { + data["output"] = json!(name); + } + BreadClient::connect(APP_ID).emit("bread.paper.changed", data); } fn handle_command(event: BreadEvent) { @@ -49,6 +162,7 @@ fn handle_command(event: BreadEvent) { }; match verb { "set" => handle_set(&event.data), + "library" => handle_library(), other => { eprintln!("breadpaper: ignoring unrecognized command verb '{other}'"); } @@ -64,25 +178,75 @@ fn handle_set(data: &Value) { ); return; }; + let output = data.get("output").and_then(Value::as_str); let path = Path::new(path_str); - match set(path) { + let result = match output { + Some(name) => set_on(path, name), + None => set(path), + }; + match result { Ok(()) => { let applied = path .canonicalize() .map(|p| p.to_string_lossy().into_owned()) .unwrap_or_else(|_| path_str.to_string()); - client.emit("bread.paper.set.done", json!({ "path": applied })); + let mut payload = json!({ "path": applied }); + if let Some(name) = output { + payload["output"] = json!(name); + } + client.emit("bread.paper.set.done", payload); } Err(e) => { eprintln!("breadpaper: bread.command.paper.set failed: {e:#}"); + let mut payload = json!({ "error": format!("{e:#}"), "path": path_str }); + if let Some(name) = output { + payload["output"] = json!(name); + } + client.emit("bread.paper.set.failed", payload); + } + } +} + +fn handle_library() { + let client = BreadClient::connect(APP_ID); + match open_library() { + Ok(()) => client.emit("bread.paper.library.done", json!({})), + Err(e) => { + eprintln!("breadpaper: bread.command.paper.library failed: {e:#}"); client.emit( - "bread.paper.set.failed", - json!({ "error": format!("{e:#}"), "path": path_str }), + "bread.paper.library.failed", + json!({ "error": format!("{e:#}") }), ); } } } +/// Spawn a one-shot `breadpaper library` so the listen loop can stay a +/// park() thread. GTK needs its own process (and argv) — mixing it into +/// `listen` would steal the main thread. +fn open_library() -> Result<()> { + spawn_library() +} + +#[cfg(not(test))] +fn spawn_library() -> Result<()> { + let exe = std::env::current_exe().context("cannot resolve breadpaper executable")?; + Command::new(exe) + .arg("library") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::inherit()) + .spawn() + .context("failed to spawn breadpaper library")?; + Ok(()) +} + +#[cfg(test)] +fn spawn_library() -> Result<()> { + // cargo test's current_exe is the test harness, not breadpaper. + Ok(()) +} + pub fn get() -> Result { let home = std::env::var("HOME").context("HOME not set")?; let wal_file = PathBuf::from(home).join(".cache/wal/wal"); @@ -93,6 +257,14 @@ pub fn get() -> Result { Ok(PathBuf::from(contents.trim())) } +/// Wallpaper path last persisted for `output` in current.json. +pub fn get_on(output: &str) -> Result { + current::Current::load() + .get_output(output) + .map(Path::to_path_buf) + .with_context(|| format!("no wallpaper saved for output {output}")) +} + pub fn apply_wallpaper(path: &Path) -> Result<()> { wallpaper::apply(path) } @@ -127,15 +299,52 @@ fn validate(path: &Path) -> Result { Ok(canonical) } +fn live_outputs() -> Vec { + if let Some(names) = hypr_output_names() { + return names; + } + wallpaper::query_outputs() +} + +fn hypr_output_names() -> Option> { + let v = bread_utils::hypr::request_json("j/monitors")?; + let names: Vec = v + .as_array()? + .iter() + .filter_map(|m| m.get("name").and_then(|n| n.as_str()).map(str::to_string)) + .collect(); + if names.is_empty() { None } else { Some(names) } +} + +fn is_focused_output(output: &str) -> bool { + bread_utils::hypr::focused_monitor() + .map(|m| m.name == output) + .unwrap_or(false) +} + #[cfg(test)] mod tests { use super::*; + fn tmp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "breadpaper-lib-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + #[test] fn emit_changed_is_silent_without_breadd() { // BreadClient::emit must never panic or error just because the // socket is missing — this is the fail-silent contract. - emit_changed(Path::new("/tmp/wallpaper.png")); + emit_changed(Path::new("/tmp/wallpaper.png"), None); + emit_changed(Path::new("/tmp/wallpaper.png"), Some("eDP-1")); } #[test] @@ -173,4 +382,48 @@ mod tests { handle_set(&json!({})); handle_set(&json!({ "path": 1 })); } + + #[test] + fn handle_set_with_output_vs_without_is_silent_without_breadd() { + // Missing files fail in validate — never reaches awww/wal. + handle_set(&json!({ "path": "/no/such/breadpaper-wallpaper.png" })); + handle_set(&json!({ + "path": "/no/such/breadpaper-wallpaper.png", + "output": "eDP-1" + })); + } + + #[test] + fn handle_command_library_is_silent_without_breadd() { + handle_command(BreadEvent { + event: "bread.command.paper.library".into(), + timestamp: 0, + data: json!({}), + }); + } + + #[test] + fn validate_rejects_bad_extensions() { + let dir = tmp_dir("validate"); + let txt = dir.join("notes.txt"); + std::fs::write(&txt, b"x").unwrap(); + assert!(validate(&txt).is_err()); + + let png = dir.join("ok.png"); + std::fs::write(&png, b"x").unwrap(); + assert_eq!(validate(&png).unwrap(), png.canonicalize().unwrap()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn handle_set_bad_extension_with_output_is_silent_without_breadd() { + let dir = tmp_dir("bad-ext"); + let txt = dir.join("notes.txt"); + std::fs::write(&txt, b"x").unwrap(); + handle_set(&json!({ + "path": txt.to_string_lossy(), + "output": "HDMI-A-1" + })); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/src/library.rs b/src/library.rs new file mode 100644 index 0000000..cc1adff --- /dev/null +++ b/src/library.rs @@ -0,0 +1,168 @@ +use std::collections::HashSet; +use std::path::{Path, PathBuf}; + +use crate::IMAGE_EXTENSIONS; + +/// Caps how many files the picker ever lists. The library is organized in +/// subfolders (show/series), so the walk is recursive — without a bound a +/// huge Pictures tree would stall the window. +pub const MAX_LIBRARY_ITEMS: usize = 200; +pub const MAX_SCAN_DEPTH: usize = 4; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Wallpaper { + pub path: PathBuf, + pub name: String, +} + +pub fn is_wallpaper_file(path: &Path) -> bool { + path.extension() + .and_then(|e| e.to_str()) + .map(|e| { + IMAGE_EXTENSIONS + .iter() + .any(|ext| ext.eq_ignore_ascii_case(e)) + }) + .unwrap_or(false) +} + +/// Recursively collect images under `dirs`. Missing directories are skipped. +/// Results are sorted by filename (case-insensitive), then full path. +pub fn scan(dirs: &[PathBuf]) -> Vec { + let mut out = Vec::new(); + let mut seen = HashSet::new(); + for dir in dirs { + if !dir.is_dir() { + continue; + } + walk(dir, MAX_SCAN_DEPTH, &mut out, &mut seen); + if out.len() >= MAX_LIBRARY_ITEMS { + break; + } + } + out.sort_by(|a, b| { + a.name + .to_lowercase() + .cmp(&b.name.to_lowercase()) + .then_with(|| a.path.cmp(&b.path)) + }); + out +} + +fn walk(dir: &Path, depth: usize, out: &mut Vec, seen: &mut HashSet) { + if depth == 0 || out.len() >= MAX_LIBRARY_ITEMS { + return; + } + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + let mut entries: Vec<_> = entries.flatten().collect(); + entries.sort_by_key(|e| e.file_name()); + for entry in entries { + if out.len() >= MAX_LIBRARY_ITEMS { + return; + } + let path = entry.path(); + let name = entry.file_name(); + if name.to_string_lossy().starts_with('.') { + continue; + } + if path.is_dir() { + walk(&path, depth - 1, out, seen); + continue; + } + if !is_wallpaper_file(&path) { + continue; + } + let canonical = path.canonicalize().unwrap_or_else(|_| path.clone()); + if !seen.insert(canonical.clone()) { + continue; + } + out.push(Wallpaper { + name: path + .file_stem() + .or_else(|| path.file_name()) + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(), + path: canonical, + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tmp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "breadpaper-scan-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn touch(path: &Path) { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + std::fs::write(path, []).unwrap(); + } + + #[test] + fn is_wallpaper_file_accepts_known_extensions() { + assert!(is_wallpaper_file(Path::new("a.PNG"))); + assert!(is_wallpaper_file(Path::new("b.jpeg"))); + assert!(is_wallpaper_file(Path::new("c.webp"))); + assert!(!is_wallpaper_file(Path::new("d.txt"))); + assert!(!is_wallpaper_file(Path::new("noext"))); + } + + #[test] + fn scan_skips_missing_dirs() { + assert!(scan(&[PathBuf::from("/no/such/breadpaper-walls")]).is_empty()); + } + + #[test] + fn scan_finds_images_and_ignores_other_files() { + let dir = tmp_dir("find"); + touch(&dir.join("keep.png")); + touch(&dir.join("notes.txt")); + touch(&dir.join(".hidden.jpg")); + touch(&dir.join("nested").join("deep.jpg")); + let found = scan(std::slice::from_ref(&dir)); + let names: Vec<_> = found.iter().map(|w| w.name.as_str()).collect(); + assert!(names.contains(&"keep"), "{names:?}"); + assert!(names.contains(&"deep"), "{names:?}"); + assert!( + !names + .iter() + .any(|n| n.contains("notes") || n.contains("hidden")) + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn scan_dedups_the_same_file_via_two_roots() { + let dir = tmp_dir("dedup"); + touch(&dir.join("one.png")); + let found = scan(&[dir.clone(), dir.clone()]); + assert_eq!(found.len(), 1); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn scan_respects_item_cap() { + let dir = tmp_dir("cap"); + for i in 0..(MAX_LIBRARY_ITEMS + 10) { + touch(&dir.join(format!("{i:04}.png"))); + } + let found = scan(std::slice::from_ref(&dir)); + assert_eq!(found.len(), MAX_LIBRARY_ITEMS); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src/main.rs b/src/main.rs index 959c184..899386f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,11 +4,19 @@ use std::process; use clap::{Parser, Subcommand}; #[derive(Parser)] -#[command(name = "breadpaper", version, about = "Wallpaper manager for the bread desktop")] +#[command( + name = "breadpaper", + version, + about = "Wallpaper manager for the bread desktop" +)] struct Cli { /// Image file to set as wallpaper (shorthand for `set`) path: Option, + /// Restrict set/get to one compositor output + #[arg(long, value_name = "NAME", global = true)] + output: Option, + #[command(subcommand)] command: Option, } @@ -16,24 +24,37 @@ struct Cli { #[derive(Subcommand)] enum Command { /// Set wallpaper, generate pywal palette, and reload bread themes - Set { - path: PathBuf, - }, + Set { path: PathBuf }, /// Print the current wallpaper path Get, - /// Honor bread.command.paper.set until killed + /// Re-apply wallpapers and per-output themes from current.json + Apply, + /// Honor bread.command.paper.set / .library until killed Listen, + /// Open the wallpaper library (alias: browse) + #[command(visible_alias = "browse")] + Library { + /// Extra directory to scan (repeatable; added to configured dirs) + #[arg(short, long = "dir", value_name = "DIR")] + dirs: Vec, + }, } fn main() { let cli = Cli::parse(); let result = match (cli.command, cli.path) { - (Some(Command::Set { path }), _) | (None, Some(path)) => breadpaper::set(&path), + (Some(Command::Set { path }), _) | (None, Some(path)) => match cli.output.as_deref() { + Some(output) => breadpaper::set_on(&path, output), + None => breadpaper::set(&path), + }, (Some(Command::Listen), _) => breadpaper::listen(), - (Some(Command::Get), _) | (None, None) => { - breadpaper::get().map(|p| println!("{}", p.display())) - } + (Some(Command::Library { dirs }), _) => breadpaper::library(dirs), + (Some(Command::Apply), _) => breadpaper::apply_saved(), + (Some(Command::Get), _) | (None, None) => match cli.output.as_deref() { + Some(output) => breadpaper::get_on(output).map(|p| println!("{}", p.display())), + None => breadpaper::get().map(|p| println!("{}", p.display())), + }, }; if let Err(e) = result { diff --git a/src/theme.rs b/src/theme.rs index 5d06076..a104e17 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -1,6 +1,8 @@ +use std::path::Path; use std::process::Command; use anyhow::{Context, Result, bail}; +use bread_theme::Palette; pub fn reload() -> Result<()> { let status = Command::new("bread-theme") @@ -13,3 +15,16 @@ pub fn reload() -> Result<()> { } Ok(()) } + +/// Per-output palette + bread-theme files. Does not run `wal -i`. +pub fn generate_for_output(output: &str, path: &Path) -> Result { + bread_theme::generate_output(output, path) + .with_context(|| format!("bread-theme generate_output({output}, {})", path.display()))?; + Ok(bread_theme::load_palette_for(output)) +} + +pub fn write_shared_from(palette: &Palette) -> Result<()> { + bread_theme::write_shared_css_from(palette) + .context("bread-theme write_shared_css_from") + .map(|_| ()) +} diff --git a/src/ui.rs b/src/ui.rs new file mode 100644 index 0000000..01e5365 --- /dev/null +++ b/src/ui.rs @@ -0,0 +1,300 @@ +use std::cell::RefCell; +use std::path::{Path, PathBuf}; +use std::rc::Rc; + +use anyhow::Result; +use gtk4::gdk_pixbuf::Pixbuf; +use gtk4::gio::ApplicationFlags; +use gtk4::prelude::*; +use gtk4::{ + Align, Application, ApplicationWindow, Box as GBox, Button, ContentFit, CssProvider, FlowBox, + FlowBoxChild, HeaderBar, Label, Orientation, Picture, PolicyType, ScrolledWindow, + SelectionMode, Stack, +}; + +use crate::library::{self, Wallpaper}; + +const APP_ID: &str = "com.breadway.breadpaper"; +const THUMB_W: i32 = 240; +const THUMB_H: i32 = 135; + +const APP_CSS: &str = "\ +headerbar {\ + background-color: @bg; color: @on-bg; box-shadow: none;\ + border-bottom: 1px solid alpha(@on-bg, 0.08);\ +}\n\ +.library-chrome { padding: 12px 16px 8px 16px; }\n\ +.library-grid { padding: 8px 12px 16px 12px; }\n\ +.library-empty { padding: 32px 24px; }\n\ +.wallpaper-tile {\ + padding: 0; background-color: @surface; color: @on-surface;\ + border-radius: 8px;\ +}\n\ +.wallpaper-tile:hover { background-color: alpha(@on-surface, 0.14); }\n\ +.wallpaper-tile.current { box-shadow: inset 0 0 0 2px @accent; }\n\ +.wallpaper-name { padding: 8px 10px; font-size: 12px; }\n\ +"; + +thread_local! { + static APP_PROVIDER: RefCell> = const { RefCell::new(None) }; +} + +pub fn run(dirs: Vec) -> Result<()> { + let app = Application::builder() + .application_id(APP_ID) + .flags(ApplicationFlags::empty()) + .build(); + + app.connect_activate(move |app| present(app, dirs.clone())); + // Clap already consumed argv; do not let GApplication re-parse `library --dir`. + let _ = app.run_with_args(&["breadpaper"]); + Ok(()) +} + +fn present(app: &Application, dirs: Vec) { + bread_theme::gtk::apply_shared(); + APP_PROVIDER.with(|cell| bread_theme::gtk::apply_css(APP_CSS, cell)); + + let window = ApplicationWindow::builder() + .application(app) + .title("Wallpapers") + .default_width(960) + .default_height(640) + .build(); + + let header = HeaderBar::new(); + window.set_titlebar(Some(&header)); + + let refresh = Button::with_label("Refresh"); + header.pack_end(&refresh); + + let root = GBox::new(Orientation::Vertical, 0); + + let chrome = GBox::new(Orientation::Vertical, 6); + chrome.add_css_class("library-chrome"); + + let summary = Label::new(None); + summary.set_xalign(0.0); + summary.set_wrap(true); + summary.add_css_class("dim"); + chrome.append(&summary); + + let status = Label::new(Some("Click a wallpaper to apply it.")); + status.set_xalign(0.0); + status.set_wrap(true); + chrome.append(&status); + root.append(&chrome); + + let flow = FlowBox::new(); + flow.set_selection_mode(SelectionMode::None); + flow.set_homogeneous(true); + flow.set_max_children_per_line(6); + flow.set_min_children_per_line(2); + flow.set_row_spacing(12); + flow.set_column_spacing(12); + flow.set_halign(Align::Fill); + flow.add_css_class("library-grid"); + + let scrolled = ScrolledWindow::builder() + .hscrollbar_policy(PolicyType::Never) + .vscrollbar_policy(PolicyType::Automatic) + .vexpand(true) + .hexpand(true) + .child(&flow) + .build(); + + let empty = Label::new(None); + empty.set_wrap(true); + empty.set_justify(gtk4::Justification::Center); + empty.add_css_class("dim"); + empty.add_css_class("library-empty"); + empty.set_hexpand(true); + empty.set_vexpand(true); + + let stack = Stack::new(); + stack.set_vexpand(true); + stack.add_named(&scrolled, Some("grid")); + stack.add_named(&empty, Some("empty")); + root.append(&stack); + + window.set_child(Some(&root)); + bread_theme::gtk::bind_window_auto(&window); + + let dirs = Rc::new(dirs); + let reload = { + let dirs = dirs.clone(); + let flow = flow.clone(); + let summary = summary.clone(); + let status = status.clone(); + let stack = stack.clone(); + let empty = empty.clone(); + let window = window.clone(); + Rc::new(move || { + let papers = library::scan(&dirs); + summary.set_text(&dirs_summary(&dirs, papers.len())); + empty.set_text(&empty_message(&dirs)); + if papers.is_empty() { + stack.set_visible_child_name("empty"); + } else { + stack.set_visible_child_name("grid"); + } + fill_grid(&flow, &papers, &status, &window); + }) + }; + + window.present(); + reload(); + { + let reload = reload.clone(); + refresh.connect_clicked(move |_| reload()); + } +} + +fn fill_grid(flow: &FlowBox, papers: &[Wallpaper], status: &Label, host: &impl IsA) { + while let Some(child) = flow.first_child() { + flow.remove(&child); + } + let current = current_path_for(host); + for paper in papers { + let is_current = current.as_deref() == Some(paper.path.as_path()); + flow.insert(&tile(paper, is_current, flow, status), -1); + } +} + +fn current_path_for(widget: &impl IsA) -> Option { + target_output(widget) + .and_then(|output| { + crate::current::Current::load() + .get_output(&output) + .map(Path::to_path_buf) + }) + .or_else(|| crate::get().ok()) +} + +fn target_output(widget: &impl IsA) -> Option { + bread_theme::gtk::output_for_widget(widget) + .or_else(|| bread_utils::hypr::focused_monitor().map(|m| m.name)) +} + +fn tile(paper: &Wallpaper, is_current: bool, flow: &FlowBox, status: &Label) -> Button { + let btn = Button::new(); + btn.add_css_class("wallpaper-tile"); + btn.set_widget_name(&paper.path.to_string_lossy()); + btn.set_tooltip_text(Some(&paper.path.to_string_lossy())); + if is_current { + btn.add_css_class("current"); + } + + let col = GBox::new(Orientation::Vertical, 0); + col.append(&thumbnail(&paper.path)); + + let name = Label::new(Some(&paper.name)); + name.add_css_class("wallpaper-name"); + name.set_xalign(0.0); + name.set_ellipsize(gtk4::pango::EllipsizeMode::End); + name.set_max_width_chars(24); + col.append(&name); + btn.set_child(Some(&col)); + + let path = paper.path.clone(); + let pretty = paper.name.clone(); + let status = status.clone(); + let flow = flow.clone(); + btn.connect_clicked(move |clicked| { + if !clicked.is_sensitive() { + return; + } + clicked.set_sensitive(false); + let output = target_output(clicked); + status.set_text(&match output.as_deref() { + Some(name) => format!("Applying {pretty} on {name}…"), + None => format!("Applying {pretty}…"), + }); + let path = path.clone(); + let pretty = pretty.clone(); + let status = status.clone(); + let flow = flow.clone(); + let clicked = clicked.clone(); + gtk4::glib::spawn_future_local(async move { + let path_thread = path.clone(); + let output_thread = output.clone(); + let result = gtk4::gio::spawn_blocking(move || match output_thread.as_deref() { + Some(name) => crate::set_on(&path_thread, name), + None => crate::set(&path_thread), + }) + .await; + clicked.set_sensitive(true); + match result { + Ok(Ok(())) => { + status.set_text(&match output.as_deref() { + Some(name) => format!("Applied {pretty} on {name}"), + None => format!("Applied {pretty}"), + }); + mark_current(&flow, &path); + } + Ok(Err(e)) => status.set_text(&format!("{e:#}")), + Err(_) => status.set_text("Failed to apply wallpaper"), + } + }); + }); + + btn +} + +fn thumbnail(path: &Path) -> Picture { + let picture = match Pixbuf::from_file_at_scale(path, THUMB_W, THUMB_H, true) { + Ok(pb) => Picture::for_paintable(>k4::gdk::Texture::for_pixbuf(&pb)), + Err(_) => Picture::for_filename(path), + }; + picture.set_content_fit(ContentFit::Cover); + picture.set_size_request(THUMB_W, THUMB_H); + picture.set_can_shrink(true); + picture.set_hexpand(true); + picture +} + +fn mark_current(flow: &FlowBox, current: &Path) { + let current = current.to_string_lossy(); + let mut i = 0; + while let Some(wrapper) = flow.child_at_index(i) { + if let Some(btn) = wrapper + .downcast_ref::() + .and_then(|c| c.child()) + .and_then(|w| w.downcast::