| 1 | use crate::views::image_memory::{bounded, preview}; |
| 2 | use std::io::Cursor; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::sync::Arc; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex}; |
| 8 | use gpui_kit::prelude::FluentBuilder as _; |
| 9 | use gpui_kit::*; |
| 10 | |
| 11 | use image::{Frame, ImageReader}; |
| 12 | |
| 13 | use super::avatar::person_avatar; |
| 14 | use super::shortcuts::{ZoomIn, ZoomOut, ZoomReset}; |
| 15 | use super::widgets::symbol; |
| 16 | use crate::app_state::AppState; |
| 17 | use crate::downloads; |
| 18 | use crate::image_clipboard::ClipboardImage; |
| 19 | use crate::image_view_gallery::{GalleryItem, ViewerRequest}; |
| 20 | use crate::image_view_math::{ |
| 21 | MAX_ZOOM, Pair, View, clamp_pan, clamp_scale, counter_label, display_size, fit_scale, |
| 22 | image_origin, next_rotation, percent_label, rotated_size, step_index, step_scale, |
| 23 | thumbnail_window, toggle_target, wheel_scale, zoom_at, |
| 24 | }; |
| 25 | use crate::theme; |
| 26 | |
| 27 | const HEADER_HEIGHT: f32 = 52.; |
| 28 | const FOOTER_HEIGHT: f32 = 120.; |
| 29 | const BUTTON_SIZE: f32 = 36.; |
| 30 | const BUTTON_RADIUS: f32 = 8.; |
| 31 | const BUTTON_ICON_SIZE: f32 = 20.; |
| 32 | const NAV_ICON_SIZE: f32 = 24.; |
| 33 | const ZOOM_LABEL_WIDTH: f32 = 52.; |
| 34 | const NAV_SIZE: f32 = 44.; |
| 35 | const NAV_MARGIN: f32 = 16.; |
| 36 | const AVATAR_SIZE: f32 = 32.; |
| 37 | const SIDE_PADDING: f32 = 16.; |
| 38 | const THUMBNAIL_SIZE: f32 = 48.; |
| 39 | const THUMBNAIL_GAP: f32 = 8.; |
| 40 | const THUMBNAIL_RADIUS: f32 = 6.; |
| 41 | const THUMBNAIL_BORDER: f32 = 2.; |
| 42 | const CAPTION_MAX_WIDTH: f32 = 720.; |
| 43 | const CAPTION_HEIGHT: f32 = 22.; |
| 44 | const STATUS_HEIGHT: f32 = 18.; |
| 45 | const STRIP_HEIGHT: f32 = THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER; |
| 46 | const WHEEL_LINE_HEIGHT: f32 = 20.; |
| 47 | const BACKDROP: u32 = 0x080809fc; |
| 48 | const DISABLED_OPACITY: f32 = 0.35; |
| 49 | const NOTICE_DURATION: Duration = Duration::from_secs(2); |
| 50 | |
| 51 | pub enum ImageViewerEvent { |
| 52 | Close, |
| 53 | } |
| 54 | |
| 55 | struct RotatedImage { |
| 56 | url: String, |
| 57 | quarter_turns: u8, |
| 58 | render: Arc<RenderImage>, |
| 59 | } |
| 60 | |
| 61 | #[derive(Clone, Copy)] |
| 62 | struct Layout { |
| 63 | stage: Pair, |
| 64 | source: Pair, |
| 65 | fit: f32, |
| 66 | scale: f32, |
| 67 | pan: Pair, |
| 68 | } |
| 69 | |
| 70 | pub struct ImageViewer { |
| 71 | app: Entity<AppState>, |
| 72 | conversation_id: String, |
| 73 | conversation_title: String, |
| 74 | items: Vec<GalleryItem>, |
| 75 | index: usize, |
| 76 | scale: Option<f32>, |
| 77 | pan: Pair, |
| 78 | quarter_turns: u8, |
| 79 | rotated: Option<RotatedImage>, |
| 80 | entered_fullscreen: bool, |
| 81 | drag_from: Option<Point<Pixels>>, |
| 82 | notice: Option<String>, |
| 83 | notice_serial: u64, |
| 84 | focus_handle: FocusHandle, |
| 85 | _observation: Subscription, |
| 86 | } |
| 87 | |
| 88 | impl EventEmitter<ImageViewerEvent> for ImageViewer {} |
| 89 | |
| 90 | fn decode(path: &Path) -> Option<image::DynamicImage> { |
| 91 | ImageReader::open(path) |
| 92 | .ok()? |
| 93 | .with_guessed_format() |
| 94 | .ok()? |
| 95 | .decode() |
| 96 | .ok() |
| 97 | } |
| 98 | |
| 99 | fn rotate_decoded(decoded: image::DynamicImage, quarter_turns: u8) -> image::DynamicImage { |
| 100 | match quarter_turns { |
| 101 | 1 => decoded.rotate90(), |
| 102 | 2 => decoded.rotate180(), |
| 103 | 3 => decoded.rotate270(), |
| 104 | _ => decoded, |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | fn rotated_render(path: &Path, quarter_turns: u8) -> Option<RenderImage> { |
| 109 | let mut pixels = rotate_decoded(decode(path)?, quarter_turns).to_rgba8(); |
| 110 | for pixel in pixels.chunks_exact_mut(4) { |
| 111 | pixel.swap(0, 2); |
| 112 | } |
| 113 | Some(RenderImage::new(vec![Frame::new(pixels)])) |
| 114 | } |
| 115 | |
| 116 | fn rotated_png(path: &Path, quarter_turns: u8) -> Option<Vec<u8>> { |
| 117 | let rotated = rotate_decoded(decode(path)?, quarter_turns); |
| 118 | let mut bytes = Vec::new(); |
| 119 | rotated |
| 120 | .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png) |
| 121 | .ok()?; |
| 122 | Some(bytes) |
| 123 | } |
| 124 | |
| 125 | fn clipboard_image(path: &Path, quarter_turns: u8) -> Option<ClipboardImage> { |
| 126 | let bytes = if quarter_turns != 0 { |
| 127 | rotated_png(path, quarter_turns)? |
| 128 | } else { |
| 129 | std::fs::read(path).ok()? |
| 130 | }; |
| 131 | ClipboardImage::from_bytes(&bytes) |
| 132 | } |
| 133 | |
| 134 | pub(super) fn suggested_name(path: &Path, rotated: bool) -> String { |
| 135 | let name = path |
| 136 | .file_name() |
| 137 | .map(|name| name.to_string_lossy().into_owned()) |
| 138 | .unwrap_or_else(|| "image".to_owned()); |
| 139 | if rotated { |
| 140 | return Path::new(&name) |
| 141 | .with_extension("png") |
| 142 | .to_string_lossy() |
| 143 | .into_owned(); |
| 144 | } |
| 145 | if path.extension().is_some() { |
| 146 | return name; |
| 147 | } |
| 148 | let extension = std::fs::read(path) |
| 149 | .ok() |
| 150 | .and_then(|bytes| image::guess_format(&bytes).ok()) |
| 151 | .and_then(|format| format.extensions_str().first().copied()) |
| 152 | .unwrap_or("png"); |
| 153 | format!("{name}.{extension}") |
| 154 | } |
| 155 | |
| 156 | pub(super) fn write_image(source: &Path, target: &Path, quarter_turns: u8) -> std::io::Result<()> { |
| 157 | if quarter_turns == 0 { |
| 158 | return std::fs::copy(source, target).map(|_| ()); |
| 159 | } |
| 160 | let bytes = rotated_png(source, quarter_turns) |
| 161 | .ok_or_else(|| std::io::Error::other("rotation failed"))?; |
| 162 | std::fs::write(target, bytes) |
| 163 | } |
| 164 | |
| 165 | fn control_button( |
| 166 | id: &'static str, |
| 167 | glyph: &'static str, |
| 168 | tooltip: &'static str, |
| 169 | enabled: bool, |
| 170 | on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, |
| 171 | ) -> Stateful<Div> { |
| 172 | div() |
| 173 | .id(id) |
| 174 | .size(px(BUTTON_SIZE)) |
| 175 | .flex_none() |
| 176 | .flex() |
| 177 | .items_center() |
| 178 | .justify_center() |
| 179 | .rounded(px(BUTTON_RADIUS)) |
| 180 | .text_color(white()) |
| 181 | .when(enabled, |button| { |
| 182 | button |
| 183 | .cursor_pointer() |
| 184 | .hover(|button| button.bg(white().opacity(0.12))) |
| 185 | }) |
| 186 | .when(!enabled, |button| button.opacity(DISABLED_OPACITY)) |
| 187 | .tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx)) |
| 188 | .child(symbol(glyph, BUTTON_ICON_SIZE, white())) |
| 189 | .on_click(move |event, window, cx| { |
| 190 | cx.stop_propagation(); |
| 191 | if enabled { |
| 192 | on_click(event, window, cx); |
| 193 | } |
| 194 | }) |
| 195 | } |
| 196 | |
| 197 | impl ImageViewer { |
| 198 | pub fn new( |
| 199 | app: Entity<AppState>, |
| 200 | request: ViewerRequest, |
| 201 | window: &mut Window, |
| 202 | cx: &mut Context<Self>, |
| 203 | ) -> Self { |
| 204 | let focus_handle = cx.focus_handle(); |
| 205 | window.focus(&focus_handle, cx); |
| 206 | let observation = cx.observe(&app, |_, _, cx| cx.notify()); |
| 207 | let mut viewer = ImageViewer { |
| 208 | app, |
| 209 | conversation_id: request.conversation_id, |
| 210 | conversation_title: request.conversation_title, |
| 211 | index: request.index.min(request.items.len().saturating_sub(1)), |
| 212 | items: request.items, |
| 213 | scale: None, |
| 214 | pan: (0., 0.), |
| 215 | quarter_turns: 0, |
| 216 | rotated: None, |
| 217 | entered_fullscreen: false, |
| 218 | drag_from: None, |
| 219 | notice: None, |
| 220 | notice_serial: 0, |
| 221 | focus_handle, |
| 222 | _observation: observation, |
| 223 | }; |
| 224 | cx.on_release_in(window, |this, window, _| { |
| 225 | this.release_rotated(window); |
| 226 | if this.entered_fullscreen && window.is_fullscreen() { |
| 227 | window.toggle_fullscreen(); |
| 228 | } |
| 229 | }) |
| 230 | .detach(); |
| 231 | viewer.preload(window, cx); |
| 232 | viewer |
| 233 | } |
| 234 | |
| 235 | pub fn focus_handle(&self) -> FocusHandle { |
| 236 | self.focus_handle.clone() |
| 237 | } |
| 238 | |
| 239 | fn preload(&mut self, window: &Window, cx: &mut Context<Self>) { |
| 240 | let last_index = self.items.len().saturating_sub(1); |
| 241 | let visible = thumbnail_window( |
| 242 | self.index, |
| 243 | self.items.len(), |
| 244 | Self::thumbnail_capacity(window), |
| 245 | ); |
| 246 | let first = visible.start.min(self.index.saturating_sub(1)); |
| 247 | let last = visible |
| 248 | .end |
| 249 | .saturating_sub(1) |
| 250 | .max((self.index + 1).min(last_index)); |
| 251 | let directory = &self.app.read(cx).directory; |
| 252 | let missing: Vec<_> = self |
| 253 | .items |
| 254 | .get(first..=last) |
| 255 | .unwrap_or_default() |
| 256 | .iter() |
| 257 | .map(|item| item.image.clone()) |
| 258 | .filter(|image| directory.image(&image.url).is_none()) |
| 259 | .collect(); |
| 260 | if !missing.is_empty() { |
| 261 | self.app |
| 262 | .update(cx, |state, cx| state.request_images(missing, cx)); |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | fn thumbnail_capacity(window: &Window) -> usize { |
| 267 | let width = f32::from(window.viewport_size().width); |
| 268 | ((width - 2. * SIDE_PADDING) / (THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER + THUMBNAIL_GAP)) |
| 269 | .floor() |
| 270 | .max(1.) as usize |
| 271 | } |
| 272 | |
| 273 | fn release_rotated(&mut self, window: &mut Window) { |
| 274 | if let Some(rotated) = self.rotated.take() { |
| 275 | window.drop_image(rotated.render).ok(); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | fn toggle_fullscreen(&mut self, window: &mut Window) { |
| 280 | self.entered_fullscreen = !window.is_fullscreen(); |
| 281 | window.toggle_fullscreen(); |
| 282 | } |
| 283 | |
| 284 | fn current(&self) -> Option<&GalleryItem> { |
| 285 | self.items.get(self.index) |
| 286 | } |
| 287 | |
| 288 | fn current_failed(&self, cx: &App) -> bool { |
| 289 | self.current() |
| 290 | .is_some_and(|item| self.app.read(cx).directory.image_failed(&item.image.url)) |
| 291 | } |
| 292 | |
| 293 | fn current_path(&self, cx: &App) -> Option<PathBuf> { |
| 294 | let item = self.current()?; |
| 295 | let entry = self.app.read(cx).directory.image(&item.image.url)?; |
| 296 | Some(entry.path.clone()) |
| 297 | } |
| 298 | |
| 299 | fn stage_size(window: &Window) -> Pair { |
| 300 | let viewport = window.viewport_size(); |
| 301 | ( |
| 302 | f32::from(viewport.width).max(1.), |
| 303 | (f32::from(viewport.height) - HEADER_HEIGHT - FOOTER_HEIGHT).max(1.), |
| 304 | ) |
| 305 | } |
| 306 | |
| 307 | fn layout(&self, window: &Window, cx: &App) -> Option<Layout> { |
| 308 | let item = self.current()?; |
| 309 | let entry = self.app.read(cx).directory.image(&item.image.url)?; |
| 310 | let stage = Self::stage_size(window); |
| 311 | let declared = item.image.width.zip(item.image.height); |
| 312 | let source = entry |
| 313 | .size |
| 314 | .or(declared) |
| 315 | .map_or(stage, |(width, height)| (width as f32, height as f32)); |
| 316 | let source = rotated_size(source, self.quarter_turns); |
| 317 | let fit = fit_scale(source, stage); |
| 318 | let scale = self.scale.map_or(fit, |scale| clamp_scale(scale, fit)); |
| 319 | let pan = clamp_pan(self.pan, display_size(source, scale), stage); |
| 320 | Some(Layout { |
| 321 | stage, |
| 322 | source, |
| 323 | fit, |
| 324 | scale, |
| 325 | pan, |
| 326 | }) |
| 327 | } |
| 328 | |
| 329 | fn anchor_of(position: Point<Pixels>, window: &Window) -> Pair { |
| 330 | let stage = Self::stage_size(window); |
| 331 | ( |
| 332 | f32::from(position.x) - stage.0 / 2., |
| 333 | f32::from(position.y) - HEADER_HEIGHT - stage.1 / 2., |
| 334 | ) |
| 335 | } |
| 336 | |
| 337 | fn zoom_to(&mut self, wanted: f32, anchor: Pair, window: &Window, cx: &mut Context<Self>) { |
| 338 | let Some(layout) = self.layout(window, cx) else { |
| 339 | return; |
| 340 | }; |
| 341 | let view = zoom_at( |
| 342 | View { |
| 343 | scale: layout.scale, |
| 344 | pan: layout.pan, |
| 345 | }, |
| 346 | wanted, |
| 347 | anchor, |
| 348 | layout.source, |
| 349 | layout.stage, |
| 350 | ); |
| 351 | self.scale = (view.scale > layout.fit).then_some(view.scale); |
| 352 | self.pan = view.pan; |
| 353 | cx.notify(); |
| 354 | } |
| 355 | |
| 356 | fn zoom_step(&mut self, direction: i32, window: &Window, cx: &mut Context<Self>) { |
| 357 | let Some(layout) = self.layout(window, cx) else { |
| 358 | return; |
| 359 | }; |
| 360 | self.zoom_to(step_scale(layout.scale, direction), (0., 0.), window, cx); |
| 361 | } |
| 362 | |
| 363 | fn zoom_fit(&mut self, cx: &mut Context<Self>) { |
| 364 | self.scale = None; |
| 365 | self.pan = (0., 0.); |
| 366 | cx.notify(); |
| 367 | } |
| 368 | |
| 369 | fn toggle_zoom(&mut self, position: Point<Pixels>, window: &Window, cx: &mut Context<Self>) { |
| 370 | let Some(layout) = self.layout(window, cx) else { |
| 371 | return; |
| 372 | }; |
| 373 | let target = toggle_target(layout.scale, layout.fit); |
| 374 | self.zoom_to(target, Self::anchor_of(position, window), window, cx); |
| 375 | } |
| 376 | |
| 377 | fn on_wheel(&mut self, event: &ScrollWheelEvent, window: &mut Window, cx: &mut Context<Self>) { |
| 378 | let Some(layout) = self.layout(window, cx) else { |
| 379 | return; |
| 380 | }; |
| 381 | let top = f32::from(event.position.y); |
| 382 | if top < HEADER_HEIGHT || top > HEADER_HEIGHT + layout.stage.1 { |
| 383 | return; |
| 384 | } |
| 385 | let delta = event.delta.pixel_delta(px(WHEEL_LINE_HEIGHT)).y.into(); |
| 386 | let anchor = Self::anchor_of(event.position, window); |
| 387 | self.zoom_to(wheel_scale(layout.scale, delta), anchor, window, cx); |
| 388 | cx.stop_propagation(); |
| 389 | } |
| 390 | |
| 391 | fn on_mouse_move( |
| 392 | &mut self, |
| 393 | event: &MouseMoveEvent, |
| 394 | window: &mut Window, |
| 395 | cx: &mut Context<Self>, |
| 396 | ) { |
| 397 | let Some(last) = self.drag_from else { |
| 398 | return; |
| 399 | }; |
| 400 | if event.pressed_button != Some(MouseButton::Left) { |
| 401 | self.drag_from = None; |
| 402 | return; |
| 403 | } |
| 404 | let Some(layout) = self.layout(window, cx) else { |
| 405 | return; |
| 406 | }; |
| 407 | let moved = ( |
| 408 | layout.pan.0 + f32::from(event.position.x - last.x), |
| 409 | layout.pan.1 + f32::from(event.position.y - last.y), |
| 410 | ); |
| 411 | self.pan = clamp_pan( |
| 412 | moved, |
| 413 | display_size(layout.source, layout.scale), |
| 414 | layout.stage, |
| 415 | ); |
| 416 | self.drag_from = Some(event.position); |
| 417 | cx.notify(); |
| 418 | } |
| 419 | |
| 420 | fn end_drag(&mut self, cx: &mut Context<Self>) { |
| 421 | if self.drag_from.take().is_some() { |
| 422 | cx.notify(); |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | fn jump(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) { |
| 427 | if index == self.index || index >= self.items.len() { |
| 428 | return; |
| 429 | } |
| 430 | self.index = index; |
| 431 | self.scale = None; |
| 432 | self.pan = (0., 0.); |
| 433 | self.quarter_turns = 0; |
| 434 | self.release_rotated(window); |
| 435 | self.drag_from = None; |
| 436 | self.preload(window, cx); |
| 437 | cx.notify(); |
| 438 | } |
| 439 | |
| 440 | fn go(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) { |
| 441 | self.jump(step_index(self.index, self.items.len(), delta), window, cx); |
| 442 | } |
| 443 | |
| 444 | fn rotate(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 445 | let (Some(path), Some(item)) = (self.current_path(cx), self.current()) else { |
| 446 | return; |
| 447 | }; |
| 448 | let url = item.image.url.clone(); |
| 449 | self.quarter_turns = next_rotation(self.quarter_turns); |
| 450 | self.scale = None; |
| 451 | self.pan = (0., 0.); |
| 452 | self.release_rotated(window); |
| 453 | let quarter_turns = self.quarter_turns; |
| 454 | if quarter_turns != 0 { |
| 455 | cx.spawn_in(window, async move |this, cx| { |
| 456 | let rotated = cx |
| 457 | .background_spawn(async move { rotated_render(&path, quarter_turns) }) |
| 458 | .await; |
| 459 | this.update_in(cx, |this, window, cx| { |
| 460 | let still_current = this.quarter_turns == quarter_turns |
| 461 | && this.current().is_some_and(|item| item.image.url == url); |
| 462 | if !still_current { |
| 463 | return; |
| 464 | } |
| 465 | match rotated { |
| 466 | Some(render) => { |
| 467 | this.release_rotated(window); |
| 468 | this.rotated = Some(RotatedImage { |
| 469 | url, |
| 470 | quarter_turns, |
| 471 | render: Arc::new(render), |
| 472 | }); |
| 473 | } |
| 474 | None => { |
| 475 | this.quarter_turns = 0; |
| 476 | this.show_notice("Could not rotate", cx); |
| 477 | } |
| 478 | } |
| 479 | cx.notify(); |
| 480 | }) |
| 481 | .ok(); |
| 482 | }) |
| 483 | .detach(); |
| 484 | } |
| 485 | cx.notify(); |
| 486 | } |
| 487 | |
| 488 | fn show_notice(&mut self, text: impl Into<String>, cx: &mut Context<Self>) { |
| 489 | self.notice_serial += 1; |
| 490 | let serial = self.notice_serial; |
| 491 | self.notice = Some(text.into()); |
| 492 | cx.spawn(async move |this, cx| { |
| 493 | cx.background_executor().timer(NOTICE_DURATION).await; |
| 494 | this.update(cx, |this, cx| { |
| 495 | if this.notice_serial == serial { |
| 496 | this.notice = None; |
| 497 | cx.notify(); |
| 498 | } |
| 499 | }) |
| 500 | .ok(); |
| 501 | }) |
| 502 | .detach(); |
| 503 | cx.notify(); |
| 504 | } |
| 505 | |
| 506 | fn rotated_render(&self) -> Option<&Arc<RenderImage>> { |
| 507 | let url = &self.current()?.image.url; |
| 508 | self.rotated |
| 509 | .as_ref() |
| 510 | .filter(|rotated| rotated.url == *url && rotated.quarter_turns == self.quarter_turns) |
| 511 | .map(|rotated| &rotated.render) |
| 512 | } |
| 513 | |
| 514 | fn rotation_pending(&self) -> bool { |
| 515 | self.quarter_turns != 0 && self.rotated_render().is_none() |
| 516 | } |
| 517 | |
| 518 | fn copy_image(&mut self, cx: &mut Context<Self>) { |
| 519 | let Some(path) = self.current_path(cx) else { |
| 520 | return; |
| 521 | }; |
| 522 | if self.rotation_pending() { |
| 523 | self.show_notice("Rotating", cx); |
| 524 | return; |
| 525 | } |
| 526 | let quarter_turns = self.quarter_turns; |
| 527 | cx.spawn(async move |this, cx| { |
| 528 | let fallback = path.clone(); |
| 529 | let item = cx |
| 530 | .background_spawn(async move { clipboard_image(&path, quarter_turns) }) |
| 531 | .await; |
| 532 | this.update(cx, |this, cx| match item { |
| 533 | Some(image) => { |
| 534 | image.write(cx); |
| 535 | this.show_notice("Image copied", cx); |
| 536 | } |
| 537 | None => { |
| 538 | cx.write_to_clipboard(ClipboardItem::new_string( |
| 539 | fallback.display().to_string(), |
| 540 | )); |
| 541 | this.show_notice("Copied file path", cx); |
| 542 | } |
| 543 | }) |
| 544 | .ok(); |
| 545 | }) |
| 546 | .detach(); |
| 547 | } |
| 548 | |
| 549 | fn save_as(&mut self, cx: &mut Context<Self>) { |
| 550 | let Some(source) = self.current_path(cx) else { |
| 551 | return; |
| 552 | }; |
| 553 | if self.rotation_pending() { |
| 554 | self.show_notice("Rotating", cx); |
| 555 | return; |
| 556 | } |
| 557 | let quarter_turns = self.quarter_turns; |
| 558 | cx.spawn(async move |this, cx| { |
| 559 | let name_source = source.clone(); |
| 560 | let name = cx |
| 561 | .background_spawn(async move { suggested_name(&name_source, quarter_turns != 0) }) |
| 562 | .await; |
| 563 | let Ok(receiver) = this.update(cx, |_, cx| { |
| 564 | cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name)) |
| 565 | }) else { |
| 566 | return; |
| 567 | }; |
| 568 | let Ok(Ok(Some(target))) = receiver.await else { |
| 569 | return; |
| 570 | }; |
| 571 | let written = cx |
| 572 | .background_spawn(async move { |
| 573 | write_image(&source, &target, quarter_turns).map(|_| target) |
| 574 | }) |
| 575 | .await; |
| 576 | this.update(cx, |this, cx| match written { |
| 577 | Ok(target) => { |
| 578 | let name = target |
| 579 | .file_name() |
| 580 | .map(|name| name.to_string_lossy().into_owned()) |
| 581 | .unwrap_or_default(); |
| 582 | this.show_notice(format!("Saved {name}"), cx) |
| 583 | } |
| 584 | Err(_) => this.show_notice("Could not save the image", cx), |
| 585 | }) |
| 586 | .ok(); |
| 587 | }) |
| 588 | .detach(); |
| 589 | } |
| 590 | |
| 591 | fn forward(&mut self, cx: &mut Context<Self>) { |
| 592 | let Some(item) = self.current() else { |
| 593 | return; |
| 594 | }; |
| 595 | let message_key = item.message_key.clone(); |
| 596 | if self.app.read(cx).mode.read_only { |
| 597 | self.show_notice("Read-only mode: message not forwarded", cx); |
| 598 | return; |
| 599 | } |
| 600 | let conversation_id = self.conversation_id.clone(); |
| 601 | self.app.update(cx, |state, cx| { |
| 602 | state.request_forward(&conversation_id, &message_key, cx) |
| 603 | }); |
| 604 | } |
| 605 | |
| 606 | fn open_externally(&mut self, cx: &mut Context<Self>) { |
| 607 | if let Some(path) = self.current_path(cx) { |
| 608 | cx.open_with_system(&path); |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) { |
| 613 | let command = event.keystroke.modifiers.secondary(); |
| 614 | match (event.keystroke.key.as_str(), command) { |
| 615 | ("escape", _) => cx.emit(ImageViewerEvent::Close), |
| 616 | ("left", false) => self.go(-1, window, cx), |
| 617 | ("right", false) => self.go(1, window, cx), |
| 618 | ("r", false) => self.rotate(window, cx), |
| 619 | ("f11", _) => self.toggle_fullscreen(window), |
| 620 | ("=" | "+", true) => self.zoom_step(1, window, cx), |
| 621 | ("-", true) => self.zoom_step(-1, window, cx), |
| 622 | ("0", true) => self.zoom_fit(cx), |
| 623 | ("c", true) => self.copy_image(cx), |
| 624 | ("s", true) => self.save_as(cx), |
| 625 | _ => {} |
| 626 | } |
| 627 | cx.stop_propagation(); |
| 628 | } |
| 629 | |
| 630 | fn header(&self, layout: Option<Layout>, cx: &mut Context<Self>) -> Stateful<Div> { |
| 631 | let item = self.current(); |
| 632 | let author = item.map(|item| item.author.clone()).unwrap_or_default(); |
| 633 | let subtitle = item |
| 634 | .map(|item| format!("{} \u{b7} {}", item.time, self.conversation_title)) |
| 635 | .unwrap_or_default(); |
| 636 | let sender_id = item.and_then(|item| item.sender_id.clone()); |
| 637 | let can_zoom_out = layout.is_some_and(|layout| layout.scale > layout.fit); |
| 638 | let can_zoom_in = layout.is_some_and(|layout| layout.scale < MAX_ZOOM); |
| 639 | let zoom_label = layout |
| 640 | .map(|layout| percent_label(layout.scale)) |
| 641 | .unwrap_or_default(); |
| 642 | let loaded = layout.is_some(); |
| 643 | h_flex() |
| 644 | .id("viewer-header") |
| 645 | .absolute() |
| 646 | .top_0() |
| 647 | .left_0() |
| 648 | .w_full() |
| 649 | .h(px(HEADER_HEIGHT)) |
| 650 | .px(px(SIDE_PADDING)) |
| 651 | .gap(px(12.)) |
| 652 | .items_center() |
| 653 | .child( |
| 654 | h_flex() |
| 655 | .flex_1() |
| 656 | .min_w_0() |
| 657 | .gap(px(10.)) |
| 658 | .items_center() |
| 659 | .child(div().size(px(AVATAR_SIZE)).flex_none().child(person_avatar( |
| 660 | &self.app.read(cx).directory, |
| 661 | sender_id.as_deref(), |
| 662 | &author, |
| 663 | AVATAR_SIZE, |
| 664 | ))) |
| 665 | .child( |
| 666 | v_flex() |
| 667 | .flex_1() |
| 668 | .min_w_0() |
| 669 | .child( |
| 670 | div() |
| 671 | .truncate() |
| 672 | .text_size(px(14.)) |
| 673 | .font_weight(FontWeight::SEMIBOLD) |
| 674 | .text_color(white()) |
| 675 | .child(author), |
| 676 | ) |
| 677 | .child( |
| 678 | div() |
| 679 | .truncate() |
| 680 | .text_size(px(12.)) |
| 681 | .text_color(white().opacity(0.6)) |
| 682 | .child(subtitle), |
| 683 | ), |
| 684 | ), |
| 685 | ) |
| 686 | .child( |
| 687 | h_flex() |
| 688 | .flex_none() |
| 689 | .gap(px(2.)) |
| 690 | .items_center() |
| 691 | .child(control_button( |
| 692 | "viewer-zoom-out", |
| 693 | "zoom_out", |
| 694 | "Zoom out (Ctrl -)", |
| 695 | can_zoom_out, |
| 696 | cx.listener(|this, _, window, cx| this.zoom_step(-1, window, cx)), |
| 697 | )) |
| 698 | .child( |
| 699 | div() |
| 700 | .w(px(ZOOM_LABEL_WIDTH)) |
| 701 | .flex_none() |
| 702 | .text_center() |
| 703 | .text_size(px(12.)) |
| 704 | .text_color(white().opacity(0.8)) |
| 705 | .child(zoom_label), |
| 706 | ) |
| 707 | .child(control_button( |
| 708 | "viewer-zoom-in", |
| 709 | "zoom_in", |
| 710 | "Zoom in (Ctrl +)", |
| 711 | can_zoom_in, |
| 712 | cx.listener(|this, _, window, cx| this.zoom_step(1, window, cx)), |
| 713 | )) |
| 714 | .child(control_button( |
| 715 | "viewer-rotate", |
| 716 | "rotate_right", |
| 717 | "Rotate (R)", |
| 718 | loaded, |
| 719 | cx.listener(|this, _, window, cx| this.rotate(window, cx)), |
| 720 | )) |
| 721 | .child(control_button( |
| 722 | "viewer-copy", |
| 723 | "content_copy", |
| 724 | "Copy image (Ctrl C)", |
| 725 | loaded, |
| 726 | cx.listener(|this, _, _, cx| this.copy_image(cx)), |
| 727 | )) |
| 728 | .child(control_button( |
| 729 | "viewer-save", |
| 730 | "download", |
| 731 | "Save as (Ctrl S)", |
| 732 | loaded, |
| 733 | cx.listener(|this, _, _, cx| this.save_as(cx)), |
| 734 | )) |
| 735 | .child(control_button( |
| 736 | "viewer-forward", |
| 737 | "forward", |
| 738 | "Forward", |
| 739 | true, |
| 740 | cx.listener(|this, _, _, cx| this.forward(cx)), |
| 741 | )) |
| 742 | .child(control_button( |
| 743 | "viewer-fullscreen", |
| 744 | "fullscreen", |
| 745 | "Full screen (F11)", |
| 746 | true, |
| 747 | cx.listener(|this, _, window, _| this.toggle_fullscreen(window)), |
| 748 | )) |
| 749 | .child(control_button( |
| 750 | "viewer-open", |
| 751 | "open_in_new", |
| 752 | "Open in Photos", |
| 753 | loaded, |
| 754 | cx.listener(|this, _, _, cx| this.open_externally(cx)), |
| 755 | )) |
| 756 | .child(control_button( |
| 757 | "viewer-close", |
| 758 | "close", |
| 759 | "Close (Esc)", |
| 760 | true, |
| 761 | cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)), |
| 762 | )), |
| 763 | ) |
| 764 | .on_click(|_, _, cx| cx.stop_propagation()) |
| 765 | } |
| 766 | |
| 767 | fn nav_button( |
| 768 | &self, |
| 769 | id: &'static str, |
| 770 | glyph: &'static str, |
| 771 | left: bool, |
| 772 | stage: Pair, |
| 773 | cx: &mut Context<Self>, |
| 774 | delta: isize, |
| 775 | ) -> Stateful<Div> { |
| 776 | let top = ((stage.1 - NAV_SIZE) / 2.).max(0.); |
| 777 | div() |
| 778 | .id(id) |
| 779 | .absolute() |
| 780 | .top(px(top)) |
| 781 | .when(left, |button| button.left(px(NAV_MARGIN))) |
| 782 | .when(!left, |button| button.right(px(NAV_MARGIN))) |
| 783 | .size(px(NAV_SIZE)) |
| 784 | .flex() |
| 785 | .items_center() |
| 786 | .justify_center() |
| 787 | .rounded_full() |
| 788 | .bg(white().opacity(0.1)) |
| 789 | .cursor_pointer() |
| 790 | .hover(|button| button.bg(white().opacity(0.2))) |
| 791 | .child(symbol(glyph, NAV_ICON_SIZE, white())) |
| 792 | .on_click(cx.listener(move |this, _, window, cx| { |
| 793 | cx.stop_propagation(); |
| 794 | this.go(delta, window, cx); |
| 795 | })) |
| 796 | } |
| 797 | |
| 798 | fn picture(&self, layout: Layout, cx: &mut Context<Self>) -> AnyElement { |
| 799 | let display = display_size(layout.source, layout.scale); |
| 800 | let origin = image_origin(display, layout.stage, layout.pan); |
| 801 | let Some(item) = self.current() else { |
| 802 | return div().into_any_element(); |
| 803 | }; |
| 804 | let source: Option<ImageSource> = if self.quarter_turns == 0 { |
| 805 | self.app |
| 806 | .read(cx) |
| 807 | .directory |
| 808 | .image(&item.image.url) |
| 809 | .map(|entry| entry.path.clone().into()) |
| 810 | } else { |
| 811 | self.rotated_render() |
| 812 | .map(|render| ImageSource::Render(render.clone())) |
| 813 | }; |
| 814 | let Some(source) = source else { |
| 815 | return loading_placeholder(); |
| 816 | }; |
| 817 | div() |
| 818 | .id("viewer-picture") |
| 819 | .absolute() |
| 820 | .left(px(origin.0)) |
| 821 | .top(px(origin.1)) |
| 822 | .w(px(display.0)) |
| 823 | .h(px(display.1)) |
| 824 | .child(img(bounded(source)).size_full().object_fit(ObjectFit::Fill)) |
| 825 | .on_mouse_down( |
| 826 | MouseButton::Left, |
| 827 | cx.listener(|this, event: &MouseDownEvent, _, cx| { |
| 828 | cx.stop_propagation(); |
| 829 | this.drag_from = Some(event.position); |
| 830 | }), |
| 831 | ) |
| 832 | .on_click(cx.listener(|this, event: &ClickEvent, window, cx| { |
| 833 | cx.stop_propagation(); |
| 834 | if event.click_count() == 2 { |
| 835 | this.toggle_zoom(event.position(), window, cx); |
| 836 | } |
| 837 | })) |
| 838 | .into_any_element() |
| 839 | } |
| 840 | |
| 841 | fn thumbnail(&self, index: usize, cx: &mut Context<Self>) -> Stateful<Div> { |
| 842 | let item = &self.items[index]; |
| 843 | let current = index == self.index; |
| 844 | let path = self |
| 845 | .app |
| 846 | .read(cx) |
| 847 | .directory |
| 848 | .image(&item.image.url) |
| 849 | .map(|entry| entry.path.clone()); |
| 850 | div() |
| 851 | .id(ElementId::Name(format!("viewer-thumbnail-{index}").into())) |
| 852 | .size(px(THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER)) |
| 853 | .flex_none() |
| 854 | .flex() |
| 855 | .items_center() |
| 856 | .justify_center() |
| 857 | .rounded(px(THUMBNAIL_RADIUS + THUMBNAIL_BORDER)) |
| 858 | .border_2() |
| 859 | .border_color(if current { |
| 860 | theme::accent() |
| 861 | } else { |
| 862 | transparent_black() |
| 863 | }) |
| 864 | .cursor_pointer() |
| 865 | .child( |
| 866 | div() |
| 867 | .size(px(THUMBNAIL_SIZE)) |
| 868 | .flex_none() |
| 869 | .flex() |
| 870 | .items_center() |
| 871 | .justify_center() |
| 872 | .overflow_hidden() |
| 873 | .rounded(px(THUMBNAIL_RADIUS)) |
| 874 | .bg(white().opacity(0.08)) |
| 875 | .when(!current, |frame| frame.opacity(0.7)) |
| 876 | .map(|frame| match path { |
| 877 | Some(path) => { |
| 878 | frame.child(img(preview(path)).size_full().object_fit(ObjectFit::Cover)) |
| 879 | } |
| 880 | None => frame.child(symbol("image", 18., white().opacity(0.5))), |
| 881 | }), |
| 882 | ) |
| 883 | .on_click(cx.listener(move |this, _, window, cx| { |
| 884 | cx.stop_propagation(); |
| 885 | this.jump(index, window, cx); |
| 886 | })) |
| 887 | } |
| 888 | |
| 889 | fn footer(&self, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> { |
| 890 | let width = f32::from(window.viewport_size().width); |
| 891 | let range = thumbnail_window( |
| 892 | self.index, |
| 893 | self.items.len(), |
| 894 | Self::thumbnail_capacity(window), |
| 895 | ); |
| 896 | let caption = self |
| 897 | .current() |
| 898 | .map(|item| item.caption.clone()) |
| 899 | .unwrap_or_default(); |
| 900 | let status = self |
| 901 | .notice |
| 902 | .clone() |
| 903 | .unwrap_or_else(|| counter_label(self.index, self.items.len())); |
| 904 | v_flex() |
| 905 | .id("viewer-footer") |
| 906 | .absolute() |
| 907 | .bottom_0() |
| 908 | .left_0() |
| 909 | .w_full() |
| 910 | .h(px(FOOTER_HEIGHT)) |
| 911 | .pb(px(12.)) |
| 912 | .gap(px(4.)) |
| 913 | .items_center() |
| 914 | .justify_end() |
| 915 | .child( |
| 916 | div() |
| 917 | .w(px((width - 2. * SIDE_PADDING).clamp(0., CAPTION_MAX_WIDTH))) |
| 918 | .h(px(CAPTION_HEIGHT)) |
| 919 | .flex_none() |
| 920 | .truncate() |
| 921 | .text_center() |
| 922 | .text_size(px(13.)) |
| 923 | .text_color(white().opacity(0.9)) |
| 924 | .child(caption), |
| 925 | ) |
| 926 | .child( |
| 927 | div() |
| 928 | .h(px(STATUS_HEIGHT)) |
| 929 | .flex_none() |
| 930 | .text_size(px(12.)) |
| 931 | .text_color(white().opacity(0.6)) |
| 932 | .child(status), |
| 933 | ) |
| 934 | .child( |
| 935 | h_flex() |
| 936 | .h(px(STRIP_HEIGHT)) |
| 937 | .flex_none() |
| 938 | .gap(px(THUMBNAIL_GAP)) |
| 939 | .items_center() |
| 940 | .children(range.map(|index| self.thumbnail(index, cx))), |
| 941 | ) |
| 942 | .on_click(|_, _, cx| cx.stop_propagation()) |
| 943 | } |
| 944 | } |
| 945 | |
| 946 | fn status_placeholder(text: &'static str) -> AnyElement { |
| 947 | v_flex() |
| 948 | .size_full() |
| 949 | .gap(px(6.)) |
| 950 | .items_center() |
| 951 | .justify_center() |
| 952 | .child(symbol("image", 28., white().opacity(0.5))) |
| 953 | .child( |
| 954 | div() |
| 955 | .text_size(px(12.)) |
| 956 | .text_color(white().opacity(0.6)) |
| 957 | .child(text), |
| 958 | ) |
| 959 | .into_any_element() |
| 960 | } |
| 961 | |
| 962 | fn loading_placeholder() -> AnyElement { |
| 963 | status_placeholder("Loading image") |
| 964 | } |
| 965 | |
| 966 | impl Render for ImageViewer { |
| 967 | fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 968 | let layout = self.layout(window, cx); |
| 969 | let stage = Self::stage_size(window); |
| 970 | let has_previous = self.index > 0; |
| 971 | let has_next = self.index + 1 < self.items.len(); |
| 972 | let picture = match layout { |
| 973 | Some(layout) => self.picture(layout, cx), |
| 974 | None if self.current_failed(cx) => status_placeholder("Image unavailable"), |
| 975 | None => loading_placeholder(), |
| 976 | }; |
| 977 | let header = self.header(layout, cx); |
| 978 | let footer = self.footer(window, cx); |
| 979 | div() |
| 980 | .id("image-viewer") |
| 981 | .key_context("ImageViewer") |
| 982 | .track_focus(&self.focus_handle) |
| 983 | .absolute() |
| 984 | .top_0() |
| 985 | .left_0() |
| 986 | .size_full() |
| 987 | .bg(rgba(BACKDROP)) |
| 988 | .occlude() |
| 989 | .on_key_down(cx.listener(Self::on_key_down)) |
| 990 | .on_action(cx.listener(|this, _: &ZoomIn, window, cx| this.zoom_step(1, window, cx))) |
| 991 | .on_action(cx.listener(|this, _: &ZoomOut, window, cx| this.zoom_step(-1, window, cx))) |
| 992 | .on_action(cx.listener(|this, _: &ZoomReset, _, cx| this.zoom_fit(cx))) |
| 993 | .on_scroll_wheel(cx.listener(Self::on_wheel)) |
| 994 | .on_mouse_move(cx.listener(Self::on_mouse_move)) |
| 995 | .on_mouse_up( |
| 996 | MouseButton::Left, |
| 997 | cx.listener(|this, _, _, cx| this.end_drag(cx)), |
| 998 | ) |
| 999 | .on_mouse_up_out( |
| 1000 | MouseButton::Left, |
| 1001 | cx.listener(|this, _, _, cx| this.end_drag(cx)), |
| 1002 | ) |
| 1003 | .on_click(cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close))) |
| 1004 | .child( |
| 1005 | div() |
| 1006 | .absolute() |
| 1007 | .top(px(HEADER_HEIGHT)) |
| 1008 | .left_0() |
| 1009 | .w(px(stage.0)) |
| 1010 | .h(px(stage.1)) |
| 1011 | .overflow_hidden() |
| 1012 | .child(picture) |
| 1013 | .when(has_previous, |stage_element| { |
| 1014 | stage_element.child(self.nav_button( |
| 1015 | "viewer-previous", |
| 1016 | "chevron_left", |
| 1017 | true, |
| 1018 | stage, |
| 1019 | cx, |
| 1020 | -1, |
| 1021 | )) |
| 1022 | }) |
| 1023 | .when(has_next, |stage_element| { |
| 1024 | stage_element.child(self.nav_button( |
| 1025 | "viewer-next", |
| 1026 | "chevron_right", |
| 1027 | false, |
| 1028 | stage, |
| 1029 | cx, |
| 1030 | 1, |
| 1031 | )) |
| 1032 | }), |
| 1033 | ) |
| 1034 | .child(header) |
| 1035 | .child(footer) |
| 1036 | } |
| 1037 | } |