Skip to content

Commit

Permalink
✨ Improve progress UI, fix midi audiosync importer, other stuff?
Browse files Browse the repository at this point in the history
  • Loading branch information
ewen-lbh committed May 12, 2024
1 parent 1d8012d commit 7f5e886
Show file tree
Hide file tree
Showing 18 changed files with 366 additions and 168 deletions.
36 changes: 36 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ console = { version = "0.15.8", features = ["windows-console-colors"] }
backtrace = "0.3.71"
slug = "0.1.5"
roxmltree = "0.19.0"
strum = { version = "0.26.2", features = ["strum_macros"] }
strum_macros = "0.26.2"


[dev-dependencies]
Expand Down
41 changes: 19 additions & 22 deletions src/canvas.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use core::panic;
use std::{cmp, collections::HashMap, io::Write as _, ops::Range};
use std::{collections::HashMap, io::Write as _, ops::Range};

use anyhow::Result;
use itertools::Itertools as _;
Expand Down Expand Up @@ -63,6 +63,10 @@ impl Canvas {
}

pub fn layer(&mut self, name: &str) -> &mut Layer {
if !self.layer_exists(name) {
panic!("Layer {} does not exist", name);
}

self.layer_safe(name).unwrap()
}

Expand All @@ -72,7 +76,7 @@ impl Canvas {
}

self.layers.push(Layer::new(name));
self.layer(name)
self.layers.last_mut().unwrap()
}

pub fn layer_or_empty(&mut self, name: &str) -> &mut Layer {
Expand All @@ -96,25 +100,16 @@ impl Canvas {
/// puts this layer on top, and the others below, without changing their order
pub fn put_layer_on_top(&mut self, name: &str) {
self.ensure_layer_exists(name);
self.layers.sort_by(|a, _| {
if a.name == name {
cmp::Ordering::Less
} else {
cmp::Ordering::Greater
}
})
let target_index = self.layers.iter().position(|l| l.name == name).unwrap();
self.layers.swap(0, target_index)
}

/// puts this layer on bottom, and the others above, without changing their order
pub fn put_layer_on_bottom(&mut self, name: &str) {
self.ensure_layer_exists(name);
self.layers.sort_by(|a, _| {
if a.name == name {
cmp::Ordering::Greater
} else {
cmp::Ordering::Less
}
})
let target_index = self.layers.iter().position(|l| l.name == name).unwrap();
let last_index = self.layers.len() - 1;
self.layers.swap(last_index, target_index)
}

/// re-order layers. The first layer in the list will be on top, the last at the bottom
Expand Down Expand Up @@ -223,7 +218,7 @@ impl Canvas {
);
}
Layer {
object_sizes: self.object_sizes.clone(),
object_sizes: self.object_sizes,
name: name.to_string(),
objects,
_render_cache: None,
Expand Down Expand Up @@ -258,7 +253,7 @@ impl Canvas {
);
}
Layer {
object_sizes: self.object_sizes.clone(),
object_sizes: self.object_sizes,
name: layer_name.to_owned(),
objects,
_render_cache: None,
Expand Down Expand Up @@ -433,9 +428,11 @@ impl Canvas {
((resolution as f32 / aspect_ratio) as usize, resolution)
};

let mut spawned = std::process::Command::new("magick")
.args(["-background", "none"])
.args(["-size", &format!("{}x{}", width, height)])
let mut spawned = std::process::Command::new("resvg")
.args(["--background", "transparent"])
.args(["--width", &format!("{width}")])
.args(["--height", &format!("{height}")])
.args(["--resources-dir", "."])
.arg("-")
.arg(at)
.stdin(std::process::Stdio::piped())
Expand All @@ -462,7 +459,7 @@ impl Canvas {
}

pub fn aspect_ratio(&self) -> f32 {
return self.width() as f32 / self.height() as f32;
self.width() as f32 / self.height() as f32
}

pub fn remove_all_objects_in(&mut self, region: &Region) {
Expand Down
14 changes: 10 additions & 4 deletions src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ use std::{

use rand::Rng;
use serde::Deserialize;
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
#[derive(Debug, Clone, Copy, PartialEq)]
#[derive(Debug, Clone, Copy, PartialEq, EnumIter)]
pub enum Color {
Black,
White,
Expand Down Expand Up @@ -53,6 +55,10 @@ pub fn random_color(except: Option<Color>) -> Color {
*candidates[rand::thread_rng().gen_range(0..candidates.len())]
}

pub fn all_colors() -> Vec<Color> {
Color::iter().collect()
}

impl Default for Color {
fn default() -> Self {
Self::Black
Expand Down Expand Up @@ -160,7 +166,7 @@ impl ColorMapping {
pub fn from_css(content: &str) -> ColorMapping {
let mut mapping = ColorMapping::default();
for line in content.lines() {
mapping.from_css_line(&line);
mapping.from_css_line(line);
}
mapping
}
Expand Down Expand Up @@ -266,8 +272,8 @@ impl ColorMapping {
}

fn from_css_line(&mut self, line: &str) {
if let Some((name, value)) = line.trim().split_once(":") {
let value = value.trim().trim_end_matches(";").to_owned();
if let Some((name, value)) = line.trim().split_once(':') {
let value = value.trim().trim_end_matches(';').to_owned();
match name.trim() {
"black" => self.black = value,
"white" => self.white = value,
Expand Down
4 changes: 2 additions & 2 deletions src/fill.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ impl FillOperations for Fill {
match self {
Fill::Solid(color) => Fill::Translucent(*color, opacity),
Fill::Translucent(color, _) => Fill::Translucent(*color, opacity),
_ => self.clone(),
_ => *self,
}
}

Expand Down Expand Up @@ -143,7 +143,7 @@ impl Fill {
.set("viewBox", format!("0,0,{},{}", size, size))
.set(
"patternTransform",
format!("rotate({})", (angle.clone() - Angle(45.0)).degrees()),
format!("rotate({})", (*angle - Angle(45.0)).degrees()),
)
// https://stackoverflow.com/a/55104220/9943464
.add(
Expand Down
2 changes: 1 addition & 1 deletion src/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ impl Filter {
format!(
"filter-{}-{}",
self.name(),
self.parameter.to_string().replace(".", "_")
self.parameter.to_string().replace('.', "_")
)
}
}
Expand Down
24 changes: 16 additions & 8 deletions src/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ pub struct Layer {
pub _render_cache: Option<svg::node::element::Group>,
}

static DISABLE_CACHE: bool = true;

impl Layer {
pub fn new(name: &str) -> Self {
Layer {
Expand All @@ -35,16 +37,20 @@ impl Layer {
}

pub fn object(&mut self, name: &str) -> &mut ColoredObject {
self.objects.get_mut(name).unwrap()
self.safe_object(name).unwrap()
}

pub fn safe_object(&mut self, name: &str) -> Option<&mut ColoredObject> {
self.objects.get_mut(name)
}

// Flush the render cache.
pub fn flush(&mut self) -> () {
pub fn flush(&mut self) {
self._render_cache = None;
}

pub fn replace(&mut self, with: Layer) -> () {
self.objects = with.objects.clone();
pub fn replace(&mut self, with: Layer) {
self.objects.clone_from(&with.objects);
self.flush();
}

Expand All @@ -55,7 +61,7 @@ impl Layer {

pub fn paint_all_objects(&mut self, fill: Fill) {
for (_id, obj) in &mut self.objects {
obj.fill = Some(fill.clone());
obj.fill = Some(fill);
}
self.flush();
}
Expand Down Expand Up @@ -119,16 +125,18 @@ impl Layer {
cell_size: usize,
object_sizes: ObjectSizes,
) -> svg::node::element::Group {
if let Some(cached_svg) = &self._render_cache {
return cached_svg.clone();
if !DISABLE_CACHE {
if let Some(cached_svg) = &self._render_cache {
return cached_svg.clone();
}
}

let mut layer_group = svg::node::element::Group::new()
.set("class", "layer")
.set("data-layer", self.name.clone());

for (id, obj) in &self.objects {
layer_group = layer_group.add(obj.render(cell_size, object_sizes, &colormap, &id));
layer_group = layer_group.add(obj.render(cell_size, object_sizes, &colormap, id));
}

self._render_cache = Some(layer_group.clone());
Expand Down
18 changes: 11 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub use canvas::*;
pub use color::*;
pub use fill::*;
pub use filter::*;
use itertools::Itertools;
pub use layer::*;
pub use midi::MidiSynchronizer;
pub use objects::*;
Expand Down Expand Up @@ -59,7 +60,14 @@ impl<'a, C> Context<'a, C> {
pub fn stem(&self, name: &str) -> StemAtInstant {
let stems = &self.syncdata.stems;
if !stems.contains_key(name) {
panic!("No stem named {:?} found.", name);
panic!(
"No stem named {:?} found. Available stems:\n{}\n",
name,
stems
.keys()
.sorted()
.fold(String::new(), |acc, k| format!("{acc}\n\t{k}"))
);
}
StemAtInstant {
amplitude: *stems[name].amplitude_db.get(self.ms).unwrap_or(&0.0),
Expand All @@ -76,12 +84,8 @@ impl<'a, C> Context<'a, C> {
}
}

pub fn dump_stems(&self, to: PathBuf) -> Result<()> {
std::fs::create_dir_all(&to)?;
for (name, stem) in self.syncdata.stems.iter() {
fs::write(to.join(name), format!("{:?}", stem))?;
}
Ok(())
pub fn dump_syncdata(&self, to: PathBuf) -> Result<()> {
Ok(serde_cbor::to_writer(fs::File::create(to)?, self.syncdata)?)
}

pub fn marker(&self) -> String {
Expand Down
Loading

0 comments on commit 7f5e886

Please sign in to comment.