Try to optimize
This commit is contained in:
@@ -85,6 +85,7 @@ struct SpectrumAnalyzer {
|
||||
fft: Arc<dyn rustfft::Fft<f32>>,
|
||||
window: [f32; FFT_SIZE],
|
||||
scratch: Vec<Complex<f32>>,
|
||||
fft_buf: Vec<Complex<f32>>,
|
||||
band_edges: [usize; NUM_BANDS + 1],
|
||||
}
|
||||
|
||||
@@ -114,6 +115,7 @@ impl SpectrumAnalyzer {
|
||||
fft,
|
||||
window,
|
||||
scratch: vec![Complex::default(); scratch_len],
|
||||
fft_buf: vec![Complex::default(); FFT_SIZE],
|
||||
band_edges,
|
||||
}
|
||||
}
|
||||
@@ -130,20 +132,19 @@ impl SpectrumAnalyzer {
|
||||
}
|
||||
|
||||
fn run_fft(&mut self, output: &SpectrumBuffer) {
|
||||
let mut buf: Vec<Complex<f32>> = (0..FFT_SIZE)
|
||||
.map(|i| {
|
||||
let idx = (self.pos + i) % FFT_SIZE;
|
||||
Complex::new(self.ring[idx] * self.window[i], 0.0)
|
||||
})
|
||||
.collect();
|
||||
for i in 0..FFT_SIZE {
|
||||
let idx = (self.pos + i) % FFT_SIZE;
|
||||
self.fft_buf[i] = Complex::new(self.ring[idx] * self.window[i], 0.0);
|
||||
}
|
||||
|
||||
self.fft.process_with_scratch(&mut buf, &mut self.scratch);
|
||||
self.fft
|
||||
.process_with_scratch(&mut self.fft_buf, &mut self.scratch);
|
||||
|
||||
let mut bands = [0.0f32; NUM_BANDS];
|
||||
for (band, mag) in bands.iter_mut().enumerate() {
|
||||
let lo = self.band_edges[band];
|
||||
let hi = self.band_edges[band + 1].max(lo + 1);
|
||||
let sum: f32 = buf[lo..hi].iter().map(|c| c.norm()).sum();
|
||||
let sum: f32 = self.fft_buf[lo..hi].iter().map(|c| c.norm()).sum();
|
||||
let avg = sum / (hi - lo) as f32;
|
||||
let amplitude = avg / (FFT_SIZE as f32 / 2.0);
|
||||
let db = 20.0 * amplitude.max(1e-10).log10();
|
||||
|
||||
@@ -93,17 +93,19 @@ pub struct ActivePatternState {
|
||||
pub iter: usize,
|
||||
}
|
||||
|
||||
pub type StepTracesMap = HashMap<(usize, usize, usize), ExecutionTrace>;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct SharedSequencerState {
|
||||
pub active_patterns: Vec<ActivePatternState>,
|
||||
pub step_traces: HashMap<(usize, usize, usize), ExecutionTrace>,
|
||||
pub step_traces: Arc<StepTracesMap>,
|
||||
pub event_count: usize,
|
||||
pub dropped_events: usize,
|
||||
}
|
||||
|
||||
pub struct SequencerSnapshot {
|
||||
pub active_patterns: Vec<ActivePatternState>,
|
||||
pub step_traces: HashMap<(usize, usize, usize), ExecutionTrace>,
|
||||
step_traces: Arc<StepTracesMap>,
|
||||
pub event_count: usize,
|
||||
pub dropped_events: usize,
|
||||
}
|
||||
@@ -146,7 +148,7 @@ impl SequencerHandle {
|
||||
let state = self.shared_state.load();
|
||||
SequencerSnapshot {
|
||||
active_patterns: state.active_patterns.clone(),
|
||||
step_traces: state.step_traces.clone(),
|
||||
step_traces: Arc::clone(&state.step_traces),
|
||||
event_count: state.event_count,
|
||||
dropped_events: state.dropped_events,
|
||||
}
|
||||
@@ -366,7 +368,6 @@ pub(crate) struct TickOutput {
|
||||
}
|
||||
|
||||
struct StepResult {
|
||||
audio_commands: Vec<String>,
|
||||
completed_iterations: Vec<PatternId>,
|
||||
any_step_fired: bool,
|
||||
}
|
||||
@@ -384,15 +385,44 @@ fn parse_chain_target(s: &str) -> Option<PatternId> {
|
||||
})
|
||||
}
|
||||
|
||||
struct KeyCache {
|
||||
speed_keys: [[String; MAX_PATTERNS]; MAX_BANKS],
|
||||
chain_keys: [[String; MAX_PATTERNS]; MAX_BANKS],
|
||||
}
|
||||
|
||||
impl KeyCache {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
speed_keys: std::array::from_fn(|bank| {
|
||||
std::array::from_fn(|pattern| format!("__speed_{bank}_{pattern}__"))
|
||||
}),
|
||||
chain_keys: std::array::from_fn(|bank| {
|
||||
std::array::from_fn(|pattern| format!("__chain_{bank}_{pattern}__"))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn speed_key(&self, bank: usize, pattern: usize) -> &str {
|
||||
&self.speed_keys[bank][pattern]
|
||||
}
|
||||
|
||||
fn chain_key(&self, bank: usize, pattern: usize) -> &str {
|
||||
&self.chain_keys[bank][pattern]
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct SequencerState {
|
||||
audio_state: AudioState,
|
||||
pattern_cache: PatternCache,
|
||||
runs_counter: RunsCounter,
|
||||
step_traces: HashMap<(usize, usize, usize), ExecutionTrace>,
|
||||
step_traces: Arc<StepTracesMap>,
|
||||
event_count: usize,
|
||||
dropped_events: usize,
|
||||
script_engine: ScriptEngine,
|
||||
variables: Variables,
|
||||
speed_overrides: HashMap<(usize, usize), f64>,
|
||||
key_cache: KeyCache,
|
||||
buf_audio_commands: Vec<String>,
|
||||
}
|
||||
|
||||
impl SequencerState {
|
||||
@@ -406,11 +436,14 @@ impl SequencerState {
|
||||
audio_state: AudioState::new(),
|
||||
pattern_cache: PatternCache::new(),
|
||||
runs_counter: RunsCounter::new(),
|
||||
step_traces: HashMap::new(),
|
||||
step_traces: Arc::new(HashMap::new()),
|
||||
event_count: 0,
|
||||
dropped_events: 0,
|
||||
script_engine,
|
||||
variables,
|
||||
speed_overrides: HashMap::new(),
|
||||
key_cache: KeyCache::new(),
|
||||
buf_audio_commands: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -459,7 +492,7 @@ impl SequencerState {
|
||||
self.audio_state.active_patterns.clear();
|
||||
self.audio_state.pending_starts.clear();
|
||||
self.audio_state.pending_stops.clear();
|
||||
self.step_traces.clear();
|
||||
Arc::make_mut(&mut self.step_traces).clear();
|
||||
self.runs_counter.counts.clear();
|
||||
}
|
||||
SeqCommand::Shutdown => {}
|
||||
@@ -491,7 +524,7 @@ impl SequencerState {
|
||||
self.audio_state.prev_beat = beat;
|
||||
|
||||
TickOutput {
|
||||
audio_commands: steps.audio_commands,
|
||||
audio_commands: std::mem::take(&mut self.buf_audio_commands),
|
||||
new_tempo: vars.new_tempo,
|
||||
shared_state: self.build_shared_state(),
|
||||
}
|
||||
@@ -500,13 +533,14 @@ impl SequencerState {
|
||||
fn tick_paused(&mut self) -> TickOutput {
|
||||
for pending in self.audio_state.pending_stops.drain(..) {
|
||||
self.audio_state.active_patterns.remove(&pending.id);
|
||||
self.step_traces.retain(|&(bank, pattern, _), _| {
|
||||
Arc::make_mut(&mut self.step_traces).retain(|&(bank, pattern, _), _| {
|
||||
bank != pending.id.bank || pattern != pending.id.pattern
|
||||
});
|
||||
}
|
||||
self.audio_state.pending_starts.clear();
|
||||
self.buf_audio_commands.clear();
|
||||
TickOutput {
|
||||
audio_commands: Vec::new(),
|
||||
audio_commands: std::mem::take(&mut self.buf_audio_commands),
|
||||
new_tempo: None,
|
||||
shared_state: self.build_shared_state(),
|
||||
}
|
||||
@@ -547,7 +581,7 @@ impl SequencerState {
|
||||
for pending in &self.audio_state.pending_stops {
|
||||
if check_quantization_boundary(pending.quantization, beat, prev_beat, quantum) {
|
||||
self.audio_state.active_patterns.remove(&pending.id);
|
||||
self.step_traces.retain(|&(bank, pattern, _), _| {
|
||||
Arc::make_mut(&mut self.step_traces).retain(|&(bank, pattern, _), _| {
|
||||
bank != pending.id.bank || pattern != pending.id.pattern
|
||||
});
|
||||
stopped.push(pending.id);
|
||||
@@ -565,32 +599,29 @@ impl SequencerState {
|
||||
fill: bool,
|
||||
nudge_secs: f64,
|
||||
) -> StepResult {
|
||||
self.buf_audio_commands.clear();
|
||||
let mut result = StepResult {
|
||||
audio_commands: Vec::new(),
|
||||
completed_iterations: Vec::new(),
|
||||
any_step_fired: false,
|
||||
};
|
||||
|
||||
let speed_overrides: HashMap<(usize, usize), f64> = {
|
||||
self.speed_overrides.clear();
|
||||
{
|
||||
let vars = self.variables.lock().unwrap();
|
||||
self.audio_state
|
||||
.active_patterns
|
||||
.keys()
|
||||
.filter_map(|id| {
|
||||
let key = format!("__speed_{}_{}__", id.bank, id.pattern);
|
||||
vars.get(&key)
|
||||
.and_then(|v| v.as_float().ok())
|
||||
.map(|v| ((id.bank, id.pattern), v))
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
for id in self.audio_state.active_patterns.keys() {
|
||||
let key = self.key_cache.speed_key(id.bank, id.pattern);
|
||||
if let Some(v) = vars.get(key).and_then(|v| v.as_float().ok()) {
|
||||
self.speed_overrides.insert((id.bank, id.pattern), v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (_id, active) in self.audio_state.active_patterns.iter_mut() {
|
||||
let Some(pattern) = self.pattern_cache.get(active.bank, active.pattern) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let speed_mult = speed_overrides
|
||||
let speed_mult = self.speed_overrides
|
||||
.get(&(active.bank, active.pattern))
|
||||
.copied()
|
||||
.unwrap_or_else(|| pattern.speed.multiplier());
|
||||
@@ -634,13 +665,13 @@ impl SequencerState {
|
||||
.script_engine
|
||||
.evaluate_with_trace(script, &ctx, &mut trace)
|
||||
{
|
||||
self.step_traces.insert(
|
||||
Arc::make_mut(&mut self.step_traces).insert(
|
||||
(active.bank, active.pattern, source_idx),
|
||||
std::mem::take(&mut trace),
|
||||
);
|
||||
for cmd in cmds {
|
||||
self.event_count += 1;
|
||||
result.audio_commands.push(cmd);
|
||||
self.buf_audio_commands.push(cmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -681,18 +712,18 @@ impl SequencerState {
|
||||
|
||||
let mut chain_transitions = Vec::new();
|
||||
for id in completed {
|
||||
let chain_key = format!("__chain_{}_{}__", id.bank, id.pattern);
|
||||
if let Some(Value::Str(s, _)) = vars.get(&chain_key) {
|
||||
let chain_key = self.key_cache.chain_key(id.bank, id.pattern);
|
||||
if let Some(Value::Str(s, _)) = vars.get(chain_key) {
|
||||
if let Some(target) = parse_chain_target(s) {
|
||||
chain_transitions.push((*id, target));
|
||||
}
|
||||
}
|
||||
vars.remove(&chain_key);
|
||||
vars.remove(chain_key);
|
||||
}
|
||||
|
||||
for id in stopped {
|
||||
let chain_key = format!("__chain_{}_{}__", id.bank, id.pattern);
|
||||
vars.remove(&chain_key);
|
||||
let chain_key = self.key_cache.chain_key(id.bank, id.pattern);
|
||||
vars.remove(chain_key);
|
||||
}
|
||||
|
||||
VariableReads {
|
||||
@@ -738,7 +769,7 @@ impl SequencerState {
|
||||
iter: a.iter,
|
||||
})
|
||||
.collect(),
|
||||
step_traces: self.step_traces.clone(),
|
||||
step_traces: Arc::clone(&self.step_traces),
|
||||
event_count: self.event_count,
|
||||
dropped_events: self.dropped_events,
|
||||
}
|
||||
|
||||
@@ -476,7 +476,7 @@ fn handle_modal_input(ctx: &mut InputContext, key: KeyEvent) -> InputResult {
|
||||
KeyCode::Char('p') if ctrl => {
|
||||
editor.search_prev();
|
||||
}
|
||||
KeyCode::Char('k') if ctrl => {
|
||||
KeyCode::Char('s') if ctrl => {
|
||||
ctx.app.editor_ctx.show_stack = !ctx.app.editor_ctx.show_stack;
|
||||
}
|
||||
KeyCode::Char('a') if ctrl => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::cell::RefCell;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use cagire_ratatui::Editor;
|
||||
@@ -55,6 +56,14 @@ pub struct EditorContext {
|
||||
pub selection_anchor: Option<usize>,
|
||||
pub copied_steps: Option<CopiedSteps>,
|
||||
pub show_stack: bool,
|
||||
pub stack_cache: RefCell<Option<StackCache>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct StackCache {
|
||||
pub cursor_line: usize,
|
||||
pub lines_hash: u64,
|
||||
pub result: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -96,6 +105,7 @@ impl Default for EditorContext {
|
||||
selection_anchor: None,
|
||||
copied_steps: None,
|
||||
show_stack: false,
|
||||
stack_cache: RefCell::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ pub mod ui;
|
||||
|
||||
pub use audio::{AudioSettings, DeviceKind, EngineSection, Metrics, SettingKind};
|
||||
pub use options::{OptionsFocus, OptionsState};
|
||||
pub use editor::{CopiedStepData, CopiedSteps, EditorContext, Focus, PatternField, PatternPropsField};
|
||||
pub use editor::{CopiedStepData, CopiedSteps, EditorContext, Focus, PatternField, PatternPropsField, StackCache};
|
||||
pub use live_keys::LiveKeyState;
|
||||
pub use modal::Modal;
|
||||
pub use panel::{PanelFocus, PanelState, SidePanel};
|
||||
|
||||
@@ -16,39 +16,90 @@ pub enum TokenKind {
|
||||
Note,
|
||||
Interval,
|
||||
Variable,
|
||||
Emit,
|
||||
Vary,
|
||||
Generator,
|
||||
Default,
|
||||
}
|
||||
|
||||
impl TokenKind {
|
||||
pub fn style(self) -> Style {
|
||||
match self {
|
||||
TokenKind::Number => Style::default().fg(Color::Rgb(255, 180, 100)),
|
||||
TokenKind::String => Style::default().fg(Color::Rgb(150, 220, 150)),
|
||||
TokenKind::Comment => Style::default().fg(Color::Rgb(100, 100, 100)),
|
||||
TokenKind::Keyword => Style::default().fg(Color::Rgb(220, 120, 220)),
|
||||
TokenKind::StackOp => Style::default().fg(Color::Rgb(120, 180, 220)),
|
||||
TokenKind::Operator => Style::default().fg(Color::Rgb(200, 200, 130)),
|
||||
TokenKind::Sound => Style::default().fg(Color::Rgb(100, 220, 200)),
|
||||
TokenKind::Param => Style::default().fg(Color::Rgb(180, 150, 220)),
|
||||
TokenKind::Context => Style::default().fg(Color::Rgb(220, 180, 120)),
|
||||
TokenKind::Note => Style::default().fg(Color::Rgb(120, 200, 160)),
|
||||
TokenKind::Interval => Style::default().fg(Color::Rgb(160, 200, 120)),
|
||||
TokenKind::Variable => Style::default().fg(Color::Rgb(200, 140, 180)),
|
||||
TokenKind::Default => Style::default().fg(Color::Rgb(200, 200, 200)),
|
||||
TokenKind::Emit => Style::default()
|
||||
.fg(Color::Rgb(255, 255, 255))
|
||||
.bg(Color::Rgb(140, 50, 50))
|
||||
.add_modifier(Modifier::BOLD),
|
||||
TokenKind::Number => Style::default()
|
||||
.fg(Color::Rgb(255, 200, 120))
|
||||
.bg(Color::Rgb(60, 40, 15)),
|
||||
TokenKind::String => Style::default()
|
||||
.fg(Color::Rgb(150, 230, 150))
|
||||
.bg(Color::Rgb(20, 55, 20)),
|
||||
TokenKind::Comment => Style::default()
|
||||
.fg(Color::Rgb(100, 100, 100))
|
||||
.bg(Color::Rgb(18, 18, 18)),
|
||||
TokenKind::Keyword => Style::default()
|
||||
.fg(Color::Rgb(230, 130, 230))
|
||||
.bg(Color::Rgb(55, 25, 55)),
|
||||
TokenKind::StackOp => Style::default()
|
||||
.fg(Color::Rgb(130, 190, 240))
|
||||
.bg(Color::Rgb(20, 40, 70)),
|
||||
TokenKind::Operator => Style::default()
|
||||
.fg(Color::Rgb(220, 220, 140))
|
||||
.bg(Color::Rgb(45, 45, 20)),
|
||||
TokenKind::Sound => Style::default()
|
||||
.fg(Color::Rgb(100, 240, 220))
|
||||
.bg(Color::Rgb(15, 60, 55)),
|
||||
TokenKind::Param => Style::default()
|
||||
.fg(Color::Rgb(190, 160, 240))
|
||||
.bg(Color::Rgb(45, 30, 70)),
|
||||
TokenKind::Context => Style::default()
|
||||
.fg(Color::Rgb(240, 190, 120))
|
||||
.bg(Color::Rgb(60, 45, 20)),
|
||||
TokenKind::Note => Style::default()
|
||||
.fg(Color::Rgb(120, 220, 170))
|
||||
.bg(Color::Rgb(20, 55, 40)),
|
||||
TokenKind::Interval => Style::default()
|
||||
.fg(Color::Rgb(170, 220, 120))
|
||||
.bg(Color::Rgb(35, 55, 20)),
|
||||
TokenKind::Variable => Style::default()
|
||||
.fg(Color::Rgb(220, 150, 190))
|
||||
.bg(Color::Rgb(60, 30, 50)),
|
||||
TokenKind::Vary => Style::default()
|
||||
.fg(Color::Rgb(230, 230, 100))
|
||||
.bg(Color::Rgb(55, 55, 15)),
|
||||
TokenKind::Generator => Style::default()
|
||||
.fg(Color::Rgb(100, 220, 180))
|
||||
.bg(Color::Rgb(15, 55, 45)),
|
||||
TokenKind::Default => Style::default()
|
||||
.fg(Color::Rgb(160, 160, 160))
|
||||
.bg(Color::Rgb(25, 25, 25)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn gap_style() -> Style {
|
||||
Style::default().bg(Color::Rgb(25, 25, 25))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Token {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub kind: TokenKind,
|
||||
pub varargs: bool,
|
||||
}
|
||||
|
||||
fn lookup_word_kind(word: &str) -> Option<TokenKind> {
|
||||
fn lookup_word_kind(word: &str) -> Option<(TokenKind, bool)> {
|
||||
if word == "." {
|
||||
return Some((TokenKind::Emit, false));
|
||||
}
|
||||
if word == ".!" {
|
||||
return Some((TokenKind::Emit, true));
|
||||
}
|
||||
|
||||
for w in WORDS {
|
||||
if w.name == word || w.aliases.contains(&word) {
|
||||
return Some(match &w.compile {
|
||||
let kind = match &w.compile {
|
||||
WordCompile::Param => TokenKind::Param,
|
||||
WordCompile::Context(_) => TokenKind::Context,
|
||||
_ => match w.category {
|
||||
@@ -58,9 +109,12 @@ fn lookup_word_kind(word: &str) -> Option<TokenKind> {
|
||||
TokenKind::Operator
|
||||
}
|
||||
"Sound" => TokenKind::Sound,
|
||||
"Randomness" | "Probability" | "Selection" => TokenKind::Vary,
|
||||
"Generator" => TokenKind::Generator,
|
||||
_ => TokenKind::Keyword,
|
||||
},
|
||||
});
|
||||
};
|
||||
return Some((kind, w.varargs));
|
||||
}
|
||||
}
|
||||
None
|
||||
@@ -98,11 +152,11 @@ pub fn tokenize_line(line: &str) -> Vec<Token> {
|
||||
}
|
||||
|
||||
if c == ';' && chars.peek().map(|(_, ch)| *ch) == Some(';') {
|
||||
// ;; starts a comment to end of line
|
||||
tokens.push(Token {
|
||||
start,
|
||||
end: line.len(),
|
||||
kind: TokenKind::Comment,
|
||||
varargs: false,
|
||||
});
|
||||
break;
|
||||
}
|
||||
@@ -119,6 +173,7 @@ pub fn tokenize_line(line: &str) -> Vec<Token> {
|
||||
start,
|
||||
end,
|
||||
kind: TokenKind::String,
|
||||
varargs: false,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@@ -133,35 +188,35 @@ pub fn tokenize_line(line: &str) -> Vec<Token> {
|
||||
}
|
||||
|
||||
let word = &line[start..end];
|
||||
let kind = classify_word(word);
|
||||
tokens.push(Token { start, end, kind });
|
||||
let (kind, varargs) = classify_word(word);
|
||||
tokens.push(Token { start, end, kind, varargs });
|
||||
}
|
||||
|
||||
tokens
|
||||
}
|
||||
|
||||
fn classify_word(word: &str) -> TokenKind {
|
||||
fn classify_word(word: &str) -> (TokenKind, bool) {
|
||||
if word.parse::<f64>().is_ok() || word.parse::<i64>().is_ok() {
|
||||
return TokenKind::Number;
|
||||
return (TokenKind::Number, false);
|
||||
}
|
||||
|
||||
if let Some(kind) = lookup_word_kind(word) {
|
||||
return kind;
|
||||
if let Some((kind, varargs)) = lookup_word_kind(word) {
|
||||
return (kind, varargs);
|
||||
}
|
||||
|
||||
if INTERVALS.contains(&word) {
|
||||
return TokenKind::Interval;
|
||||
return (TokenKind::Interval, false);
|
||||
}
|
||||
|
||||
if is_note(&word.to_ascii_lowercase()) {
|
||||
return TokenKind::Note;
|
||||
return (TokenKind::Note, false);
|
||||
}
|
||||
|
||||
if word.len() > 1 && (word.starts_with('@') || word.starts_with('!')) {
|
||||
return TokenKind::Variable;
|
||||
return (TokenKind::Variable, false);
|
||||
}
|
||||
|
||||
TokenKind::Default
|
||||
(TokenKind::Default, false)
|
||||
}
|
||||
|
||||
pub fn highlight_line(line: &str) -> Vec<(Style, String)> {
|
||||
@@ -179,13 +234,11 @@ pub fn highlight_line_with_runtime(
|
||||
|
||||
let executed_bg = Color::Rgb(40, 35, 50);
|
||||
let selected_bg = Color::Rgb(80, 60, 20);
|
||||
let gap_style = TokenKind::gap_style();
|
||||
|
||||
for token in tokens {
|
||||
if token.start > last_end {
|
||||
result.push((
|
||||
TokenKind::Default.style(),
|
||||
line[last_end..token.start].to_string(),
|
||||
));
|
||||
result.push((gap_style, line[last_end..token.start].to_string()));
|
||||
}
|
||||
|
||||
let is_selected = selected_spans
|
||||
@@ -196,6 +249,9 @@ pub fn highlight_line_with_runtime(
|
||||
.any(|span| overlaps(token.start, token.end, span.start, span.end));
|
||||
|
||||
let mut style = token.kind.style();
|
||||
if token.varargs {
|
||||
style = style.add_modifier(Modifier::UNDERLINED);
|
||||
}
|
||||
if is_selected {
|
||||
style = style.bg(selected_bg).add_modifier(Modifier::BOLD);
|
||||
} else if is_executed {
|
||||
@@ -207,7 +263,7 @@ pub fn highlight_line_with_runtime(
|
||||
}
|
||||
|
||||
if last_end < line.len() {
|
||||
result.push((TokenKind::Default.style(), line[last_end..].to_string()));
|
||||
result.push((gap_style, line[last_end..].to_string()));
|
||||
}
|
||||
|
||||
result
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Instant;
|
||||
|
||||
@@ -15,7 +17,7 @@ use crate::app::App;
|
||||
use crate::engine::{LinkState, SequencerSnapshot};
|
||||
use crate::model::{SourceSpan, StepContext, Value};
|
||||
use crate::page::Page;
|
||||
use crate::state::{FlashKind, Modal, PanelFocus, PatternField, SidePanel};
|
||||
use crate::state::{FlashKind, Modal, PanelFocus, PatternField, SidePanel, StackCache};
|
||||
use crate::views::highlight::{self, highlight_line, highlight_line_with_runtime};
|
||||
use crate::widgets::{
|
||||
ConfirmModal, ModalFrame, NavMinimap, NavTile, SampleBrowser, TextInputModal,
|
||||
@@ -25,43 +27,67 @@ use super::{
|
||||
dict_view, engine_view, help_view, main_view, options_view, patterns_view, title_view,
|
||||
};
|
||||
|
||||
fn compute_stack_display(lines: &[String], editor: &cagire_ratatui::Editor) -> String {
|
||||
fn compute_stack_display(lines: &[String], editor: &cagire_ratatui::Editor, cache: &std::cell::RefCell<Option<StackCache>>) -> String {
|
||||
let cursor_line = editor.cursor().0;
|
||||
|
||||
let mut hasher = DefaultHasher::new();
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
if i > cursor_line {
|
||||
break;
|
||||
}
|
||||
line.hash(&mut hasher);
|
||||
}
|
||||
let lines_hash = hasher.finish();
|
||||
|
||||
if let Some(ref c) = *cache.borrow() {
|
||||
if c.cursor_line == cursor_line && c.lines_hash == lines_hash {
|
||||
return c.result.clone();
|
||||
}
|
||||
}
|
||||
|
||||
let partial: Vec<&str> = lines.iter().take(cursor_line + 1).map(|s| s.as_str()).collect();
|
||||
let script = partial.join("\n");
|
||||
|
||||
if script.trim().is_empty() {
|
||||
return "Stack: []".to_string();
|
||||
}
|
||||
let result = if script.trim().is_empty() {
|
||||
"Stack: []".to_string()
|
||||
} else {
|
||||
let vars = Arc::new(Mutex::new(HashMap::new()));
|
||||
let dict = Arc::new(Mutex::new(HashMap::new()));
|
||||
let rng = Arc::new(Mutex::new(StdRng::seed_from_u64(42)));
|
||||
let forth = Forth::new(vars, dict, rng);
|
||||
|
||||
let vars = Arc::new(Mutex::new(HashMap::new()));
|
||||
let dict = Arc::new(Mutex::new(HashMap::new()));
|
||||
let rng = Arc::new(Mutex::new(StdRng::seed_from_u64(42)));
|
||||
let forth = Forth::new(vars, dict, rng);
|
||||
let ctx = StepContext {
|
||||
step: 0,
|
||||
beat: 0.0,
|
||||
bank: 0,
|
||||
pattern: 0,
|
||||
tempo: 120.0,
|
||||
phase: 0.0,
|
||||
slot: 0,
|
||||
runs: 0,
|
||||
iter: 0,
|
||||
speed: 1.0,
|
||||
fill: false,
|
||||
nudge_secs: 0.0,
|
||||
};
|
||||
|
||||
let ctx = StepContext {
|
||||
step: 0,
|
||||
beat: 0.0,
|
||||
bank: 0,
|
||||
pattern: 0,
|
||||
tempo: 120.0,
|
||||
phase: 0.0,
|
||||
slot: 0,
|
||||
runs: 0,
|
||||
iter: 0,
|
||||
speed: 1.0,
|
||||
fill: false,
|
||||
nudge_secs: 0.0,
|
||||
match forth.evaluate(&script, &ctx) {
|
||||
Ok(_) => {
|
||||
let stack = forth.stack();
|
||||
let formatted: Vec<String> = stack.iter().map(format_value).collect();
|
||||
format!("Stack: [{}]", formatted.join(" "))
|
||||
}
|
||||
Err(e) => format!("Error: {e}"),
|
||||
}
|
||||
};
|
||||
|
||||
match forth.evaluate(&script, &ctx) {
|
||||
Ok(_) => {
|
||||
let stack = forth.stack();
|
||||
let formatted: Vec<String> = stack.iter().map(format_value).collect();
|
||||
format!("Stack: [{}]", formatted.join(" "))
|
||||
}
|
||||
Err(e) => format!("Error: {e}"),
|
||||
}
|
||||
*cache.borrow_mut() = Some(StackCache {
|
||||
cursor_line,
|
||||
lines_hash,
|
||||
result: result.clone(),
|
||||
});
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn format_value(v: &Value) -> String {
|
||||
@@ -740,13 +766,13 @@ fn render_modal(frame: &mut Frame, app: &App, snapshot: &SequencerSnapshot, term
|
||||
]);
|
||||
frame.render_widget(Paragraph::new(hint).alignment(Alignment::Right), hint_area);
|
||||
} else if app.editor_ctx.show_stack {
|
||||
let stack_text = compute_stack_display(text_lines, &app.editor_ctx.editor);
|
||||
let stack_text = compute_stack_display(text_lines, &app.editor_ctx.editor, &app.editor_ctx.stack_cache);
|
||||
let hint = Line::from(vec![
|
||||
Span::styled("Esc", key),
|
||||
Span::styled(" save ", dim),
|
||||
Span::styled("C-e", key),
|
||||
Span::styled(" eval ", dim),
|
||||
Span::styled("C-k", key),
|
||||
Span::styled("C-s", key),
|
||||
Span::styled(" hide", dim),
|
||||
]);
|
||||
let [hint_left, stack_right] = Layout::horizontal([
|
||||
@@ -767,7 +793,7 @@ fn render_modal(frame: &mut Frame, app: &App, snapshot: &SequencerSnapshot, term
|
||||
Span::styled(" eval ", dim),
|
||||
Span::styled("C-f", key),
|
||||
Span::styled(" find ", dim),
|
||||
Span::styled("C-k", key),
|
||||
Span::styled("C-s", key),
|
||||
Span::styled(" stack ", dim),
|
||||
Span::styled("C-u", key),
|
||||
Span::styled("/", dim),
|
||||
|
||||
Reference in New Issue
Block a user