feat(wallpaper): extend commands with gallery, delete image, and crop

The plugin now exposes gallery retrieval, image deletion and image crop
across Android, desktop and mobile. The Rust core and Android
bridge are wired to handle these commands, updating state as needed.

- Add gallery, delete_image, and set_image_crop commands
- across Android, desktop and mobile.
- Update permissions, defaults, and schema to enable new commands.
This commit is contained in:
2026-08-20 22:06:00 +02:00
parent 734c757c67
commit 2cfc7c5dcb
22 changed files with 649 additions and 89 deletions
@@ -17,12 +17,25 @@ import java.util.concurrent.Executors
@InvokeArg
class SettingArgs { lateinit var name: String; var value: Boolean = false }
@InvokeArg
class GalleryArgs { var offset: Int = 0; var limit: Int = 48 }
@InvokeArg
class DeleteImageArgs { lateinit var id: String }
@TauriPlugin
class WallpaperPlugin(private val activity: Activity) : Plugin(activity) {
private val io = Executors.newSingleThreadExecutor()
@Command fun getState(invoke: Invoke) = io.execute { invoke.resolve(WallpaperStore.state(activity)) }
@Command fun getGallery(invoke: Invoke) = io.execute {
try {
val args = invoke.parseArgs(GalleryArgs::class.java)
invoke.resolve(WallpaperStore.gallery(activity, args.offset, args.limit))
} catch (error: Exception) { invoke.reject(error.message ?: "Galerie konnte nicht geladen werden") }
}
@Command fun selectImages(invoke: Invoke) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
@@ -33,6 +46,14 @@ class WallpaperPlugin(private val activity: Activity) : Plugin(activity) {
startActivityForResult(invoke, intent, "selectedImages")
}
@Command fun deleteImage(invoke: Invoke) = io.execute {
try {
val args = invoke.parseArgs(DeleteImageArgs::class.java)
if (!WallpaperStore.delete(activity, args.id)) throw IllegalArgumentException("Bild wurde nicht gefunden")
invoke.resolve(WallpaperStore.state(activity))
} catch (error: Exception) { invoke.reject(error.message ?: "Bild konnte nicht gelöscht werden") }
}
@ActivityCallback
fun selectedImages(invoke: Invoke, result: ActivityResult) {
if (result.resultCode != Activity.RESULT_OK) { invoke.reject("Bildauswahl abgebrochen"); return }
@@ -44,6 +44,45 @@ object WallpaperStore {
}
}
fun gallery(context: Context, offset: Int, limit: Int): JSObject {
val originals = files(context)
val selectedIndex = prefs(context).getInt(KEY_INDEX, 0).coerceIn(0, (originals.size - 1).coerceAtLeast(0))
val safeOffset = offset.coerceAtLeast(0).coerceAtMost(originals.size)
val safeLimit = limit.coerceIn(1, 100)
val items = JSArray()
originals.drop(safeOffset).take(safeLimit).forEachIndexed { pageIndex, file ->
items.put(JSObject().apply {
put("id", file.name)
put("url", thumbnailDataUrl(file))
put("selected", safeOffset + pageIndex == selectedIndex)
})
}
return JSObject().apply {
put("total", originals.size)
put("items", items)
}
}
@Synchronized
fun delete(context: Context, id: String): Boolean {
if (id.isBlank() || File(id).name != id) return false
val originals = files(context)
val position = originals.indexOfFirst { it.name == id }
if (position < 0 || !originals[position].delete()) return false
val preferences = prefs(context)
val previousIndex = preferences.getInt(KEY_INDEX, 0).coerceIn(0, (originals.size - 1).coerceAtLeast(0))
val remaining = originals.size - 1
val nextIndex = when {
remaining <= 0 -> 0
position < previousIndex -> previousIndex - 1
previousIndex >= remaining -> remaining - 1
else -> previousIndex
}
preferences.edit().putInt(KEY_INDEX, nextIndex).apply()
return true
}
private fun thumbnailDataUrl(file: File): String {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(file.absolutePath, bounds)
+13 -5
View File
@@ -1,8 +1,16 @@
const COMMANDS: &[&str] = &["get_state", "select_images", "set_setting", "next_wallpaper"];
const COMMANDS: &[&str] = &[
"get_state",
"get_gallery",
"select_images",
"delete_image",
"set_image_crop",
"set_setting",
"next_wallpaper",
];
fn main() {
tauri_plugin::Builder::new(COMMANDS)
.android_path("android")
.ios_path("ios")
.build();
tauri_plugin::Builder::new(COMMANDS)
.android_path("android")
.ios_path("ios")
.build();
}
@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-delete-image"
description = "Enables the delete_image command without any pre-configured scope."
commands.allow = ["delete_image"]
[[permission]]
identifier = "deny-delete-image"
description = "Denies the delete_image command without any pre-configured scope."
commands.deny = ["delete_image"]
@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-get-gallery"
description = "Enables the get_gallery command without any pre-configured scope."
commands.allow = ["get_gallery"]
[[permission]]
identifier = "deny-get-gallery"
description = "Denies the get_gallery command without any pre-configured scope."
commands.deny = ["get_gallery"]
@@ -5,7 +5,9 @@ Allow the LockScreenWallpaper app to manage its wallpaper collection
#### This default permission set includes the following:
- `allow-get-state`
- `allow-get-gallery`
- `allow-select-images`
- `allow-delete-image`
- `allow-set-setting`
- `allow-next-wallpaper`
@@ -18,6 +20,58 @@ Allow the LockScreenWallpaper app to manage its wallpaper collection
</tr>
<tr>
<td>
`wallpaper:allow-delete-image`
</td>
<td>
Enables the delete_image command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`wallpaper:deny-delete-image`
</td>
<td>
Denies the delete_image command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`wallpaper:allow-get-gallery`
</td>
<td>
Enables the get_gallery command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`wallpaper:deny-get-gallery`
</td>
<td>
Denies the get_gallery command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
+1 -1
View File
@@ -1,3 +1,3 @@
[default]
description = "Allow the LockScreenWallpaper app to manage its wallpaper collection"
permissions = ["allow-get-state", "allow-select-images", "allow-set-setting", "allow-next-wallpaper"]
permissions = ["allow-get-state", "allow-get-gallery", "allow-select-images", "allow-delete-image", "allow-set-image-crop", "allow-set-setting", "allow-next-wallpaper"]
+26 -2
View File
@@ -294,6 +294,30 @@
"PermissionKind": {
"type": "string",
"oneOf": [
{
"description": "Enables the delete_image command without any pre-configured scope.",
"type": "string",
"const": "allow-delete-image",
"markdownDescription": "Enables the delete_image command without any pre-configured scope."
},
{
"description": "Denies the delete_image command without any pre-configured scope.",
"type": "string",
"const": "deny-delete-image",
"markdownDescription": "Denies the delete_image command without any pre-configured scope."
},
{
"description": "Enables the get_gallery command without any pre-configured scope.",
"type": "string",
"const": "allow-get-gallery",
"markdownDescription": "Enables the get_gallery command without any pre-configured scope."
},
{
"description": "Denies the get_gallery command without any pre-configured scope.",
"type": "string",
"const": "deny-get-gallery",
"markdownDescription": "Denies the get_gallery command without any pre-configured scope."
},
{
"description": "Enables the get_state command without any pre-configured scope.",
"type": "string",
@@ -343,10 +367,10 @@
"markdownDescription": "Denies the set_setting command without any pre-configured scope."
},
{
"description": "Allow the LockScreenWallpaper app to manage its wallpaper collection\n#### This default permission set includes:\n\n- `allow-get-state`\n- `allow-select-images`\n- `allow-set-setting`\n- `allow-next-wallpaper`",
"description": "Allow the LockScreenWallpaper app to manage its wallpaper collection\n#### This default permission set includes:\n\n- `allow-get-state`\n- `allow-get-gallery`\n- `allow-select-images`\n- `allow-delete-image`\n- `allow-set-setting`\n- `allow-next-wallpaper`",
"type": "string",
"const": "default",
"markdownDescription": "Allow the LockScreenWallpaper app to manage its wallpaper collection\n#### This default permission set includes:\n\n- `allow-get-state`\n- `allow-select-images`\n- `allow-set-setting`\n- `allow-next-wallpaper`"
"markdownDescription": "Allow the LockScreenWallpaper app to manage its wallpaper collection\n#### This default permission set includes:\n\n- `allow-get-state`\n- `allow-get-gallery`\n- `allow-select-images`\n- `allow-delete-image`\n- `allow-set-setting`\n- `allow-next-wallpaper`"
}
]
}
+54 -5
View File
@@ -1,10 +1,59 @@
use tauri::{AppHandle, command, Runtime};
use tauri::{command, AppHandle, Runtime};
use crate::models::*;
use crate::Result;
use crate::WallpaperExt;
#[command] pub(crate) async fn get_state<R: Runtime>(app: AppHandle<R>) -> Result<WallpaperState> { app.wallpaper().get_state() }
#[command] pub(crate) async fn select_images<R: Runtime>(app: AppHandle<R>) -> Result<WallpaperState> { app.wallpaper().select_images() }
#[command] pub(crate) async fn set_setting<R: Runtime>(app: AppHandle<R>, name: String, value: bool) -> Result<WallpaperState> { app.wallpaper().set_setting(SettingRequest { name, value }) }
#[command] pub(crate) async fn next_wallpaper<R: Runtime>(app: AppHandle<R>) -> Result<WallpaperState> { app.wallpaper().next_wallpaper() }
#[command]
pub(crate) async fn get_state<R: Runtime>(app: AppHandle<R>) -> Result<WallpaperState> {
app.wallpaper().get_state()
}
#[command]
pub(crate) async fn get_gallery<R: Runtime>(
app: AppHandle<R>,
offset: usize,
limit: usize,
) -> Result<GalleryPage> {
app.wallpaper()
.get_gallery(GalleryRequest { offset, limit })
}
#[command]
pub(crate) async fn select_images<R: Runtime>(app: AppHandle<R>) -> Result<WallpaperState> {
app.wallpaper().select_images()
}
#[command]
pub(crate) async fn delete_image<R: Runtime>(
app: AppHandle<R>,
id: String,
) -> Result<WallpaperState> {
app.wallpaper().delete_image(DeleteImageRequest { id })
}
#[command]
pub(crate) async fn set_image_crop<R: Runtime>(
app: AppHandle<R>,
id: String,
mode: String,
zoom: f64,
position_x: f64,
position_y: f64,
) -> Result<GalleryImage> {
app.wallpaper().set_image_crop(ImageCropRequest {
id,
mode,
zoom,
position_x,
position_y,
})
}
#[command]
pub(crate) async fn set_setting<R: Runtime>(
app: AppHandle<R>,
name: String,
value: bool,
) -> Result<WallpaperState> {
app.wallpaper().set_setting(SettingRequest { name, value })
}
#[command]
pub(crate) async fn next_wallpaper<R: Runtime>(app: AppHandle<R>) -> Result<WallpaperState> {
app.wallpaper().next_wallpaper()
}
+76 -8
View File
@@ -4,19 +4,87 @@ use tauri::{plugin::PluginApi, AppHandle, Runtime};
use crate::models::*;
pub fn init<R: Runtime, C: DeserializeOwned>(
app: &AppHandle<R>,
_api: PluginApi<R, C>,
app: &AppHandle<R>,
_api: PluginApi<R, C>,
) -> crate::Result<Wallpaper<R>> {
Ok(Wallpaper(app.clone()))
Ok(Wallpaper(app.clone()))
}
/// Access to the wallpaper APIs.
pub struct Wallpaper<R: Runtime>(AppHandle<R>);
impl<R: Runtime> Wallpaper<R> {
fn demo() -> WallpaperState { WallpaperState { image_count: 3, enabled: true, shuffle: true, lock_screen_only: true, current_index: 0, image_urls: vec!["/wallpapers/alpine.png".into(), "/wallpapers/waterfall.png".into(), "/wallpapers/coast.png".into()] } }
pub fn get_state(&self) -> crate::Result<WallpaperState> { Ok(Self::demo()) }
pub fn select_images(&self) -> crate::Result<WallpaperState> { Ok(Self::demo()) }
pub fn set_setting(&self, payload: SettingRequest) -> crate::Result<WallpaperState> { let mut state = Self::demo(); match payload.name.as_str() { "enabled" => state.enabled = payload.value, "shuffle" => state.shuffle = payload.value, "lockScreenOnly" => state.lock_screen_only = payload.value, _ => {} }; Ok(state) }
pub fn next_wallpaper(&self) -> crate::Result<WallpaperState> { let mut state = Self::demo(); state.current_index = 1; Ok(state) }
fn demo() -> WallpaperState {
WallpaperState {
image_count: 3,
enabled: true,
shuffle: true,
lock_screen_only: true,
current_index: 0,
image_urls: vec![
"/wallpapers/alpine.png".into(),
"/wallpapers/waterfall.png".into(),
"/wallpapers/coast.png".into(),
],
}
}
pub fn get_state(&self) -> crate::Result<WallpaperState> {
Ok(Self::demo())
}
pub fn get_gallery(&self, payload: GalleryRequest) -> crate::Result<GalleryPage> {
let urls = Self::demo().image_urls;
let items = urls
.into_iter()
.enumerate()
.skip(payload.offset)
.take(payload.limit)
.map(|(index, url)| GalleryImage {
id: format!("demo-{index}"),
url,
selected: index == 0,
crop_mode: "cover".into(),
crop_zoom: 1.0,
crop_position_x: 0.5,
crop_position_y: 0.5,
})
.collect();
Ok(GalleryPage { total: 3, items })
}
pub fn select_images(&self) -> crate::Result<WallpaperState> {
Ok(Self::demo())
}
pub fn delete_image(&self, _payload: DeleteImageRequest) -> crate::Result<WallpaperState> {
Ok(Self::demo())
}
pub fn set_image_crop(&self, payload: ImageCropRequest) -> crate::Result<GalleryImage> {
let url = Self::demo()
.image_urls
.into_iter()
.nth(payload.id.trim_start_matches("demo-").parse().unwrap_or(0))
.unwrap_or_default();
Ok(GalleryImage {
id: payload.id,
url,
selected: false,
crop_mode: payload.mode,
crop_zoom: payload.zoom,
crop_position_x: payload.position_x,
crop_position_y: payload.position_y,
})
}
pub fn set_setting(&self, payload: SettingRequest) -> crate::Result<WallpaperState> {
let mut state = Self::demo();
match payload.name.as_str() {
"enabled" => state.enabled = payload.value,
"shuffle" => state.shuffle = payload.value,
"lockScreenOnly" => state.lock_screen_only = payload.value,
_ => {}
};
Ok(state)
}
pub fn next_wallpaper(&self) -> crate::Result<WallpaperState> {
let mut state = Self::demo();
state.current_index = 1;
Ok(state)
}
}
+11 -11
View File
@@ -4,18 +4,18 @@ pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Io(#[from] std::io::Error),
#[cfg(mobile)]
#[error(transparent)]
PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
#[error(transparent)]
Io(#[from] std::io::Error),
#[cfg(mobile)]
#[error(transparent)]
PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
+25 -17
View File
@@ -1,6 +1,6 @@
use tauri::{
plugin::{Builder, TauriPlugin},
Manager, Runtime,
plugin::{Builder, TauriPlugin},
Manager, Runtime,
};
pub use models::*;
@@ -23,26 +23,34 @@ use mobile::Wallpaper;
/// Extensions to [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`] to access the wallpaper APIs.
pub trait WallpaperExt<R: Runtime> {
fn wallpaper(&self) -> &Wallpaper<R>;
fn wallpaper(&self) -> &Wallpaper<R>;
}
impl<R: Runtime, T: Manager<R>> crate::WallpaperExt<R> for T {
fn wallpaper(&self) -> &Wallpaper<R> {
self.state::<Wallpaper<R>>().inner()
}
fn wallpaper(&self) -> &Wallpaper<R> {
self.state::<Wallpaper<R>>().inner()
}
}
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("wallpaper")
.invoke_handler(tauri::generate_handler![commands::get_state, commands::select_images, commands::set_setting, commands::next_wallpaper])
.setup(|app, api| {
#[cfg(mobile)]
let wallpaper = mobile::init(app, api)?;
#[cfg(desktop)]
let wallpaper = desktop::init(app, api)?;
app.manage(wallpaper);
Ok(())
})
.build()
Builder::new("wallpaper")
.invoke_handler(tauri::generate_handler![
commands::get_state,
commands::get_gallery,
commands::select_images,
commands::delete_image,
commands::set_image_crop,
commands::set_setting,
commands::next_wallpaper
])
.setup(|app, api| {
#[cfg(mobile)]
let wallpaper = mobile::init(app, api)?;
#[cfg(desktop)]
let wallpaper = desktop::init(app, api)?;
app.manage(wallpaper);
Ok(())
})
.build()
}
+42 -13
View File
@@ -1,7 +1,7 @@
use serde::de::DeserializeOwned;
use tauri::{
plugin::{PluginApi, PluginHandle},
AppHandle, Runtime,
plugin::{PluginApi, PluginHandle},
AppHandle, Runtime,
};
use crate::models::*;
@@ -11,22 +11,51 @@ tauri::ios_plugin_binding!(init_plugin_wallpaper);
// initializes the Kotlin or Swift plugin classes
pub fn init<R: Runtime, C: DeserializeOwned>(
_app: &AppHandle<R>,
api: PluginApi<R, C>,
_app: &AppHandle<R>,
api: PluginApi<R, C>,
) -> crate::Result<Wallpaper<R>> {
#[cfg(target_os = "android")]
let handle = api.register_android_plugin("de.wechselbild.wallpaper", "WallpaperPlugin")?;
#[cfg(target_os = "ios")]
let handle = api.register_ios_plugin(init_plugin_wallpaper)?;
Ok(Wallpaper(handle))
#[cfg(target_os = "android")]
let handle = api.register_android_plugin("de.wechselbild.wallpaper", "WallpaperPlugin")?;
#[cfg(target_os = "ios")]
let handle = api.register_ios_plugin(init_plugin_wallpaper)?;
Ok(Wallpaper(handle))
}
/// Access to the wallpaper APIs.
pub struct Wallpaper<R: Runtime>(PluginHandle<R>);
impl<R: Runtime> Wallpaper<R> {
pub fn get_state(&self) -> crate::Result<WallpaperState> { self.0.run_mobile_plugin("getState", ()).map_err(Into::into) }
pub fn select_images(&self) -> crate::Result<WallpaperState> { self.0.run_mobile_plugin("selectImages", ()).map_err(Into::into) }
pub fn set_setting(&self, payload: SettingRequest) -> crate::Result<WallpaperState> { self.0.run_mobile_plugin("setSetting", payload).map_err(Into::into) }
pub fn next_wallpaper(&self) -> crate::Result<WallpaperState> { self.0.run_mobile_plugin("nextWallpaper", ()).map_err(Into::into) }
pub fn get_state(&self) -> crate::Result<WallpaperState> {
self.0.run_mobile_plugin("getState", ()).map_err(Into::into)
}
pub fn get_gallery(&self, payload: GalleryRequest) -> crate::Result<GalleryPage> {
self.0
.run_mobile_plugin("getGallery", payload)
.map_err(Into::into)
}
pub fn select_images(&self) -> crate::Result<WallpaperState> {
self.0
.run_mobile_plugin("selectImages", ())
.map_err(Into::into)
}
pub fn delete_image(&self, payload: DeleteImageRequest) -> crate::Result<WallpaperState> {
self.0
.run_mobile_plugin("deleteImage", payload)
.map_err(Into::into)
}
pub fn set_image_crop(&self, payload: ImageCropRequest) -> crate::Result<GalleryImage> {
self.0
.run_mobile_plugin("setImageCrop", payload)
.map_err(Into::into)
}
pub fn set_setting(&self, payload: SettingRequest) -> crate::Result<WallpaperState> {
self.0
.run_mobile_plugin("setSetting", payload)
.map_err(Into::into)
}
pub fn next_wallpaper(&self) -> crate::Result<WallpaperState> {
self.0
.run_mobile_plugin("nextWallpaper", ())
.map_err(Into::into)
}
}
+52 -7
View File
@@ -3,14 +3,59 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WallpaperState {
pub image_count: usize,
pub enabled: bool,
pub shuffle: bool,
pub lock_screen_only: bool,
pub current_index: usize,
pub image_urls: Vec<String>,
pub image_count: usize,
pub enabled: bool,
pub shuffle: bool,
pub lock_screen_only: bool,
pub current_index: usize,
pub image_urls: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SettingRequest { pub name: String, pub value: bool }
pub struct SettingRequest {
pub name: String,
pub value: bool,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GalleryRequest {
pub offset: usize,
pub limit: usize,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteImageRequest {
pub id: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ImageCropRequest {
pub id: String,
pub mode: String,
pub zoom: f64,
pub position_x: f64,
pub position_y: f64,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GalleryImage {
pub id: String,
pub url: String,
pub selected: bool,
pub crop_mode: String,
pub crop_zoom: f64,
pub crop_position_x: f64,
pub crop_position_y: f64,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GalleryPage {
pub total: usize,
pub items: Vec<GalleryImage>,
}