wip: refactor pt.34 (35e) more traits, fewer structs

This commit is contained in:
🪞👃🪞 2024-11-15 01:44:51 +01:00
parent cbbecc5aba
commit beca1a6ade
19 changed files with 361 additions and 379 deletions

View file

@ -0,0 +1,100 @@
use crate::*;
pub trait HasScenes<S: ArrangerSceneApi> {
fn scenes (&self) -> &Vec<S>;
fn scenes_mut (&mut self) -> &mut Vec<S>;
fn scene_default_name (&self) -> String {
format!("Scene {}", self.scenes().len() + 1)
}
fn scene_add (&mut self, name: Option<&str>, color: Option<ItemColor>)
-> Usually<&mut S>
{
let name = name.map_or_else(||self.scene_default_name(), |x|x.to_string());
let scene = ArrangerScene {
name: Arc::new(name.into()),
clips: vec![None;self.tracks().len()],
color: color.unwrap_or_else(||ItemColor::random()),
};
self.scenes_mut().push(scene);
let index = self.scenes().len() - 1;
Ok(&mut self.scenes_mut()[index])
}
fn scene_del (&mut self, index: usize) {
self.scenes_mut().remove(index);
}
}
#[derive(Clone, Debug)]
pub enum ArrangerSceneCommand {
Add,
Delete(usize),
RandomColor,
Play(usize),
Swap(usize, usize),
SetSize(usize),
SetZoom(usize),
}
//impl<T: ArrangerApi> Command<T> for ArrangerSceneCommand {
//fn execute (self, state: &mut T) -> Perhaps<Self> {
//match self {
//Self::Delete(index) => { state.scene_del(index); },
//_ => todo!()
//}
//Ok(None)
//}
//}
pub trait ArrangerSceneApi: Sized {
fn name () -> Arc<RwLock<String>>;
fn clips () -> Vec<Option<Arc<RwLock<Phrase>>>>;
fn color () -> ItemColor;
fn ppqs (scenes: &[Self], factor: usize) -> Vec<(usize, usize)> {
let mut total = 0;
if factor == 0 {
scenes.iter().map(|scene|{
let pulses = scene.pulses().max(PPQ);
total = total + pulses;
(pulses, total - pulses)
}).collect()
} else {
(0..=scenes.len()).map(|i|{
(factor*PPQ, factor*PPQ*i)
}).collect()
}
}
fn longest_name (scenes: &[Self]) -> usize {
scenes.iter().map(|s|s.name().read().unwrap().len()).fold(0, usize::max)
}
/// Returns the pulse length of the longest phrase in the scene
fn pulses (&self) -> usize {
self.clips().iter().fold(0, |a, p|{
a.max(p.as_ref().map(|q|q.read().unwrap().length).unwrap_or(0))
})
}
/// Returns true if all phrases in the scene are
/// currently playing on the given collection of tracks.
fn is_playing (&self, tracks: &[ArrangerTrack]) -> bool {
self.clips().iter().any(|clip|clip.is_some()) && self.clips.iter().enumerate()
.all(|(track_index, clip)|match clip {
Some(clip) => tracks
.get(track_index)
.map(|track|if let Some((_, Some(phrase))) = &track.player.phrase {
*phrase.read().unwrap() == *clip.read().unwrap()
} else {
false
})
.unwrap_or(false),
None => true
})
}
fn clip (&self, index: usize) -> Option<&Arc<RwLock<Phrase>>> {
match self.clips().get(index) { Some(Some(clip)) => Some(clip), _ => None }
}
}