forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

grading.rs230 lines, 9.7 KiBHistoryRawDownload
1//! The colour card's tools beside its sliders, and the viewer's compare view they are checked
2//! against: Auto (a correction read off the picture as shot), Looks (built-in and saved grades,
3//! each one undo step) and Compare (the picture as shot beside the graded one, preview only).
4//!
5//! The picture as shot is the timeline composed with every grade taken off
6//! ([`engine::export::compose_ungraded_at`]). It is read in the background, one at a time, so a
7//! playing timeline keeps its own pace and the compare view catches up when the picture settles.
8
9use crate::player::text_field::{FieldKey, TextField};
10use crate::viewer_view::Compare;
11use crate::*;
12use engine::color::ColorParams;
13use gpui::RenderImage;
14use std::sync::Arc;
15
16/// The look last applied to a clip: which clip, its name, and the grade it left. The Looks row
17/// shows the name while the grade is still that one, and "Custom" once a slider or wheel moves.
18/// Kept in session state only, so the project format does not change. The clip is keyed by its
19/// source and in point, which a move leaves alone.
20#[derive(Clone, Debug)]
21pub(crate) struct LookMark {
22 pub(crate) clip: (usize, u32),
23 pub(crate) name: String,
24 pub(crate) params: ColorParams,
25}
26
27/// The most characters a look name may hold (the engine's own limit).
28pub(crate) const LOOK_NAME_MAX: usize = 60;
29
30/// The widest a picture is read at for Auto, in pixels: the statistics do not need more.
31const READ_W: u32 = 640;
32
33/// `(w, h)` scaled to at most [`READ_W`] wide, keeping the aspect.
34fn read_size(w: u32, h: u32) -> (u32, u32) {
35 if w <= READ_W || w == 0 {
36 return (w.max(2), h.max(2));
37 }
38 (READ_W, (u64::from(h) * u64::from(READ_W) / u64::from(w)).max(2) as u32)
39}
40
41impl Player {
42 /// View > Compare grade, and the card's Compare row: which compare view is on.
43 pub(crate) fn set_compare(&mut self, mode: Compare, cx: &mut Context<Self>) {
44 self.compare = mode;
45 self.before_at = None;
46 cx.notify();
47 }
48
49 /// Reads the picture as shot at the frame on screen, in the background, when the compare view
50 /// is on and that frame is not in hand. One read runs at a time; when it lands, a frame that
51 /// moved on in the meantime is read again.
52 pub(crate) fn refresh_before(&mut self, window: &mut Window, cx: &mut Context<Self>) {
53 let Some((at, w, h)) = self.shown_frame else {
54 return;
55 };
56 if self.compare == Compare::Off || self.preview_session.is_some() || self.before_busy || self.before_at == Some(at) {
57 return;
58 }
59 let Some(session) = self.session.as_ref() else {
60 return;
61 };
62 let (project, meta) = session.export_snapshot();
63 self.before_busy = true;
64 let read = cx.background_executor().spawn(async move {
65 // The frame comes back at the size it was composed at, which can differ by a pixel
66 // from the one asked for; the image is built from that size, or it is never shown.
67 let r = engine::export::compose_ungraded_at(&project, &meta, at, w, h);
68 r.ok().map(|f| (f.width, f.height, f.bgra))
69 });
70 cx.spawn_in(window, async move |this, cx| {
71 let frame = read.await;
72 this.update_in(cx, |this, window, cx| {
73 this.before_busy = false;
74 if let Some(buf) = frame.and_then(|(w, h, b)| image::RgbaImage::from_raw(w, h, b)) {
75 let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
76 if let Some(old) = this.before.replace(next) {
77 let _ = window.drop_image(old);
78 }
79 this.before_at = Some(at);
80 }
81 this.refresh_before(window, cx);
82 cx.notify();
83 })
84 .ok();
85 })
86 .detach();
87 }
88
89 /// The colour card's Auto, and Edit > Auto colour: reads a correction off the card's clip
90 /// as shot at its middle frame and writes it onto the grade in one undo step. The card opens
91 /// on the playhead's clip first when none is open.
92 pub(crate) fn auto_colour(&mut self, cx: &mut Context<Self>) {
93 if self.color_open.is_none() {
94 self.open_color(cx);
95 }
96 let Some((lane, idx)) = self.color_open else {
97 return;
98 };
99 let Some(session) = self.session.as_ref() else {
100 return;
101 };
102 let keyed = session.color_keys_of(lane, idx).len();
103 if keyed > 0 {
104 self.notify_user("Auto colour is off while colour keys grade this clip; the keys are kept".into());
105 cx.notify();
106 return;
107 }
108 let Some(clip) = session.lane_clips(lane).get(idx) else {
109 return;
110 };
111 let mid = clip.start + clip.len() / 2;
112 let (project, meta) = session.export_snapshot();
113 let (w, h) = read_size(meta.width, meta.height);
114 let read = cx.background_executor().spawn(async move {
115 let f = engine::export::compose_ungraded_at(&project, &meta, mid, w, h).ok()?;
116 let rgb: Vec<u8> = f.bgra.as_chunks::<4>().0.iter().flat_map(|p| [p[2], p[1], p[0]]).collect();
117 engine::auto_color::analyse(&rgb, f.width as usize, f.height as usize)
118 });
119 cx.spawn(async move |this, cx| {
120 let fix = read.await;
121 this.update(cx, |this, cx| {
122 let Some(fix) = fix else {
123 this.notify_user("Auto colour: there is no picture to read at this clip".into());
124 cx.notify();
125 return;
126 };
127 let Some(session) = this.session.as_ref() else {
128 return;
129 };
130 let next = fix.apply(session.color_of(lane, idx).copied().unwrap_or_default());
131 this.named_step("Auto colour", |this| this.write_color_now(next, false, cx));
132 cx.notify();
133 })
134 .ok();
135 })
136 .detach();
137 }
138
139 /// The names the Looks dropdown lists: the built-ins, then the user's saved looks.
140 pub(crate) fn look_names(&self) -> Vec<String> {
141 engine::looks::builtins()
142 .iter()
143 .map(|(n, _)| n.to_string())
144 .chain(self.saved_looks.iter().cloned())
145 .collect()
146 }
147
148 /// The card's clip, by its source and in point (see [`LookMark`]).
149 fn look_key(&self) -> Option<(usize, u32)> {
150 let (lane, idx) = self.color_open?;
151 let clip = self.session.as_ref()?.lane_clips(lane).get(idx)?;
152 Some((clip.source, clip.in_frame))
153 }
154
155 /// What the Looks row shows: the look applied to this clip while its grade is still that one,
156 /// "Custom" once it has moved, and "Choose a look" before any look went on this clip.
157 pub(crate) fn look_label(&self) -> String {
158 match (&self.look_mark, self.look_key()) {
159 (Some(mark), Some(clip)) if mark.clip == clip && self.color_params() == mark.params => mark.name.clone(),
160 (Some(mark), Some(clip)) if mark.clip == clip => "Custom".to_owned(),
161 _ => "Choose a look".to_owned(),
162 }
163 }
164
165 /// Opens or closes the Looks dropdown; opening re-reads the saved looks.
166 pub(crate) fn toggle_look_list(&mut self, cx: &mut Context<Self>) {
167 self.look_open = !self.look_open;
168 if self.look_open {
169 self.saved_looks = engine::looks::saved_names();
170 }
171 cx.notify();
172 }
173
174 /// Puts the look called `name` on the card's clip, replacing its grade, as one undo step.
175 pub(crate) fn apply_look(&mut self, name: &str, cx: &mut Context<Self>) {
176 self.look_open = false;
177 if self.color_open.is_none() {
178 return;
179 }
180 match engine::looks::load(name) {
181 Ok(params) => {
182 let label = format!("Look {name}");
183 self.named_step(&label, |this| this.write_color_now(params, false, cx));
184 // The grade as the clip now holds it, so the name holds until something moves.
185 self.look_mark = self.look_key().map(|clip| LookMark { clip, name: name.to_owned(), params: self.color_params() });
186 }
187 Err(why) => self.notify_user(why.into()),
188 }
189 cx.notify();
190 }
191
192 /// "Save current as look…": opens the name field under the Looks row.
193 pub(crate) fn begin_look_save(&mut self, cx: &mut Context<Self>) {
194 self.look_open = false;
195 self.look_name = Some(TextField::selected(String::new()));
196 cx.notify();
197 }
198
199 /// Keys for the look name field: Enter saves, Escape cancels, the rest types.
200 pub(crate) fn look_name_key(&mut self, key: &str, ctrl: bool, alt: bool, key_char: Option<&str>, cx: &mut Context<Self>) {
201 let Some(field) = self.look_name.as_mut() else {
202 return;
203 };
204 match field.key(key, ctrl, alt, key_char, LOOK_NAME_MAX) {
205 FieldKey::Cancel => self.look_name = None,
206 FieldKey::Commit => self.commit_look_save(cx),
207 FieldKey::Edited => {}
208 }
209 cx.notify();
210 }
211
212 /// Saves the card's grade under the typed name. A name that will not do is said in a note
213 /// and the field stays open with what was typed.
214 pub(crate) fn commit_look_save(&mut self, cx: &mut Context<Self>) {
215 let Some(field) = &self.look_name else {
216 return;
217 };
218 let name = field.text.clone();
219 let params: ColorParams = self.color_params();
220 match engine::looks::save(&name, &params) {
221 Ok(_) => {
222 self.look_name = None;
223 self.saved_looks = engine::looks::saved_names();
224 self.notify_user(format!("Saved look {}", name.trim()).into());
225 }
226 Err(why) => self.notify_user(why.into()),
227 }
228 cx.notify();
229 }
230}