// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::manager::DefaultArgs;
use crate::{
api::rpc::{format_callback, format_callback_result},
app::App,
Params, StateManager, Window,
};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::{future::Future, sync::Arc};
/// A closure that is run when the Tauri application is setting up.
pub type SetupHook
=
Box) -> Result<(), Box> + Send>;
/// A closure that is run everytime Tauri receives a message it doesn't explicitly handle.
pub type InvokeHandler = dyn Fn(Invoke
) + Send + Sync + 'static;
/// A closure that is run once every time a window is created and loaded.
pub type OnPageLoad
= dyn Fn(Window
, PageLoadPayload) + Send + Sync + 'static;
/// The payload for the [`OnPageLoad`] hook.
#[derive(Debug, Clone, Deserialize)]
pub struct PageLoadPayload {
url: String,
}
impl PageLoadPayload {
/// The page URL.
pub fn url(&self) -> &str {
&self.url
}
}
/// The message and resolver given to a custom command.
pub struct Invoke {
/// The message passed.
pub message: InvokeMessage,
/// The resolver of the message.
pub resolver: InvokeResolver
,
}
/// Error response from an [`InvokeMessage`].
#[derive(Debug)]
pub struct InvokeError(JsonValue);
impl InvokeError {
/// Create an [`InvokeError`] as a string of the [`serde_json::Error`] message.
#[inline(always)]
pub fn from_serde_json(error: serde_json::Error) -> Self {
Self(JsonValue::String(error.to_string()))
}
}
impl From for InvokeError {
#[inline]
fn from(value: T) -> Self {
serde_json::to_value(value)
.map(Self)
.unwrap_or_else(Self::from_serde_json)
}
}
impl From for InvokeError {
#[inline(always)]
fn from(error: crate::Error) -> Self {
Self(JsonValue::String(error.to_string()))
}
}
/// Response from a [`InvokeMessage`] passed to the [`InvokeResolver`].
#[derive(Debug)]
pub enum InvokeResponse {
/// Resolve the promise.
Ok(JsonValue),
/// Reject the promise.
Err(InvokeError),
}
impl InvokeResponse {
/// Turn a [`InvokeResponse`] back into a serializable result.
#[inline(always)]
pub fn into_result(self) -> Result {
match self {
Self::Ok(v) => Ok(v),
Self::Err(e) => Err(e.0),
}
}
}
impl From> for InvokeResponse {
#[inline]
fn from(result: Result) -> Self {
match result {
Ok(ok) => match serde_json::to_value(ok) {
Ok(value) => Self::Ok(value),
Err(err) => Self::Err(InvokeError::from_serde_json(err)),
},
Err(err) => Self::Err(err),
}
}
}
impl From for InvokeResponse {
fn from(error: InvokeError) -> Self {
Self::Err(error)
}
}
/// Resolver of a invoke message.
pub struct InvokeResolver {
window: Window,
pub(crate) callback: String,
pub(crate) error: String,
}
impl InvokeResolver {
pub(crate) fn new(window: Window
, callback: String, error: String) -> Self {
Self {
window,
callback,
error,
}
}
/// Reply to the invoke promise with an async task.
pub fn respond_async(self, task: F)
where
T: Serialize,
F: Future