image base64 + json write
This commit is contained in:
@ -1,16 +1,43 @@
|
||||
use arboard::{Clipboard, ImageData};
|
||||
use image::codecs::png::{PngDecoder, PngEncoder};
|
||||
use image::{ColorType, DynamicImage, ExtendedColorType, ImageEncoder, RgbaImage};
|
||||
use image::codecs::png::PngEncoder;
|
||||
use image::{ExtendedColorType, ImageEncoder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::result::Result;
|
||||
use std::{error::Error, time::SystemTime};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ClipboardEntry {
|
||||
pub content: ClipboardData,
|
||||
#[serde(with = "serde_millis")]
|
||||
pub timestamp: SystemTime,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub enum ClipboardData {
|
||||
Text(String),
|
||||
Image(Vec<u8>), // png storage
|
||||
#[serde(with = "base64_vec")]
|
||||
Image(Vec<u8>),
|
||||
}
|
||||
|
||||
mod base64_vec {
|
||||
use serde::{Deserialize, Deserializer, Serializer};
|
||||
pub fn serialize<S: Serializer>(v: &Vec<u8>, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let base64_str = base64::encode(v);
|
||||
serializer.serialize_str(&base64_str)
|
||||
}
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
|
||||
let base64_str = String::deserialize(deserializer)?;
|
||||
match base64::decode(base64_str) {
|
||||
Ok(bytes) => Ok(bytes),
|
||||
Err(error_base64) => {
|
||||
let error_serde = serde::de::Error::custom(error_base64);
|
||||
Err(error_serde)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ImageDataExt {
|
||||
@ -61,4 +88,25 @@ impl ClipboardEntry {
|
||||
timestamp: SystemTime::now(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn new_json(path: &str) -> Result<(), Box<dyn Error>> {
|
||||
if Path::new(path).exists() {
|
||||
Err("File already exists.".into())
|
||||
} else {
|
||||
File::create(path)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
pub fn write_entry_json(&self, path: &str) -> Result<(), Box<dyn Error>> {
|
||||
let json = serde_json::to_string_pretty(self)?;
|
||||
let mut file = File::create(path)?;
|
||||
file.write_all(json.as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn read_entry_json(path: &str) -> Result<Self, Box<dyn Error>> {
|
||||
let data = fs::read_to_string(path)?;
|
||||
let entry: ClipboardEntry = serde_json::from_str(&data)?;
|
||||
Ok(entry)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user