use crate::{
element::{ClipboardImage, ClipboardItem, JsError, System, codes, module},
platform::clipboard::MAX_IMAGE_BYTES,
};
fn granted(sys: &System) -> Result<(), JsError> {
if sys.access.allows_clipboard() {
return Ok(());
}
Err(JsError::access_denied(
"the clipboard is not granted: add `\"clipboard\": true` to capabilities in nsh.json",
"clipboard",
"",
))
}
fn has_images(sys: &System) -> bool {
sys.clipboard_images
.unwrap_or(sys.os != crate::platform::Os::Android)
}
fn images_available(sys: &System, call: &str) -> Result<(), JsError> {
if has_images(sys) {
return Ok(());
}
Err(JsError::Error(format!(
"Clipboard.{call}: the clipboard holds text only on {}",
sys.os.name()
))
.with_code(codes::UNAVAILABLE))
}
fn refused() -> JsError {
JsError::access_denied(
"Clipboard.readText: the person did not allow the paste",
"clipboard",
"",
)
}
fn too_large(bytes: usize) -> JsError {
JsError::Error(format!(
"Clipboard.readImage: the clipboard's image is {} bytes ({} MB), over the {} MB an app reads",
bytes,
bytes.div_ceil(1 << 20),
MAX_IMAGE_BYTES >> 20
))
.with_code(codes::QUOTA_EXCEEDED)
}
#[module]
pub(crate) struct Clipboard;
#[module]
impl Clipboard {
pub(crate) async fn write_text(text: String, sys: System) -> Result<(), JsError> {
granted(&sys)?;
crate::prelude::set_clipboard(text);
Ok(())
}
pub(crate) async fn write(item: ClipboardItem, sys: System) -> Result<(), JsError> {
granted(&sys)?;
crate::prelude::set_clipboard_item(item);
Ok(())
}
pub(crate) async fn read_text(sys: System) -> Result<String, JsError> {
granted(&sys)?;
crate::element::clipboard_checked_string()
.await
.ok_or_else(refused)
}
pub(crate) async fn has_text(sys: System) -> Result<bool, JsError> {
granted(&sys)?;
Ok(crate::prelude::clipboard_has_string().await)
}
pub(crate) async fn write_image(src: String, sys: System) -> Result<(), JsError> {
granted(&sys)?;
images_available(&sys, "writeImage")?;
crate::prelude::set_clipboard_image(src);
Ok(())
}
pub(crate) async fn read_image(sys: System) -> Result<Option<ClipboardImage>, JsError> {
granted(&sys)?;
images_available(&sys, "readImage")?;
crate::element::clipboard_checked_image()
.await
.map_err(too_large)
}
pub(crate) async fn has_image(sys: System) -> Result<bool, JsError> {
granted(&sys)?;
if !has_images(&sys) {
return Ok(false);
}
Ok(crate::prelude::clipboard_has_image().await)
}
pub(crate) async fn read_files(sys: System) -> Result<Vec<String>, JsError> {
granted(&sys)?;
Ok(crate::prelude::clipboard_files().await)
}
}