Passagen, Übungsmodus, Stimmfinder-Überarbeitung, Gerätedesign, Metronom und Akkorde

- Passagenwahl, Original-Kurve, Spulen/Üben und Pause
- Startseite, Klartext-Oberfläche, Stimmfinder mit Stimmtyp-Vorschlag
- Gerätedesign (Regler, Schalter, LED) und Metronom (frei/songsynchron, Tap)
- Akkorderkennung aus der Begleitung, Akkordleiste und -karte
- zweiter Song als Chart

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-31 13:38:27 +01:00
parent a5fdab8b49
commit 4112f88e54
29 changed files with 6367 additions and 622 deletions

View File

@ -168,16 +168,31 @@ impl App {
pub(super) fn calib_ui(&mut self, ui: &mut egui::Ui) {
self.calib_poll();
let cfg = self.config.calib.clone();
ui.heading("Latenzkalibrierung");
ui.heading("Mikrofon-Abgleich");
ui.label(
"Misst, wie lange ein Klick vom Ausgang bis in die Aufnahme braucht. Dieser Versatz wird beim \
Scoring und im Review abgezogen.",
);
ui.label(
"Aufbau: Kopfhörer mit der Hörmuschel direkt an die Mikrofonkapsel halten (oder Ausgang per \
Kabel auf den Eingang legen, Loopback). Im Raum möglichst ruhig, Eigenstimme/Direct-Monitoring \
aus. Der Eingangspegel unten sollte bei jedem Klick deutlich ausschlagen.",
egui::RichText::new(
"Damit die Wertung fair ist, misst die App einmal, wie lange der Ton von deinem Kopfhörer bis ins \
Mikrofon braucht. Das dauert etwa 20 Sekunden und muss nur einmal gemacht werden.",
)
.size(16.0)
.color(Color32::from_gray(225)),
);
ui.add_space(4.0);
ui.label("So geht’s:");
for l in [
"1 Setz die Kopfhörer auf und sorge für Ruhe im Raum.",
"2 Halte eine Hörmuschel direkt an das Mikrofon (oder verbinde Kopfhörer-Ausgang und Mikrofon-Eingang mit einem Kabel).",
"3 Klick auf „Messung starten“ und halte still. Du hörst zehn kurze Klicks.",
] {
ui.label(format!(" {l}"));
}
// Zeigt, ob das Mikrofon die Klicks hört.
let frac = ((self.peak_db + 60.0) / 60.0).clamp(0.0, 1.0);
ui.horizontal(|ui| {
ui.label("Das Mikrofon hört:");
super::gear::led_ladder(ui, frac, 26, 300.0);
ui.weak("Der Balken sollte bei jedem Klick deutlich ausschlagen.");
});
if let Some(e) = &self.engine {
// Während der Kalibrierung nur den Klick hören.
let s = &e.shared;
@ -211,7 +226,7 @@ impl App {
cfg.click_count
));
}
} else if ui.button("▶ Messung starten").clicked() {
} else if super::gear::accent_button(ui, "▶ Messung starten", 16.0, true).clicked() {
self.calib_start();
}
});
@ -239,14 +254,15 @@ impl App {
Color32::from_rgb(230, 100, 80),
),
Verdict::Implausible => (
"Versatz unplausibel; Aufbau prüfen und wiederholen.".to_string(),
"Die Verzögerung ist unplausibel; prüfe den Aufbau und wiederhole die Messung."
.to_string(),
Color32::from_rgb(230, 100, 80),
),
};
ui.colored_label(color, text);
if let (Some(o), Some(sp)) = (r.offset_ms, r.spread_ms) {
ui.label(
egui::RichText::new(format!("Versatz {o:.1} ms (Streuung ± {sp:.1} ms)"))
egui::RichText::new(format!("Verzögerung {o:.1} ms (Schwankung ± {sp:.1} ms)"))
.size(22.0)
.strong(),
);
@ -272,7 +288,7 @@ impl App {
if ui.add_enabled(usable, egui::Button::new(label)).clicked() {
self.calib.message =
Some(match self.calib_apply(r.verdict == Verdict::Unstable) {
Ok(o) => format!("Versatz {o:.1} ms gespeichert"),
Ok(o) => format!("Verzögerung {o:.1} ms gespeichert"),
Err(e) => e,
});
}
@ -281,20 +297,24 @@ impl App {
ui.separator();
ui.horizontal(|ui| {
ui.label("Aktueller Versatz");
ui.label("Aktuelle Verzögerung");
ui.add(
egui::DragValue::new(&mut self.config.audio.latency_offset_ms)
.range(0.0..=500.0)
.suffix(" ms")
.speed(0.5),
);
if ui.button("Speichern").clicked() {
if ui
.button("Speichern")
.on_hover_text("Speichert die Einstellung dauerhaft")
.clicked()
{
self.calib.message = Some(match self.config.save_to(&self.config_path) {
Ok(()) => "Config gespeichert".into(),
Err(e) => format!("Config speichern: {e:#}"),
});
}
if ui.button("Auf 0 setzen").clicked() {
if ui.button("Zurücksetzen").clicked() {
self.config.audio.latency_offset_ms = 0.0;
}
});
@ -307,7 +327,7 @@ mod tests {
use crate::config::Config;
fn test_app(name: &str) -> App {
let mut app = App::new(true, false, false);
let mut app = App::new(true, false, false, None);
let dir = std::env::temp_dir().join(format!(
"singtrainer-calibapp-{}-{name}",
std::process::id()

File diff suppressed because it is too large Load Diff

465
src/ui/gear.rs Normal file
View File

@ -0,0 +1,465 @@
//! Bedienelemente im Stil von Musikgeräten: Frontplatte mit Schrauben, Drehregler, Kippschalter mit LED,
//! LED-Pegelkette. Die Mathematik (Winkel, Ziehen, LED-Anzahl) ist rein und getestet.
use eframe::egui::{self, Align2, Color32, FontId, Rect, Response, Sense, Stroke, Ui, pos2, vec2};
/// Warmes Bernstein als Akzent (Beleuchtung, aktive Elemente).
pub const AMBER: Color32 = Color32::from_rgb(255, 176, 48);
pub const AMBER_DIM: Color32 = Color32::from_rgb(120, 78, 16);
pub const LED_GREEN: Color32 = Color32::from_rgb(90, 235, 120);
pub const LED_YELLOW: Color32 = Color32::from_rgb(245, 205, 60);
pub const LED_RED: Color32 = Color32::from_rgb(245, 80, 65);
/// Gehäuse- und Plattenfarben.
pub const CASE_BG: Color32 = Color32::from_rgb(24, 22, 20);
pub const PLATE_BG: Color32 = Color32::from_rgb(38, 35, 32);
pub const PLATE_EDGE: Color32 = Color32::from_rgb(78, 70, 62);
pub const ENGRAVING: Color32 = Color32::from_rgb(190, 175, 150);
const LED_OFF: Color32 = Color32::from_rgb(46, 44, 42);
/// Warmes, dunkles Geräte-Design für die ganze Oberfläche: Metall-Grau, Bernstein als Akzent.
pub fn apply_theme(ctx: &egui::Context) {
let mut v = egui::Visuals::dark();
v.panel_fill = CASE_BG;
v.window_fill = PLATE_BG;
v.extreme_bg_color = Color32::from_rgb(14, 13, 12);
v.faint_bg_color = Color32::from_rgb(32, 30, 28);
v.selection.bg_fill = AMBER_DIM;
v.selection.stroke = Stroke::new(1.0, AMBER);
v.hyperlink_color = AMBER;
let w = &mut v.widgets;
w.noninteractive.fg_stroke = Stroke::new(1.0, Color32::from_rgb(205, 195, 178));
let metal = Color32::from_rgb(58, 53, 48);
for (st, fill, fg) in [
(&mut w.inactive, metal, Color32::from_rgb(228, 218, 200)),
(
&mut w.hovered,
Color32::from_rgb(86, 76, 64),
Color32::from_rgb(255, 238, 205),
),
(&mut w.active, AMBER_DIM, Color32::WHITE),
] {
st.bg_fill = fill;
st.weak_bg_fill = fill;
st.fg_stroke = Stroke::new(1.0, fg);
st.bg_stroke = Stroke::new(1.0, PLATE_EDGE);
st.corner_radius = egui::CornerRadius::same(5);
}
ctx.set_visuals(v);
}
/// Hauptknopf im Geräte-Stil: leuchtendes Bernstein mit dunkler Schrift.
pub fn accent_button(ui: &mut Ui, text: &str, size: f32, enabled: bool) -> Response {
ui.add_enabled(
enabled,
egui::Button::new(
egui::RichText::new(text)
.size(size)
.strong()
.color(Color32::from_rgb(34, 22, 4)),
)
.fill(AMBER)
.stroke(Stroke::new(1.5, Color32::from_rgb(255, 214, 130)))
.min_size(vec2(190.0, 38.0)),
)
}
/// Winkel (Radiant, 0 = oben, im Uhrzeigersinn) für einen Reglerwert 0..=1: 270° Drehbereich von −135° bis +135°.
pub fn knob_angle(frac: f32) -> f32 {
(-135.0 + 270.0 * frac.clamp(0.0, 1.0)).to_radians()
}
/// Neuer Wert nach Ziehen: `dy_px` Pixel nach oben (positiv) bewegen den Regler; 200 px = voller Bereich,
/// mit `fine` zehnmal feiner. Ergebnis bleibt im Bereich.
pub fn knob_drag(value: f32, min: f32, max: f32, dy_px: f32, fine: bool) -> f32 {
let per_px = (max - min) / 200.0 * if fine { 0.1 } else { 1.0 };
(value + dy_px * per_px).clamp(min, max)
}
/// Anzahl leuchtender LEDs einer Kette mit `n` Segmenten bei Pegel `frac` (0..=1).
pub fn lit_segments(frac: f32, n: usize) -> usize {
(frac.clamp(0.0, 1.0) * n as f32).round() as usize
}
/// LED-Farbe für Segment `i` von `n`: unten grün, oben gelb, ganz oben rot.
pub fn segment_color(i: usize, n: usize) -> Color32 {
let f = i as f32 / n.max(1) as f32;
if f < 0.62 {
LED_GREEN
} else if f < 0.85 {
LED_YELLOW
} else {
LED_RED
}
}
fn dim(c: Color32, k: f32) -> Color32 {
c.gamma_multiply(k)
}
/// Frontplatte: dunkles Metall mit Rand, gravierter Überschrift und vier Schrauben.
pub fn panel<R>(ui: &mut Ui, title: &str, add: impl FnOnce(&mut Ui) -> R) -> R {
let frame = egui::Frame::new()
.fill(PLATE_BG)
.stroke(Stroke::new(1.5, PLATE_EDGE))
.corner_radius(8.0)
.inner_margin(egui::Margin::symmetric(14, 10));
let out = frame.show(ui, |ui| {
ui.label(
egui::RichText::new(title.to_uppercase())
.small()
.strong()
.color(ENGRAVING),
);
ui.add_space(2.0);
add(ui)
});
let r = out.response.rect;
for (x, y) in [(6.0, 6.0), (-6.0, 6.0), (6.0, -6.0), (-6.0, -6.0)] {
let c = pos2(
if x > 0.0 { r.left() + x } else { r.right() + x },
if y > 0.0 { r.top() + y } else { r.bottom() + y },
);
screw(ui.painter(), c);
}
out.inner
}
fn screw(p: &egui::Painter, c: egui::Pos2) {
p.circle_filled(c, 3.2, Color32::from_rgb(92, 86, 78));
p.circle_stroke(c, 3.2, Stroke::new(0.8, Color32::from_rgb(30, 28, 26)));
p.line_segment(
[c + vec2(-2.0, 0.5), c + vec2(2.0, -0.5)],
Stroke::new(1.0, Color32::from_rgb(40, 37, 33)),
);
}
/// Eine LED (leuchtend mit Schein oder dunkel).
pub fn led(p: &egui::Painter, c: egui::Pos2, on: bool, color: Color32, r: f32) {
if on {
p.circle_filled(c, r * 2.0, dim(color, 0.18));
p.circle_filled(c, r, color);
p.circle_filled(
c - vec2(r * 0.3, r * 0.3),
r * 0.35,
Color32::from_white_alpha(150),
);
} else {
p.circle_filled(c, r, LED_OFF);
p.circle_stroke(c, r, Stroke::new(0.8, Color32::from_rgb(20, 19, 18)));
}
}
/// Drehregler mit Beschriftung. Ziehen (hoch/runter) oder Mausrad ändert den Wert (Umschalt = fein),
/// Doppelklick setzt auf `default` zurück. `show` formatiert den Wert für die Anzeige beim Bedienen.
pub fn knob(
ui: &mut Ui,
value: &mut f32,
(min, max): (f32, f32),
default: f32,
label: &str,
show: impl Fn(f32) -> String,
enabled: bool,
) -> Response {
const SIZE: f32 = 64.0;
let width = SIZE.max(
ui.fonts_mut(|f| {
f.layout_no_wrap(
label.to_string(),
FontId::proportional(13.0),
Color32::WHITE,
)
.size()
.x
}) + 6.0,
);
let (rect, mut resp) = ui.allocate_exact_size(
vec2(width, SIZE + 34.0),
if enabled {
Sense::click_and_drag()
} else {
Sense::hover()
},
);
if enabled {
let fine = ui.input(|i| i.modifiers.shift);
if resp.dragged() {
*value = knob_drag(*value, min, max, -resp.drag_delta().y, fine);
resp.mark_changed();
}
if resp.hovered() {
let scroll = ui.input(|i| i.smooth_scroll_delta.y);
if scroll != 0.0 {
*value = knob_drag(*value, min, max, scroll * 0.5, fine);
resp.mark_changed();
}
}
if resp.double_clicked() {
*value = default.clamp(min, max);
resp.mark_changed();
}
}
let frac = if max > min {
(*value - min) / (max - min)
} else {
0.0
};
let p = ui.painter_at(rect);
let c = pos2(rect.center().x, rect.top() + SIZE / 2.0 + 2.0);
let alpha = if enabled { 1.0 } else { 0.4 };
// Skala: 11 Striche, bis zum Wert beleuchtet.
for i in 0..=10 {
let f = i as f32 / 10.0;
let a = knob_angle(f);
let (s, co) = a.sin_cos();
let (r0, r1) = (
SIZE / 2.0 + 1.0,
SIZE / 2.0 + if i % 5 == 0 { 7.0 } else { 5.0 },
);
let lit = f <= frac + 0.001 && frac > 0.0;
p.line_segment(
[c + vec2(s * r0, -co * r0), c + vec2(s * r1, -co * r1)],
Stroke::new(
2.0,
dim(
if lit {
AMBER
} else {
Color32::from_rgb(70, 64, 56)
},
alpha,
),
),
);
}
// Reglerkörper: Rand, Fläche, Glanz.
let hot = resp.hovered() || resp.dragged();
p.circle_filled(c, SIZE / 2.0 - 2.0, Color32::from_rgb(20, 19, 18));
p.circle_filled(
c,
SIZE / 2.0 - 5.0,
dim(Color32::from_rgb(70, 66, 62), alpha),
);
p.circle_filled(
c,
SIZE / 2.0 - 9.0,
dim(Color32::from_rgb(54, 50, 47), alpha),
);
p.circle_filled(
c - vec2(6.0, 8.0),
SIZE / 2.0 - 22.0,
Color32::from_white_alpha(if hot { 14 } else { 8 }),
);
let a = knob_angle(frac);
let (s, co) = a.sin_cos();
p.line_segment(
[
c + vec2(s * 8.0, -co * 8.0),
c + vec2(s * (SIZE / 2.0 - 8.0), -co * (SIZE / 2.0 - 8.0)),
],
Stroke::new(3.5, dim(AMBER, alpha)),
);
// Beschriftung, darunter der Wert (nur beim Bedienen/Überfahren, sonst Platz freihalten).
p.text(
pos2(rect.center().x, rect.bottom() - 22.0),
Align2::CENTER_CENTER,
label,
FontId::proportional(13.0),
dim(ENGRAVING, alpha),
);
p.text(
pos2(rect.center().x, rect.bottom() - 6.0),
Align2::CENTER_CENTER,
if hot { show(*value) } else { String::new() },
FontId::monospace(12.0),
AMBER,
);
resp.on_hover_text(format!(
"{label}: ziehen oder Mausrad (Umschalt = fein), Doppelklick = zurücksetzen"
))
}
/// Kippschalter mit LED und Beschriftung; Klick schaltet um.
pub fn toggle(ui: &mut Ui, on: &mut bool, label: &str, enabled: bool) -> Response {
let text_w = ui.fonts_mut(|f| {
f.layout_no_wrap(
label.to_string(),
FontId::proportional(14.0),
Color32::WHITE,
)
.size()
.x
});
let (rect, mut resp) = ui.allocate_exact_size(
vec2(text_w + 78.0, 34.0),
if enabled {
Sense::click()
} else {
Sense::hover()
},
);
if enabled && resp.clicked() {
*on = !*on;
resp.mark_changed();
}
let p = ui.painter_at(rect);
let alpha = if enabled { 1.0 } else { 0.4 };
let y = rect.center().y;
led(
&p,
pos2(rect.left() + 8.0, y),
*on && enabled,
LED_GREEN,
4.0,
);
// Wippe: Gehäuse und Hebel, der sich nach rechts/links neigt.
let body = Rect::from_center_size(pos2(rect.left() + 42.0, y), vec2(34.0, 18.0));
p.rect_filled(body, 9.0, Color32::from_rgb(16, 15, 14));
p.rect_stroke(
body,
9.0,
Stroke::new(1.0, PLATE_EDGE),
egui::StrokeKind::Inside,
);
let knob_x = if *on {
body.right() - 9.0
} else {
body.left() + 9.0
};
p.circle_filled(
pos2(knob_x, y),
7.0,
dim(
if *on {
AMBER
} else {
Color32::from_rgb(120, 114, 106)
},
alpha,
),
);
p.circle_filled(
pos2(knob_x - 2.0, y - 2.0),
2.2,
Color32::from_white_alpha(120),
);
p.text(
pos2(rect.left() + 66.0, y),
Align2::LEFT_CENTER,
label,
FontId::proportional(14.0),
dim(Color32::from_gray(225), alpha),
);
resp
}
/// Kleines Display: dunkles Glas mit leuchtender Schrift und kleiner Beschriftung.
pub fn lcd(ui: &mut Ui, text: &str, caption: &str, color: Color32, width: f32) -> Response {
let (rect, resp) = ui.allocate_exact_size(vec2(width, 58.0), Sense::hover());
let p = ui.painter_at(rect);
p.rect_filled(rect, 5.0, Color32::from_rgb(10, 13, 11));
p.rect_stroke(
rect,
5.0,
Stroke::new(1.5, PLATE_EDGE),
egui::StrokeKind::Inside,
);
p.text(
rect.left_top() + vec2(8.0, 9.0),
Align2::LEFT_CENTER,
caption.to_uppercase(),
FontId::proportional(11.0),
color.gamma_multiply(0.75),
);
let pos = rect.left_center() + vec2(10.0, 8.0);
p.text(
pos,
Align2::LEFT_CENTER,
text,
FontId::monospace(30.0),
color.gamma_multiply(0.3),
);
p.text(
pos,
Align2::LEFT_CENTER,
text,
FontId::monospace(30.0),
color,
);
resp
}
/// Waagerechte LED-Pegelkette (`frac` 0..=1) aus `n` Segmenten.
pub fn led_ladder(ui: &mut Ui, frac: f32, n: usize, width: f32) -> Response {
let (rect, resp) = ui.allocate_exact_size(vec2(width, 16.0), Sense::hover());
let p = ui.painter_at(rect);
let lit = lit_segments(frac, n);
let step = rect.width() / n as f32;
for i in 0..n {
let cx = rect.left() + (i as f32 + 0.5) * step;
led(
&p,
pos2(cx, rect.center().y),
i < lit,
segment_color(i, n),
(step * 0.32).clamp(2.0, 5.0),
);
}
resp
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn knob_angle_spans_270_degrees_centered_on_top() {
assert!((knob_angle(0.0).to_degrees() + 135.0).abs() < 1e-3);
assert!(knob_angle(0.5).abs() < 1e-6, "Mitte zeigt nach oben");
assert!((knob_angle(1.0).to_degrees() - 135.0).abs() < 1e-3);
assert_eq!(knob_angle(-3.0), knob_angle(0.0));
assert_eq!(knob_angle(9.0), knob_angle(1.0));
}
#[test]
fn knob_drag_scales_clamps_and_has_a_fine_mode() {
// 200 Pixel nach oben = voller Bereich.
assert!((knob_drag(0.0, 0.0, 1.0, 200.0, false) - 1.0).abs() < 1e-6);
assert!((knob_drag(0.5, 0.0, 1.0, 50.0, false) - 0.75).abs() < 1e-6);
assert!(
(knob_drag(0.5, 0.0, 1.0, -50.0, false) - 0.25).abs() < 1e-6,
"nach unten = leiser"
);
assert!(
(knob_drag(0.5, 0.0, 1.0, 50.0, true) - 0.525).abs() < 1e-6,
"fein: ein Zehntel"
);
assert_eq!(knob_drag(0.9, 0.0, 1.0, 500.0, false), 1.0, "oben begrenzt");
assert_eq!(
knob_drag(0.1, 0.0, 1.0, -500.0, false),
0.0,
"unten begrenzt"
);
assert!(
(knob_drag(10.0, 0.0, 100.0, 100.0, false) - 60.0).abs() < 1e-4,
"andere Bereiche"
);
}
#[test]
fn led_ladder_counts_and_colors() {
assert_eq!(lit_segments(0.0, 20), 0);
assert_eq!(lit_segments(1.0, 20), 20);
assert_eq!(lit_segments(0.5, 20), 10);
assert_eq!(lit_segments(2.0, 20), 20, "begrenzt");
assert_eq!(lit_segments(-1.0, 20), 0);
assert_eq!(segment_color(0, 20), LED_GREEN);
assert_eq!(segment_color(14, 20), LED_YELLOW);
assert_eq!(segment_color(19, 20), LED_RED);
// Nur das obere Ende ist rot, der größte Teil grün.
let reds = (0..20).filter(|&i| segment_color(i, 20) == LED_RED).count();
let greens = (0..20)
.filter(|&i| segment_color(i, 20) == LED_GREEN)
.count();
assert!(reds <= 4 && greens >= 11, "rot {reds}, grün {greens}");
}
}

305
src/ui/home_view.rs Normal file
View File

@ -0,0 +1,305 @@
//! Startseite (Willkommen, Checkliste, große Aktionen) und Einstellungen (Geräte, Pegel, Technisches).
use super::{App, FLOOR_DB, Mode, device_combo, list_devices};
use crate::config::Config;
use eframe::egui::{self, Color32, RichText, vec2};
use std::sync::atomic::Ordering;
/// Ab diesem Spitzenpegel (dBFS) gilt das Mikrofon als „hört etwas“.
const HEARING_DB: f32 = -48.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum MicStatus {
/// Simulationsmodus ohne Audio.
Simulation,
/// Kein Eingang geöffnet (kein Gerät gefunden oder nicht erreichbar).
NotFound,
/// Eingang offen, aber (noch) kein Signal.
Silent,
/// Eingang offen und Signal vorhanden.
Hearing,
}
pub(super) fn mic_status(has_input: bool, sim: bool, peak_db: f32) -> MicStatus {
if sim {
MicStatus::Simulation
} else if !has_input {
MicStatus::NotFound
} else if peak_db > HEARING_DB {
MicStatus::Hearing
} else {
MicStatus::Silent
}
}
impl MicStatus {
/// Aussage in einfachen Worten.
pub(super) fn text(self) -> &'static str {
match self {
MicStatus::Simulation => "Testmodus ohne Mikrofon",
MicStatus::NotFound => {
"Kein Mikrofon gefunden – wähle unter „Einstellungen“ dein Mikrofon aus"
}
MicStatus::Silent => {
"Mikrofon bereit – sprich oder summe kurz, dann sehe ich, ob es dich hört"
}
MicStatus::Hearing => "Mikrofon hört dich",
}
}
fn ok(self) -> Option<bool> {
match self {
MicStatus::Hearing => Some(true),
MicStatus::NotFound => Some(false),
_ => None,
}
}
}
/// Eine Zeile der Checkliste.
struct CheckItem {
/// `Some(true)` erledigt, `Some(false)` Problem, `None` offen/neutral.
done: Option<bool>,
title: &'static str,
text: String,
action: Option<(&'static str, Mode)>,
}
impl App {
fn mic_status_now(&self) -> MicStatus {
mic_status(
self.engine.as_ref().is_some_and(|e| e.input_rate.is_some()),
self.sim_start.is_some(),
self.peak_db,
)
}
pub(super) fn home_ui(&mut self, ui: &mut egui::Ui) {
let mut go: Option<Mode> = None;
ui.add_space(6.0);
ui.label(RichText::new("Willkommen!").size(32.0).strong());
ui.label(
RichText::new("Hier kannst du singen üben, deine Stimme finden und sehen, wie du dich verbesserst.")
.size(17.0)
.color(Color32::from_gray(225)),
);
ui.add_space(12.0);
let mic = self.mic_status_now();
let voice = self
.active_profile()
.and_then(crate::voice::classify::classify)
.map(|c| c.best.name());
let calibrated = self.config.audio.latency_offset_ms > 0.5;
let items = [
CheckItem {
done: mic.ok(),
title: "Mikrofon",
text: mic.text().to_string(),
action: (mic == MicStatus::NotFound).then_some(("Einstellungen öffnen", Mode::Settings)),
},
CheckItem {
done: None,
title: "Kopfhörer",
text: "Tipp: Sing mit Kopfhörern, damit die Musik nicht ins Mikrofon läuft.".to_string(),
action: None,
},
CheckItem {
done: Some(voice.is_some()),
title: "Deine Stimme",
text: voice.map_or(
"Noch nicht gemessen – dauert etwa 5 Minuten und zeigt, welcher Stimmtyp du bist.".to_string(),
|t| format!("Dein Stimmtyp: {t}."),
),
action: Some((if voice.is_some() { "Neu messen" } else { "Jetzt messen" }, Mode::Voice)),
},
CheckItem {
done: Some(calibrated),
title: "Mikrofon-Abgleich",
text: if calibrated {
format!("Erledigt (Verzögerung {:.0} ms).", self.config.audio.latency_offset_ms)
} else {
"Noch nicht gemacht – dauert 20 Sekunden und macht die Wertung fairer.".to_string()
},
action: Some((if calibrated { "Wiederholen" } else { "Jetzt abgleichen" }, Mode::Calib)),
},
];
super::gear::panel(ui, "Bist du bereit?", |ui| {
for it in &items {
ui.horizontal(|ui| {
let (mark, color) = match it.done {
Some(true) => ("✓", Color32::from_rgb(90, 210, 120)),
Some(false) => ("○", Color32::from_gray(150)),
None => ("•", Color32::from_gray(150)),
};
// Nicht bestandene Prüfung (Mikrofon fehlt) fällt auf.
let color = if it.done == Some(false) && it.title == "Mikrofon" {
Color32::from_rgb(240, 130, 60)
} else {
color
};
ui.label(RichText::new(mark).size(18.0).color(color));
ui.label(RichText::new(it.title).strong().size(16.0));
ui.label(&it.text);
if let Some((label, mode)) = it.action
&& ui.button(label).clicked()
{
go = Some(mode);
}
});
}
});
ui.add_space(14.0);
ui.label(RichText::new("Was möchtest du tun?").size(20.0).strong());
ui.add_space(4.0);
let actions = [
(
"Einen Song singen",
"Sing mit der Musik mit und sieh, wie genau du die Töne triffst.",
Mode::Chart,
),
(
"Stimme finden",
"Finde heraus, welcher Stimmtyp du bist und wo du am bequemsten singst.",
Mode::Voice,
),
(
"Töne üben",
"Summe oder singe einen Ton – ich zeige dir sofort, welcher es ist.",
Mode::Tuner,
),
];
ui.columns(3, |cols| {
for (col, (title, text, mode)) in cols.iter_mut().zip(actions) {
let w = col.available_width();
col.vertical(|ui| {
// Große Metalltaste mit beleuchteter Beschriftung.
let r = ui.add(
egui::Button::new(
RichText::new(title)
.size(22.0)
.strong()
.color(super::gear::AMBER),
)
.fill(Color32::from_rgb(52, 47, 42))
.stroke(egui::Stroke::new(2.0, super::gear::AMBER_DIM))
.min_size(vec2(w, 74.0)),
);
if r.clicked() {
go = Some(mode);
}
ui.label(RichText::new(text).color(Color32::from_gray(200)));
});
}
});
ui.add_space(10.0);
if ui
.button("Meine bisherigen Songs und Ergebnisse ansehen")
.clicked()
{
go = Some(Mode::History);
}
if let Some(m) = go {
self.mode = m;
}
}
pub(super) fn settings_ui(&mut self, ui: &mut egui::Ui, dt: f32) {
ui.add_space(4.0);
ui.heading("Einstellungen");
let mic = self.mic_status_now();
ui.label(RichText::new(mic.text()).size(16.0));
ui.add_space(4.0);
let frac = ((self.peak_db - FLOOR_DB) / -FLOOR_DB).clamp(0.0, 1.0);
super::gear::panel(ui, "Mikrofon-Pegel", |ui| {
super::gear::led_ladder(ui, frac, 30, 420.0);
});
ui.separator();
let mut changed = false;
changed |= device_combo(
ui,
"Mikrofon",
&self.devices.inputs,
&mut self.config.audio.input_device,
);
changed |= device_combo(
ui,
"Kopfhörer / Lautsprecher",
&self.devices.outputs,
&mut self.config.audio.output_device,
);
ui.horizontal(|ui| {
if ui.button("Geräte neu suchen").clicked() {
self.devices = list_devices();
}
if ui.button("Einstellungen speichern").clicked() {
self.config.ui.reference_midi = self.ref_midi;
self.messages = match self.config.save_to(&self.config_path) {
Ok(()) => vec!["Einstellungen gespeichert.".to_string()],
Err(e) => vec![format!("Speichern fehlgeschlagen: {e:#}")],
};
}
});
if changed {
self.restart();
}
egui::CollapsingHeader::new("Erweitert (nur bei Problemen)").show(ui, |ui| {
ui.horizontal(|ui| {
ui.label("Abtastrate in Hz (leer = automatisch)");
ui.add(egui::TextEdit::singleline(&mut self.sample_rate_text).desired_width(70.0));
ui.label("Puffergröße (leer = automatisch)");
ui.add(egui::TextEdit::singleline(&mut self.buffer_text).desired_width(70.0));
});
if ui.button("Audio neu starten").clicked() {
self.restart();
}
let (rate_in, rate_out, xruns) = self.engine.as_ref().map_or((None, None, 0), |e| {
(
e.input_rate,
e.output_rate,
e.shared.xruns.load(Ordering::Relaxed),
)
});
ui.weak(format!(
"Mikrofon {} Hz · Ausgabe {} Hz · Aussetzer {} · {:.0} Bilder/s · Pegel {:.0} dB",
rate_in.map_or("–".into(), |r| r.to_string()),
rate_out.map_or("–".into(), |r| r.to_string()),
xruns,
1.0 / dt.max(1e-4),
self.peak_db.max(FLOOR_DB)
));
ui.weak(format!("Einstellungsdatei: {}", Config::path().display()));
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mic_status_covers_all_cases() {
assert_eq!(mic_status(false, true, -60.0), MicStatus::Simulation);
assert_eq!(mic_status(false, false, -60.0), MicStatus::NotFound);
assert_eq!(mic_status(true, false, -60.0), MicStatus::Silent);
assert_eq!(mic_status(true, false, -20.0), MicStatus::Hearing);
assert_eq!(
mic_status(true, false, HEARING_DB),
MicStatus::Silent,
"genau auf der Schwelle: noch still"
);
for s in [
MicStatus::Simulation,
MicStatus::NotFound,
MicStatus::Silent,
MicStatus::Hearing,
] {
assert!(s.text().len() > 10);
}
assert_eq!(MicStatus::Hearing.ok(), Some(true));
assert_eq!(MicStatus::NotFound.ok(), Some(false));
assert_eq!(MicStatus::Silent.ok(), None);
}
}

369
src/ui/metro_view.rs Normal file
View File

@ -0,0 +1,369 @@
//! Metronom-Bedienung: Tempo-Display, Regler, Taktwahl, Tap-Tempo, LED-Schlaganzeige.
use super::gear::{AMBER, LED_RED, knob, lcd, led, panel, toggle};
use super::{App, Mode};
use crate::audio::metronome::tap_bpm;
use crate::audio::store_f32;
use eframe::egui::{self, Sense, pos2, vec2};
use std::sync::atomic::Ordering;
use std::time::Instant;
/// Dauer, in der eine LED nach einem Klick nachleuchtet.
const FLASH_S: f32 = 0.16;
/// Bereich des Tempo-Reglers (BPM).
const BPM_RANGE: (f32, f32) = (40.0, 220.0);
pub(super) struct MetroState {
pub on: bool,
pub bpm: f32,
pub beats: u32,
pub volume: f32,
/// Zeitpunkte (egui-Sekunden) der Tipps für das Tap-Tempo.
taps: Vec<f64>,
/// Zuletzt gesehene Klickzahl der Engine und Zeitpunkt/Taktposition des letzten Klicks.
seen: u32,
flash_at: Option<Instant>,
beat_shown: u32,
/// Simulation ohne Audio: Start der Anzeige-Uhr und zuletzt angezeigter Schlag.
sim_start: Option<Instant>,
sim_idx: i64,
}
impl MetroState {
pub fn new() -> Self {
Self {
on: false,
bpm: 100.0,
beats: 4,
volume: 0.5,
taps: Vec::new(),
seen: 0,
flash_at: None,
beat_shown: 0,
sim_start: None,
sim_idx: -1,
}
}
}
/// Helligkeit (0..=1) einer LED `elapsed` Sekunden nach dem Klick.
pub(super) fn flash_level(elapsed_s: f32) -> f32 {
(1.0 - elapsed_s / FLASH_S).clamp(0.0, 1.0)
}
impl App {
/// Tempo und Synchronität des Metronoms: Im Tab „Singen“ gibt ein Chart mit Tempo (`bpm`) den Takt vor und
/// das Metronom läuft mit der Wiedergabe (inkl. Einzähler); sonst gilt das eigene Tempo, frei laufend.
pub(super) fn effective_metronome(&self) -> (f32, bool) {
let chart_bpm = (self.mode == Mode::Chart)
.then(|| self.chart.as_ref().and_then(|c| c.bpm))
.flatten();
let playing = self
.session
.as_ref()
.is_some_and(|s| s.phase == crate::session::Phase::Running && !s.is_paused())
|| self.practice.as_ref().is_some_and(|p| p.playing);
match chart_bpm {
Some(b) => (b as f32, playing),
None => (self.metro.bpm, false),
}
}
/// Jedes Bild: Parameter an die Engine, LED-Zustand aus dem Klickzähler (bzw. der Anzeige-Uhr ohne Audio).
pub(super) fn apply_metronome(&mut self) {
let (bpm, sync) = self.effective_metronome();
if let Some(e) = &self.engine {
let s = &e.shared;
s.met_on.store(self.metro.on, Ordering::Relaxed);
store_f32(&s.met_bpm, bpm);
s.met_beats.store(self.metro.beats, Ordering::Relaxed);
store_f32(&s.met_gain, self.metro.volume);
s.met_sync.store(sync, Ordering::Relaxed);
let count = s.met_count.load(Ordering::Relaxed);
if count != self.metro.seen {
self.metro.seen = count;
self.metro.flash_at = Some(Instant::now());
self.metro.beat_shown = s.met_beat.load(Ordering::Relaxed);
}
} else if self.metro.on {
// Ohne Audio: Anzeige-Uhr, damit die LEDs im Testmodus laufen.
let start = *self.metro.sim_start.get_or_insert_with(Instant::now);
let idx = (start.elapsed().as_secs_f64() * f64::from(bpm) / 60.0).floor() as i64;
if idx != self.metro.sim_idx {
self.metro.sim_idx = idx;
self.metro.flash_at = Some(Instant::now());
self.metro.beat_shown = idx.rem_euclid(i64::from(self.metro.beats.max(1))) as u32;
}
} else {
self.metro.sim_start = None;
self.metro.sim_idx = -1;
}
}
/// Taktposition des letzten Klicks und Helligkeit seiner LED.
pub(super) fn metronome_light(&self) -> (u32, f32) {
let level = self
.metro
.flash_at
.map_or(0.0, |t| flash_level(t.elapsed().as_secs_f32()));
(
self.metro.beat_shown,
if self.metro.on { level } else { 0.0 },
)
}
/// Ein Tipp (egui-Zeit in Sekunden) für das Tap-Tempo; setzt das Tempo, sobald es ein Ergebnis gibt.
pub(super) fn metronome_tap(&mut self, now_s: f64) {
self.metro.taps.push(now_s);
if self.metro.taps.len() > 8 {
self.metro.taps.remove(0);
}
if let Some(b) = tap_bpm(&self.metro.taps) {
self.metro.bpm = b.round().clamp(BPM_RANGE.0, 300.0);
}
}
fn beat_leds(&self, ui: &mut egui::Ui) {
let (cur, level) = self.metronome_light();
let n = self.metro.beats.clamp(1, 12) as usize;
let (rect, _) = ui.allocate_exact_size(vec2(24.0 * n as f32, 18.0), Sense::hover());
let p = ui.painter_at(rect);
for i in 0..n {
let color = if i == 0 { LED_RED } else { AMBER };
let on = i as u32 == cur && level > 0.05;
led(
&p,
pos2(rect.left() + 12.0 + 24.0 * i as f32, rect.center().y),
on,
color,
5.0,
);
}
}
/// Großes Metronom-Gerät für die Stimmanzeige.
pub(super) fn metronome_panel(&mut self, ui: &mut egui::Ui) {
let (bpm_now, synced_to_song) = {
let (b, _) = self.effective_metronome();
(
b,
self.mode == Mode::Chart && self.chart.as_ref().is_some_and(|c| c.bpm.is_some()),
)
};
panel(ui, "Metronom", |ui| {
ui.horizontal(|ui| {
lcd(
ui,
&format!("{bpm_now:>3.0}"),
"Tempo (Schläge/min)",
AMBER,
150.0,
);
let mut bpm = self.metro.bpm;
if knob(
ui,
&mut bpm,
BPM_RANGE,
100.0,
"Tempo",
|v| format!("{v:.0} BPM"),
!synced_to_song,
)
.changed()
{
self.metro.bpm = bpm.round();
}
ui.vertical(|ui| {
ui.add_space(8.0);
ui.horizontal(|ui| {
if ui
.add_enabled(!synced_to_song, egui::Button::new("−"))
.clicked()
{
self.metro.bpm = (self.metro.bpm - 1.0).max(BPM_RANGE.0);
}
if ui
.add_enabled(!synced_to_song, egui::Button::new("+"))
.clicked()
{
self.metro.bpm = (self.metro.bpm + 1.0).min(BPM_RANGE.1);
}
});
let tap_time = ui.input(|i| i.time);
if ui
.add_enabled(!synced_to_song, egui::Button::new("Tap"))
.on_hover_text("Im gewünschten Tempo mehrfach antippen")
.clicked()
{
self.metronome_tap(tap_time);
}
});
ui.add_space(8.0);
ui.vertical(|ui| {
ui.add_space(4.0);
ui.label("Takt");
ui.horizontal(|ui| {
for b in [2u32, 3, 4, 6] {
ui.selectable_value(&mut self.metro.beats, b, format!("{b}/4"));
}
});
self.beat_leds(ui);
});
ui.add_space(8.0);
knob(
ui,
&mut self.metro.volume,
(0.0, 1.0),
0.5,
"Lautstärke",
|v| format!("{:.0} %", v * 100.0),
true,
);
ui.add_space(8.0);
ui.vertical(|ui| {
ui.add_space(10.0);
toggle(ui, &mut self.metro.on, "Metronom an", true);
});
});
if synced_to_song {
ui.label("Dieser Song hat ein festes Tempo; das Metronom läuft im Takt des Songs.");
} else if self.engine.is_none() && self.sim_start.is_none() {
ui.weak("Kein Audio-Ausgang: das Metronom ist stumm.");
}
});
}
/// Kompakte Fassung für das Mischpult im Tab „Singen“: Schalter, Lautstärke, Tempo, Schlag-LEDs.
pub(super) fn metronome_compact(&mut self, ui: &mut egui::Ui) {
let (bpm_now, _) = self.effective_metronome();
let synced = self.chart.as_ref().is_some_and(|c| c.bpm.is_some());
ui.horizontal(|ui| {
toggle(ui, &mut self.metro.on, "Metronom", true)
.on_hover_text("Klickt im Takt – bei Songs mit Tempo im Songtakt, mit Einzähler");
ui.label(
egui::RichText::new(format!("♩ = {bpm_now:.0}"))
.monospace()
.color(AMBER),
);
if synced {
ui.weak("(Songtempo)");
} else {
if ui.small_button("−").clicked() {
self.metro.bpm = (self.metro.bpm - 1.0).max(BPM_RANGE.0);
}
if ui.small_button("+").clicked() {
self.metro.bpm = (self.metro.bpm + 1.0).min(BPM_RANGE.1);
}
}
self.beat_leds(ui);
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::chart::NoteChart;
use std::sync::Arc;
use std::time::Duration;
fn app() -> App {
App::new(true, false, false, None)
}
fn chart_with_bpm(bpm: Option<f64>) -> Arc<NoteChart> {
let head = bpm.map_or(String::new(), |b| format!("bpm = {b}\n"));
Arc::new(
NoteChart::from_toml_str(
&format!("title=\"t\"\n{head}[[notes]]\nstart_ms=0\ndauer_ms=500\nmidi_pitch=60\n"),
None,
)
.unwrap(),
)
}
#[test]
fn flash_fades_out_within_a_fraction_of_a_second() {
assert_eq!(flash_level(0.0), 1.0);
assert!(flash_level(0.08) > 0.4 && flash_level(0.08) < 0.6);
assert_eq!(flash_level(0.16), 0.0);
assert_eq!(flash_level(5.0), 0.0);
assert_eq!(flash_level(-1.0), 1.0);
}
#[test]
fn song_tempo_wins_in_the_sing_tab_and_syncs_only_while_playing() {
let mut a = app();
a.metro.bpm = 90.0;
a.chart = Some(chart_with_bpm(Some(100.0)));
// Stimmanzeige: eigenes Tempo, nie synchron.
a.mode = Mode::Tuner;
assert_eq!(a.effective_metronome(), (90.0, false));
// Singen: Songtempo; synchron erst bei laufender Wiedergabe (Probe).
a.mode = Mode::Chart;
assert_eq!(a.effective_metronome(), (100.0, false));
a.practice = Some(crate::ui::chart_view::Practice {
playing: true,
pos_ms: 0.0,
});
assert_eq!(a.effective_metronome(), (100.0, true));
a.practice = Some(crate::ui::chart_view::Practice {
playing: false,
pos_ms: 0.0,
});
assert_eq!(
a.effective_metronome(),
(100.0, false),
"in der Pause frei laufend"
);
// Chart ohne Tempo: eigenes Tempo.
a.chart = Some(chart_with_bpm(None));
assert_eq!(a.effective_metronome(), (90.0, false));
}
#[test]
fn tap_tempo_sets_the_bpm() {
let mut a = app();
for t in [10.0, 10.5, 11.0, 11.5] {
a.metronome_tap(t);
}
assert_eq!(a.metro.bpm, 120.0);
a.metronome_tap(40.0); // lange Pause → neue Zählung, noch kein Ergebnis → Tempo bleibt
assert_eq!(a.metro.bpm, 120.0);
a.metronome_tap(40.4);
assert_eq!(a.metro.bpm, 150.0);
}
#[test]
fn simulated_display_clock_flashes_the_beat_leds() {
let mut a = app();
a.metro.on = true;
a.metro.bpm = 120.0;
a.metro.beats = 4;
// Anzeige-Uhr lief schon 1,3 s: Schlag 2 (0,5 s je Schlag) → Position 2 im Takt.
a.metro.sim_start = Some(Instant::now() - Duration::from_millis(1300));
a.apply_metronome();
let (beat, level) = a.metronome_light();
assert_eq!(beat, 2);
assert!(level > 0.5, "frisch geklickt: {level}");
// Aus: keine Anzeige und die Uhr wird zurückgesetzt.
a.metro.on = false;
a.apply_metronome();
assert_eq!(a.metronome_light().1, 0.0);
assert!(a.metro.sim_start.is_none());
}
#[test]
fn metronome_switches_off_when_leaving_its_tabs() {
let mut a = app();
a.mode = Mode::Tuner;
a.handle_mode_change();
a.metro.on = true;
a.mode = Mode::Chart;
a.handle_mode_change();
assert!(a.metro.on, "zwischen Stimmanzeige und Singen bleibt es an");
a.mode = Mode::Voice;
a.handle_mode_change();
assert!(!a.metro.on, "außerhalb schaltet es sich aus");
}
}

View File

@ -2,6 +2,9 @@
mod calib_view;
mod chart_view;
mod gear;
mod home_view;
mod metro_view;
mod review_view;
mod roll;
mod voice_view;
@ -26,7 +29,7 @@ use voice_view::Wizard;
const FLOOR_DB: f32 = -60.0;
const PEAK_HOLD_DECAY_DB_PER_S: f32 = 20.0;
/// Höhe unterhalb der Piano-Roll (Steuerung, Pegel, Einstellungskopf).
const BELOW_ROLL_PX: f32 = 170.0;
const BELOW_ROLL_PX: f32 = 200.0;
/// Verlauf, der für Anzeige und Nachführung vorgehalten wird.
const HISTORY_S: f64 = 30.0;
const SIM_RATE_HZ: f64 = 100.0;
@ -59,6 +62,8 @@ fn audio_variant(m: Mode) -> u8 {
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
Home,
Settings,
Tuner,
Chart,
History,
@ -69,11 +74,17 @@ enum Mode {
pub struct App {
mode: Mode,
/// Modus des vorigen Bildes: Wechsel lösen zentral Aufräumarbeiten aus.
last_mode: Mode,
zoom_set: bool,
chart: Option<Arc<NoteChart>>,
chart_path_text: String,
session: Option<Session>,
/// Simulation: Startzeit der laufenden Session (Wanduhr) und Sim-Zeit dazu.
sim_session_start: Option<Instant>,
/// Simulation: laufende Pause seit und bisher pausierte Zeit (s).
sim_pause_since: Option<Instant>,
sim_paused_total: f64,
session_sim_t0: f64,
gain_backing: f32,
original_on: bool,
@ -95,6 +106,20 @@ pub struct App {
chart_base: Option<Arc<NoteChart>>,
transpose: i32,
calib: CalibState,
/// Probe-Modus im Chart-Tab: Wiedergabe ohne Wertung und Aufnahme, mit Spulen.
practice: Option<chart_view::Practice>,
metro: metro_view::MetroState,
/// Gefundene Songs für die Auswahl.
charts: Vec<chart_view::ChartEntry>,
/// Gewählte Passage (Index in `chart.sections`); `None` = ganzes Lied.
section: Option<usize>,
/// Probe: Passage in Schleife abspielen.
practice_loop: bool,
/// Pitch-Verlauf des Original-Gesangs und ob er im Chart gezeichnet wird.
original: Option<chart_view::OriginalCurve>,
show_original: bool,
/// Akkordleiste und Akkordkarte anzeigen.
show_chords: bool,
calib_wav: std::path::PathBuf,
config_path: std::path::PathBuf,
config: Config,
@ -115,14 +140,20 @@ pub struct App {
}
impl App {
pub fn new(sim: bool, autostart: bool, review_latest: bool) -> Self {
let config = Config::load();
let chart = NoteChart::load(Path::new(&config.session.chart_path))
.ok()
.map(Arc::new);
/// `chart_arg`: Chart-Datei, die beim Start geladen wird (öffnet den Chart-Tab).
pub fn new(sim: bool, autostart: bool, review_latest: bool, chart_arg: Option<String>) -> Self {
let mut config = Config::load();
if let Some(p) = &chart_arg {
config.session.chart_path = p.clone();
}
let chart_result = NoteChart::load(Path::new(&config.session.chart_path));
let chart_error = chart_result.as_ref().err().map(|e| format!("{e:#}"));
let chart = chart_result.ok().map(Arc::new);
let chart_base = chart.clone();
let mut app = Self {
mode: Mode::Tuner,
mode: Mode::Home,
last_mode: Mode::Home,
zoom_set: false,
gain_guide: if chart.as_ref().is_some_and(|c| c.backing.is_none()) {
0.6
} else {
@ -132,6 +163,8 @@ impl App {
chart_path_text: config.session.chart_path.clone(),
session: None,
sim_session_start: None,
sim_pause_since: None,
sim_paused_total: 0.0,
session_sim_t0: 0.0,
gain_backing: 0.8,
original_on: false,
@ -147,6 +180,14 @@ impl App {
chart_base,
transpose: 0,
calib: CalibState::new(),
practice: None,
metro: metro_view::MetroState::new(),
charts: Vec::new(),
section: None,
practice_loop: true,
original: None,
show_original: true,
show_chords: true,
calib_wav: calib_view::default_wav_path(),
config_path: Config::path(),
sample_rate_text: config
@ -180,6 +221,13 @@ impl App {
}
app.refresh_records();
app.refresh_profiles();
app.refresh_charts();
if chart_arg.is_some() {
app.mode = Mode::Chart;
if let Some(e) = chart_error {
app.messages.push(format!("Chart laden: {e}"));
}
}
if review_latest {
app.open_review(0);
}
@ -190,6 +238,79 @@ impl App {
app
}
/// Entwicklungshilfe (`--tab`, `--wizard`): öffnet gezielt eine Ansicht, der Stimmfinder mit simulierten Daten.
/// Tabs: tuner, chart, verlauf, stimmfinder, kalibrierung. Wizard: intro, speech, speech-rec, holds-rec, result.
pub fn demo_view(&mut self, tab: Option<&str>, wizard: Option<&str>) {
if let Some(t) = tab {
self.mode = match t {
"metronom" => {
self.metro.on = true;
Mode::Tuner
}
"start" => Mode::Home,
"einstellungen" => Mode::Settings,
"singen" | "chart" => Mode::Chart,
"verlauf" => Mode::History,
"stimmfinder" | "voice" => Mode::Voice,
"kalibrierung" | "abgleich" => Mode::Calib,
_ => Mode::Tuner,
};
self.last_mode = self.mode;
}
let Some(w) = wizard else { return };
self.mode = Mode::Voice;
self.wizard_begin();
let feed = |app: &mut App, step: crate::voice::sim::SimStep, fraction: f64| {
app.wizard_record_start();
let (t0, seed) = app
.wizard
.as_ref()
.map_or((0.0, 0), |w| (w.rec_t0.unwrap_or(0.0), w.seed));
let n = (step.duration_s() * fraction * 100.0) as usize;
if let Ok(mut h) = app.history.lock() {
for i in 0..n {
let t = i as f64 * 0.01;
h.push(
t0 + t,
crate::voice::sim::sim_voice(step, t, seed)
.map(|m| PitchEstimate::from_midi(m, 0.95)),
);
}
}
app.sim_t = t0 + n as f64 * 0.01 + 1.0;
};
use crate::voice::sim::SimStep;
match w {
"intro" => {}
"speech" => self.wizard_next(),
"speech-rec" => {
self.wizard_next();
feed(self, SimStep::Speech, 0.45);
}
"holds-rec" | "result" => {
self.wizard_next();
for (step, last) in [
(SimStep::Speech, false),
(SimStep::Legato, false),
(SimStep::Siren, false),
] {
let _ = last;
feed(self, step, 1.0);
self.wizard_record_finish();
self.wizard_next();
}
if w == "holds-rec" {
feed(self, SimStep::Holds, 0.35);
} else {
feed(self, SimStep::Holds, 1.0);
self.wizard_record_finish();
self.wizard_next();
}
}
_ => {}
}
}
fn restart(&mut self) {
self.engine = None; // Streams erst schließen, dann neu öffnen
if let Ok(mut h) = self.history.lock() {
@ -225,17 +346,76 @@ impl App {
}
}
fn readout(&self, ui: &mut egui::Ui, est: Option<PitchEstimate>) {
let text = match est {
Some(e) => format!(
"{:<4} {:+4.0} Cent {:6.1} Hz",
note_name(e.note),
e.cents,
e.freq_hz
),
None => "–".to_string(),
/// Zwei Karten der Stimmanzeige: dein aktueller Ton und der Referenzton.
fn tuner_cards(&self, ui: &mut egui::Ui) {
use roll::{PitchCard, USER_COLOR, draw_pitch_cards};
let gray = egui::Color32::from_gray(170);
let est = self
.history
.lock()
.ok()
.and_then(|h| h.latest().and_then(|p| p.est));
let du = PitchCard {
title: "Dein Ton".into(),
color: USER_COLOR,
midi: est.map(|e| e.midi),
big: None,
lines: est.map_or_else(Vec::new, |e| {
vec![
(format!("{:.1} Hz", e.freq_hz), gray),
(format!("{:+.0} Cent", e.cents), gray),
]
}),
level: None,
meter: est.map(|e| e.cents),
};
ui.label(egui::RichText::new(text).size(30.0).monospace());
let reference = PitchCard {
title: "Referenzton".into(),
color: egui::Color32::from_rgb(130, 175, 255),
midi: self.ref_on.then_some(self.ref_midi as f32),
big: None,
lines: if self.ref_on {
vec![(
format!(
"{:.1} Hz",
440.0 * 2f32.powf((self.ref_midi as f32 - 69.0) / 12.0)
),
gray,
)]
} else {
vec![("aus".to_string(), gray)]
},
level: None,
meter: None,
};
draw_pitch_cards(ui, &[du, reference]);
}
/// Aufräumarbeiten beim Wechsel des Tabs (auch wenn ein Knopf auf der Startseite ihn auslöst).
fn handle_mode_change(&mut self) {
let (before, now) = (self.last_mode, self.mode);
if before == now {
return;
}
self.last_mode = now;
if before == Mode::Chart {
self.stop_session(false);
self.practice_stop();
}
if before == Mode::Calib {
self.calib_cancel();
}
// Review (Mikrospur) und Abgleich (Klickzug) brauchen eigene Audio-Streams.
if audio_variant(before) != audio_variant(now) && self.sim_start.is_none() {
self.restart();
}
// Das Metronom gehört zu Stimmanzeige und Singen; beim Verlassen schaltet es sich aus.
if !matches!(now, Mode::Tuner | Mode::Chart) {
self.metro.on = false;
}
if now == Mode::History {
self.refresh_records();
}
}
fn roll_view(&mut self, ui: &mut egui::Ui, below_px: f32) -> Option<PitchEstimate> {
@ -305,6 +485,11 @@ impl App {
ui.weak("(kein Audio)");
}
});
self.apply_reference();
}
/// Übergibt Referenzton-Einstellungen (Note, Klang, an/aus) an die Audio-Engine.
pub(super) fn apply_reference(&self) {
if let Some(engine) = &self.engine {
let hz = 440.0 * 2f32.powf((self.ref_midi as f32 - 69.0) / 12.0);
let s = &engine.shared;
@ -341,26 +526,6 @@ fn device_combo(
changed
}
fn meter(ui: &mut egui::Ui, label: &str, db: f32) {
ui.horizontal(|ui| {
ui.label(format!("{label:5}"));
let frac = ((db - FLOOR_DB) / -FLOOR_DB).clamp(0.0, 1.0);
let color = if db > -3.0 {
egui::Color32::from_rgb(220, 60, 60)
} else if db > -12.0 {
egui::Color32::from_rgb(230, 190, 50)
} else {
egui::Color32::from_rgb(70, 180, 90)
};
ui.add(
egui::ProgressBar::new(frac)
.desired_width(400.0)
.fill(color)
.text(format!("{db:.1} dBFS")),
);
});
}
impl eframe::App for App {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let dt = ui.input(|i| i.stable_dt);
@ -372,49 +537,68 @@ impl eframe::App for App {
}
self.sim_tick();
self.session_tick();
self.apply_metronome();
ui.ctx().request_repaint();
egui::CentralPanel::default().show(ui, |ui| {
if !self.zoom_set {
// Etwas größere Darstellung für gute Lesbarkeit.
ui.ctx().set_zoom_factor(self.config.ui.zoom);
gear::apply_theme(ui.ctx());
self.zoom_set = true;
}
self.handle_mode_change();
egui::CentralPanel::default()
.frame(egui::Frame::new().fill(gear::CASE_BG).inner_margin(egui::Margin::same(10)))
.show(ui, |ui| {
egui::ScrollArea::vertical()
.auto_shrink(false)
.show(ui, |ui| {
ui.horizontal(|ui| {
let before = self.mode;
ui.selectable_value(&mut self.mode, Mode::Tuner, "Tuner");
ui.selectable_value(&mut self.mode, Mode::Chart, "Chart");
ui.selectable_value(&mut self.mode, Mode::History, "Verlauf");
ui.selectable_value(&mut self.mode, Mode::Voice, "Stimmfinder");
ui.selectable_value(&mut self.mode, Mode::Calib, "Kalibrierung");
ui.horizontal_wrapped(|ui| {
const TABS: [(Mode, &str); 7] = [
(Mode::Home, "Start"),
(Mode::Chart, "Singen"),
(Mode::Voice, "Stimmfinder"),
(Mode::History, "Verlauf"),
(Mode::Tuner, "Stimmanzeige"),
(Mode::Calib, "Mikrofon-Abgleich"),
(Mode::Settings, "Einstellungen"),
];
for (mode, label) in TABS {
ui.selectable_value(&mut self.mode, mode, label);
}
if self.review.is_some() {
ui.selectable_value(&mut self.mode, Mode::Review, "Review");
}
if before == Mode::Chart && self.mode != before {
self.stop_session(false);
}
// Die Review-Wiedergabe braucht einen eigenen Stream-Satz (Mikrospur, Backing).
if before == Mode::Calib && self.mode != before {
self.calib_cancel();
}
if audio_variant(before) != audio_variant(self.mode)
&& self.sim_start.is_none()
{
self.restart();
}
if before != Mode::History && self.mode == Mode::History {
self.refresh_records();
ui.selectable_value(&mut self.mode, Mode::Review, "Auswertung");
}
});
// Hinweise und Fehlermeldungen gut sichtbar oben.
if !self.messages.is_empty() {
ui.horizontal_wrapped(|ui| {
for m in &self.messages {
ui.colored_label(egui::Color32::from_rgb(235, 150, 70), m);
}
if ui.small_button("✕").on_hover_text("Hinweis ausblenden").clicked() {
self.messages.clear();
}
});
}
match self.mode {
Mode::Home => self.home_ui(ui),
Mode::Settings => self.settings_ui(ui, dt),
Mode::Tuner => {
let est_slot = self
.history
.lock()
.ok()
.and_then(|h| h.latest().and_then(|p| p.est));
self.readout(ui, est_slot);
self.roll_view(ui, BELOW_ROLL_PX);
ui.label(
egui::RichText::new(
"Summe oder singe einen Ton – hier siehst du, welcher es ist und ob du ihn triffst.",
)
.size(16.0)
.color(egui::Color32::from_gray(225)),
);
self.tuner_cards(ui);
self.roll_view(ui, BELOW_ROLL_PX + 120.0);
ui.add_space(4.0);
self.reference_controls(ui);
ui.add_space(6.0);
self.metronome_panel(ui);
}
Mode::Chart => self.chart_ui(ui),
Mode::History => self.history_ui(ui),
@ -422,72 +606,6 @@ impl eframe::App for App {
Mode::Voice => self.voice_ui(ui),
Mode::Calib => self.calib_ui(ui),
}
meter(ui, "Spitze", self.peak_db);
meter(ui, "RMS", self.rms_db);
egui::CollapsingHeader::new("Audio-Einstellungen").show(ui, |ui| {
let mut changed = false;
changed |= device_combo(
ui,
"Eingang",
&self.devices.inputs,
&mut self.config.audio.input_device,
);
changed |= device_combo(
ui,
"Ausgang",
&self.devices.outputs,
&mut self.config.audio.output_device,
);
ui.horizontal(|ui| {
ui.label("Samplerate (leer = Standard)");
ui.add(
egui::TextEdit::singleline(&mut self.sample_rate_text)
.desired_width(70.0),
);
ui.label("Puffer in Frames (leer = Standard)");
ui.add(
egui::TextEdit::singleline(&mut self.buffer_text)
.desired_width(70.0),
);
});
ui.horizontal(|ui| {
if ui.button("Streams (neu) starten").clicked() || changed {
self.restart();
}
if ui.button("Geräte neu einlesen").clicked() {
self.devices = list_devices();
}
if ui.button("Config speichern").clicked() {
self.config.ui.reference_midi = self.ref_midi;
self.messages = match self.config.save_to(&self.config_path) {
Ok(()) => {
vec![format!("Gespeichert: {}", Config::path().display())]
}
Err(e) => vec![format!("Speichern fehlgeschlagen: {e:#}")],
};
}
});
});
let (rate_in, rate_out, xruns) =
self.engine.as_ref().map_or((None, None, 0), |e| {
(
e.input_rate,
e.output_rate,
e.shared.xruns.load(Ordering::Relaxed),
)
});
ui.weak(format!(
"Eingang {} Hz · Ausgang {} Hz · Xruns {} · {:.0} fps",
rate_in.map_or("–".into(), |r| r.to_string()),
rate_out.map_or("–".into(), |r| r.to_string()),
xruns,
1.0 / dt.max(1e-4)
));
for m in &self.messages {
ui.colored_label(egui::Color32::from_rgb(230, 120, 60), m);
}
});
});
}

View File

@ -1,6 +1,6 @@
//! Verlauf (Liste gespeicherter Sessions) und Review (Auswertung, Wiedergabe solo/gemischt).
use super::chart_view::{draw_chart_roll, score_table};
use super::chart_view::{RollData, draw_chart_roll, score_table};
use super::{App, Mode};
use crate::audio::{ChartAudio, store_f32};
use crate::pitch::HistoryPoint;
@ -36,14 +36,15 @@ impl App {
curve: record.curve(),
verified: record.rescore() == record.result,
dir,
scrub_ms: record.range_start_ms,
record,
scrub_ms: 0.0,
playing: false,
mixed: false,
gain_rec: 1.0,
gain_backing: 0.8,
});
self.mode = Mode::Review;
self.last_mode = Mode::Review; // der Neustart unten erledigt den Streamwechsel schon
if self.sim_start.is_none() {
self.restart(); // Mikrospur und Backing dieser Session laden
}
@ -53,29 +54,34 @@ impl App {
pub(super) fn review_audio(&self) -> Option<ChartAudio> {
let st = self.review.as_ref()?;
let mut audio = ChartAudio::from_chart(&st.record.chart);
audio.recording = st
.record
.wav
.as_ref()
.map(|w| (st.dir.join(w), st.record.countdown_ms + st.record.offset_ms));
audio.recording = st.record.wav.as_ref().map(|w| {
(
st.dir.join(w),
st.record.countdown_ms + st.record.offset_ms - st.record.range_start_ms,
)
});
Some(audio)
}
pub(super) fn history_ui(&mut self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
ui.heading("Verlauf");
ui.heading("Mein Verlauf");
if ui.button("Aktualisieren").clicked() {
self.refresh_records();
}
ui.weak(self.sessions_root.display().to_string());
});
if self.records.is_empty() {
ui.label("Noch keine gespeicherten Sessions. Eine Chart-Session bis zum Ende singen.");
ui.label(
egui::RichText::new(
"Hier erscheinen deine gesungenen Songs mit Punktzahl. Sing im Tab „Singen“ einen Song bis zum Ende – dann siehst du ihn hier und kannst dir anhören, wie du geklungen hast.",
)
.size(16.0),
);
return;
}
let mut open = None;
egui::Grid::new("history").striped(true).show(ui, |ui| {
for h in ["Datum", "Chart", "Score", "Aufnahme", ""] {
for h in ["Datum", "Song", "Punkte", "Aufnahme", ""] {
ui.strong(h);
}
ui.end_row();
@ -112,7 +118,7 @@ impl App {
if st.scrub_ms > end_ms {
e.shared.playing.store(false, Ordering::Relaxed);
st.playing = false;
st.scrub_ms = 0.0;
st.scrub_ms = st.record.range_start_ms;
}
}
let seek = |ms: f64| {
@ -161,7 +167,13 @@ impl App {
}
let mut secs = st.scrub_ms / 1000.0;
if ui
.add(egui::Slider::new(&mut secs, 0.0..=end_ms / 1000.0).suffix(" s"))
.add(
egui::Slider::new(
&mut secs,
st.record.range_start_ms / 1000.0..=end_ms / 1000.0,
)
.suffix(" s"),
)
.changed()
{
st.scrub_ms = secs * 1000.0;
@ -204,14 +216,25 @@ impl App {
store_f32(&s.gain_monitor, 0.0);
}
self.original_tick(st.record.chart.vocals.clone());
let original = self.original_view(st.scrub_ms, st.record.transpose, &st.record.chart);
draw_chart_roll(
ui,
&st.record.chart,
&st.curve,
st.scrub_ms,
Some(&st.record.result),
&RollData {
chart: &st.record.chart,
curve: &st.curve,
now_ms: st.scrub_ms,
result: Some(&st.record.result),
octave_tolerant: st.record.score_cfg.octave_tolerant,
original: &original,
chords: if self.show_chords {
&st.record.chart.chords
} else {
&[]
},
chord_flats: crate::import::chords::prefer_flats(&st.record.chart.chords),
},
&self.config.ui,
st.record.score_cfg.octave_tolerant,
);
score_table(ui, &st.record.chart, &st.record.result);
self.review = Some(st);

View File

@ -1,6 +1,6 @@
//! Piano-Roll-Ansicht: scrollende Tonhöhenkurve. Abbildung und Segmentierung sind rein und getestet.
use crate::chart::{NoteChart, NoteKind};
use crate::chart::{ChordSpan, NoteChart, NoteKind};
use crate::config::UiConfig;
use crate::pitch::{HistoryPoint, note_name};
use crate::score::ChartScore;
@ -62,6 +62,216 @@ pub fn segments<'a>(points: impl Iterator<Item = &'a HistoryPoint>) -> Vec<Vec<C
out
}
/// Kurvenstücke des Original-Gesangs für das Zeitfenster [t_from, t_to] (Sekunden), um `shift` Halbtöne
/// verschoben. Mit `fold_to` werden Oktavfehler der Erkennung auf die Oktave der Zielnote gefaltet.
pub fn original_segments(
frames: &[(f64, Option<f32>)],
t_from: f64,
t_to: f64,
shift: f32,
fold_to: Option<&NoteChart>,
) -> Vec<Vec<CurvePoint>> {
let lo = frames.partition_point(|f| f.0 < t_from);
let hi = frames.partition_point(|f| f.0 <= t_to);
let mut out: Vec<Vec<CurvePoint>> = Vec::new();
let mut open = false;
for &(t, m) in &frames[lo..hi.max(lo)] {
let Some(mut midi) = m else {
open = false;
continue;
};
midi += shift;
if let Some(c) = fold_to
&& let Some(i) = c.note_at(t * 1000.0)
{
midi = fold_to_target(midi, c.notes[i].midi_pitch);
}
let p = CurvePoint {
t,
midi,
cents: 0.0,
};
if open {
out.last_mut().expect("offenes Segment").push(p);
} else {
out.push(vec![p]);
open = true;
}
}
out
}
/// Eine Tonhöhen-Karte (Ziel, Original oder Du): großer Notenname, Zusatzzeilen und Cent-Anzeige.
pub struct PitchCard {
pub title: String,
pub color: Color32,
/// Kontinuierliche MIDI-Zahl; `None` = kein Ton (Karte gedämpft).
pub midi: Option<f32>,
/// Ersetzt den großen Notennamen durch einen anderen Text (z. B. Status).
pub big: Option<String>,
pub lines: Vec<(String, Color32)>,
/// Abweichung von der nächsten Halbtonstufe in Cent für die Anzeige unten.
pub meter: Option<f32>,
/// Pegel 0..=1 als LED-Kette (statt der Cent-Anzeige), z. B. für das Mikrofon.
pub level: Option<f32>,
}
/// Feste Höhe der Karten: die Anordnung darunter bleibt stabil, egal was angezeigt wird.
pub const CARD_H: f32 = 88.0;
/// Zeichnet die Karten nebeneinander als Geräte-Displays (dunkles Glas, leuchtende Schrift, LED-Anzeige).
pub fn draw_pitch_cards(ui: &mut egui::Ui, cards: &[PitchCard]) {
use super::gear;
// Etwas schmaler als die Fläche: die Bildlaufleiste schneidet sonst die rechte Karte an.
let (rect, _) = ui.allocate_exact_size(
egui::vec2(ui.available_width() - 14.0, CARD_H),
egui::Sense::hover(),
);
let painter = ui.painter_at(rect);
let gap = 8.0;
let w = (rect.width() - gap * (cards.len() as f32 - 1.0)) / cards.len() as f32;
for (i, c) in cards.iter().enumerate() {
let r = Rect::from_min_size(
pos2(rect.left() + i as f32 * (w + gap), rect.top()),
egui::vec2(w, CARD_H),
);
let active = c.midi.is_some();
// Gehäuse mit Rand, darin das dunkle Display.
painter.rect_filled(r, 7.0, gear::PLATE_BG);
painter.rect_stroke(
r,
7.0,
Stroke::new(1.5, gear::PLATE_EDGE),
egui::StrokeKind::Inside,
);
let lcd = r.shrink(5.0);
painter.rect_filled(lcd, 4.0, Color32::from_rgb(10, 13, 11));
painter.rect_stroke(
lcd,
4.0,
Stroke::new(
1.0,
if active {
c.color.gamma_multiply(0.45)
} else {
Color32::from_rgb(34, 38, 35)
},
),
egui::StrokeKind::Inside,
);
painter.text(
pos2(lcd.left() + 9.0, lcd.top() + 10.0),
Align2::LEFT_CENTER,
c.title.to_uppercase(),
FontId::proportional(11.5),
c.color.gamma_multiply(if active { 0.95 } else { 0.7 }),
);
let letter = c.big.clone().unwrap_or_else(|| {
c.midi
.map_or("–".to_string(), |m| note_name(m.round() as i32))
});
let glow = if active {
c.color
} else {
Color32::from_gray(70)
};
let letter_pos = pos2(lcd.left() + 9.0, lcd.top() + 38.0);
// Kurze große Texte (Notenname, Akkord) groß; lange Statustexte kleiner.
let font = FontId::monospace(if c.big.as_ref().is_some_and(|b| b.chars().count() > 4) {
20.0
} else {
38.0
});
// Schein hinter der Schrift.
painter.text(
letter_pos + egui::vec2(0.0, 0.0),
Align2::LEFT_CENTER,
&letter,
font.clone(),
glow.gamma_multiply(0.35),
);
painter.text(
letter_pos,
Align2::LEFT_CENTER,
letter,
font,
if active {
Color32::WHITE.gamma_multiply(0.92)
} else {
glow
},
);
for (k, (text, color)) in c.lines.iter().take(2).enumerate() {
if c.big.as_ref().is_some_and(|b| b.chars().count() > 4) {
// Statuskarten: Zusatzzeile rechts oben, damit sie den langen Statustext nicht überdeckt.
painter.text(
pos2(lcd.right() - 9.0, lcd.top() + 10.0 + k as f32 * 14.0),
Align2::RIGHT_CENTER,
text,
FontId::monospace(11.5),
*color,
);
} else {
painter.text(
pos2(
lcd.left() + lcd.width() * 0.46,
lcd.top() + 28.0 + k as f32 * 16.0,
),
Align2::LEFT_CENTER,
text,
FontId::monospace(12.5),
*color,
);
}
}
// Anzeige unten: LED-Pegelkette oder Cent-Skala (−50 … +50, Mitte = genau auf dem Ton).
let (ml, mw) = (lcd.left() + 9.0, lcd.width() - 18.0);
let my = lcd.bottom() - 10.0;
if let Some(level) = c.level {
let n = 28;
let lit = gear::lit_segments(level, n);
let step = mw / n as f32;
for k in 0..n {
gear::led(
&painter,
pos2(ml + (k as f32 + 0.5) * step, my),
k < lit,
gear::segment_color(k, n),
(step * 0.32).clamp(1.8, 3.6),
);
}
} else {
const N: usize = 21; // alle 5 Cent eine LED
let active_idx = c.meter.filter(|_| active).map(|cents| {
(((cents.clamp(-50.0, 50.0) + 50.0) / 5.0).round() as usize).min(N - 1)
});
let step = mw / N as f32;
for k in 0..N {
let cents = -50.0 + k as f32 * 5.0;
let color = if cents.abs() <= 15.0 {
gear::LED_GREEN
} else if cents.abs() <= 35.0 {
gear::LED_YELLOW
} else {
gear::LED_RED
};
let cx = ml + (k as f32 + 0.5) * step;
gear::led(
&painter,
pos2(cx, my),
Some(k) == active_idx,
color,
if k == N / 2 { 3.8 } else { 2.8 },
);
}
}
}
}
/// Farben im Chart-Modus: Original-Gesang und Gesang des Nutzers.
pub const ORIGINAL_COLOR: Color32 = Color32::from_rgb(80, 200, 235);
pub const USER_COLOR: Color32 = Color32::from_rgb(245, 110, 200);
/// Gewünschte Mitte des Ausschnitts: unverändert, solange das Ziel im Innenbereich liegt.
pub fn follow(center: f32, target: f32, half_range: f32, margin: f32) -> f32 {
let inner = half_range - margin;
@ -82,6 +292,11 @@ pub fn fold_to_target(midi: f32, target: i32) -> f32 {
/// Zusatzdaten für den Chart-Modus.
pub struct ChartOverlay<'a> {
pub chart: &'a NoteChart,
/// Kurve des Original-Gesangs (leer = ausgeblendet).
pub original: &'a [Vec<CurvePoint>],
/// Akkordleiste (leer = ausgeblendet) und ob mit Been geschrieben wird.
pub chords: &'a [ChordSpan],
pub chord_flats: bool,
pub now_ms: f64,
pub result: Option<&'a ChartScore>,
}
@ -169,7 +384,36 @@ pub fn draw(
}
if let Some(o) = overlay {
draw_chord_lane(&painter, vp, o);
draw_notes(&painter, vp, o);
for seg in o.original {
for w in seg.windows(2) {
painter.line_segment(
[
pos2(vp.x(w[0].t), vp.y(w[0].midi)),
pos2(vp.x(w[1].t), vp.y(w[1].midi)),
],
Stroke::new(2.5, ORIGINAL_COLOR.gamma_multiply(0.9)),
);
}
}
// Legende.
let lx = vp.rect.right() - 150.0;
for (i, (color, label)) in [(ORIGINAL_COLOR, "Original"), (USER_COLOR, "Du")]
.into_iter()
.enumerate()
{
let lane = if o.chords.is_empty() { 0.0 } else { 26.0 };
let y = vp.rect.top() + 12.0 + lane + i as f32 * 16.0;
painter.line_segment([pos2(lx, y), pos2(lx + 22.0, y)], Stroke::new(3.0, color));
painter.text(
pos2(lx + 28.0, y),
Align2::LEFT_CENTER,
label,
FontId::proportional(12.0),
Color32::from_gray(210),
);
}
// „Jetzt“-Linie.
let x = vp.x(o.now_ms / 1000.0);
painter.line_segment(
@ -194,7 +438,14 @@ pub fn draw(
let (a, b) = (&w[0], &w[1]);
painter.line_segment(
[pos2(vp.x(a.t), vp.y(a.midi)), pos2(vp.x(b.t), vp.y(b.midi))],
Stroke::new(3.0, cents_color(b.cents, cfg)),
Stroke::new(
3.0,
if overlay.is_some() {
USER_COLOR
} else {
cents_color(b.cents, cfg)
},
),
);
}
}
@ -204,7 +455,11 @@ pub fn draw(
painter.circle_filled(
pos2(vp.x(last.t), vp.y(last.midi)),
6.0,
cents_color(last.cents, cfg),
if overlay.is_some() {
USER_COLOR
} else {
cents_color(last.cents, cfg)
},
);
}
}
@ -215,6 +470,49 @@ fn score_color(total: f32) -> Color32 {
Color32::from_rgb((220.0 - 130.0 * t) as u8, (70.0 + 140.0 * t) as u8, 90)
}
/// Akkordleiste am oberen Rand: ein Feld je Akkord, der gerade klingende ist hervorgehoben.
fn draw_chord_lane(painter: &egui::Painter, vp: &Viewport, o: &ChartOverlay<'_>) {
const H: f32 = 22.0;
let (t_left, t_right) = (vp.t_now + vp.lead_s - vp.window_s, vp.t_now + vp.lead_s);
for c in o.chords {
let (a, b) = (c.start_ms / 1000.0, c.end_ms / 1000.0);
if b < t_left || a > t_right {
continue;
}
let (x0, x1) = (vp.x(a).max(vp.rect.left()), vp.x(b).min(vp.rect.right()));
if x1 - x0 < 2.0 {
continue;
}
let minor = c.name.ends_with('m');
let active = o.now_ms >= c.start_ms && o.now_ms < c.end_ms;
let fill = if active {
Color32::from_rgb(255, 176, 48)
} else if minor {
Color32::from_rgb(78, 62, 96)
} else {
Color32::from_rgb(58, 70, 92)
};
let r = Rect::from_min_max(
pos2(x0 + 1.0, vp.rect.top() + 2.0),
pos2(x1 - 1.0, vp.rect.top() + H),
);
painter.rect_filled(r, 4.0, fill);
if r.width() > 22.0 {
painter.text(
pos2(r.left() + 6.0, r.center().y),
Align2::LEFT_CENTER,
crate::import::chords::display_chord(&c.name, o.chord_flats),
FontId::proportional(14.0),
if active {
Color32::from_rgb(34, 22, 4)
} else {
Color32::WHITE
},
);
}
}
}
/// Zielbalken mit Silben; nach der Wertung nach Notenscore eingefärbt.
fn draw_notes(painter: &egui::Painter, vp: &Viewport, o: &ChartOverlay<'_>) {
for (i, n) in o.chart.notes.iter().enumerate() {
@ -249,6 +547,16 @@ fn draw_notes(painter: &egui::Painter, vp: &Viewport, o: &ChartOverlay<'_>) {
egui::StrokeKind::Outside,
);
}
// Notenname im Balken, wenn Platz ist.
if rect.width() >= 26.0 && rect.height() >= 11.0 {
painter.text(
rect.center(),
Align2::CENTER_CENTER,
note_name(n.midi_pitch),
FontId::monospace((rect.height() * 0.62).clamp(9.0, 13.0)),
Color32::from_white_alpha(if active { 255 } else { 190 }),
);
}
}
}
@ -374,6 +682,39 @@ mod tests {
assert_eq!(follow(60.0, 40.0, 12.0, 3.0), 49.0);
}
#[test]
fn original_segments_window_shift_fold_and_gaps() {
let frames: Vec<(f64, Option<f32>)> = (0..100)
.map(|i| {
(
i as f64 * 0.01,
if (40..50).contains(&i) {
None
} else {
Some(48.0)
},
)
})
.collect();
// Fenster 0,2–0,7 s: Lücke bei 0,40–0,50 teilt in zwei Stücke.
let s = original_segments(&frames, 0.2, 0.7, 0.0, None);
assert_eq!(s.len(), 2, "{s:?}");
assert!((s[0][0].t - 0.2).abs() < 1e-9 && s[1].last().unwrap().t <= 0.7 + 1e-9);
// Verschiebung.
assert!((original_segments(&frames, 0.0, 0.1, 3.0, None)[0][0].midi - 51.0).abs() < 1e-6);
// Oktavfaltung auf die Zielnote (60): 48 → 60.
let c = NoteChart::from_toml_str(
"title=\"t\"\n[[notes]]\nstart_ms=0\ndauer_ms=1000\nmidi_pitch=60",
None,
)
.unwrap();
let f = original_segments(&frames, 0.0, 0.3, 0.0, Some(&c));
assert!((f[0][0].midi - 60.0).abs() < 1e-6);
// Außerhalb der Daten: leer.
assert!(original_segments(&frames, 5.0, 6.0, 0.0, None).is_empty());
assert!(original_segments(&[], 0.0, 1.0, 0.0, None).is_empty());
}
#[test]
fn black_keys() {
assert!(is_black_key(61) && is_black_key(70) && is_black_key(-2));

File diff suppressed because it is too large Load Diff