dspk-app-core 0.0.8

DSP App core: the workbench for any multichannel signal (open, view, process, write) and the plugin interface the domain plugins (electrophysiology: dspk-app-synapse) extend
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! One time view (traces or heatmap): its settings ([`TimeView`]), the frame on screen and the
//! window it was drawn for, and the hover readout.
//!
//! Rendering is asked for on change, never polled: a timeline, selection, size or setting change
//! schedules one request, sent once the current update ends (so a burst of changes costs one
//! request), and only while the view is displayed. Frames come back over this view's own channel;
//! the image they replace is released one frame later (it may still be on screen).

use std::sync::Arc;
use std::time::{Duration, Instant};

use gpui_kit::{App, Context, Entity, EventEmitter, RenderImage, Subscription, Task};

use crate::data::recording::SourceSet;
use crate::data::work_pool::JobKey;
use crate::screens::explore::trace::hover::{HoverReply, HoverRequest};
use crate::screens::explore::trace::renderer::{render_on_worker, TimeViewKind};
use crate::screens::explore::trace::view::{HoverTarget, TimeView, ViewId};
use crate::navigation::route::Workspace;
use crate::data::store::{AppEvent, Store};

use crate::data::services::{Services, RENDER_SLOT};

/// The frame on screen and what it shows.
#[derive(Clone)]
pub struct Shown {
    pub image: Arc<RenderImage>,
    /// Time window it was drawn for (seconds).
    pub start: f64,
    pub window: f64,
}

struct Delivered {
    shown: Shown,
    scale: Option<f32>,
    /// Every column was available (else redraw as the pyramid builds).
    complete: bool,
    elapsed: Duration,
    samples_per_px: f64,
}

pub enum TraceEvent {
    /// The view was pressed: it becomes the focused view.
    Pressed,
    /// Kind, source or title changed (tab title, settings panel).
    Changed,
    /// The view no longer shows this session view (its source changed).
    Released(String),
}

pub struct TraceVm {
    store: Entity<Store>,
    pub view: TimeView,
    pub shown: Option<Shown>,
    /// Replaced image, released when the next frame arrives.
    retired: Option<Arc<RenderImage>>,
    /// Displayed in its tab group (hidden views do not render).
    active: bool,
    scheduled: bool,
    /// The frame on screen has columns the pyramid had not built yet.
    incomplete: bool,
    pub hover: String,
    frames: async_channel::Sender<Delivered>,
    hover_reply: HoverReply,
    _tasks: Vec<Task<()>>,
    _store: Subscription,
    home: Workspace,
}

impl EventEmitter<TraceEvent> for TraceVm {}

impl TraceVm {
    /// A view of `kind` on `source` (its id in the open file).
    pub fn new(store: Entity<Store>, id: ViewId, kind: TimeViewKind, source: &str, cx: &mut Context<Self>) -> Self {
        let mut view = TimeView::new(id, kind, Vec::new());
        Self::attach(&mut view, &store, source, cx);
        let (frames, frames_rx) = async_channel::unbounded::<Delivered>();
        let (hover_tx, hover_rx) = async_channel::unbounded::<(u64, String)>();
        let hover_reply: HoverReply = Arc::new(move |seq, text| {
            let _ = hover_tx.try_send((seq, text));
        });
        let frame_task = cx.spawn(async move |this, cx| {
            while let Ok(d) = frames_rx.recv().await {
                if this.update(cx, |vm, cx| vm.on_frame(d, cx)).is_err() {
                    break;
                }
            }
        });
        let hover_task = cx.spawn(async move |this, cx| {
            while let Ok((seq, text)) = hover_rx.recv().await {
                let alive = this.update(cx, |vm, cx| {
                    if vm.view.hover_seq == seq {
                        vm.hover = text;
                        cx.notify();
                    }
                });
                if alive.is_err() {
                    break;
                }
            }
        });
        let sub = cx.subscribe(&store, |vm, store, event, cx| match event {
            AppEvent::WindowMoved | AppEvent::PaletteChanged => vm.request_render(cx),
            // Back on its workspace: draw what changed while another one was shown
            AppEvent::WorkspaceChanged if vm.view.needs_render => vm.request_render(cx),
            AppEvent::RecordingChanged if vm.home != Workspace::Explore => {
                let source = store.read(cx).sources().map(|s| s.default_entry().id.clone()).unwrap_or_default();
                vm.set_source(&source, cx);
            }
            AppEvent::PlaybackChanged => cx.notify(),
            AppEvent::PyramidProgress(source) if *source == vm.view.source && vm.incomplete => vm.request_render(cx),
            AppEvent::SelectionChanged(source) if *source == vm.view.source && !vm.view.pinned_selection => {
                let channels = store.read(cx).selection(source).to_vec();
                let total = store.read(cx).sources().map_or(0, |s| s.entry(source).channels);
                vm.view.set_selection(channels, total);
                vm.request_render(cx);
            }
            _ => {}
        });
        let this = cx.weak_entity();
        cx.defer(move |cx| {
            let _ = this.update(cx, |vm, cx| vm.bind(cx));
        });
        Self {
            store,
            view,
            shown: None,
            retired: None,
            active: true,
            scheduled: false,
            incomplete: false,
            hover: String::new(),
            frames,
            hover_reply,
            _tasks: vec![frame_task, hover_task],
            _store: sub,
            home: Workspace::Explore,
        }
    }

    /// The workspace showing this view (Explore's views by default; a plugin's strip its own):
    /// it renders only while that workspace is in front.
    pub fn set_home(&mut self, home: Workspace, cx: &mut Context<Self>) {
        self.home = home;
        self.request_render(cx);
    }

    /// Points `view` at `source` of the open recording, with that source's shared selection.
    fn attach(view: &mut TimeView, store: &Entity<Store>, source: &str, cx: &App) {
        let s = store.read(cx);
        let Some(sources) = s.sources() else { return };
        let e = sources.entry(source);
        view.set_source(&e.id, &e.name, &e.unit, e.channels);
        view.set_selection(s.selection(&e.id).to_vec(), e.channels);
    }

    pub fn id(&self) -> ViewId {
        self.view.id
    }

    pub fn store(&self) -> &Entity<Store> {
        &self.store
    }

    fn sources(&self, cx: &App) -> Option<Arc<SourceSet>> {
        self.store.read(cx).sources().cloned()
    }

    // ------------------------------------------------------------------------
    // Rendering
    // ------------------------------------------------------------------------

    /// Asks for a frame once the current update ends.
    pub fn request_render(&mut self, cx: &mut Context<Self>) {
        self.view.needs_render = true;
        cx.notify();
        if self.scheduled {
            return;
        }
        self.scheduled = true;
        let this = cx.weak_entity();
        cx.defer(move |cx| {
            let _ = this.update(cx, |vm, cx| {
                vm.scheduled = false;
                vm.submit(cx);
            });
        });
    }

    fn submit(&mut self, cx: &mut Context<Self>) {
        if !self.active || !self.view.needs_render || self.view.canvas_width == 0 || self.view.canvas_height == 0 {
            return;
        }
        // Hidden behind another workspace: draw when its workspace shows again (the work pool
        // and the device stay free for the workspace in front)
        if self.store.read(cx).workspace != self.home {
            return;
        }
        let Some(sources) = self.sources(cx) else { return };
        self.view.needs_render = false;
        // The pyramid builds in the background, nearest what this view shows first
        let (source_id, focus) = (self.view.source.clone(), self.store.read(cx).timeline.window_start_sec);
        self.store.update(cx, |s, cx| s.focus_pyramid(&source_id, focus, cx));
        let store = self.store.read(cx);
        let dataset = sources.get(&self.view.source);
        let on_default = sources.index_of(&self.view.source) == sources.index_of("");
        let events = match &store.recording {
            Some(r) if on_default => r.events.clone(),
            _ => Default::default(),
        };
        // This view's session view: its processed preview, else the recording as stored
        let shown = self.shown_view(store);
        let signal = shown.and_then(|v| store.preview_of(&v.id)).unwrap_or_else(|| dataset.signal().clone());
        let mut req = self.view.render_request(&store.timeline, signal, events, store.palette());
        let window = req.window_start_sec..req.window_start_sec + req.window_sec;
        match req.mode {
            TimeViewKind::Traces if self.view.spikes => {
                req.overlay = shown.and_then(|v| crate::plugin::plugins().iter().find_map(|p| p.trace_overlay(store, v, window.clone(), cx))).map(Arc::new);
            }
            TimeViewKind::Raster => {
                req.raster = shown.and_then(|v| crate::plugin::plugins().iter().find_map(|p| p.raster(store, v, window.clone(), cx))).map(Arc::new);
            }
            _ => {}
        }
        let samples_per_px = req.window_sec * dataset.sample_rate / req.width.max(1) as f64;
        let (start, window) = (req.window_start_sec, req.window_sec);
        let tx = self.frames.clone();
        let work = Box::new(move |cancel: &std::sync::atomic::AtomicBool| {
            let t0 = Instant::now();
            let Some((frame, scale, complete)) = render_on_worker(&req, cancel) else { return };
            let (w, h) = (frame.width, frame.height);
            let Some(buffer) = image::RgbaImage::from_raw(w, h, frame.into_bgra()) else { return };
            // Converted here, on the work thread: the UI thread only shows it
            let image = Arc::new(RenderImage::new(vec![image::Frame::new(buffer)]));
            let shown = Shown { image, start, window };
            let _ = tx.try_send(Delivered { shown, scale: Some(scale), complete, elapsed: t0.elapsed(), samples_per_px });
        });
        cx.global::<Services>().pool.request(JobKey::new(self.view.id, RENDER_SLOT), work);
    }

    fn on_frame(&mut self, d: Delivered, cx: &mut Context<Self>) {
        if let Some(scale) = d.scale {
            // The scale bar follows the scale the frame was drawn with
            self.view.amp_scale = scale;
        }
        self.incomplete = !d.complete;
        if let Some(old) = self.retired.take() {
            cx.drop_image(old, None);
        }
        self.retired = self.shown.replace(d.shown).map(|s| s.image);
        let info = format!("Render {:.1} ms · {:.1} samples/px", d.elapsed.as_secs_f64() * 1e3, d.samples_per_px);
        self.store.update(cx, |s, cx| s.set_render_info(info, cx));
        cx.notify();
    }

    /// Plot area size in physical pixels.
    pub fn set_plot_size(&mut self, width: u32, height: u32, scale: f32, cx: &mut Context<Self>) {
        if (width, height, scale) != (self.view.canvas_width, self.view.canvas_height, self.view.scale_factor) {
            self.view.set_canvas(width, height, scale);
            self.request_render(cx);
        }
    }

    /// Shown or hidden in its tab group (or its dock opened / closed).
    pub fn set_active(&mut self, active: bool, cx: &mut Context<Self>) {
        self.active = active;
        if active && self.view.needs_render {
            self.request_render(cx);
        }
    }

    /// The view left the dock: stop its jobs and release its images.
    pub fn close(&mut self, cx: &mut Context<Self>) {
        self.active = false;
        cx.global::<Services>().pool.forget(self.view.id);
        for image in self.shown.take().map(|s| s.image).into_iter().chain(self.retired.take()) {
            cx.drop_image(image, None);
        }
    }

    // ------------------------------------------------------------------------
    // Settings (this view only)
    // ------------------------------------------------------------------------

    pub fn set_kind(&mut self, kind: TimeViewKind, cx: &mut Context<Self>) {
        if self.view.kind != kind {
            self.view.kind = kind;
            self.view.retitle();
            cx.emit(TraceEvent::Changed);
            self.request_render(cx);
        }
    }

    /// Traces with the spikes coloured (`spikes`), or alone.
    pub fn set_spikes(&mut self, spikes: bool, cx: &mut Context<Self>) {
        if self.view.spikes != spikes {
            self.view.spikes = spikes;
            cx.emit(TraceEvent::Changed);
            self.request_render(cx);
        }
    }

    pub fn set_color_by(&mut self, color_by: crate::screens::explore::trace::renderer::ColorBy, cx: &mut Context<Self>) {
        if self.view.color_by != color_by {
            self.view.color_by = color_by;
            cx.emit(TraceEvent::Changed);
            self.request_render(cx);
        }
    }

    /// Shows another source of the open file (Explore's views: with that source's session view
    /// and its processing).
    pub fn set_source(&mut self, source: &str, cx: &mut Context<Self>) {
        if self.view.source != source {
            Self::attach(&mut self.view, &self.store, source, cx);
            let old = std::mem::take(&mut self.view.doc_view);
            if !old.is_empty() {
                cx.emit(TraceEvent::Released(old));
            }
            self.shown = None;
            self.bind(cx);
            cx.emit(TraceEvent::Changed);
            self.request_render(cx);
        }
    }

    /// Explore's views show a session view of their own: the one of their source with all its
    /// channels (made when none). The workspaces' strips follow the active session view instead.
    fn bind(&mut self, cx: &mut Context<Self>) {
        if self.home != Workspace::Explore || !self.view.doc_view.is_empty() {
            return;
        }
        let (store, source) = (self.store.clone(), self.view.source.clone());
        let this = cx.weak_entity();
        // After this update: making the session view updates the store
        cx.defer(move |cx| {
            let id = store.update(cx, |s, cx| s.view_for_source(&source, cx));
            let _ = this.update(cx, |vm, cx| {
                if let Some(id) = id
                    && vm.view.source == source
                {
                    vm.view.doc_view = id;
                    cx.emit(TraceEvent::Changed);
                }
                vm.request_render(cx);
            });
        });
    }

    /// The session view this view draws: its own (Explore), else the active one when it reads this
    /// view's source (the strips).
    pub fn shown_view<'a>(&self, store: &'a Store) -> Option<&'a crate::domain::session::ViewDoc> {
        if !self.view.doc_view.is_empty() {
            return store.doc.view(&self.view.doc_view);
        }
        store.active_view().filter(|v| store.view_source(v) == self.view.source)
    }

    pub fn set_lanes(&mut self, lanes: usize, cx: &mut Context<Self>) {
        self.view.set_lanes(lanes);
        cx.emit(TraceEvent::Changed);
        self.request_render(cx);
    }

    pub fn scroll_by(&mut self, delta: i64, cx: &mut Context<Self>) {
        let before = self.view.scroll;
        self.view.scroll_by(delta);
        if self.view.scroll != before {
            self.request_render(cx);
        }
    }

    pub fn page(&mut self, forward: bool, cx: &mut Context<Self>) {
        let before = self.view.scroll;
        self.view.page(forward);
        if self.view.scroll != before {
            self.request_render(cx);
        }
    }

    pub fn zoom_gain(&mut self, factor: f32, cx: &mut Context<Self>) {
        self.view.zoom_gain(factor);
        cx.emit(TraceEvent::Changed);
        self.request_render(cx);
    }

    pub fn set_auto_scale(&mut self, on: bool, cx: &mut Context<Self>) {
        self.view.auto_scale = on;
        cx.emit(TraceEvent::Changed);
        self.request_render(cx);
    }

    pub fn set_remove_dc(&mut self, on: bool, cx: &mut Context<Self>) {
        self.view.remove_dc = on;
        cx.emit(TraceEvent::Changed);
        self.request_render(cx);
    }

    /// Pins (or unpins) this view's channel selection from the source's shared selection.
    pub fn set_pinned_selection(&mut self, pinned: bool, cx: &mut Context<Self>) {
        if self.view.pinned_selection == pinned {
            return;
        }
        self.view.pinned_selection = pinned;
        if !pinned {
            let s = self.store.read(cx);
            let channels = s.selection(&self.view.source).to_vec();
            let total = s.sources().map_or(0, |ss| ss.entry(&self.view.source).channels);
            self.view.set_selection(channels, total);
        }
        cx.emit(TraceEvent::Changed);
        self.request_render(cx);
    }

    fn total_channels(&self, cx: &App) -> usize {
        self.store.read(cx).sources().map_or(0, |s| s.entry(&self.view.source).channels)
    }

    pub fn set_selection(&mut self, channels: impl IntoIterator<Item = usize>, cx: &mut Context<Self>) {
        let total = self.total_channels(cx);
        self.view.set_selection(channels, total);
        cx.emit(TraceEvent::Changed);
        self.request_render(cx);
    }

    pub fn toggle_channel(&mut self, channel: usize, cx: &mut Context<Self>) {
        let total = self.total_channels(cx);
        self.view.toggle_channel(channel, total);
        cx.emit(TraceEvent::Changed);
        self.request_render(cx);
    }

    pub fn select_all(&mut self, cx: &mut Context<Self>) {
        let total = self.total_channels(cx);
        self.set_selection(0..total, cx);
    }

    pub fn select_none(&mut self, cx: &mut Context<Self>) {
        self.set_selection([], cx);
    }

    pub fn select_invert(&mut self, cx: &mut Context<Self>) {
        let total = self.total_channels(cx);
        let keep: Vec<usize> = (0..total).filter(|c| !self.view.selection.contains(c)).collect();
        self.set_selection(keep, cx);
    }

    pub fn select_ranges(&mut self, text: &str, cx: &mut Context<Self>) -> Result<(), String> {
        let channels = crate::screens::explore::trace::view::parse_channel_ranges(text, self.total_channels(cx))?;
        self.set_selection(channels, cx);
        Ok(())
    }

    /// Scrolls so `channel` is on screen; false when this view does not show it.
    pub fn reveal(&mut self, channel: usize, cx: &mut Context<Self>) -> bool {
        let found = self.view.reveal(channel);
        if found {
            self.request_render(cx);
        }
        found
    }

    pub fn pressed(&mut self, cx: &mut Context<Self>) {
        cx.emit(TraceEvent::Pressed);
    }

    // ------------------------------------------------------------------------
    // Pointer (positions as fractions of the plot area)
    // ------------------------------------------------------------------------

    /// The pointer at (`fx`, `fy`) of the plot: a readout now, or once its sample is read.
    pub fn hover_at(&mut self, fx: f32, fy: f32, cx: &mut Context<Self>) {
        let Some(sources) = self.sources(cx) else { return };
        let dataset = sources.get(&self.view.source);
        let (w, h) = (self.view.canvas_width as f32, self.view.canvas_height as f32);
        self.view.hover_seq += 1;
        let target = self.view.hover_target(fx * w, fy * h, &dataset, &self.store.read(cx).timeline);
        match target {
            HoverTarget::Text(text) => {
                self.hover = text;
                cx.notify();
            }
            HoverTarget::Sample { channel, sample, prefix, unit } => {
                let req = HoverRequest { seq: self.view.hover_seq, dataset, channel, sample, prefix, unit, reply: self.hover_reply.clone() };
                cx.global::<Services>().hover.request(req);
            }
        }
    }

    pub fn hover_left(&mut self, cx: &mut Context<Self>) {
        self.view.hover_seq += 1;
        if !self.hover.is_empty() {
            self.hover.clear();
            cx.notify();
        }
    }

    /// Channel at a height (fraction of the plot).
    pub fn channel_at(&self, fy: f32) -> Option<usize> {
        self.view.channel_at(fy * self.view.canvas_height as f32)
    }
}