Skip to content

Commit

Permalink
chore: clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelOsborne committed Jan 17, 2024
1 parent 54e3891 commit 7ab06c0
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 123 deletions.
111 changes: 65 additions & 46 deletions dotlottie-fms/src/dolottie_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,39 @@ impl DotLottieManager {
pub fn new(dotlottie: Option<Vec<u8>>) -> Self {
if let Some(dotlottie) = dotlottie {
// Initialize the manager with the dotLottie file
let manifest = get_manifest(&dotlottie).unwrap();
let mut id = String::new();

if let Some(first_animation) = &manifest.active_animation_id {
id = first_animation.clone();
} else if let Ok(animations) = manifest.animations.lock() {
id = animations.index(0).id.clone();
} else {
panic!("No animations found in dotLottie file");
}

DotLottieManager {
current_animation_id: id,
manifest,
zip_data: dotlottie,
animation_settings_cache: HashMap::new(),
animation_data_cache: HashMap::new(),
let manifest = get_manifest(&dotlottie);

match manifest {
Ok(manifest) => {
let mut id = String::new();

if let Some(first_animation) = &manifest.active_animation_id {
id = first_animation.clone();
} else if let Ok(animations) = manifest.animations.read() {
id = animations.index(0).id.clone();
} else {
panic!("No animations found in dotLottie file");
}

DotLottieManager {
current_animation_id: id,
manifest,
zip_data: dotlottie,
animation_settings_cache: HashMap::new(),
animation_data_cache: HashMap::new(),
}
}
Err(error) => {
eprintln!("Unable to initialize dotLottie manager: {}", error);

DotLottieManager {
current_animation_id: String::new(),
manifest: Manifest::new(),
zip_data: vec![],
animation_settings_cache: HashMap::new(),
animation_data_cache: HashMap::new(),
}
}
}
} else {
DotLottieManager {
Expand All @@ -45,42 +61,47 @@ impl DotLottieManager {

pub fn init(&mut self, dotlottie: Vec<u8>) {
// Initialize the manager with the dotLottie file
let manifest = get_manifest(&dotlottie).unwrap();
let mut id = String::new();
let manifest = get_manifest(&dotlottie);

match manifest {
Ok(manifest) => {
let mut id = String::new();

if let Some(first_animation) = &manifest.active_animation_id {
id = first_animation.clone();
} else if let Ok(animations) = manifest.animations.read() {
id = animations.index(0).id.clone();
} else {
panic!("No animations found in dotLottie file");
}

if let Some(first_animation) = &manifest.active_animation_id {
id = first_animation.clone();
} else if let Ok(animations) = manifest.animations.lock() {
id = animations.index(0).id.clone();
} else {
panic!("No animations found in dotLottie file");
self.current_animation_id = id;
self.manifest = manifest;
self.zip_data = dotlottie;
}
Err(error) => {
eprintln!("Unable to initialize dotLottie manager: {}", error);
}
}

self.current_animation_id = id;
self.manifest = manifest;
self.zip_data = dotlottie;
}

/// Advances to the next animation and returns it's animation data as a string.
pub fn next_animation(&mut self) -> Result<String, DotLottieError> {
let mut i = 0;
let mut new_current_animation_id = self.current_animation_id.clone();
let animations = self.manifest.animations.lock().unwrap();
let animations = match self.manifest.animations.read() {
Ok(animations) => animations,
Err(_) => return Err(DotLottieError::MutexLockError),
};

// match animations {
// Ok(animations) => {
for anim in animations.iter() {
println!("Animation ID {}", anim.id);

if anim.id == self.current_animation_id {
// return Result::Ok(true);
if i + 1 < animations.len() {
self.current_animation_id = animations[i + 1].id.clone();

new_current_animation_id = animations[i + 1].id.clone();
std::mem::drop(animations);

println!("Found next animation : {}", new_current_animation_id);
std::mem::drop(animations);

return self.get_animation(&new_current_animation_id);
}
Expand All @@ -98,32 +119,30 @@ impl DotLottieManager {
/// Reverses to the previous animation and returns it's animation data as a string.
pub fn previous_animation(&mut self) -> Result<String, DotLottieError> {
let mut new_current_animation_id = self.current_animation_id.clone();
let animations = self.manifest.animations.lock().unwrap();
let animations = match self.manifest.animations.read() {
Ok(animations) => animations,
Err(_) => return Err(DotLottieError::MutexLockError),
};
let mut i = 0;

for anim in animations.iter() {
println!("Animation ID {}", anim.id);

if anim.id == self.current_animation_id {
// return Result::Ok(true);
if i > 0 {
self.current_animation_id = animations[i - 1].id.clone();

new_current_animation_id = animations[i - 1].id.clone();
std::mem::drop(animations);

println!("Found next animation : {}", new_current_animation_id);

return self.get_animation(&new_current_animation_id);
}
}
i += 1;
}

std::mem::drop(animations);

let current_animation_id = self.current_animation_id.clone();

println!("PREVIOUS ANIMATION ID {}", current_animation_id);
self.get_animation(&current_animation_id)
}

Expand All @@ -139,7 +158,7 @@ impl DotLottieManager {
return Result::Ok(cloned_animation);
}

if let Ok(animations) = self.manifest.animations.lock() {
if let Ok(animations) = self.manifest.animations.read() {
for anim in animations.iter() {
if &anim.id == animation_id {
self.animation_settings_cache
Expand All @@ -154,7 +173,7 @@ impl DotLottieManager {
}

pub fn contains_animation(&self, animation_id: &str) -> Result<bool, DotLottieError> {
if let Ok(animations) = self.manifest.animations.lock() {
if let Ok(animations) = self.manifest.animations.read() {
for anim in animations.iter() {
if anim.id == animation_id {
return Result::Ok(true);
Expand Down
30 changes: 5 additions & 25 deletions dotlottie-fms/src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ use std::io::{self, Read};
use std::path::Path;

use base64::{engine::general_purpose, Engine};
// use json::JsonValue;
use serde_json::{json, Value};
use serde_json::Value;
use zip::ZipArchive;

/// Extract a single animation with its image assets inlined.
///
/// bytes: The bytes of the dotLottie file
/// animation_id: The id of the animation to extract
/// Result<String, DotLottieError>: The extracted animation, or an error
/// Notes: This function uses jzon rather than serde as serde was exporting invalid JSON
pub fn get_animation(bytes: &Vec<u8>, animation_id: &str) -> Result<String, DotLottieError> {
let mut archive =
ZipArchive::new(io::Cursor::new(bytes)).map_err(|_| DotLottieError::ArchiveOpenError)?;
Expand All @@ -34,10 +34,9 @@ pub fn get_animation(bytes: &Vec<u8>, animation_id: &str) -> Result<String, DotL
// We can drop result so that we can use archive later, everything has been read in to content variable
drop(result);

let animation_data = String::from_utf8_lossy(&content).to_string();
let animation_data = String::from_utf8(content).unwrap();

// Untyped JSON value
// let mut lottie_animation: Value = serde_json::from_str(&animation_data).unwrap();
let mut lottie_animation = jzon::parse(&animation_data).unwrap();

// Loop through the parsed lottie animation and check for image assets
Expand Down Expand Up @@ -70,32 +69,13 @@ pub fn get_animation(bytes: &Vec<u8>, animation_id: &str) -> Result<String, DotL
// Write the image data to the lottie
let image_data_base64 = general_purpose::STANDARD.encode(&content);

// assets[i]["u"] = serde_json::Value::String("".to_string());
// assets[i]["p"] = serde_json::Value::String(
// format!("data:image/{};base64,{}", image_ext, image_data_base64).to_string(),
// );

assets[i]["u"] = "".into();
assets[i]["p"] =
format!("data:image/{};base64,{}", image_ext, image_data_base64).into();
}
}
}
// let mut ad = serde_json::to_string(&animation_data).unwrap();

// ad = ad.replace("\\", "");
// ad.remove(0);
// ad.remove(ad.len() - 1);

// Ok(ad)

// Ok(animation_data)

// Ok(lottie_animation.to_string())

// Ok(serde_json::to_string(&lottie_animation.clone()).unwrap())

//works
Ok(jzon::stringify(lottie_animation))
}

Expand All @@ -121,15 +101,15 @@ pub fn get_animations(bytes: &Vec<u8>) -> Result<Vec<Animation>, DotLottieError>
let animation = get_animation(bytes, file_stem_str).unwrap();

let item = Animation {
id: String::from(file.name()),
id: file_stem_str.to_string(),
animation_data: animation,
};

file_contents.push(item);
}
} else {
// Handle the case where the path has no file stem
println!("Invalid file path");
return Err(DotLottieError::ReadContentError);
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions dotlottie-fms/src/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ use json::{self, array, object};
use crate::{ManifestAnimation, ManifestThemes};
use serde::{Deserialize, Serialize};

use std::{fmt::Display, sync::Mutex};
use std::{fmt::Display, sync::RwLock};

#[derive(Debug, Serialize, Deserialize)]
pub struct Manifest {
pub active_animation_id: Option<String>,
pub animations: Mutex<Vec<ManifestAnimation>>,
pub animations: RwLock<Vec<ManifestAnimation>>,
pub author: Option<String>,
// pub custom: Option<record(string(), an>))>
pub description: Option<String>,
Expand All @@ -24,7 +24,7 @@ impl Manifest {
pub fn new() -> Self {
Self {
active_animation_id: None,
animations: Mutex::new(vec![]),
animations: RwLock::new(vec![]),
author: Some("LottieFiles".to_string()),
// custom,
description: None,
Expand All @@ -44,7 +44,7 @@ impl Manifest {
}

pub fn to_json(&self) -> json::JsonValue {
let animations_lock = self.animations.lock().unwrap();
let animations_lock = self.animations.read().unwrap();
let mut json = object! {
"activeAnimationId" => self.active_animation_id.clone(),
"animations" => animations_lock.iter().map(|animation| animation.to_json()).collect::<Vec<json::JsonValue>>(),
Expand Down
8 changes: 4 additions & 4 deletions dotlottie-fms/src/tests/dotlottie_manager/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fn get_animation_test() {

animation_file.read_to_end(&mut buffer).unwrap();

let dotlottie = DotLottieManager::new(Some(buffer));
let mut dotlottie = DotLottieManager::new(Some(buffer));

let mut anger_animation_file = File::open(anger_file_path).unwrap();
let mut anger_buffer = Vec::new();
Expand Down Expand Up @@ -61,8 +61,8 @@ fn get_animations_test() {

assert_eq!(animation.len(), 62);

assert_eq!(animation[0].id, "animations/anger.json");
assert_eq!(animation[5].id, "animations/confused.json");
assert_eq!(animation[0].id, "anger");
assert_eq!(animation[5].id, "confused");
}

#[test]
Expand All @@ -86,7 +86,7 @@ fn get_manifest_test() {
let manifest = dotlottie.manifest();

// First and last animations
let first_animation_lock = manifest.animations.lock().unwrap();
let first_animation_lock = manifest.animations.read().unwrap();

let first_animation = first_animation_lock.first().unwrap();

Expand Down
6 changes: 3 additions & 3 deletions dotlottie-fms/src/tests/functions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ fn get_animations_test() {

assert_eq!(animation.len(), 62);

assert_eq!(animation[0].id, "animations/anger.json");
assert_eq!(animation[5].id, "animations/confused.json");
assert_eq!(animation[0].id, "anger");
assert_eq!(animation[5].id, "confused");
}

#[test]
Expand All @@ -62,7 +62,7 @@ fn get_manifest_test() {
let manifest = crate::get_manifest(&buffer).unwrap();

// First and last animations
let first_animation_lock = manifest.animations.lock().unwrap();
let first_animation_lock = manifest.animations.read().unwrap();

let first_animation = first_animation_lock.first().unwrap();

Expand Down
6 changes: 3 additions & 3 deletions dotlottie-fms/src/tests/manifest/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ fn manifest_has_correct_default_values() {
#[test]
fn display() {
use json::object;
use std::sync::Mutex;
use std::sync::RwLock;

let mut animations: Vec<ManifestAnimation> = Vec::new();
let mut multi_animations: Vec<ManifestAnimation> = Vec::new();
Expand Down Expand Up @@ -68,7 +68,7 @@ fn display() {
let mut manifest = Manifest::new();
manifest.active_animation_id = Some("default_animation_id".to_string());
manifest.author = Some("test_author".to_string());
manifest.animations = Mutex::new(animations);
manifest.animations = RwLock::new(animations);

let dis = manifest.to_json();

Expand Down Expand Up @@ -102,7 +102,7 @@ fn display() {

let mut manifest_with_two_animations = Manifest::new();
manifest_with_two_animations.active_animation_id = Some("default_animation_id".to_string());
manifest_with_two_animations.animations = Mutex::new(multi_animations);
manifest_with_two_animations.animations = RwLock::new(multi_animations);
manifest_with_two_animations.author = Some("test_author".to_string());
manifest_with_two_animations.description = Some("Multi animation".to_string());
manifest_with_two_animations.generator = Some("dotLottie-utils".to_string());
Expand Down
Loading

0 comments on commit 7ab06c0

Please sign in to comment.