BlueGit

ict rusty-teams

feat(app): built-in image viewer with zoom, rotate, copy, save and chat navigation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-11 · 7 weeks ago

Hash
1937648c347ad3d83f0ee9aedebd4340389bdb9d
Parent
5b9c7baa
22 files changed +1462 −6
crates/app/assets/symbols/chevron_left.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M560-240 320-480l240-240 56 56-184 184 184 184-56 56Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M560-240 320-480l240-240 56 56-184 184 184 184-56 56Z"/></svg>
crates/app/assets/symbols/chevron_right.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M504-480 320-664l56-56 240 240-240 240-56-56 184-184Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M504-480 320-664l56-56 240 240-240 240-56-56 184-184Z"/></svg>
crates/app/assets/symbols/forward.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="m640-280-57-56 184-184-184-184 57-56 240 240-240 240ZM80-200v-160q0-83 58.5-141.5T280-560h247L383-704l57-56 240 240-240 240-57-56 144-144H280q-50 0-85 35t-35 85v160H80Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="m640-280-57-56 184-184-184-184 57-56 240 240-240 240ZM80-200v-160q0-83 58.5-141.5T280-560h247L383-704l57-56 240 240-240 240-57-56 144-144H280q-50 0-85 35t-35 85v160H80Z"/></svg>
crates/app/assets/symbols/fullscreen.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M120-120v-200h80v120h120v80H120Zm520 0v-80h120v-120h80v200H640ZM120-640v-200h200v80H200v120h-80Zm640 0v-120H640v-80h200v200h-80Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M120-120v-200h80v120h120v80H120Zm520 0v-80h120v-120h80v200H640ZM120-640v-200h200v80H200v120h-80Zm640 0v-120H640v-80h200v200h-80Z"/></svg>
crates/app/assets/symbols/open_in_new.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h280v80H200v560h560v-280h80v280q0 33-23.5 56.5T760-120H200Zm188-212-56-56 372-372H560v-80h280v280h-80v-144L388-332Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h280v80H200v560h560v-280h80v280q0 33-23.5 56.5T760-120H200Zm188-212-56-56 372-372H560v-80h280v280h-80v-144L388-332Z"/></svg>
crates/app/assets/symbols/rotate_right.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M522-80v-82q34-5 66.5-18t61.5-34l56 58q-42 32-88 51.5T522-80Zm-80 0Q304-98 213-199.5T122-438q0-75 28.5-140.5t77-114q48.5-48.5 114-77T482-798h6l-62-62 56-58 160 160-160 160-56-56 64-64h-8q-117 0-198.5 81.5T202-438q0 104 68 182.5T442-162v82Zm322-134-58-56q21-29 34-61.5t18-66.5h82q-5 50-24.5 96T764-214Zm76-264h-82q-5-34-18-66.5T706-606l58-56q32 39 51 86t25 98Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M522-80v-82q34-5 66.5-18t61.5-34l56 58q-42 32-88 51.5T522-80Zm-80 0Q304-98 213-199.5T122-438q0-75 28.5-140.5t77-114q48.5-48.5 114-77T482-798h6l-62-62 56-58 160 160-160 160-56-56 64-64h-8q-117 0-198.5 81.5T202-438q0 104 68 182.5T442-162v82Zm322-134-58-56q21-29 34-61.5t18-66.5h82q-5 50-24.5 96T764-214Zm76-264h-82q-5-34-18-66.5T706-606l58-56q32 39 51 86t25 98Z"/></svg>
crates/app/assets/symbols/zoom_in.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M784-120 532-372q-30 24-69 38t-83 14q-109 0-184.5-75.5T120-580q0-109 75.5-184.5T380-840q109 0 184.5 75.5T640-580q0 44-14 83t-38 69l252 252-56 56ZM380-400q75 0 127.5-52.5T560-580q0-75-52.5-127.5T380-760q-75 0-127.5 52.5T200-580q0 75 52.5 127.5T380-400Zm-40-60v-80h-80v-80h80v-80h80v80h80v80h-80v80h-80Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M784-120 532-372q-30 24-69 38t-83 14q-109 0-184.5-75.5T120-580q0-109 75.5-184.5T380-840q109 0 184.5 75.5T640-580q0 44-14 83t-38 69l252 252-56 56ZM380-400q75 0 127.5-52.5T560-580q0-75-52.5-127.5T380-760q-75 0-127.5 52.5T200-580q0 75 52.5 127.5T380-400Zm-40-60v-80h-80v-80h80v-80h80v80h80v80h-80v80h-80Z"/></svg>
crates/app/assets/symbols/zoom_out.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M784-120 532-372q-30 24-69 38t-83 14q-109 0-184.5-75.5T120-580q0-109 75.5-184.5T380-840q109 0 184.5 75.5T640-580q0 44-14 83t-38 69l252 252-56 56ZM380-400q75 0 127.5-52.5T560-580q0-75-52.5-127.5T380-760q-75 0-127.5 52.5T200-580q0 75 52.5 127.5T380-400ZM280-540v-80h200v80H280Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M784-120 532-372q-30 24-69 38t-83 14q-109 0-184.5-75.5T120-580q0-109 75.5-184.5T380-840q109 0 184.5 75.5T640-580q0 44-14 83t-38 69l252 252-56 56ZM380-400q75 0 127.5-52.5T560-580q0-75-52.5-127.5T380-760q-75 0-127.5 52.5T200-580q0 75 52.5 127.5T380-400ZM280-540v-80h200v80H280Z"/></svg>
crates/app/src/app_state.rs +4 −0
@@ -16,6 +16,7 @@ use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
16 16 use calling::meeting::LiveMeeting;
17 17 use crate::card_state::{CardState, TaskDialogState};
18 18 use crate::data::{self, Directory};
19 use crate::image_view_gallery::ViewerRequest;
19 20 use crate::local_previews::{LocalPreview, load_local_previews};
20 21 use crate::message_actions::{ForwardSource, SavedSet};
21 22 use crate::notice::Notice;
@@ -59,6 +60,7 @@ pub enum AppEvent {
59 60 CallHistory,
60 61 Translation,
61 62 Forward,
63 ImageViewer,
62 64 StatusMessage,
63 65 NotificationSettings,
64 66 Profile,
@@ -110,6 +112,7 @@ pub struct AppState {
110 112 pub calls_list: crate::call::CallsList,
111 113 pub pins: HashMap<String, Vec<PinnedMessage>>,
112 114 pub forward_request: Option<ForwardSource>,
115 pub image_viewer_request: Option<ViewerRequest>,
113 116 pub own_status: PresenceStatus,
114 117 pub own_email: String,
115 118 pub status_menu_open: bool,
@@ -211,6 +214,7 @@ impl AppState {
211 214 calls_list: crate::call::CallsList::default(),
212 215 pins: HashMap::new(),
213 216 forward_request: None,
217 image_viewer_request: None,
214 218 own_status: PresenceStatus::default(),
215 219 own_email: String::new(),
216 220 status_menu_open: false,
@@ -16,6 +16,7 @@ use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
16use calling::meeting::LiveMeeting;
16use calling::meeting::LiveMeeting;
17use crate::card_state::{CardState, TaskDialogState};
17use crate::card_state::{CardState, TaskDialogState};
18use crate::data::{self, Directory};
18use crate::data::{self, Directory};
19use crate::image_view_gallery::ViewerRequest;
19use crate::local_previews::{LocalPreview, load_local_previews};
20use crate::local_previews::{LocalPreview, load_local_previews};
20use crate::message_actions::{ForwardSource, SavedSet};
21use crate::message_actions::{ForwardSource, SavedSet};
21use crate::notice::Notice;
22use crate::notice::Notice;
@@ -59,6 +60,7 @@ pub enum AppEvent {
59 CallHistory,
60 CallHistory,
60 Translation,
61 Translation,
61 Forward,
62 Forward,
63 ImageViewer,
62 StatusMessage,
64 StatusMessage,
63 NotificationSettings,
65 NotificationSettings,
64 Profile,
66 Profile,
@@ -110,6 +112,7 @@ pub struct AppState {
110 pub calls_list: crate::call::CallsList,
112 pub calls_list: crate::call::CallsList,
111 pub pins: HashMap<String, Vec<PinnedMessage>>,
113 pub pins: HashMap<String, Vec<PinnedMessage>>,
112 pub forward_request: Option<ForwardSource>,
114 pub forward_request: Option<ForwardSource>,
115 pub image_viewer_request: Option<ViewerRequest>,
113 pub own_status: PresenceStatus,
116 pub own_status: PresenceStatus,
114 pub own_email: String,
117 pub own_email: String,
115 pub status_menu_open: bool,
118 pub status_menu_open: bool,
@@ -211,6 +214,7 @@ impl AppState {
211 calls_list: crate::call::CallsList::default(),
214 calls_list: crate::call::CallsList::default(),
212 pins: HashMap::new(),
215 pins: HashMap::new(),
213 forward_request: None,
216 forward_request: None,
217 image_viewer_request: None,
214 own_status: PresenceStatus::default(),
218 own_status: PresenceStatus::default(),
215 own_email: String::new(),
219 own_email: String::new(),
216 status_menu_open: false,
220 status_menu_open: false,
crates/app/src/assets.rs +9 −1
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 32] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 40] = symbols![
12 12 "done",
13 13 "done_all",
14 14 "keyboard_return",
@@ -41,6 +41,14 @@ const SYMBOLS: [(&str, &[u8]); 32] = symbols![
41 41 "status_dnd",
42 42 "status_away",
43 43 "status_ring",
44 "zoom_in",
45 "zoom_out",
46 "rotate_right",
47 "forward",
48 "open_in_new",
49 "chevron_left",
50 "chevron_right",
51 "fullscreen",
44 52 ];
45 53
46 54 pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 32] = symbols![
11const SYMBOLS: [(&str, &[u8]); 40] = symbols![
12 "done",
12 "done",
13 "done_all",
13 "done_all",
14 "keyboard_return",
14 "keyboard_return",
@@ -41,6 +41,14 @@ const SYMBOLS: [(&str, &[u8]); 32] = symbols![
41 "status_dnd",
41 "status_dnd",
42 "status_away",
42 "status_away",
43 "status_ring",
43 "status_ring",
44 "zoom_in",
45 "zoom_out",
46 "rotate_right",
47 "forward",
48 "open_in_new",
49 "chevron_left",
50 "chevron_right",
51 "fullscreen",
44];
52];
45
53
46pub struct AppAssets;
54pub struct AppAssets;
crates/app/src/image_view_math.rs added +251 −0
@@ -0,0 +1,251 @@
1 use std::ops::Range;
2
3 pub type Pair = (f32, f32);
4
5 pub const MAX_ZOOM: f32 = 4.;
6 pub const ZOOM_STEP: f32 = 1.25;
7 const WHEEL_SENSITIVITY: f32 = 0.01;
8 const SCALE_EPSILON: f32 = 0.001;
9
10 pub fn rotated_size(size: Pair, quarter_turns: u8) -> Pair {
11 if quarter_turns % 2 == 0 {
12 size
13 } else {
14 (size.1, size.0)
15 }
16 }
17
18 pub fn next_rotation(quarter_turns: u8) -> u8 {
19 (quarter_turns + 1) % 4
20 }
21
22 pub fn fit_scale(image: Pair, stage: Pair) -> f32 {
23 if image.0 <= 0. || image.1 <= 0. || stage.0 <= 0. || stage.1 <= 0. {
24 return 1.;
25 }
26 (stage.0 / image.0).min(stage.1 / image.1).min(1.)
27 }
28
29 pub fn clamp_scale(scale: f32, fit: f32) -> f32 {
30 scale.clamp(fit, MAX_ZOOM.max(fit))
31 }
32
33 pub fn display_size(image: Pair, scale: f32) -> Pair {
34 (image.0 * scale, image.1 * scale)
35 }
36
37 pub fn clamp_pan(pan: Pair, display: Pair, stage: Pair) -> Pair {
38 let limit = |display: f32, stage: f32| ((display - stage) / 2.).max(0.);
39 let (limit_x, limit_y) = (limit(display.0, stage.0), limit(display.1, stage.1));
40 (
41 pan.0.clamp(-limit_x, limit_x),
42 pan.1.clamp(-limit_y, limit_y),
43 )
44 }
45
46 pub fn image_origin(display: Pair, stage: Pair, pan: Pair) -> Pair {
47 (
48 (stage.0 - display.0) / 2. + pan.0,
49 (stage.1 - display.1) / 2. + pan.1,
50 )
51 }
52
53 #[derive(Debug, Clone, Copy, PartialEq)]
54 pub struct View {
55 pub scale: f32,
56 pub pan: Pair,
57 }
58
59 pub fn zoom_at(view: View, wanted: f32, anchor: Pair, image: Pair, stage: Pair) -> View {
60 let fit = fit_scale(image, stage);
61 let scale = clamp_scale(wanted, fit);
62 let ratio = scale / view.scale;
63 let pan = (
64 anchor.0 - (anchor.0 - view.pan.0) * ratio,
65 anchor.1 - (anchor.1 - view.pan.1) * ratio,
66 );
67 View {
68 scale,
69 pan: clamp_pan(pan, display_size(image, scale), stage),
70 }
71 }
72
73 pub fn wheel_scale(scale: f32, delta_y: f32) -> f32 {
74 scale * (delta_y * WHEEL_SENSITIVITY).exp()
75 }
76
77 pub fn step_scale(scale: f32, direction: i32) -> f32 {
78 scale * ZOOM_STEP.powi(direction)
79 }
80
81 pub fn toggle_target(scale: f32, fit: f32) -> f32 {
82 if scale > fit + SCALE_EPSILON {
83 fit
84 } else {
85 1_f32.max(fit)
86 }
87 }
88
89 pub fn percent_label(scale: f32) -> String {
90 format!("{}%", (scale * 100.).round() as u32)
91 }
92
93 pub fn step_index(current: usize, len: usize, delta: isize) -> usize {
94 if len == 0 {
95 return 0;
96 }
97 current
98 .saturating_add_signed(delta)
99 .min(len - 1)
100 }
101
102 pub fn counter_label(index: usize, len: usize) -> String {
103 format!("{} of {}", index + 1, len)
104 }
105
106 pub fn thumbnail_window(index: usize, len: usize, capacity: usize) -> Range<usize> {
107 let capacity = capacity.max(1).min(len);
108 let start = index
109 .saturating_sub(capacity / 2)
110 .min(len.saturating_sub(capacity));
111 start..start + capacity
112 }
113
114 #[cfg(test)]
115 mod tests {
116 use super::*;
117
118 const STAGE: Pair = (800., 600.);
119
120 #[test]
121 fn fit_contains_large_images_and_never_upscales() {
122 assert_eq!(fit_scale((1600., 1200.), STAGE), 0.5);
123 assert_eq!(fit_scale((1600., 300.), STAGE), 0.5);
124 assert_eq!(fit_scale((100., 100.), STAGE), 1.);
125 assert_eq!(fit_scale((0., 100.), STAGE), 1.);
126 }
127
128 #[test]
129 fn rotation_swaps_the_sides_on_odd_quarter_turns() {
130 assert_eq!(rotated_size((400., 200.), 0), (400., 200.));
131 assert_eq!(rotated_size((400., 200.), 1), (200., 400.));
132 assert_eq!(rotated_size((400., 200.), 2), (400., 200.));
133 assert_eq!(rotated_size((400., 200.), 3), (200., 400.));
134 assert_eq!(next_rotation(3), 0);
135 assert_eq!(next_rotation(0), 1);
136 }
137
138 #[test]
139 fn scale_is_limited_to_fit_and_four_times_the_source() {
140 assert_eq!(clamp_scale(0.1, 0.5), 0.5);
141 assert_eq!(clamp_scale(9., 0.5), MAX_ZOOM);
142 assert_eq!(clamp_scale(2., 0.5), 2.);
143 }
144
145 #[test]
146 fn pan_is_clamped_to_the_image_bounds() {
147 let display = (1600., 400.);
148 assert_eq!(clamp_pan((900., 50.), display, STAGE), (400., 0.));
149 assert_eq!(clamp_pan((-900., -50.), display, STAGE), (-400., 0.));
150 assert_eq!(clamp_pan((10., 10.), (400., 300.), STAGE), (0., 0.));
151 }
152
153 #[test]
154 fn image_origin_centers_and_follows_the_pan() {
155 assert_eq!(image_origin((400., 300.), STAGE, (0., 0.)), (200., 150.));
156 assert_eq!(image_origin((1600., 600.), STAGE, (-100., 0.)), (-500., 0.));
157 }
158
159 #[test]
160 fn zoom_keeps_the_point_under_the_cursor_fixed() {
161 let image = (2000., 1500.);
162 let start = View {
163 scale: 0.4,
164 pan: (0., 0.),
165 };
166 let anchor = (100., 50.);
167 let zoomed = zoom_at(start, 1., anchor, image, STAGE);
168 assert_eq!(zoomed.scale, 1.);
169 let before = ((anchor.0 - start.pan.0) / start.scale, (anchor.1 - start.pan.1) / start.scale);
170 let after = ((anchor.0 - zoomed.pan.0) / zoomed.scale, (anchor.1 - zoomed.pan.1) / zoomed.scale);
171 assert!((before.0 - after.0).abs() < 0.01);
172 assert!((before.1 - after.1).abs() < 0.01);
173 }
174
175 #[test]
176 fn zooming_back_to_fit_recenters() {
177 let image = (2000., 1500.);
178 let zoomed = View {
179 scale: 2.,
180 pan: (300., -200.),
181 };
182 let fit = zoom_at(zoomed, 0.1, (50., 50.), image, STAGE);
183 assert_eq!(fit.scale, 0.4);
184 assert_eq!(fit.pan, (0., 0.));
185 }
186
187 #[test]
188 fn zoom_never_pans_past_the_edges() {
189 let image = (2000., 1500.);
190 let start = View {
191 scale: 0.4,
192 pan: (0., 0.),
193 };
194 let zoomed = zoom_at(start, 4., (-400., -300.), image, STAGE);
195 let limit = (2000. * 4. - 800.) / 2.;
196 assert!(zoomed.pan.0.abs() <= limit);
197 }
198
199 #[test]
200 fn wheel_zooms_in_up_and_out_down_symmetrically() {
201 assert!(wheel_scale(1., 20.) > 1.);
202 assert!(wheel_scale(1., -20.) < 1.);
203 assert!((wheel_scale(wheel_scale(1., 20.), -20.) - 1.).abs() < 1e-5);
204 assert_eq!(wheel_scale(1., 0.), 1.);
205 }
206
207 #[test]
208 fn keyboard_steps_multiply_and_divide_by_the_step() {
209 assert_eq!(step_scale(1., 1), ZOOM_STEP);
210 assert!((step_scale(ZOOM_STEP, -1) - 1.).abs() < 1e-6);
211 }
212
213 #[test]
214 fn double_click_toggles_between_fit_and_full_size() {
215 assert_eq!(toggle_target(0.4, 0.4), 1.);
216 assert_eq!(toggle_target(1., 0.4), 0.4);
217 assert_eq!(toggle_target(2., 0.4), 0.4);
218 assert_eq!(toggle_target(1., 1.), 1.);
219 }
220
221 #[test]
222 fn percent_label_is_relative_to_the_source_size() {
223 assert_eq!(percent_label(1.), "100%");
224 assert_eq!(percent_label(0.375), "38%");
225 assert_eq!(percent_label(4.), "400%");
226 }
227
228 #[test]
229 fn navigation_stops_at_both_ends() {
230 assert_eq!(step_index(0, 5, -1), 0);
231 assert_eq!(step_index(4, 5, 1), 4);
232 assert_eq!(step_index(2, 5, 1), 3);
233 assert_eq!(step_index(2, 5, -1), 1);
234 assert_eq!(step_index(0, 0, 1), 0);
235 }
236
237 #[test]
238 fn counter_is_one_based() {
239 assert_eq!(counter_label(2, 12), "3 of 12");
240 }
241
242 #[test]
243 fn thumbnail_window_follows_the_current_image_inside_the_list() {
244 assert_eq!(thumbnail_window(0, 20, 5), 0..5);
245 assert_eq!(thumbnail_window(10, 20, 5), 8..13);
246 assert_eq!(thumbnail_window(19, 20, 5), 15..20);
247 assert_eq!(thumbnail_window(1, 3, 5), 0..3);
248 assert_eq!(thumbnail_window(0, 0, 5), 0..0);
249 assert_eq!(thumbnail_window(2, 4, 0), 2..3);
250 }
251 }
@@ -0,0 +1,251 @@
1use std::ops::Range;
2
3pub type Pair = (f32, f32);
4
5pub const MAX_ZOOM: f32 = 4.;
6pub const ZOOM_STEP: f32 = 1.25;
7const WHEEL_SENSITIVITY: f32 = 0.01;
8const SCALE_EPSILON: f32 = 0.001;
9
10pub fn rotated_size(size: Pair, quarter_turns: u8) -> Pair {
11 if quarter_turns % 2 == 0 {
12 size
13 } else {
14 (size.1, size.0)
15 }
16}
17
18pub fn next_rotation(quarter_turns: u8) -> u8 {
19 (quarter_turns + 1) % 4
20}
21
22pub fn fit_scale(image: Pair, stage: Pair) -> f32 {
23 if image.0 <= 0. || image.1 <= 0. || stage.0 <= 0. || stage.1 <= 0. {
24 return 1.;
25 }
26 (stage.0 / image.0).min(stage.1 / image.1).min(1.)
27}
28
29pub fn clamp_scale(scale: f32, fit: f32) -> f32 {
30 scale.clamp(fit, MAX_ZOOM.max(fit))
31}
32
33pub fn display_size(image: Pair, scale: f32) -> Pair {
34 (image.0 * scale, image.1 * scale)
35}
36
37pub fn clamp_pan(pan: Pair, display: Pair, stage: Pair) -> Pair {
38 let limit = |display: f32, stage: f32| ((display - stage) / 2.).max(0.);
39 let (limit_x, limit_y) = (limit(display.0, stage.0), limit(display.1, stage.1));
40 (
41 pan.0.clamp(-limit_x, limit_x),
42 pan.1.clamp(-limit_y, limit_y),
43 )
44}
45
46pub fn image_origin(display: Pair, stage: Pair, pan: Pair) -> Pair {
47 (
48 (stage.0 - display.0) / 2. + pan.0,
49 (stage.1 - display.1) / 2. + pan.1,
50 )
51}
52
53#[derive(Debug, Clone, Copy, PartialEq)]
54pub struct View {
55 pub scale: f32,
56 pub pan: Pair,
57}
58
59pub fn zoom_at(view: View, wanted: f32, anchor: Pair, image: Pair, stage: Pair) -> View {
60 let fit = fit_scale(image, stage);
61 let scale = clamp_scale(wanted, fit);
62 let ratio = scale / view.scale;
63 let pan = (
64 anchor.0 - (anchor.0 - view.pan.0) * ratio,
65 anchor.1 - (anchor.1 - view.pan.1) * ratio,
66 );
67 View {
68 scale,
69 pan: clamp_pan(pan, display_size(image, scale), stage),
70 }
71}
72
73pub fn wheel_scale(scale: f32, delta_y: f32) -> f32 {
74 scale * (delta_y * WHEEL_SENSITIVITY).exp()
75}
76
77pub fn step_scale(scale: f32, direction: i32) -> f32 {
78 scale * ZOOM_STEP.powi(direction)
79}
80
81pub fn toggle_target(scale: f32, fit: f32) -> f32 {
82 if scale > fit + SCALE_EPSILON {
83 fit
84 } else {
85 1_f32.max(fit)
86 }
87}
88
89pub fn percent_label(scale: f32) -> String {
90 format!("{}%", (scale * 100.).round() as u32)
91}
92
93pub fn step_index(current: usize, len: usize, delta: isize) -> usize {
94 if len == 0 {
95 return 0;
96 }
97 current
98 .saturating_add_signed(delta)
99 .min(len - 1)
100}
101
102pub fn counter_label(index: usize, len: usize) -> String {
103 format!("{} of {}", index + 1, len)
104}
105
106pub fn thumbnail_window(index: usize, len: usize, capacity: usize) -> Range<usize> {
107 let capacity = capacity.max(1).min(len);
108 let start = index
109 .saturating_sub(capacity / 2)
110 .min(len.saturating_sub(capacity));
111 start..start + capacity
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117
118 const STAGE: Pair = (800., 600.);
119
120 #[test]
121 fn fit_contains_large_images_and_never_upscales() {
122 assert_eq!(fit_scale((1600., 1200.), STAGE), 0.5);
123 assert_eq!(fit_scale((1600., 300.), STAGE), 0.5);
124 assert_eq!(fit_scale((100., 100.), STAGE), 1.);
125 assert_eq!(fit_scale((0., 100.), STAGE), 1.);
126 }
127
128 #[test]
129 fn rotation_swaps_the_sides_on_odd_quarter_turns() {
130 assert_eq!(rotated_size((400., 200.), 0), (400., 200.));
131 assert_eq!(rotated_size((400., 200.), 1), (200., 400.));
132 assert_eq!(rotated_size((400., 200.), 2), (400., 200.));
133 assert_eq!(rotated_size((400., 200.), 3), (200., 400.));
134 assert_eq!(next_rotation(3), 0);
135 assert_eq!(next_rotation(0), 1);
136 }
137
138 #[test]
139 fn scale_is_limited_to_fit_and_four_times_the_source() {
140 assert_eq!(clamp_scale(0.1, 0.5), 0.5);
141 assert_eq!(clamp_scale(9., 0.5), MAX_ZOOM);
142 assert_eq!(clamp_scale(2., 0.5), 2.);
143 }
144
145 #[test]
146 fn pan_is_clamped_to_the_image_bounds() {
147 let display = (1600., 400.);
148 assert_eq!(clamp_pan((900., 50.), display, STAGE), (400., 0.));
149 assert_eq!(clamp_pan((-900., -50.), display, STAGE), (-400., 0.));
150 assert_eq!(clamp_pan((10., 10.), (400., 300.), STAGE), (0., 0.));
151 }
152
153 #[test]
154 fn image_origin_centers_and_follows_the_pan() {
155 assert_eq!(image_origin((400., 300.), STAGE, (0., 0.)), (200., 150.));
156 assert_eq!(image_origin((1600., 600.), STAGE, (-100., 0.)), (-500., 0.));
157 }
158
159 #[test]
160 fn zoom_keeps_the_point_under_the_cursor_fixed() {
161 let image = (2000., 1500.);
162 let start = View {
163 scale: 0.4,
164 pan: (0., 0.),
165 };
166 let anchor = (100., 50.);
167 let zoomed = zoom_at(start, 1., anchor, image, STAGE);
168 assert_eq!(zoomed.scale, 1.);
169 let before = ((anchor.0 - start.pan.0) / start.scale, (anchor.1 - start.pan.1) / start.scale);
170 let after = ((anchor.0 - zoomed.pan.0) / zoomed.scale, (anchor.1 - zoomed.pan.1) / zoomed.scale);
171 assert!((before.0 - after.0).abs() < 0.01);
172 assert!((before.1 - after.1).abs() < 0.01);
173 }
174
175 #[test]
176 fn zooming_back_to_fit_recenters() {
177 let image = (2000., 1500.);
178 let zoomed = View {
179 scale: 2.,
180 pan: (300., -200.),
181 };
182 let fit = zoom_at(zoomed, 0.1, (50., 50.), image, STAGE);
183 assert_eq!(fit.scale, 0.4);
184 assert_eq!(fit.pan, (0., 0.));
185 }
186
187 #[test]
188 fn zoom_never_pans_past_the_edges() {
189 let image = (2000., 1500.);
190 let start = View {
191 scale: 0.4,
192 pan: (0., 0.),
193 };
194 let zoomed = zoom_at(start, 4., (-400., -300.), image, STAGE);
195 let limit = (2000. * 4. - 800.) / 2.;
196 assert!(zoomed.pan.0.abs() <= limit);
197 }
198
199 #[test]
200 fn wheel_zooms_in_up_and_out_down_symmetrically() {
201 assert!(wheel_scale(1., 20.) > 1.);
202 assert!(wheel_scale(1., -20.) < 1.);
203 assert!((wheel_scale(wheel_scale(1., 20.), -20.) - 1.).abs() < 1e-5);
204 assert_eq!(wheel_scale(1., 0.), 1.);
205 }
206
207 #[test]
208 fn keyboard_steps_multiply_and_divide_by_the_step() {
209 assert_eq!(step_scale(1., 1), ZOOM_STEP);
210 assert!((step_scale(ZOOM_STEP, -1) - 1.).abs() < 1e-6);
211 }
212
213 #[test]
214 fn double_click_toggles_between_fit_and_full_size() {
215 assert_eq!(toggle_target(0.4, 0.4), 1.);
216 assert_eq!(toggle_target(1., 0.4), 0.4);
217 assert_eq!(toggle_target(2., 0.4), 0.4);
218 assert_eq!(toggle_target(1., 1.), 1.);
219 }
220
221 #[test]
222 fn percent_label_is_relative_to_the_source_size() {
223 assert_eq!(percent_label(1.), "100%");
224 assert_eq!(percent_label(0.375), "38%");
225 assert_eq!(percent_label(4.), "400%");
226 }
227
228 #[test]
229 fn navigation_stops_at_both_ends() {
230 assert_eq!(step_index(0, 5, -1), 0);
231 assert_eq!(step_index(4, 5, 1), 4);
232 assert_eq!(step_index(2, 5, 1), 3);
233 assert_eq!(step_index(2, 5, -1), 1);
234 assert_eq!(step_index(0, 0, 1), 0);
235 }
236
237 #[test]
238 fn counter_is_one_based() {
239 assert_eq!(counter_label(2, 12), "3 of 12");
240 }
241
242 #[test]
243 fn thumbnail_window_follows_the_current_image_inside_the_list() {
244 assert_eq!(thumbnail_window(0, 20, 5), 0..5);
245 assert_eq!(thumbnail_window(10, 20, 5), 8..13);
246 assert_eq!(thumbnail_window(19, 20, 5), 15..20);
247 assert_eq!(thumbnail_window(1, 3, 5), 0..3);
248 assert_eq!(thumbnail_window(0, 0, 5), 0..0);
249 assert_eq!(thumbnail_window(2, 4, 0), 2..3);
250 }
251}
crates/app/src/main.rs +2 −0
@@ -32,6 +32,8 @@ mod format;
32 32 mod frame_log;
33 33 mod fuzzy;
34 34 mod gifs;
35 mod image_view_gallery;
36 mod image_view_math;
35 37 mod local_previews;
36 38 mod message_actions;
37 39 mod notice;
@@ -32,6 +32,8 @@ mod format;
32mod frame_log;
32mod frame_log;
33mod fuzzy;
33mod fuzzy;
34mod gifs;
34mod gifs;
35mod image_view_gallery;
36mod image_view_math;
35mod local_previews;
37mod local_previews;
36mod message_actions;
38mod message_actions;
37mod notice;
39mod notice;
crates/app/src/message_actions.rs +11 −0
@@ -7,6 +7,7 @@ use teams_core::{PinnedMessage, SavedMessage};
7 7
8 8 use crate::app_state::{AppEvent, AppState, Selection};
9 9 use crate::format;
10 use crate::image_view_gallery::ViewerRequest;
10 11 use crate::notice::short_error;
11 12 use crate::notify::selection_for;
12 13 use crate::rows::{message_text, reply_excerpt};
@@ -335,6 +336,16 @@ impl AppState {
335 336 cx.notify();
336 337 }
337 338
339 pub fn request_image_viewer(&mut self, request: ViewerRequest, cx: &mut Context<Self>) {
340 self.image_viewer_request = Some(request);
341 cx.emit(AppEvent::ImageViewer);
342 cx.notify();
343 }
344
345 pub fn take_image_viewer_request(&mut self) -> Option<ViewerRequest> {
346 self.image_viewer_request.take()
347 }
348
338 349 pub fn take_forward_request(&mut self) -> Option<ForwardSource> {
339 350 self.forward_request.take()
340 351 }
@@ -7,6 +7,7 @@ use teams_core::{PinnedMessage, SavedMessage};
7
7
8use crate::app_state::{AppEvent, AppState, Selection};
8use crate::app_state::{AppEvent, AppState, Selection};
9use crate::format;
9use crate::format;
10use crate::image_view_gallery::ViewerRequest;
10use crate::notice::short_error;
11use crate::notice::short_error;
11use crate::notify::selection_for;
12use crate::notify::selection_for;
12use crate::rows::{message_text, reply_excerpt};
13use crate::rows::{message_text, reply_excerpt};
@@ -335,6 +336,16 @@ impl AppState {
335 cx.notify();
336 cx.notify();
336 }
337 }
337
338
339 pub fn request_image_viewer(&mut self, request: ViewerRequest, cx: &mut Context<Self>) {
340 self.image_viewer_request = Some(request);
341 cx.emit(AppEvent::ImageViewer);
342 cx.notify();
343 }
344
345 pub fn take_image_viewer_request(&mut self) -> Option<ViewerRequest> {
346 self.image_viewer_request.take()
347 }
348
338 pub fn take_forward_request(&mut self) -> Option<ForwardSource> {
349 pub fn take_forward_request(&mut self) -> Option<ForwardSource> {
339 self.forward_request.take()
350 self.forward_request.take()
340 }
351 }
crates/app/src/views/attachments.rs +16 −3
@@ -29,6 +29,7 @@ const LOCAL_IMAGE_PREFIX: &str = "../hostedContents/";
29 29 const LOCAL_IMAGE_SUFFIX: &str = "/$value";
30 30
31 31 pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;
32 pub type ImageOpen = Rc<dyn Fn(&str, &mut App)>;
32 33
33 34 #[derive(Clone)]
34 35 pub struct FileActions {
@@ -68,7 +69,12 @@ pub fn image_size(image: &ImageRef, directory: &Directory) -> (f32, f32) {
68 69 fit_image_within(declared_size(image).or(loaded), max_height)
69 70 }
70 71
71 fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement {
72 fn image_view(
73 image: &ImageRef,
74 id: String,
75 directory: &Directory,
76 open_image: Option<&ImageOpen>,
77 ) -> AnyElement {
72 78 let (width, height) = image_size(image, directory);
73 79 let frame = div()
74 80 .id(ElementId::Name(id.into()))
@@ -97,6 +103,7 @@ fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement
97 103 .into_any_element();
98 104 };
99 105 let path = entry.path.clone();
106 let (url, open_image) = (image.url.clone(), open_image.cloned());
100 107 frame
101 108 .cursor_pointer()
102 109 .child(
@@ -105,7 +112,10 @@ fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement
105 112 .rounded(px(IMAGE_RADIUS))
106 113 .object_fit(ObjectFit::Cover),
107 114 )
108 .on_click(move |_, _, cx| cx.open_with_system(&path))
115 .on_click(move |_, _, cx| match &open_image {
116 Some(open_image) => open_image(&url, cx),
117 None => cx.open_with_system(&path),
118 })
109 119 .into_any_element()
110 120 }
111 121
@@ -324,6 +334,7 @@ pub fn message_body(
324 334 id: &str,
325 335 own: bool,
326 336 directory: &Directory,
337 open_image: Option<&ImageOpen>,
327 338 cx: &App,
328 339 ) -> Vec<AnyElement> {
329 340 if !blocks
@@ -351,6 +362,7 @@ pub fn message_body(
351 362 &images[position],
352 363 format!("{id}-image-{position}"),
353 364 directory,
365 open_image,
354 366 )),
355 367 Some(Placement::Local(position)) => elements.push(local_image_view(
356 368 &local_images[position],
@@ -371,6 +383,7 @@ pub fn attachments_view(
371 383 id: &str,
372 384 directory: &Directory,
373 385 file_actions: Option<&FileActions>,
386 open_image: Option<&ImageOpen>,
374 387 ) -> Option<Div> {
375 388 let placed = placements(blocks, images, local_images.len());
376 389 let unplaced_images: Vec<(usize, &ImageRef)> = images
@@ -392,7 +405,7 @@ pub fn attachments_view(
392 405 .items_start()
393 406 .children(
394 407 unplaced_images.into_iter().map(|(index, image)| {
395 image_view(image, format!("{id}-image-{index}"), directory)
408 image_view(image, format!("{id}-image-{index}"), directory, open_image)
396 409 }),
397 410 )
398 411 .children(
@@ -29,6 +29,7 @@ const LOCAL_IMAGE_PREFIX: &str = "../hostedContents/";
29const LOCAL_IMAGE_SUFFIX: &str = "/$value";
29const LOCAL_IMAGE_SUFFIX: &str = "/$value";
30
30
31pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;
31pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;
32pub type ImageOpen = Rc<dyn Fn(&str, &mut App)>;
32
33
33#[derive(Clone)]
34#[derive(Clone)]
34pub struct FileActions {
35pub struct FileActions {
@@ -68,7 +69,12 @@ pub fn image_size(image: &ImageRef, directory: &Directory) -> (f32, f32) {
68 fit_image_within(declared_size(image).or(loaded), max_height)
69 fit_image_within(declared_size(image).or(loaded), max_height)
69}
70}
70
71
71fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement {
72fn image_view(
73 image: &ImageRef,
74 id: String,
75 directory: &Directory,
76 open_image: Option<&ImageOpen>,
77) -> AnyElement {
72 let (width, height) = image_size(image, directory);
78 let (width, height) = image_size(image, directory);
73 let frame = div()
79 let frame = div()
74 .id(ElementId::Name(id.into()))
80 .id(ElementId::Name(id.into()))
@@ -97,6 +103,7 @@ fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement
97 .into_any_element();
103 .into_any_element();
98 };
104 };
99 let path = entry.path.clone();
105 let path = entry.path.clone();
106 let (url, open_image) = (image.url.clone(), open_image.cloned());
100 frame
107 frame
101 .cursor_pointer()
108 .cursor_pointer()
102 .child(
109 .child(
@@ -105,7 +112,10 @@ fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement
105 .rounded(px(IMAGE_RADIUS))
112 .rounded(px(IMAGE_RADIUS))
106 .object_fit(ObjectFit::Cover),
113 .object_fit(ObjectFit::Cover),
107 )
114 )
108 .on_click(move |_, _, cx| cx.open_with_system(&path))
115 .on_click(move |_, _, cx| match &open_image {
116 Some(open_image) => open_image(&url, cx),
117 None => cx.open_with_system(&path),
118 })
109 .into_any_element()
119 .into_any_element()
110}
120}
111
121
@@ -324,6 +334,7 @@ pub fn message_body(
324 id: &str,
334 id: &str,
325 own: bool,
335 own: bool,
326 directory: &Directory,
336 directory: &Directory,
337 open_image: Option<&ImageOpen>,
327 cx: &App,
338 cx: &App,
328) -> Vec<AnyElement> {
339) -> Vec<AnyElement> {
329 if !blocks
340 if !blocks
@@ -351,6 +362,7 @@ pub fn message_body(
351 &images[position],
362 &images[position],
352 format!("{id}-image-{position}"),
363 format!("{id}-image-{position}"),
353 directory,
364 directory,
365 open_image,
354 )),
366 )),
355 Some(Placement::Local(position)) => elements.push(local_image_view(
367 Some(Placement::Local(position)) => elements.push(local_image_view(
356 &local_images[position],
368 &local_images[position],
@@ -371,6 +383,7 @@ pub fn attachments_view(
371 id: &str,
383 id: &str,
372 directory: &Directory,
384 directory: &Directory,
373 file_actions: Option<&FileActions>,
385 file_actions: Option<&FileActions>,
386 open_image: Option<&ImageOpen>,
374) -> Option<Div> {
387) -> Option<Div> {
375 let placed = placements(blocks, images, local_images.len());
388 let placed = placements(blocks, images, local_images.len());
376 let unplaced_images: Vec<(usize, &ImageRef)> = images
389 let unplaced_images: Vec<(usize, &ImageRef)> = images
@@ -392,7 +405,7 @@ pub fn attachments_view(
392 .items_start()
405 .items_start()
393 .children(
406 .children(
394 unplaced_images.into_iter().map(|(index, image)| {
407 unplaced_images.into_iter().map(|(index, image)| {
395 image_view(image, format!("{id}-image-{index}"), directory)
408 image_view(image, format!("{id}-image-{index}"), directory, open_image)
396 }),
409 }),
397 )
410 )
398 .children(
411 .children(
crates/app/src/views/conversation.rs +21 −0
@@ -47,6 +47,7 @@ use crate::demo_library::DemoLibrary;
47 47 use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
48 48 use crate::embedded_web::EmbeddedWeb;
49 49 use crate::emoji;
50 use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
50 51 use crate::notice::short_error;
51 52 use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
52 53 use crate::pending_rows::pending_row;
@@ -298,6 +299,25 @@ impl ConversationView {
298 299 }
299 300 }
300 301
302 fn open_image_viewer(&mut self, message_key: &str, url: &str, cx: &mut Context<Self>) {
303 let Some(current) = self.current.as_ref() else {
304 return;
305 };
306 let now = Local::now();
307 let items = collect_gallery(&self.rows.borrow(), now.date_naive(), now.offset().fix());
308 let Some(index) = position_of(&items, message_key, url) else {
309 return;
310 };
311 let request = ViewerRequest {
312 conversation_id: current.selection.conversation_id().to_owned(),
313 conversation_title: selection_title(&self.app.read(cx).sidebar, &current.selection),
314 items,
315 index,
316 };
317 self.app
318 .update(cx, |state, cx| state.request_image_viewer(request, cx));
319 }
320
301 321 fn activate_file(
302 322 &mut self,
303 323 conversation_id: &str,
@@ -564,6 +584,7 @@ impl ConversationView {
564 584 AppEvent::TaskDialog
565 585 | AppEvent::LocalPreviews
566 586 | AppEvent::Forward
587 | AppEvent::ImageViewer
567 588 | AppEvent::StatusMessage
568 589 | AppEvent::NotificationSettings
569 590 | AppEvent::Profile
@@ -47,6 +47,7 @@ use crate::demo_library::DemoLibrary;
47use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
47use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
48use crate::embedded_web::EmbeddedWeb;
48use crate::embedded_web::EmbeddedWeb;
49use crate::emoji;
49use crate::emoji;
50use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
50use crate::notice::short_error;
51use crate::notice::short_error;
51use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
52use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
52use crate::pending_rows::pending_row;
53use crate::pending_rows::pending_row;
@@ -298,6 +299,25 @@ impl ConversationView {
298 }
299 }
299 }
300 }
300
301
302 fn open_image_viewer(&mut self, message_key: &str, url: &str, cx: &mut Context<Self>) {
303 let Some(current) = self.current.as_ref() else {
304 return;
305 };
306 let now = Local::now();
307 let items = collect_gallery(&self.rows.borrow(), now.date_naive(), now.offset().fix());
308 let Some(index) = position_of(&items, message_key, url) else {
309 return;
310 };
311 let request = ViewerRequest {
312 conversation_id: current.selection.conversation_id().to_owned(),
313 conversation_title: selection_title(&self.app.read(cx).sidebar, &current.selection),
314 items,
315 index,
316 };
317 self.app
318 .update(cx, |state, cx| state.request_image_viewer(request, cx));
319 }
320
301 fn activate_file(
321 fn activate_file(
302 &mut self,
322 &mut self,
303 conversation_id: &str,
323 conversation_id: &str,
@@ -564,6 +584,7 @@ impl ConversationView {
564 AppEvent::TaskDialog
584 AppEvent::TaskDialog
565 | AppEvent::LocalPreviews
585 | AppEvent::LocalPreviews
566 | AppEvent::Forward
586 | AppEvent::Forward
587 | AppEvent::ImageViewer
567 | AppEvent::StatusMessage
588 | AppEvent::StatusMessage
568 | AppEvent::NotificationSettings
589 | AppEvent::NotificationSettings
569 | AppEvent::Profile
590 | AppEvent::Profile
crates/app/src/views/conversation/render_env.rs +9 −0
@@ -12,6 +12,7 @@ use crate::app_state::AppState;
12 12 use crate::rows::{Delivery, MessageRow, PostRow};
13 13 use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
14 14 use crate::translation::TranslationLine;
15 use crate::views::attachments::ImageOpen;
15 16 use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
16 17 use crate::views::composer::Composer;
17 18 use crate::views::message_row::{DeliveryActions, RowActions};
@@ -193,6 +194,13 @@ impl RenderEnv {
193 194 .read(cx)
194 195 .file_actions(&message.key, &message.files, view.clone())
195 196 });
197 let open_image = (is_real && !message.deleted && !message.images.is_empty()).then(|| {
198 let (view, key) = (view.clone(), message.key.clone());
199 Rc::new(move |url: &str, cx: &mut App| {
200 view.update(cx, |this, cx| this.open_image_viewer(&key, url, cx))
201 .ok();
202 }) as ImageOpen
203 });
196 204 let bot = self.bot_identity(message, cx);
197 205 let translation = (is_real && !message.deleted)
198 206 .then(|| self.translation_actions(message))
@@ -222,6 +230,7 @@ impl RenderEnv {
222 230 react,
223 231 reaction_controls,
224 232 files,
233 open_image,
225 234 highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),
226 235 saved: self
227 236 .app
@@ -12,6 +12,7 @@ use crate::app_state::AppState;
12use crate::rows::{Delivery, MessageRow, PostRow};
12use crate::rows::{Delivery, MessageRow, PostRow};
13use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
13use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
14use crate::translation::TranslationLine;
14use crate::translation::TranslationLine;
15use crate::views::attachments::ImageOpen;
15use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
16use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
16use crate::views::composer::Composer;
17use crate::views::composer::Composer;
17use crate::views::message_row::{DeliveryActions, RowActions};
18use crate::views::message_row::{DeliveryActions, RowActions};
@@ -193,6 +194,13 @@ impl RenderEnv {
193 .read(cx)
194 .read(cx)
194 .file_actions(&message.key, &message.files, view.clone())
195 .file_actions(&message.key, &message.files, view.clone())
195 });
196 });
197 let open_image = (is_real && !message.deleted && !message.images.is_empty()).then(|| {
198 let (view, key) = (view.clone(), message.key.clone());
199 Rc::new(move |url: &str, cx: &mut App| {
200 view.update(cx, |this, cx| this.open_image_viewer(&key, url, cx))
201 .ok();
202 }) as ImageOpen
203 });
196 let bot = self.bot_identity(message, cx);
204 let bot = self.bot_identity(message, cx);
197 let translation = (is_real && !message.deleted)
205 let translation = (is_real && !message.deleted)
198 .then(|| self.translation_actions(message))
206 .then(|| self.translation_actions(message))
@@ -222,6 +230,7 @@ impl RenderEnv {
222 react,
230 react,
223 reaction_controls,
231 reaction_controls,
224 files,
232 files,
233 open_image,
225 highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),
234 highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),
226 saved: self
235 saved: self
227 .app
236 .app
crates/app/src/views/image_viewer.rs added +908 −0
@@ -0,0 +1,908 @@
1 use std::io::Cursor;
2 use std::path::{Path, PathBuf};
3 use std::sync::Arc;
4 use std::time::Duration;
5
6 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7 use gpui_kit::prelude::FluentBuilder as _;
8 use gpui_kit::*;
9
10 use super::avatar::person_avatar;
11 use super::widgets::symbol;
12 use crate::app_state::AppState;
13 use crate::downloads;
14 use crate::image_view_gallery::{GalleryItem, ViewerRequest};
15 use crate::theme;
16 use crate::image_view_math::{
17 MAX_ZOOM, Pair, View, clamp_pan, clamp_scale, counter_label, display_size,
18 fit_scale, image_origin, next_rotation, percent_label, rotated_size, step_index, step_scale,
19 thumbnail_window, toggle_target, wheel_scale, zoom_at,
20 };
21
22 const HEADER_HEIGHT: f32 = 52.;
23 const FOOTER_HEIGHT: f32 = 120.;
24 const BUTTON_SIZE: f32 = 36.;
25 const BUTTON_RADIUS: f32 = 8.;
26 const BUTTON_ICON_SIZE: f32 = 20.;
27 const NAV_ICON_SIZE: f32 = 24.;
28 const ZOOM_LABEL_WIDTH: f32 = 52.;
29 const NAV_SIZE: f32 = 44.;
30 const NAV_MARGIN: f32 = 16.;
31 const AVATAR_SIZE: f32 = 32.;
32 const SIDE_PADDING: f32 = 16.;
33 const THUMBNAIL_SIZE: f32 = 48.;
34 const THUMBNAIL_GAP: f32 = 8.;
35 const THUMBNAIL_RADIUS: f32 = 6.;
36 const THUMBNAIL_BORDER: f32 = 2.;
37 const CAPTION_MAX_WIDTH: f32 = 720.;
38 const CAPTION_HEIGHT: f32 = 22.;
39 const STATUS_HEIGHT: f32 = 18.;
40 const STRIP_HEIGHT: f32 = THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER;
41 const WHEEL_LINE_HEIGHT: f32 = 20.;
42 const BACKDROP: u32 = 0x080809f0;
43 const DISABLED_OPACITY: f32 = 0.35;
44 const NOTICE_DURATION: Duration = Duration::from_secs(2);
45
46 pub enum ImageViewerEvent {
47 Close,
48 }
49
50 struct RotatedImage {
51 url: String,
52 quarter_turns: u8,
53 image: Arc<Image>,
54 }
55
56 #[derive(Clone, Copy)]
57 struct Layout {
58 stage: Pair,
59 source: Pair,
60 fit: f32,
61 scale: f32,
62 pan: Pair,
63 }
64
65 pub struct ImageViewer {
66 app: Entity<AppState>,
67 conversation_id: String,
68 conversation_title: String,
69 items: Vec<GalleryItem>,
70 index: usize,
71 scale: Option<f32>,
72 pan: Pair,
73 quarter_turns: u8,
74 rotated: Option<RotatedImage>,
75 drag_from: Option<Point<Pixels>>,
76 notice: Option<String>,
77 notice_serial: u64,
78 focus_handle: FocusHandle,
79 _observation: Subscription,
80 }
81
82 impl EventEmitter<ImageViewerEvent> for ImageViewer {}
83
84 fn rotate_file(path: &Path, quarter_turns: u8) -> Option<Image> {
85 let decoded = image::open(path).ok()?;
86 let rotated = match quarter_turns {
87 1 => decoded.rotate90(),
88 2 => decoded.rotate180(),
89 3 => decoded.rotate270(),
90 _ => decoded,
91 };
92 let mut bytes = Vec::new();
93 rotated
94 .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
95 .ok()?;
96 Some(Image::from_bytes(ImageFormat::Png, bytes))
97 }
98
99 fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {
100 match image::guess_format(bytes).ok()? {
101 image::ImageFormat::Png => Some(ImageFormat::Png),
102 image::ImageFormat::Jpeg => Some(ImageFormat::Jpeg),
103 image::ImageFormat::Gif => Some(ImageFormat::Gif),
104 image::ImageFormat::WebP => Some(ImageFormat::Webp),
105 image::ImageFormat::Bmp => Some(ImageFormat::Bmp),
106 _ => None,
107 }
108 }
109
110 fn suggested_name(path: &Path) -> String {
111 let name = path
112 .file_name()
113 .map(|name| name.to_string_lossy().into_owned())
114 .unwrap_or_else(|| "image".to_owned());
115 if path.extension().is_some() {
116 return name;
117 }
118 let extension = std::fs::read(path)
119 .ok()
120 .and_then(|bytes| image::guess_format(&bytes).ok())
121 .and_then(|format| format.extensions_str().first().copied())
122 .unwrap_or("png");
123 format!("{name}.{extension}")
124 }
125
126 fn control_button(
127 id: &'static str,
128 glyph: &'static str,
129 tooltip: &'static str,
130 enabled: bool,
131 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
132 ) -> Stateful<Div> {
133 div()
134 .id(id)
135 .size(px(BUTTON_SIZE))
136 .flex_none()
137 .flex()
138 .items_center()
139 .justify_center()
140 .rounded(px(BUTTON_RADIUS))
141 .text_color(white())
142 .when(enabled, |button| {
143 button
144 .cursor_pointer()
145 .hover(|button| button.bg(white().opacity(0.12)))
146 })
147 .when(!enabled, |button| button.opacity(DISABLED_OPACITY))
148 .tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx))
149 .child(symbol(glyph, BUTTON_ICON_SIZE, white()))
150 .on_click(move |event, window, cx| {
151 cx.stop_propagation();
152 if enabled {
153 on_click(event, window, cx);
154 }
155 })
156 }
157
158 impl ImageViewer {
159 pub fn new(
160 app: Entity<AppState>,
161 request: ViewerRequest,
162 window: &mut Window,
163 cx: &mut Context<Self>,
164 ) -> Self {
165 let focus_handle = cx.focus_handle();
166 window.focus(&focus_handle, cx);
167 let observation = cx.observe(&app, |_, _, cx| cx.notify());
168 let mut viewer = ImageViewer {
169 app,
170 conversation_id: request.conversation_id,
171 conversation_title: request.conversation_title,
172 index: request.index.min(request.items.len().saturating_sub(1)),
173 items: request.items,
174 scale: None,
175 pan: (0., 0.),
176 quarter_turns: 0,
177 rotated: None,
178 drag_from: None,
179 notice: None,
180 notice_serial: 0,
181 focus_handle,
182 _observation: observation,
183 };
184 viewer.preload(cx);
185 viewer
186 }
187
188 pub fn focus_handle(&self) -> FocusHandle {
189 self.focus_handle.clone()
190 }
191
192 fn preload(&mut self, cx: &mut Context<Self>) {
193 let first = self.index.saturating_sub(1);
194 let last = (self.index + 1).min(self.items.len().saturating_sub(1));
195 let directory = &self.app.read(cx).directory;
196 let missing: Vec<_> = self
197 .items
198 .get(first..=last)
199 .unwrap_or_default()
200 .iter()
201 .map(|item| item.image.clone())
202 .filter(|image| directory.image(&image.url).is_none())
203 .collect();
204 if !missing.is_empty() {
205 self.app
206 .update(cx, |state, cx| state.request_images(missing, cx));
207 }
208 }
209
210 fn current(&self) -> Option<&GalleryItem> {
211 self.items.get(self.index)
212 }
213
214 fn current_path(&self, cx: &App) -> Option<PathBuf> {
215 let item = self.current()?;
216 let entry = self.app.read(cx).directory.image(&item.image.url)?;
217 Some(entry.path.clone())
218 }
219
220 fn stage_size(window: &Window) -> Pair {
221 let viewport = window.viewport_size();
222 (
223 f32::from(viewport.width).max(1.),
224 (f32::from(viewport.height) - HEADER_HEIGHT - FOOTER_HEIGHT).max(1.),
225 )
226 }
227
228 fn layout(&self, window: &Window, cx: &App) -> Option<Layout> {
229 let item = self.current()?;
230 let entry = self.app.read(cx).directory.image(&item.image.url)?;
231 let stage = Self::stage_size(window);
232 let declared = item.image.width.zip(item.image.height);
233 let source = entry
234 .size
235 .or(declared)
236 .map_or(stage, |(width, height)| (width as f32, height as f32));
237 let source = rotated_size(source, self.quarter_turns);
238 let fit = fit_scale(source, stage);
239 let scale = self.scale.map_or(fit, |scale| clamp_scale(scale, fit));
240 let pan = clamp_pan(self.pan, display_size(source, scale), stage);
241 Some(Layout {
242 stage,
243 source,
244 fit,
245 scale,
246 pan,
247 })
248 }
249
250 fn anchor_of(position: Point<Pixels>, window: &Window) -> Pair {
251 let stage = Self::stage_size(window);
252 (
253 f32::from(position.x) - stage.0 / 2.,
254 f32::from(position.y) - HEADER_HEIGHT - stage.1 / 2.,
255 )
256 }
257
258 fn zoom_to(&mut self, wanted: f32, anchor: Pair, window: &Window, cx: &mut Context<Self>) {
259 let Some(layout) = self.layout(window, cx) else {
260 return;
261 };
262 let view = zoom_at(
263 View {
264 scale: layout.scale,
265 pan: layout.pan,
266 },
267 wanted,
268 anchor,
269 layout.source,
270 layout.stage,
271 );
272 self.scale = (view.scale > layout.fit).then_some(view.scale);
273 self.pan = view.pan;
274 cx.notify();
275 }
276
277 fn zoom_step(&mut self, direction: i32, window: &Window, cx: &mut Context<Self>) {
278 let Some(layout) = self.layout(window, cx) else {
279 return;
280 };
281 self.zoom_to(step_scale(layout.scale, direction), (0., 0.), window, cx);
282 }
283
284 fn zoom_fit(&mut self, cx: &mut Context<Self>) {
285 self.scale = None;
286 self.pan = (0., 0.);
287 cx.notify();
288 }
289
290 fn toggle_zoom(&mut self, position: Point<Pixels>, window: &Window, cx: &mut Context<Self>) {
291 let Some(layout) = self.layout(window, cx) else {
292 return;
293 };
294 let target = toggle_target(layout.scale, layout.fit);
295 self.zoom_to(target, Self::anchor_of(position, window), window, cx);
296 }
297
298 fn on_wheel(&mut self, event: &ScrollWheelEvent, window: &mut Window, cx: &mut Context<Self>) {
299 let Some(layout) = self.layout(window, cx) else {
300 return;
301 };
302 let delta = event.delta.pixel_delta(px(WHEEL_LINE_HEIGHT)).y.into();
303 let anchor = Self::anchor_of(event.position, window);
304 self.zoom_to(wheel_scale(layout.scale, delta), anchor, window, cx);
305 cx.stop_propagation();
306 }
307
308 fn on_mouse_move(
309 &mut self,
310 event: &MouseMoveEvent,
311 window: &mut Window,
312 cx: &mut Context<Self>,
313 ) {
314 let Some(last) = self.drag_from else {
315 return;
316 };
317 if event.pressed_button != Some(MouseButton::Left) {
318 self.drag_from = None;
319 return;
320 }
321 let Some(layout) = self.layout(window, cx) else {
322 return;
323 };
324 let moved = (
325 layout.pan.0 + f32::from(event.position.x - last.x),
326 layout.pan.1 + f32::from(event.position.y - last.y),
327 );
328 self.pan = clamp_pan(moved, display_size(layout.source, layout.scale), layout.stage);
329 self.drag_from = Some(event.position);
330 cx.notify();
331 }
332
333 fn end_drag(&mut self, cx: &mut Context<Self>) {
334 if self.drag_from.take().is_some() {
335 cx.notify();
336 }
337 }
338
339 fn jump(&mut self, index: usize, cx: &mut Context<Self>) {
340 if index == self.index || index >= self.items.len() {
341 return;
342 }
343 self.index = index;
344 self.scale = None;
345 self.pan = (0., 0.);
346 self.quarter_turns = 0;
347 self.rotated = None;
348 self.drag_from = None;
349 self.preload(cx);
350 cx.notify();
351 }
352
353 fn go(&mut self, delta: isize, cx: &mut Context<Self>) {
354 self.jump(step_index(self.index, self.items.len(), delta), cx);
355 }
356
357 fn rotate(&mut self, cx: &mut Context<Self>) {
358 let (Some(path), Some(item)) = (self.current_path(cx), self.current()) else {
359 return;
360 };
361 let url = item.image.url.clone();
362 self.quarter_turns = next_rotation(self.quarter_turns);
363 self.scale = None;
364 self.pan = (0., 0.);
365 self.rotated = None;
366 let quarter_turns = self.quarter_turns;
367 if quarter_turns != 0 {
368 cx.spawn(async move |this, cx| {
369 let task_url = url.clone();
370 let rotated = cx
371 .background_spawn(async move { rotate_file(&path, quarter_turns) })
372 .await;
373 this.update(cx, |this, cx| {
374 let still_current = this.quarter_turns == quarter_turns
375 && this.current().is_some_and(|item| item.image.url == task_url);
376 if let Some(image) = rotated.filter(|_| still_current) {
377 this.rotated = Some(RotatedImage {
378 url: task_url,
379 quarter_turns,
380 image: Arc::new(image),
381 });
382 cx.notify();
383 }
384 })
385 .ok();
386 })
387 .detach();
388 }
389 cx.notify();
390 }
391
392 fn show_notice(&mut self, text: impl Into<String>, cx: &mut Context<Self>) {
393 self.notice_serial += 1;
394 let serial = self.notice_serial;
395 self.notice = Some(text.into());
396 cx.spawn(async move |this, cx| {
397 cx.background_executor().timer(NOTICE_DURATION).await;
398 this.update(cx, |this, cx| {
399 if this.notice_serial == serial {
400 this.notice = None;
401 cx.notify();
402 }
403 })
404 .ok();
405 })
406 .detach();
407 cx.notify();
408 }
409
410 fn rotated_image(&self) -> Option<&Arc<Image>> {
411 let url = &self.current()?.image.url;
412 self.rotated
413 .as_ref()
414 .filter(|rotated| rotated.url == *url && rotated.quarter_turns == self.quarter_turns)
415 .map(|rotated| &rotated.image)
416 }
417
418 fn copy_image(&mut self, cx: &mut Context<Self>) {
419 let Some(path) = self.current_path(cx) else {
420 return;
421 };
422 let item = match self.rotated_image() {
423 Some(rotated) => Some(ClipboardItem::new_image(rotated)),
424 None => std::fs::read(&path).ok().and_then(|bytes| {
425 let format = clipboard_format(&bytes)?;
426 Some(ClipboardItem::new_image(&Image::from_bytes(format, bytes)))
427 }),
428 };
429 match item {
430 Some(item) => {
431 cx.write_to_clipboard(item);
432 self.show_notice("Image copied", cx);
433 }
434 None => {
435 cx.write_to_clipboard(ClipboardItem::new_string(path.display().to_string()));
436 self.show_notice("Copied file path", cx);
437 }
438 }
439 }
440
441 fn save_as(&mut self, cx: &mut Context<Self>) {
442 let Some(source) = self.current_path(cx) else {
443 return;
444 };
445 let receiver =
446 cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&suggested_name(&source)));
447 cx.spawn(async move |this, cx| {
448 let Ok(Ok(Some(target))) = receiver.await else {
449 return;
450 };
451 let copied = cx
452 .background_spawn(async move {
453 std::fs::copy(&source, &target).map(|_| target)
454 })
455 .await;
456 this.update(cx, |this, cx| match copied {
457 Ok(target) => {
458 let name = target
459 .file_name()
460 .map(|name| name.to_string_lossy().into_owned())
461 .unwrap_or_default();
462 this.show_notice(format!("Saved {name}"), cx)
463 }
464 Err(_) => this.show_notice("Could not save the image", cx),
465 })
466 .ok();
467 })
468 .detach();
469 }
470
471 fn forward(&mut self, cx: &mut Context<Self>) {
472 let Some(item) = self.current() else {
473 return;
474 };
475 let message_key = item.message_key.clone();
476 if self.app.read(cx).mode.read_only {
477 self.show_notice("Read-only mode: message not forwarded", cx);
478 return;
479 }
480 let conversation_id = self.conversation_id.clone();
481 self.app.update(cx, |state, cx| {
482 state.request_forward(&conversation_id, &message_key, cx)
483 });
484 }
485
486 fn open_externally(&mut self, cx: &mut Context<Self>) {
487 if let Some(path) = self.current_path(cx) {
488 cx.open_with_system(&path);
489 }
490 }
491
492 fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
493 let command = event.keystroke.modifiers.secondary();
494 match (event.keystroke.key.as_str(), command) {
495 ("escape", _) => cx.emit(ImageViewerEvent::Close),
496 ("left", false) => self.go(-1, cx),
497 ("right", false) => self.go(1, cx),
498 ("r", false) => self.rotate(cx),
499 ("f11", _) => window.toggle_fullscreen(),
500 ("=" | "+", true) => self.zoom_step(1, window, cx),
501 ("-", true) => self.zoom_step(-1, window, cx),
502 ("0", true) => self.zoom_fit(cx),
503 ("c", true) => self.copy_image(cx),
504 ("s", true) => self.save_as(cx),
505 _ => {}
506 }
507 cx.stop_propagation();
508 }
509
510 fn header(&self, layout: Option<Layout>, cx: &mut Context<Self>) -> Div {
511 let item = self.current();
512 let author = item.map(|item| item.author.clone()).unwrap_or_default();
513 let subtitle = item
514 .map(|item| format!("{} \u{b7} {}", item.time, self.conversation_title))
515 .unwrap_or_default();
516 let sender_id = item.and_then(|item| item.sender_id.clone());
517 let can_zoom_out = layout.is_some_and(|layout| layout.scale > layout.fit);
518 let can_zoom_in = layout.is_some_and(|layout| layout.scale < MAX_ZOOM);
519 let zoom_label = layout.map(|layout| percent_label(layout.scale)).unwrap_or_default();
520 let loaded = layout.is_some();
521 h_flex()
522 .absolute()
523 .top_0()
524 .left_0()
525 .w_full()
526 .h(px(HEADER_HEIGHT))
527 .px(px(SIDE_PADDING))
528 .gap(px(12.))
529 .items_center()
530 .child(
531 h_flex()
532 .flex_1()
533 .min_w_0()
534 .gap(px(10.))
535 .items_center()
536 .child(
537 div()
538 .size(px(AVATAR_SIZE))
539 .flex_none()
540 .child(person_avatar(
541 &self.app.read(cx).directory,
542 sender_id.as_deref(),
543 &author,
544 AVATAR_SIZE,
545 )),
546 )
547 .child(
548 v_flex()
549 .flex_1()
550 .min_w_0()
551 .child(
552 div()
553 .truncate()
554 .text_size(px(14.))
555 .font_weight(FontWeight::SEMIBOLD)
556 .text_color(white())
557 .child(author),
558 )
559 .child(
560 div()
561 .truncate()
562 .text_size(px(12.))
563 .text_color(white().opacity(0.6))
564 .child(subtitle),
565 ),
566 ),
567 )
568 .child(
569 h_flex()
570 .flex_none()
571 .gap(px(2.))
572 .items_center()
573 .child(control_button(
574 "viewer-zoom-out",
575 "zoom_out",
576 "Zoom out (Ctrl -)",
577 can_zoom_out,
578 cx.listener(|this, _, window, cx| this.zoom_step(-1, window, cx)),
579 ))
580 .child(
581 div()
582 .w(px(ZOOM_LABEL_WIDTH))
583 .flex_none()
584 .text_center()
585 .text_size(px(12.))
586 .text_color(white().opacity(0.8))
587 .child(zoom_label),
588 )
589 .child(control_button(
590 "viewer-zoom-in",
591 "zoom_in",
592 "Zoom in (Ctrl +)",
593 can_zoom_in,
594 cx.listener(|this, _, window, cx| this.zoom_step(1, window, cx)),
595 ))
596 .child(control_button(
597 "viewer-rotate",
598 "rotate_right",
599 "Rotate (R)",
600 loaded,
601 cx.listener(|this, _, _, cx| this.rotate(cx)),
602 ))
603 .child(control_button(
604 "viewer-copy",
605 "content_copy",
606 "Copy image (Ctrl C)",
607 loaded,
608 cx.listener(|this, _, _, cx| this.copy_image(cx)),
609 ))
610 .child(control_button(
611 "viewer-save",
612 "download",
613 "Save as (Ctrl S)",
614 loaded,
615 cx.listener(|this, _, _, cx| this.save_as(cx)),
616 ))
617 .child(control_button(
618 "viewer-forward",
619 "forward",
620 "Forward",
621 true,
622 cx.listener(|this, _, _, cx| this.forward(cx)),
623 ))
624 .child(control_button(
625 "viewer-fullscreen",
626 "fullscreen",
627 "Full screen (F11)",
628 true,
629 cx.listener(|_, _, window, _| window.toggle_fullscreen()),
630 ))
631 .child(control_button(
632 "viewer-open",
633 "open_in_new",
634 "Open in Photos",
635 loaded,
636 cx.listener(|this, _, _, cx| this.open_externally(cx)),
637 ))
638 .child(control_button(
639 "viewer-close",
640 "close",
641 "Close (Esc)",
642 true,
643 cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)),
644 )),
645 )
646 }
647
648 fn nav_button(
649 &self,
650 id: &'static str,
651 glyph: &'static str,
652 left: bool,
653 stage: Pair,
654 cx: &mut Context<Self>,
655 delta: isize,
656 ) -> Stateful<Div> {
657 let top = ((stage.1 - NAV_SIZE) / 2.).max(0.);
658 div()
659 .id(id)
660 .absolute()
661 .top(px(top))
662 .when(left, |button| button.left(px(NAV_MARGIN)))
663 .when(!left, |button| button.right(px(NAV_MARGIN)))
664 .size(px(NAV_SIZE))
665 .flex()
666 .items_center()
667 .justify_center()
668 .rounded_full()
669 .bg(white().opacity(0.1))
670 .cursor_pointer()
671 .hover(|button| button.bg(white().opacity(0.2)))
672 .child(symbol(glyph, NAV_ICON_SIZE, white()))
673 .on_click(cx.listener(move |this, _, _, cx| {
674 cx.stop_propagation();
675 this.go(delta, cx);
676 }))
677 }
678
679 fn picture(&self, layout: Layout, cx: &mut Context<Self>) -> AnyElement {
680 let display = display_size(layout.source, layout.scale);
681 let origin = image_origin(display, layout.stage, layout.pan);
682 let Some(item) = self.current() else {
683 return div().into_any_element();
684 };
685 let source: Option<ImageSource> = if self.quarter_turns == 0 {
686 self.app
687 .read(cx)
688 .directory
689 .image(&item.image.url)
690 .map(|entry| entry.path.clone().into())
691 } else {
692 self.rotated_image().map(|image| ImageSource::Image(image.clone()))
693 };
694 let Some(source) = source else {
695 return loading_placeholder();
696 };
697 div()
698 .id("viewer-picture")
699 .absolute()
700 .left(px(origin.0))
701 .top(px(origin.1))
702 .w(px(display.0))
703 .h(px(display.1))
704 .child(img(source).size_full().object_fit(ObjectFit::Fill))
705 .on_mouse_down(
706 MouseButton::Left,
707 cx.listener(|this, event: &MouseDownEvent, _, cx| {
708 cx.stop_propagation();
709 this.drag_from = Some(event.position);
710 }),
711 )
712 .on_click(cx.listener(|this, event: &ClickEvent, window, cx| {
713 cx.stop_propagation();
714 if event.click_count() == 2 {
715 this.toggle_zoom(event.position(), window, cx);
716 }
717 }))
718 .into_any_element()
719 }
720
721 fn thumbnail(&self, index: usize, cx: &mut Context<Self>) -> Stateful<Div> {
722 let item = &self.items[index];
723 let current = index == self.index;
724 let path = self
725 .app
726 .read(cx)
727 .directory
728 .image(&item.image.url)
729 .map(|entry| entry.path.clone());
730 div()
731 .id(ElementId::Name(format!("viewer-thumbnail-{index}").into()))
732 .size(px(THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER))
733 .flex_none()
734 .flex()
735 .items_center()
736 .justify_center()
737 .rounded(px(THUMBNAIL_RADIUS + THUMBNAIL_BORDER))
738 .border_2()
739 .border_color(if current {
740 theme::accent()
741 } else {
742 transparent_black()
743 })
744 .cursor_pointer()
745 .child(
746 div()
747 .size(px(THUMBNAIL_SIZE))
748 .flex_none()
749 .flex()
750 .items_center()
751 .justify_center()
752 .overflow_hidden()
753 .rounded(px(THUMBNAIL_RADIUS))
754 .bg(white().opacity(0.08))
755 .when(!current, |frame| frame.opacity(0.7))
756 .map(|frame| match path {
757 Some(path) => frame.child(
758 img(path)
759 .size_full()
760 .object_fit(ObjectFit::Cover),
761 ),
762 None => frame.child(symbol("image", 18., white().opacity(0.5))),
763 }),
764 )
765 .on_click(cx.listener(move |this, _, _, cx| {
766 cx.stop_propagation();
767 this.jump(index, cx);
768 }))
769 }
770
771 fn footer(&self, window: &Window, cx: &mut Context<Self>) -> Div {
772 let width = f32::from(window.viewport_size().width);
773 let capacity = ((width - 2. * SIDE_PADDING) / (THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER + THUMBNAIL_GAP))
774 .floor()
775 .max(1.) as usize;
776 let range = thumbnail_window(self.index, self.items.len(), capacity);
777 let caption = self
778 .current()
779 .map(|item| item.caption.clone())
780 .unwrap_or_default();
781 let status = self
782 .notice
783 .clone()
784 .unwrap_or_else(|| counter_label(self.index, self.items.len()));
785 v_flex()
786 .absolute()
787 .bottom_0()
788 .left_0()
789 .w_full()
790 .h(px(FOOTER_HEIGHT))
791 .pb(px(12.))
792 .gap(px(4.))
793 .items_center()
794 .justify_end()
795 .child(
796 div()
797 .w(px((width - 2. * SIDE_PADDING).clamp(0., CAPTION_MAX_WIDTH)))
798 .h(px(CAPTION_HEIGHT))
799 .flex_none()
800 .truncate()
801 .text_center()
802 .text_size(px(13.))
803 .text_color(white().opacity(0.9))
804 .child(caption),
805 )
806 .child(
807 div()
808 .h(px(STATUS_HEIGHT))
809 .flex_none()
810 .text_size(px(12.))
811 .text_color(white().opacity(0.6))
812 .child(status),
813 )
814 .child(
815 h_flex()
816 .h(px(STRIP_HEIGHT))
817 .flex_none()
818 .gap(px(THUMBNAIL_GAP))
819 .items_center()
820 .children(range.map(|index| self.thumbnail(index, cx))),
821 )
822 }
823 }
824
825 fn loading_placeholder() -> AnyElement {
826 v_flex()
827 .size_full()
828 .gap(px(6.))
829 .items_center()
830 .justify_center()
831 .child(symbol("image", 28., white().opacity(0.5)))
832 .child(
833 div()
834 .text_size(px(12.))
835 .text_color(white().opacity(0.6))
836 .child("Loading image"),
837 )
838 .into_any_element()
839 }
840
841 impl Render for ImageViewer {
842 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
843 let layout = self.layout(window, cx);
844 let stage = Self::stage_size(window);
845 let has_previous = self.index > 0;
846 let has_next = self.index + 1 < self.items.len();
847 let picture = match layout {
848 Some(layout) => self.picture(layout, cx),
849 None => loading_placeholder(),
850 };
851 let header = self.header(layout, cx);
852 let footer = self.footer(window, cx);
853 div()
854 .id("image-viewer")
855 .key_context("ImageViewer")
856 .track_focus(&self.focus_handle)
857 .absolute()
858 .top_0()
859 .left_0()
860 .size_full()
861 .bg(rgba(BACKDROP))
862 .occlude()
863 .on_key_down(cx.listener(Self::on_key_down))
864 .on_scroll_wheel(cx.listener(Self::on_wheel))
865 .on_mouse_move(cx.listener(Self::on_mouse_move))
866 .on_mouse_up(
867 MouseButton::Left,
868 cx.listener(|this, _, _, cx| this.end_drag(cx)),
869 )
870 .on_mouse_up_out(
871 MouseButton::Left,
872 cx.listener(|this, _, _, cx| this.end_drag(cx)),
873 )
874 .on_click(cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)))
875 .child(
876 div()
877 .absolute()
878 .top(px(HEADER_HEIGHT))
879 .left_0()
880 .w(px(stage.0))
881 .h(px(stage.1))
882 .overflow_hidden()
883 .child(picture)
884 .when(has_previous, |stage_element| {
885 stage_element.child(self.nav_button(
886 "viewer-previous",
887 "chevron_left",
888 true,
889 stage,
890 cx,
891 -1,
892 ))
893 })
894 .when(has_next, |stage_element| {
895 stage_element.child(self.nav_button(
896 "viewer-next",
897 "chevron_right",
898 false,
899 stage,
900 cx,
901 1,
902 ))
903 }),
904 )
905 .child(header)
906 .child(footer)
907 }
908 }
@@ -0,0 +1,908 @@
1use std::io::Cursor;
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4use std::time::Duration;
5
6use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9
10use super::avatar::person_avatar;
11use super::widgets::symbol;
12use crate::app_state::AppState;
13use crate::downloads;
14use crate::image_view_gallery::{GalleryItem, ViewerRequest};
15use crate::theme;
16use crate::image_view_math::{
17 MAX_ZOOM, Pair, View, clamp_pan, clamp_scale, counter_label, display_size,
18 fit_scale, image_origin, next_rotation, percent_label, rotated_size, step_index, step_scale,
19 thumbnail_window, toggle_target, wheel_scale, zoom_at,
20};
21
22const HEADER_HEIGHT: f32 = 52.;
23const FOOTER_HEIGHT: f32 = 120.;
24const BUTTON_SIZE: f32 = 36.;
25const BUTTON_RADIUS: f32 = 8.;
26const BUTTON_ICON_SIZE: f32 = 20.;
27const NAV_ICON_SIZE: f32 = 24.;
28const ZOOM_LABEL_WIDTH: f32 = 52.;
29const NAV_SIZE: f32 = 44.;
30const NAV_MARGIN: f32 = 16.;
31const AVATAR_SIZE: f32 = 32.;
32const SIDE_PADDING: f32 = 16.;
33const THUMBNAIL_SIZE: f32 = 48.;
34const THUMBNAIL_GAP: f32 = 8.;
35const THUMBNAIL_RADIUS: f32 = 6.;
36const THUMBNAIL_BORDER: f32 = 2.;
37const CAPTION_MAX_WIDTH: f32 = 720.;
38const CAPTION_HEIGHT: f32 = 22.;
39const STATUS_HEIGHT: f32 = 18.;
40const STRIP_HEIGHT: f32 = THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER;
41const WHEEL_LINE_HEIGHT: f32 = 20.;
42const BACKDROP: u32 = 0x080809f0;
43const DISABLED_OPACITY: f32 = 0.35;
44const NOTICE_DURATION: Duration = Duration::from_secs(2);
45
46pub enum ImageViewerEvent {
47 Close,
48}
49
50struct RotatedImage {
51 url: String,
52 quarter_turns: u8,
53 image: Arc<Image>,
54}
55
56#[derive(Clone, Copy)]
57struct Layout {
58 stage: Pair,
59 source: Pair,
60 fit: f32,
61 scale: f32,
62 pan: Pair,
63}
64
65pub struct ImageViewer {
66 app: Entity<AppState>,
67 conversation_id: String,
68 conversation_title: String,
69 items: Vec<GalleryItem>,
70 index: usize,
71 scale: Option<f32>,
72 pan: Pair,
73 quarter_turns: u8,
74 rotated: Option<RotatedImage>,
75 drag_from: Option<Point<Pixels>>,
76 notice: Option<String>,
77 notice_serial: u64,
78 focus_handle: FocusHandle,
79 _observation: Subscription,
80}
81
82impl EventEmitter<ImageViewerEvent> for ImageViewer {}
83
84fn rotate_file(path: &Path, quarter_turns: u8) -> Option<Image> {
85 let decoded = image::open(path).ok()?;
86 let rotated = match quarter_turns {
87 1 => decoded.rotate90(),
88 2 => decoded.rotate180(),
89 3 => decoded.rotate270(),
90 _ => decoded,
91 };
92 let mut bytes = Vec::new();
93 rotated
94 .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
95 .ok()?;
96 Some(Image::from_bytes(ImageFormat::Png, bytes))
97}
98
99fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {
100 match image::guess_format(bytes).ok()? {
101 image::ImageFormat::Png => Some(ImageFormat::Png),
102 image::ImageFormat::Jpeg => Some(ImageFormat::Jpeg),
103 image::ImageFormat::Gif => Some(ImageFormat::Gif),
104 image::ImageFormat::WebP => Some(ImageFormat::Webp),
105 image::ImageFormat::Bmp => Some(ImageFormat::Bmp),
106 _ => None,
107 }
108}
109
110fn suggested_name(path: &Path) -> String {
111 let name = path
112 .file_name()
113 .map(|name| name.to_string_lossy().into_owned())
114 .unwrap_or_else(|| "image".to_owned());
115 if path.extension().is_some() {
116 return name;
117 }
118 let extension = std::fs::read(path)
119 .ok()
120 .and_then(|bytes| image::guess_format(&bytes).ok())
121 .and_then(|format| format.extensions_str().first().copied())
122 .unwrap_or("png");
123 format!("{name}.{extension}")
124}
125
126fn control_button(
127 id: &'static str,
128 glyph: &'static str,
129 tooltip: &'static str,
130 enabled: bool,
131 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
132) -> Stateful<Div> {
133 div()
134 .id(id)
135 .size(px(BUTTON_SIZE))
136 .flex_none()
137 .flex()
138 .items_center()
139 .justify_center()
140 .rounded(px(BUTTON_RADIUS))
141 .text_color(white())
142 .when(enabled, |button| {
143 button
144 .cursor_pointer()
145 .hover(|button| button.bg(white().opacity(0.12)))
146 })
147 .when(!enabled, |button| button.opacity(DISABLED_OPACITY))
148 .tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx))
149 .child(symbol(glyph, BUTTON_ICON_SIZE, white()))
150 .on_click(move |event, window, cx| {
151 cx.stop_propagation();
152 if enabled {
153 on_click(event, window, cx);
154 }
155 })
156}
157
158impl ImageViewer {
159 pub fn new(
160 app: Entity<AppState>,
161 request: ViewerRequest,
162 window: &mut Window,
163 cx: &mut Context<Self>,
164 ) -> Self {
165 let focus_handle = cx.focus_handle();
166 window.focus(&focus_handle, cx);
167 let observation = cx.observe(&app, |_, _, cx| cx.notify());
168 let mut viewer = ImageViewer {
169 app,
170 conversation_id: request.conversation_id,
171 conversation_title: request.conversation_title,
172 index: request.index.min(request.items.len().saturating_sub(1)),
173 items: request.items,
174 scale: None,
175 pan: (0., 0.),
176 quarter_turns: 0,
177 rotated: None,
178 drag_from: None,
179 notice: None,
180 notice_serial: 0,
181 focus_handle,
182 _observation: observation,
183 };
184 viewer.preload(cx);
185 viewer
186 }
187
188 pub fn focus_handle(&self) -> FocusHandle {
189 self.focus_handle.clone()
190 }
191
192 fn preload(&mut self, cx: &mut Context<Self>) {
193 let first = self.index.saturating_sub(1);
194 let last = (self.index + 1).min(self.items.len().saturating_sub(1));
195 let directory = &self.app.read(cx).directory;
196 let missing: Vec<_> = self
197 .items
198 .get(first..=last)
199 .unwrap_or_default()
200 .iter()
201 .map(|item| item.image.clone())
202 .filter(|image| directory.image(&image.url).is_none())
203 .collect();
204 if !missing.is_empty() {
205 self.app
206 .update(cx, |state, cx| state.request_images(missing, cx));
207 }
208 }
209
210 fn current(&self) -> Option<&GalleryItem> {
211 self.items.get(self.index)
212 }
213
214 fn current_path(&self, cx: &App) -> Option<PathBuf> {
215 let item = self.current()?;
216 let entry = self.app.read(cx).directory.image(&item.image.url)?;
217 Some(entry.path.clone())
218 }
219
220 fn stage_size(window: &Window) -> Pair {
221 let viewport = window.viewport_size();
222 (
223 f32::from(viewport.width).max(1.),
224 (f32::from(viewport.height) - HEADER_HEIGHT - FOOTER_HEIGHT).max(1.),
225 )
226 }
227
228 fn layout(&self, window: &Window, cx: &App) -> Option<Layout> {
229 let item = self.current()?;
230 let entry = self.app.read(cx).directory.image(&item.image.url)?;
231 let stage = Self::stage_size(window);
232 let declared = item.image.width.zip(item.image.height);
233 let source = entry
234 .size
235 .or(declared)
236 .map_or(stage, |(width, height)| (width as f32, height as f32));
237 let source = rotated_size(source, self.quarter_turns);
238 let fit = fit_scale(source, stage);
239 let scale = self.scale.map_or(fit, |scale| clamp_scale(scale, fit));
240 let pan = clamp_pan(self.pan, display_size(source, scale), stage);
241 Some(Layout {
242 stage,
243 source,
244 fit,
245 scale,
246 pan,
247 })
248 }
249
250 fn anchor_of(position: Point<Pixels>, window: &Window) -> Pair {
251 let stage = Self::stage_size(window);
252 (
253 f32::from(position.x) - stage.0 / 2.,
254 f32::from(position.y) - HEADER_HEIGHT - stage.1 / 2.,
255 )
256 }
257
258 fn zoom_to(&mut self, wanted: f32, anchor: Pair, window: &Window, cx: &mut Context<Self>) {
259 let Some(layout) = self.layout(window, cx) else {
260 return;
261 };
262 let view = zoom_at(
263 View {
264 scale: layout.scale,
265 pan: layout.pan,
266 },
267 wanted,
268 anchor,
269 layout.source,
270 layout.stage,
271 );
272 self.scale = (view.scale > layout.fit).then_some(view.scale);
273 self.pan = view.pan;
274 cx.notify();
275 }
276
277 fn zoom_step(&mut self, direction: i32, window: &Window, cx: &mut Context<Self>) {
278 let Some(layout) = self.layout(window, cx) else {
279 return;
280 };
281 self.zoom_to(step_scale(layout.scale, direction), (0., 0.), window, cx);
282 }
283
284 fn zoom_fit(&mut self, cx: &mut Context<Self>) {
285 self.scale = None;
286 self.pan = (0., 0.);
287 cx.notify();
288 }
289
290 fn toggle_zoom(&mut self, position: Point<Pixels>, window: &Window, cx: &mut Context<Self>) {
291 let Some(layout) = self.layout(window, cx) else {
292 return;
293 };
294 let target = toggle_target(layout.scale, layout.fit);
295 self.zoom_to(target, Self::anchor_of(position, window), window, cx);
296 }
297
298 fn on_wheel(&mut self, event: &ScrollWheelEvent, window: &mut Window, cx: &mut Context<Self>) {
299 let Some(layout) = self.layout(window, cx) else {
300 return;
301 };
302 let delta = event.delta.pixel_delta(px(WHEEL_LINE_HEIGHT)).y.into();
303 let anchor = Self::anchor_of(event.position, window);
304 self.zoom_to(wheel_scale(layout.scale, delta), anchor, window, cx);
305 cx.stop_propagation();
306 }
307
308 fn on_mouse_move(
309 &mut self,
310 event: &MouseMoveEvent,
311 window: &mut Window,
312 cx: &mut Context<Self>,
313 ) {
314 let Some(last) = self.drag_from else {
315 return;
316 };
317 if event.pressed_button != Some(MouseButton::Left) {
318 self.drag_from = None;
319 return;
320 }
321 let Some(layout) = self.layout(window, cx) else {
322 return;
323 };
324 let moved = (
325 layout.pan.0 + f32::from(event.position.x - last.x),
326 layout.pan.1 + f32::from(event.position.y - last.y),
327 );
328 self.pan = clamp_pan(moved, display_size(layout.source, layout.scale), layout.stage);
329 self.drag_from = Some(event.position);
330 cx.notify();
331 }
332
333 fn end_drag(&mut self, cx: &mut Context<Self>) {
334 if self.drag_from.take().is_some() {
335 cx.notify();
336 }
337 }
338
339 fn jump(&mut self, index: usize, cx: &mut Context<Self>) {
340 if index == self.index || index >= self.items.len() {
341 return;
342 }
343 self.index = index;
344 self.scale = None;
345 self.pan = (0., 0.);
346 self.quarter_turns = 0;
347 self.rotated = None;
348 self.drag_from = None;
349 self.preload(cx);
350 cx.notify();
351 }
352
353 fn go(&mut self, delta: isize, cx: &mut Context<Self>) {
354 self.jump(step_index(self.index, self.items.len(), delta), cx);
355 }
356
357 fn rotate(&mut self, cx: &mut Context<Self>) {
358 let (Some(path), Some(item)) = (self.current_path(cx), self.current()) else {
359 return;
360 };
361 let url = item.image.url.clone();
362 self.quarter_turns = next_rotation(self.quarter_turns);
363 self.scale = None;
364 self.pan = (0., 0.);
365 self.rotated = None;
366 let quarter_turns = self.quarter_turns;
367 if quarter_turns != 0 {
368 cx.spawn(async move |this, cx| {
369 let task_url = url.clone();
370 let rotated = cx
371 .background_spawn(async move { rotate_file(&path, quarter_turns) })
372 .await;
373 this.update(cx, |this, cx| {
374 let still_current = this.quarter_turns == quarter_turns
375 && this.current().is_some_and(|item| item.image.url == task_url);
376 if let Some(image) = rotated.filter(|_| still_current) {
377 this.rotated = Some(RotatedImage {
378 url: task_url,
379 quarter_turns,
380 image: Arc::new(image),
381 });
382 cx.notify();
383 }
384 })
385 .ok();
386 })
387 .detach();
388 }
389 cx.notify();
390 }
391
392 fn show_notice(&mut self, text: impl Into<String>, cx: &mut Context<Self>) {
393 self.notice_serial += 1;
394 let serial = self.notice_serial;
395 self.notice = Some(text.into());
396 cx.spawn(async move |this, cx| {
397 cx.background_executor().timer(NOTICE_DURATION).await;
398 this.update(cx, |this, cx| {
399 if this.notice_serial == serial {
400 this.notice = None;
401 cx.notify();
402 }
403 })
404 .ok();
405 })
406 .detach();
407 cx.notify();
408 }
409
410 fn rotated_image(&self) -> Option<&Arc<Image>> {
411 let url = &self.current()?.image.url;
412 self.rotated
413 .as_ref()
414 .filter(|rotated| rotated.url == *url && rotated.quarter_turns == self.quarter_turns)
415 .map(|rotated| &rotated.image)
416 }
417
418 fn copy_image(&mut self, cx: &mut Context<Self>) {
419 let Some(path) = self.current_path(cx) else {
420 return;
421 };
422 let item = match self.rotated_image() {
423 Some(rotated) => Some(ClipboardItem::new_image(rotated)),
424 None => std::fs::read(&path).ok().and_then(|bytes| {
425 let format = clipboard_format(&bytes)?;
426 Some(ClipboardItem::new_image(&Image::from_bytes(format, bytes)))
427 }),
428 };
429 match item {
430 Some(item) => {
431 cx.write_to_clipboard(item);
432 self.show_notice("Image copied", cx);
433 }
434 None => {
435 cx.write_to_clipboard(ClipboardItem::new_string(path.display().to_string()));
436 self.show_notice("Copied file path", cx);
437 }
438 }
439 }
440
441 fn save_as(&mut self, cx: &mut Context<Self>) {
442 let Some(source) = self.current_path(cx) else {
443 return;
444 };
445 let receiver =
446 cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&suggested_name(&source)));
447 cx.spawn(async move |this, cx| {
448 let Ok(Ok(Some(target))) = receiver.await else {
449 return;
450 };
451 let copied = cx
452 .background_spawn(async move {
453 std::fs::copy(&source, &target).map(|_| target)
454 })
455 .await;
456 this.update(cx, |this, cx| match copied {
457 Ok(target) => {
458 let name = target
459 .file_name()
460 .map(|name| name.to_string_lossy().into_owned())
461 .unwrap_or_default();
462 this.show_notice(format!("Saved {name}"), cx)
463 }
464 Err(_) => this.show_notice("Could not save the image", cx),
465 })
466 .ok();
467 })
468 .detach();
469 }
470
471 fn forward(&mut self, cx: &mut Context<Self>) {
472 let Some(item) = self.current() else {
473 return;
474 };
475 let message_key = item.message_key.clone();
476 if self.app.read(cx).mode.read_only {
477 self.show_notice("Read-only mode: message not forwarded", cx);
478 return;
479 }
480 let conversation_id = self.conversation_id.clone();
481 self.app.update(cx, |state, cx| {
482 state.request_forward(&conversation_id, &message_key, cx)
483 });
484 }
485
486 fn open_externally(&mut self, cx: &mut Context<Self>) {
487 if let Some(path) = self.current_path(cx) {
488 cx.open_with_system(&path);
489 }
490 }
491
492 fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
493 let command = event.keystroke.modifiers.secondary();
494 match (event.keystroke.key.as_str(), command) {
495 ("escape", _) => cx.emit(ImageViewerEvent::Close),
496 ("left", false) => self.go(-1, cx),
497 ("right", false) => self.go(1, cx),
498 ("r", false) => self.rotate(cx),
499 ("f11", _) => window.toggle_fullscreen(),
500 ("=" | "+", true) => self.zoom_step(1, window, cx),
501 ("-", true) => self.zoom_step(-1, window, cx),
502 ("0", true) => self.zoom_fit(cx),
503 ("c", true) => self.copy_image(cx),
504 ("s", true) => self.save_as(cx),
505 _ => {}
506 }
507 cx.stop_propagation();
508 }
509
510 fn header(&self, layout: Option<Layout>, cx: &mut Context<Self>) -> Div {
511 let item = self.current();
512 let author = item.map(|item| item.author.clone()).unwrap_or_default();
513 let subtitle = item
514 .map(|item| format!("{} \u{b7} {}", item.time, self.conversation_title))
515 .unwrap_or_default();
516 let sender_id = item.and_then(|item| item.sender_id.clone());
517 let can_zoom_out = layout.is_some_and(|layout| layout.scale > layout.fit);
518 let can_zoom_in = layout.is_some_and(|layout| layout.scale < MAX_ZOOM);
519 let zoom_label = layout.map(|layout| percent_label(layout.scale)).unwrap_or_default();
520 let loaded = layout.is_some();
521 h_flex()
522 .absolute()
523 .top_0()
524 .left_0()
525 .w_full()
526 .h(px(HEADER_HEIGHT))
527 .px(px(SIDE_PADDING))
528 .gap(px(12.))
529 .items_center()
530 .child(
531 h_flex()
532 .flex_1()
533 .min_w_0()
534 .gap(px(10.))
535 .items_center()
536 .child(
537 div()
538 .size(px(AVATAR_SIZE))
539 .flex_none()
540 .child(person_avatar(
541 &self.app.read(cx).directory,
542 sender_id.as_deref(),
543 &author,
544 AVATAR_SIZE,
545 )),
546 )
547 .child(
548 v_flex()
549 .flex_1()
550 .min_w_0()
551 .child(
552 div()
553 .truncate()
554 .text_size(px(14.))
555 .font_weight(FontWeight::SEMIBOLD)
556 .text_color(white())
557 .child(author),
558 )
559 .child(
560 div()
561 .truncate()
562 .text_size(px(12.))
563 .text_color(white().opacity(0.6))
564 .child(subtitle),
565 ),
566 ),
567 )
568 .child(
569 h_flex()
570 .flex_none()
571 .gap(px(2.))
572 .items_center()
573 .child(control_button(
574 "viewer-zoom-out",
575 "zoom_out",
576 "Zoom out (Ctrl -)",
577 can_zoom_out,
578 cx.listener(|this, _, window, cx| this.zoom_step(-1, window, cx)),
579 ))
580 .child(
581 div()
582 .w(px(ZOOM_LABEL_WIDTH))
583 .flex_none()
584 .text_center()
585 .text_size(px(12.))
586 .text_color(white().opacity(0.8))
587 .child(zoom_label),
588 )
589 .child(control_button(
590 "viewer-zoom-in",
591 "zoom_in",
592 "Zoom in (Ctrl +)",
593 can_zoom_in,
594 cx.listener(|this, _, window, cx| this.zoom_step(1, window, cx)),
595 ))
596 .child(control_button(
597 "viewer-rotate",
598 "rotate_right",
599 "Rotate (R)",
600 loaded,
601 cx.listener(|this, _, _, cx| this.rotate(cx)),
602 ))
603 .child(control_button(
604 "viewer-copy",
605 "content_copy",
606 "Copy image (Ctrl C)",
607 loaded,
608 cx.listener(|this, _, _, cx| this.copy_image(cx)),
609 ))
610 .child(control_button(
611 "viewer-save",
612 "download",
613 "Save as (Ctrl S)",
614 loaded,
615 cx.listener(|this, _, _, cx| this.save_as(cx)),
616 ))
617 .child(control_button(
618 "viewer-forward",
619 "forward",
620 "Forward",
621 true,
622 cx.listener(|this, _, _, cx| this.forward(cx)),
623 ))
624 .child(control_button(
625 "viewer-fullscreen",
626 "fullscreen",
627 "Full screen (F11)",
628 true,
629 cx.listener(|_, _, window, _| window.toggle_fullscreen()),
630 ))
631 .child(control_button(
632 "viewer-open",
633 "open_in_new",
634 "Open in Photos",
635 loaded,
636 cx.listener(|this, _, _, cx| this.open_externally(cx)),
637 ))
638 .child(control_button(
639 "viewer-close",
640 "close",
641 "Close (Esc)",
642 true,
643 cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)),
644 )),
645 )
646 }
647
648 fn nav_button(
649 &self,
650 id: &'static str,
651 glyph: &'static str,
652 left: bool,
653 stage: Pair,
654 cx: &mut Context<Self>,
655 delta: isize,
656 ) -> Stateful<Div> {
657 let top = ((stage.1 - NAV_SIZE) / 2.).max(0.);
658 div()
659 .id(id)
660 .absolute()
661 .top(px(top))
662 .when(left, |button| button.left(px(NAV_MARGIN)))
663 .when(!left, |button| button.right(px(NAV_MARGIN)))
664 .size(px(NAV_SIZE))
665 .flex()
666 .items_center()
667 .justify_center()
668 .rounded_full()
669 .bg(white().opacity(0.1))
670 .cursor_pointer()
671 .hover(|button| button.bg(white().opacity(0.2)))
672 .child(symbol(glyph, NAV_ICON_SIZE, white()))
673 .on_click(cx.listener(move |this, _, _, cx| {
674 cx.stop_propagation();
675 this.go(delta, cx);
676 }))
677 }
678
679 fn picture(&self, layout: Layout, cx: &mut Context<Self>) -> AnyElement {
680 let display = display_size(layout.source, layout.scale);
681 let origin = image_origin(display, layout.stage, layout.pan);
682 let Some(item) = self.current() else {
683 return div().into_any_element();
684 };
685 let source: Option<ImageSource> = if self.quarter_turns == 0 {
686 self.app
687 .read(cx)
688 .directory
689 .image(&item.image.url)
690 .map(|entry| entry.path.clone().into())
691 } else {
692 self.rotated_image().map(|image| ImageSource::Image(image.clone()))
693 };
694 let Some(source) = source else {
695 return loading_placeholder();
696 };
697 div()
698 .id("viewer-picture")
699 .absolute()
700 .left(px(origin.0))
701 .top(px(origin.1))
702 .w(px(display.0))
703 .h(px(display.1))
704 .child(img(source).size_full().object_fit(ObjectFit::Fill))
705 .on_mouse_down(
706 MouseButton::Left,
707 cx.listener(|this, event: &MouseDownEvent, _, cx| {
708 cx.stop_propagation();
709 this.drag_from = Some(event.position);
710 }),
711 )
712 .on_click(cx.listener(|this, event: &ClickEvent, window, cx| {
713 cx.stop_propagation();
714 if event.click_count() == 2 {
715 this.toggle_zoom(event.position(), window, cx);
716 }
717 }))
718 .into_any_element()
719 }
720
721 fn thumbnail(&self, index: usize, cx: &mut Context<Self>) -> Stateful<Div> {
722 let item = &self.items[index];
723 let current = index == self.index;
724 let path = self
725 .app
726 .read(cx)
727 .directory
728 .image(&item.image.url)
729 .map(|entry| entry.path.clone());
730 div()
731 .id(ElementId::Name(format!("viewer-thumbnail-{index}").into()))
732 .size(px(THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER))
733 .flex_none()
734 .flex()
735 .items_center()
736 .justify_center()
737 .rounded(px(THUMBNAIL_RADIUS + THUMBNAIL_BORDER))
738 .border_2()
739 .border_color(if current {
740 theme::accent()
741 } else {
742 transparent_black()
743 })
744 .cursor_pointer()
745 .child(
746 div()
747 .size(px(THUMBNAIL_SIZE))
748 .flex_none()
749 .flex()
750 .items_center()
751 .justify_center()
752 .overflow_hidden()
753 .rounded(px(THUMBNAIL_RADIUS))
754 .bg(white().opacity(0.08))
755 .when(!current, |frame| frame.opacity(0.7))
756 .map(|frame| match path {
757 Some(path) => frame.child(
758 img(path)
759 .size_full()
760 .object_fit(ObjectFit::Cover),
761 ),
762 None => frame.child(symbol("image", 18., white().opacity(0.5))),
763 }),
764 )
765 .on_click(cx.listener(move |this, _, _, cx| {
766 cx.stop_propagation();
767 this.jump(index, cx);
768 }))
769 }
770
771 fn footer(&self, window: &Window, cx: &mut Context<Self>) -> Div {
772 let width = f32::from(window.viewport_size().width);
773 let capacity = ((width - 2. * SIDE_PADDING) / (THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER + THUMBNAIL_GAP))
774 .floor()
775 .max(1.) as usize;
776 let range = thumbnail_window(self.index, self.items.len(), capacity);
777 let caption = self
778 .current()
779 .map(|item| item.caption.clone())
780 .unwrap_or_default();
781 let status = self
782 .notice
783 .clone()
784 .unwrap_or_else(|| counter_label(self.index, self.items.len()));
785 v_flex()
786 .absolute()
787 .bottom_0()
788 .left_0()
789 .w_full()
790 .h(px(FOOTER_HEIGHT))
791 .pb(px(12.))
792 .gap(px(4.))
793 .items_center()
794 .justify_end()
795 .child(
796 div()
797 .w(px((width - 2. * SIDE_PADDING).clamp(0., CAPTION_MAX_WIDTH)))
798 .h(px(CAPTION_HEIGHT))
799 .flex_none()
800 .truncate()
801 .text_center()
802 .text_size(px(13.))
803 .text_color(white().opacity(0.9))
804 .child(caption),
805 )
806 .child(
807 div()
808 .h(px(STATUS_HEIGHT))
809 .flex_none()
810 .text_size(px(12.))
811 .text_color(white().opacity(0.6))
812 .child(status),
813 )
814 .child(
815 h_flex()
816 .h(px(STRIP_HEIGHT))
817 .flex_none()
818 .gap(px(THUMBNAIL_GAP))
819 .items_center()
820 .children(range.map(|index| self.thumbnail(index, cx))),
821 )
822 }
823}
824
825fn loading_placeholder() -> AnyElement {
826 v_flex()
827 .size_full()
828 .gap(px(6.))
829 .items_center()
830 .justify_center()
831 .child(symbol("image", 28., white().opacity(0.5)))
832 .child(
833 div()
834 .text_size(px(12.))
835 .text_color(white().opacity(0.6))
836 .child("Loading image"),
837 )
838 .into_any_element()
839}
840
841impl Render for ImageViewer {
842 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
843 let layout = self.layout(window, cx);
844 let stage = Self::stage_size(window);
845 let has_previous = self.index > 0;
846 let has_next = self.index + 1 < self.items.len();
847 let picture = match layout {
848 Some(layout) => self.picture(layout, cx),
849 None => loading_placeholder(),
850 };
851 let header = self.header(layout, cx);
852 let footer = self.footer(window, cx);
853 div()
854 .id("image-viewer")
855 .key_context("ImageViewer")
856 .track_focus(&self.focus_handle)
857 .absolute()
858 .top_0()
859 .left_0()
860 .size_full()
861 .bg(rgba(BACKDROP))
862 .occlude()
863 .on_key_down(cx.listener(Self::on_key_down))
864 .on_scroll_wheel(cx.listener(Self::on_wheel))
865 .on_mouse_move(cx.listener(Self::on_mouse_move))
866 .on_mouse_up(
867 MouseButton::Left,
868 cx.listener(|this, _, _, cx| this.end_drag(cx)),
869 )
870 .on_mouse_up_out(
871 MouseButton::Left,
872 cx.listener(|this, _, _, cx| this.end_drag(cx)),
873 )
874 .on_click(cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)))
875 .child(
876 div()
877 .absolute()
878 .top(px(HEADER_HEIGHT))
879 .left_0()
880 .w(px(stage.0))
881 .h(px(stage.1))
882 .overflow_hidden()
883 .child(picture)
884 .when(has_previous, |stage_element| {
885 stage_element.child(self.nav_button(
886 "viewer-previous",
887 "chevron_left",
888 true,
889 stage,
890 cx,
891 -1,
892 ))
893 })
894 .when(has_next, |stage_element| {
895 stage_element.child(self.nav_button(
896 "viewer-next",
897 "chevron_right",
898 false,
899 stage,
900 cx,
901 1,
902 ))
903 }),
904 )
905 .child(header)
906 .child(footer)
907 }
908}
crates/app/src/views/message_row.rs +7 −1
@@ -5,7 +5,7 @@ use gpui_kit::*;
5 5 use std::time::Duration;
6 6
7 7 use super::adaptive_card::cards_view;
8 use super::attachments::{FileActions, attachments_view, message_body};
8 use super::attachments::{FileActions, ImageOpen, attachments_view, message_body};
9 9 use super::avatar::{bot_avatar, person_avatar};
10 10 use super::link_preview::{link_preview_card, meeting_join_chip};
11 11 use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
@@ -54,6 +54,7 @@ pub struct RowActions {
54 54 pub react: Option<PickHandler>,
55 55 pub reaction_controls: Option<ReactionControls>,
56 56 pub files: Option<FileActions>,
57 pub open_image: Option<ImageOpen>,
57 58 pub highlighted: bool,
58 59 pub saved: bool,
59 60 pub translation: Option<TranslationActions>,
@@ -161,6 +162,7 @@ fn bubble(
161 162 &format!("message-{index}"),
162 163 own,
163 164 directory,
165 extras.open_image.as_ref(),
164 166 cx,
165 167 ));
166 168 }
@@ -172,6 +174,7 @@ fn bubble(
172 174 &format!("message-{index}"),
173 175 directory,
174 176 extras.files.as_ref(),
177 extras.open_image.as_ref(),
175 178 ));
176 179 content = content.children(
177 180 row.meeting_link
@@ -259,6 +262,7 @@ struct BubbleExtras {
259 262 react: Option<PickHandler>,
260 263 controls: Option<ReactionControls>,
261 264 files: Option<FileActions>,
265 open_image: Option<ImageOpen>,
262 266 saved: bool,
263 267 translation: Option<TranslationActions>,
264 268 }
@@ -560,6 +564,7 @@ pub fn render_message_row(
560 564 react,
561 565 reaction_controls,
562 566 files,
567 open_image,
563 568 highlighted,
564 569 saved,
565 570 translation,
@@ -571,6 +576,7 @@ pub fn render_message_row(
571 576 react,
572 577 controls: reaction_controls,
573 578 files,
579 open_image,
574 580 saved,
575 581 translation,
576 582 };
@@ -5,7 +5,7 @@ use gpui_kit::*;
5use std::time::Duration;
5use std::time::Duration;
6
6
7use super::adaptive_card::cards_view;
7use super::adaptive_card::cards_view;
8use super::attachments::{FileActions, attachments_view, message_body};
8use super::attachments::{FileActions, ImageOpen, attachments_view, message_body};
9use super::avatar::{bot_avatar, person_avatar};
9use super::avatar::{bot_avatar, person_avatar};
10use super::link_preview::{link_preview_card, meeting_join_chip};
10use super::link_preview::{link_preview_card, meeting_join_chip};
11use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
@@ -54,6 +54,7 @@ pub struct RowActions {
54 pub react: Option<PickHandler>,
54 pub react: Option<PickHandler>,
55 pub reaction_controls: Option<ReactionControls>,
55 pub reaction_controls: Option<ReactionControls>,
56 pub files: Option<FileActions>,
56 pub files: Option<FileActions>,
57 pub open_image: Option<ImageOpen>,
57 pub highlighted: bool,
58 pub highlighted: bool,
58 pub saved: bool,
59 pub saved: bool,
59 pub translation: Option<TranslationActions>,
60 pub translation: Option<TranslationActions>,
@@ -161,6 +162,7 @@ fn bubble(
161 &format!("message-{index}"),
162 &format!("message-{index}"),
162 own,
163 own,
163 directory,
164 directory,
165 extras.open_image.as_ref(),
164 cx,
166 cx,
165 ));
167 ));
166 }
168 }
@@ -172,6 +174,7 @@ fn bubble(
172 &format!("message-{index}"),
174 &format!("message-{index}"),
173 directory,
175 directory,
174 extras.files.as_ref(),
176 extras.files.as_ref(),
177 extras.open_image.as_ref(),
175 ));
178 ));
176 content = content.children(
179 content = content.children(
177 row.meeting_link
180 row.meeting_link
@@ -259,6 +262,7 @@ struct BubbleExtras {
259 react: Option<PickHandler>,
262 react: Option<PickHandler>,
260 controls: Option<ReactionControls>,
263 controls: Option<ReactionControls>,
261 files: Option<FileActions>,
264 files: Option<FileActions>,
265 open_image: Option<ImageOpen>,
262 saved: bool,
266 saved: bool,
263 translation: Option<TranslationActions>,
267 translation: Option<TranslationActions>,
264}
268}
@@ -560,6 +564,7 @@ pub fn render_message_row(
560 react,
564 react,
561 reaction_controls,
565 reaction_controls,
562 files,
566 files,
567 open_image,
563 highlighted,
568 highlighted,
564 saved,
569 saved,
565 translation,
570 translation,
@@ -571,6 +576,7 @@ pub fn render_message_row(
571 react,
576 react,
572 controls: reaction_controls,
577 controls: reaction_controls,
573 files,
578 files,
579 open_image,
574 saved,
580 saved,
575 translation,
581 translation,
576 };
582 };
crates/app/src/views/mod.rs +1 −0
@@ -27,6 +27,7 @@ pub mod draft_style;
27 27 pub mod emoji_popup;
28 28 pub mod format_toolbar;
29 29 pub mod forward_dialog;
30 pub mod image_viewer;
30 31 pub mod join_dialog;
31 32 pub mod link_preview;
32 33 pub mod fun_picker;
@@ -27,6 +27,7 @@ pub mod draft_style;
27pub mod emoji_popup;
27pub mod emoji_popup;
28pub mod format_toolbar;
28pub mod format_toolbar;
29pub mod forward_dialog;
29pub mod forward_dialog;
30pub mod image_viewer;
30pub mod join_dialog;
31pub mod join_dialog;
31pub mod link_preview;
32pub mod link_preview;
32pub mod fun_picker;
33pub mod fun_picker;
crates/app/src/views/post_card.rs +2 −0
@@ -91,6 +91,7 @@ fn message_content(
91 91 &format!("message-{index}"),
92 92 false,
93 93 directory,
94 actions.open_image.as_ref(),
94 95 cx,
95 96 )),
96 97 );
@@ -103,6 +104,7 @@ fn message_content(
103 104 &format!("message-{index}"),
104 105 directory,
105 106 actions.files.as_ref(),
107 actions.open_image.as_ref(),
106 108 ));
107 109 content = content.children(
108 110 row.meeting_link
@@ -91,6 +91,7 @@ fn message_content(
91 &format!("message-{index}"),
91 &format!("message-{index}"),
92 false,
92 false,
93 directory,
93 directory,
94 actions.open_image.as_ref(),
94 cx,
95 cx,
95 )),
96 )),
96 );
97 );
@@ -103,6 +104,7 @@ fn message_content(
103 &format!("message-{index}"),
104 &format!("message-{index}"),
104 directory,
105 directory,
105 actions.files.as_ref(),
106 actions.files.as_ref(),
107 actions.open_image.as_ref(),
106 ));
108 ));
107 content = content.children(
109 content = content.children(
108 row.meeting_link
110 row.meeting_link
crates/app/src/views/shell.rs +43 −1
@@ -8,6 +8,7 @@ use super::call_view::render_call_view;
8 8 use super::conversation::{ConversationView, ReplyToHovered};
9 9 use super::dialog_overlay::render_task_dialog;
10 10 use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};
11 use super::image_viewer::{ImageViewer, ImageViewerEvent};
11 12 use super::profile_card::{ProfileCard, ProfileCardEvent};
12 13 use super::rail::RailView;
13 14 use super::saved_panel::{SavedPanel, SavedPanelEvent};
@@ -65,6 +66,7 @@ pub struct AppShell {
65 66 notifications: Entity<NotificationCenter>,
66 67 _call_windows: Entity<CallWindows>,
67 68 forward_dialog: Option<Entity<ForwardDialog>>,
69 image_viewer: Option<Entity<ImageViewer>>,
68 70 status_dialog: Option<Entity<StatusMessageDialog>>,
69 71 shortcuts_dialog: Option<Entity<ShortcutsDialog>>,
70 72 profile_card: Option<Entity<ProfileCard>>,
@@ -134,6 +136,9 @@ impl AppShell {
134 136 if matches!(event, AppEvent::Forward) {
135 137 this.open_forward_dialog(window, cx);
136 138 }
139 if matches!(event, AppEvent::ImageViewer) {
140 this.open_image_viewer(window, cx);
141 }
137 142 if matches!(event, AppEvent::StatusMessage) {
138 143 this.open_status_dialog(window, cx);
139 144 }
@@ -173,6 +178,7 @@ impl AppShell {
173 178 notifications,
174 179 _call_windows: call_windows,
175 180 forward_dialog: None,
181 image_viewer: None,
176 182 status_dialog: None,
177 183 shortcuts_dialog: None,
178 184 profile_card: None,
@@ -433,6 +439,40 @@ impl AppShell {
433 439 cx.notify();
434 440 }
435 441
442 fn open_image_viewer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
443 let Some(request) = self
444 .state
445 .update(cx, |state, _| state.take_image_viewer_request())
446 else {
447 return;
448 };
449 self.switcher = None;
450 let app = self.state.clone();
451 let viewer = cx.new(|cx| ImageViewer::new(app, request, window, cx));
452 cx.subscribe_in(
453 &viewer,
454 window,
455 |this, _, _: &ImageViewerEvent, window, cx| {
456 this.image_viewer = None;
457 window.focus(&this.focus_handle, cx);
458 cx.notify();
459 },
460 )
461 .detach();
462 self.image_viewer = Some(viewer);
463 cx.notify();
464 }
465
466 fn restore_focus(&self, window: &mut Window, cx: &mut Context<Self>) {
467 match &self.image_viewer {
468 Some(viewer) => {
469 let handle = viewer.read(cx).focus_handle();
470 window.focus(&handle, cx)
471 }
472 None => window.focus(&self.focus_handle, cx),
473 }
474 }
475
436 476 fn open_forward_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
437 477 let Some(source) = self
438 478 .state
@@ -449,7 +489,7 @@ impl AppShell {
449 489 window,
450 490 |this, _, event: &ForwardDialogEvent, window, cx| {
451 491 this.forward_dialog = None;
452 window.focus(&this.focus_handle, cx);
492 this.restore_focus(window, cx);
453 493 if let ForwardDialogEvent::Sent { target, title } = event {
454 494 let target = target.clone();
455 495 let open = NoticeAction::new("Open", move |state, cx| {
@@ -531,6 +571,7 @@ impl Render for AppShell {
531 571 }
532 572 let panels = self.switcher.is_some()
533 573 || self.forward_dialog.is_some()
574 || self.image_viewer.is_some()
534 575 || self.status_dialog.is_some()
535 576 || self.shortcuts_dialog.is_some()
536 577 || self.profile_card.is_some()
@@ -633,6 +674,7 @@ impl Render for AppShell {
633 674 )
634 675 .children(call_mini)
635 676 .children(stage_overlay)
677 .children(self.image_viewer.clone())
636 678 .children(self.switcher.clone())
637 679 .children(render_task_dialog(self.state.read(cx), cx))
638 680 .children(self.forward_dialog.clone())
@@ -8,6 +8,7 @@ use super::call_view::render_call_view;
8use super::conversation::{ConversationView, ReplyToHovered};
8use super::conversation::{ConversationView, ReplyToHovered};
9use super::dialog_overlay::render_task_dialog;
9use super::dialog_overlay::render_task_dialog;
10use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};
10use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};
11use super::image_viewer::{ImageViewer, ImageViewerEvent};
11use super::profile_card::{ProfileCard, ProfileCardEvent};
12use super::profile_card::{ProfileCard, ProfileCardEvent};
12use super::rail::RailView;
13use super::rail::RailView;
13use super::saved_panel::{SavedPanel, SavedPanelEvent};
14use super::saved_panel::{SavedPanel, SavedPanelEvent};
@@ -65,6 +66,7 @@ pub struct AppShell {
65 notifications: Entity<NotificationCenter>,
66 notifications: Entity<NotificationCenter>,
66 _call_windows: Entity<CallWindows>,
67 _call_windows: Entity<CallWindows>,
67 forward_dialog: Option<Entity<ForwardDialog>>,
68 forward_dialog: Option<Entity<ForwardDialog>>,
69 image_viewer: Option<Entity<ImageViewer>>,
68 status_dialog: Option<Entity<StatusMessageDialog>>,
70 status_dialog: Option<Entity<StatusMessageDialog>>,
69 shortcuts_dialog: Option<Entity<ShortcutsDialog>>,
71 shortcuts_dialog: Option<Entity<ShortcutsDialog>>,
70 profile_card: Option<Entity<ProfileCard>>,
72 profile_card: Option<Entity<ProfileCard>>,
@@ -134,6 +136,9 @@ impl AppShell {
134 if matches!(event, AppEvent::Forward) {
136 if matches!(event, AppEvent::Forward) {
135 this.open_forward_dialog(window, cx);
137 this.open_forward_dialog(window, cx);
136 }
138 }
139 if matches!(event, AppEvent::ImageViewer) {
140 this.open_image_viewer(window, cx);
141 }
137 if matches!(event, AppEvent::StatusMessage) {
142 if matches!(event, AppEvent::StatusMessage) {
138 this.open_status_dialog(window, cx);
143 this.open_status_dialog(window, cx);
139 }
144 }
@@ -173,6 +178,7 @@ impl AppShell {
173 notifications,
178 notifications,
174 _call_windows: call_windows,
179 _call_windows: call_windows,
175 forward_dialog: None,
180 forward_dialog: None,
181 image_viewer: None,
176 status_dialog: None,
182 status_dialog: None,
177 shortcuts_dialog: None,
183 shortcuts_dialog: None,
178 profile_card: None,
184 profile_card: None,
@@ -433,6 +439,40 @@ impl AppShell {
433 cx.notify();
439 cx.notify();
434 }
440 }
435
441
442 fn open_image_viewer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
443 let Some(request) = self
444 .state
445 .update(cx, |state, _| state.take_image_viewer_request())
446 else {
447 return;
448 };
449 self.switcher = None;
450 let app = self.state.clone();
451 let viewer = cx.new(|cx| ImageViewer::new(app, request, window, cx));
452 cx.subscribe_in(
453 &viewer,
454 window,
455 |this, _, _: &ImageViewerEvent, window, cx| {
456 this.image_viewer = None;
457 window.focus(&this.focus_handle, cx);
458 cx.notify();
459 },
460 )
461 .detach();
462 self.image_viewer = Some(viewer);
463 cx.notify();
464 }
465
466 fn restore_focus(&self, window: &mut Window, cx: &mut Context<Self>) {
467 match &self.image_viewer {
468 Some(viewer) => {
469 let handle = viewer.read(cx).focus_handle();
470 window.focus(&handle, cx)
471 }
472 None => window.focus(&self.focus_handle, cx),
473 }
474 }
475
436 fn open_forward_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
476 fn open_forward_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
437 let Some(source) = self
477 let Some(source) = self
438 .state
478 .state
@@ -449,7 +489,7 @@ impl AppShell {
449 window,
489 window,
450 |this, _, event: &ForwardDialogEvent, window, cx| {
490 |this, _, event: &ForwardDialogEvent, window, cx| {
451 this.forward_dialog = None;
491 this.forward_dialog = None;
452 window.focus(&this.focus_handle, cx);
492 this.restore_focus(window, cx);
453 if let ForwardDialogEvent::Sent { target, title } = event {
493 if let ForwardDialogEvent::Sent { target, title } = event {
454 let target = target.clone();
494 let target = target.clone();
455 let open = NoticeAction::new("Open", move |state, cx| {
495 let open = NoticeAction::new("Open", move |state, cx| {
@@ -531,6 +571,7 @@ impl Render for AppShell {
531 }
571 }
532 let panels = self.switcher.is_some()
572 let panels = self.switcher.is_some()
533 || self.forward_dialog.is_some()
573 || self.forward_dialog.is_some()
574 || self.image_viewer.is_some()
534 || self.status_dialog.is_some()
575 || self.status_dialog.is_some()
535 || self.shortcuts_dialog.is_some()
576 || self.shortcuts_dialog.is_some()
536 || self.profile_card.is_some()
577 || self.profile_card.is_some()
@@ -633,6 +674,7 @@ impl Render for AppShell {
633 )
674 )
634 .children(call_mini)
675 .children(call_mini)
635 .children(stage_overlay)
676 .children(stage_overlay)
677 .children(self.image_viewer.clone())
636 .children(self.switcher.clone())
678 .children(self.switcher.clone())
637 .children(render_task_dialog(self.state.read(cx), cx))
679 .children(render_task_dialog(self.state.read(cx), cx))
638 .children(self.forward_dialog.clone())
680 .children(self.forward_dialog.clone())