Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add recent items submenu to tray and improve image handling

Richie McIlroy13986b5c2c97
diff --git a/apps/desktop/src-tauri/src/screenshot_editor.rs b/apps/desktop/src-tauri/src/screenshot_editor.rs
index ad23e0ebd..e52510b7d 100644
--- a/apps/desktop/src-tauri/src/screenshot_editor.rs
+++ b/apps/desktop/src-tauri/src/screenshot_editor.rs
@@ -141,8 +141,31 @@ impl ScreenshotEditorInstances {
let rgba_img: image::RgbaImage = rgb_img.convert();
(rgba_img.into_raw(), width, height)
} else {
- let img =
- image::open(&path).map_err(|e| format!("Failed to open image: {e}"))?;
+ let image_path = if path.is_dir() {
+ let original = path.join("original.png");
+ if original.exists() {
+ original
+ } else {
+ std::fs::read_dir(&path)
+ .ok()
+ .and_then(|dir| {
+ dir.flatten()
+ .find(|e| {
+ e.path().extension().and_then(|s| s.to_str())
+ == Some("png")
+ })
+ .map(|e| e.path())
+ })
+ .ok_or_else(|| {
+ format!("No PNG file found in directory: {:?}", path)
+ })?
+ }
+ } else {
+ path.clone()
+ };
+
+ let img = image::open(&image_path)
+ .map_err(|e| format!("Failed to open image: {e}"))?;
let (w, h) = img.dimensions();
if w > MAX_DIMENSION || h > MAX_DIMENSION {
@@ -157,15 +180,22 @@ impl ScreenshotEditorInstances {
}
};
- // Try to load existing meta if in a .cap directory
- let (recording_meta, loaded_config) = if let Some(parent) = path.parent() {
+ let cap_dir = if path.extension().and_then(|s| s.to_str()) == Some("cap") {
+ Some(path.clone())
+ } else if let Some(parent) = path.parent() {
if parent.extension().and_then(|s| s.to_str()) == Some("cap") {
- let meta = RecordingMeta::load_for_project(parent).ok();
- let config = ProjectConfiguration::load(parent).ok();
- (meta, config)
+ Some(parent.to_path_buf())
} else {
- (None, None)
+ None
}
+ } else {
+ None
+ };
+
+ let (recording_meta, loaded_config) = if let Some(cap_dir) = &cap_dir {
+ let meta = RecordingMeta::load_for_project(cap_dir).ok();
+ let config = ProjectConfiguration::load(cap_dir).ok();
+ (meta, config)
} else {
(None, None)
};
diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs
index c7268e5bb..a9347fb3d 100644
--- a/apps/desktop/src-tauri/src/tray.rs
+++ b/apps/desktop/src-tauri/src/tray.rs
@@ -1,14 +1,17 @@
use crate::{
- RecordingStarted, RecordingStopped, RequestOpenRecordingPicker, RequestOpenSettings, recording,
+ NewScreenshotAdded, NewStudioRecordingAdded, RecordingStarted, RecordingStopped,
+ RequestOpenRecordingPicker, RequestOpenSettings, recording,
recording_settings::RecordingTargetMode, windows::ShowCapWindow,
};
-use std::sync::{
- Arc,
- atomic::{AtomicBool, Ordering},
+use cap_project::{RecordingMeta, RecordingMetaInner};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::{
+ path::PathBuf,
+ sync::{Arc, Mutex},
};
use tauri::Manager;
-use tauri::menu::{MenuId, PredefinedMenuItem};
+use tauri::menu::{IconMenuItem, MenuId, PredefinedMenuItem, Submenu};
use tauri::{
AppHandle,
image::Image,
@@ -16,18 +19,26 @@ use tauri::{
tray::TrayIconBuilder,
};
use tauri_plugin_dialog::DialogExt;
+use tauri_plugin_opener::OpenerExt;
use tauri_specta::Event;
+const PREVIOUS_ITEM_PREFIX: &str = "previous_item_";
+const MAX_PREVIOUS_ITEMS: usize = 6;
+const MAX_TITLE_LENGTH: usize = 30;
+const THUMBNAIL_SIZE: u32 = 32;
+
+#[derive(Debug)]
pub enum TrayItem {
OpenCap,
RecordDisplay,
RecordWindow,
RecordArea,
- PreviousRecordings,
- PreviousScreenshots,
+ ViewAllRecordings,
+ ViewAllScreenshots,
OpenSettings,
UploadLogs,
Quit,
+ PreviousItem(String),
}
impl From<TrayItem> for MenuId {
@@ -37,11 +48,14 @@ impl From<TrayItem> for MenuId {
TrayItem::RecordDisplay => "record_display",
TrayItem::RecordWindow => "record_window",
TrayItem::RecordArea => "record_area",
- TrayItem::PreviousRecordings => "previous_recordings",
- TrayItem::PreviousScreenshots => "previous_screenshots",
+ TrayItem::ViewAllRecordings => "view_all_recordings",
+ TrayItem::ViewAllScreenshots => "view_all_screenshots",
TrayItem::OpenSettings => "open_settings",
TrayItem::UploadLogs => "upload_logs",
TrayItem::Quit => "quit",
+ TrayItem::PreviousItem(id) => {
+ return format!("{PREVIOUS_ITEM_PREFIX}{id}").into();
+ }
}
.into()
}
@@ -51,13 +65,19 @@ impl TryFrom<MenuId> for TrayItem {
type Error = String;
fn try_from(value: MenuId) -> Result<Self, Self::Error> {
- match value.0.as_str() {
+ let id_str = value.0.as_str();
+
+ if let Some(path) = id_str.strip_prefix(PREVIOUS_ITEM_PREFIX) {
+ return Ok(TrayItem::PreviousItem(path.to_string()));
+ }
+
+ match id_str {
"open_cap" => Ok(TrayItem::OpenCap),
"record_display" => Ok(TrayItem::RecordDisplay),
"record_window" => Ok(TrayItem::RecordWindow),
"record_area" => Ok(TrayItem::RecordArea),
- "previous_recordings" => Ok(TrayItem::PreviousRecordings),
- "previous_screenshots" => Ok(TrayItem::PreviousScreenshots),
+ "view_all_recordings" => Ok(TrayItem::ViewAllRecordings),
+ "view_all_screenshots" => Ok(TrayItem::ViewAllScreenshots),
"open_settings" => Ok(TrayItem::OpenSettings),
"upload_logs" => Ok(TrayItem::UploadLogs),
"quit" => Ok(TrayItem::Quit),
@@ -66,8 +86,224 @@ impl TryFrom<MenuId> for TrayItem {
}
}
-pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {
- let menu = Menu::with_items(
+#[derive(Debug, Clone)]
+enum PreviousItemType {
+ StudioRecording,
+ InstantRecording { link: Option<String> },
+ Screenshot,
+}
+
+#[derive(Clone)]
+struct CachedPreviousItem {
+ path: PathBuf,
+ pretty_name: String,
+ thumbnail: Option<Vec<u8>>,
+ thumbnail_width: u32,
+ thumbnail_height: u32,
+ item_type: PreviousItemType,
+ created_at: std::time::SystemTime,
+}
+
+struct PreviousItemsCache {
+ items: Vec<CachedPreviousItem>,
+}
+
+impl Default for PreviousItemsCache {
+ fn default() -> Self {
+ Self { items: Vec::new() }
+ }
+}
+
+fn recordings_path(app: &AppHandle) -> PathBuf {
+ let path = app.path().app_data_dir().unwrap().join("recordings");
+ std::fs::create_dir_all(&path).unwrap_or_default();
+ path
+}
+
+fn screenshots_path(app: &AppHandle) -> PathBuf {
+ let path = app.path().app_data_dir().unwrap().join("screenshots");
+ std::fs::create_dir_all(&path).unwrap_or_default();
+ path
+}
+
+fn truncate_title(title: &str) -> String {
+ if title.len() <= MAX_TITLE_LENGTH {
+ title.to_string()
+ } else {
+ format!("{}…", &title[..MAX_TITLE_LENGTH - 1])
+ }
+}
+
+fn load_thumbnail_data(path: &PathBuf) -> Option<(Vec<u8>, u32, u32)> {
+ use image::imageops::FilterType;
+ use image::{GenericImageView, RgbaImage};
+
+ let image_data = std::fs::read(path).ok()?;
+ let img = image::load_from_memory(&image_data).ok()?;
+
+ let (orig_w, orig_h) = img.dimensions();
+ let size = THUMBNAIL_SIZE;
+
+ let scale = (size as f32 / orig_w as f32).max(size as f32 / orig_h as f32);
+ let scaled_w = (orig_w as f32 * scale).round() as u32;
+ let scaled_h = (orig_h as f32 * scale).round() as u32;
+
+ let scaled = img.resize_exact(scaled_w, scaled_h, FilterType::Triangle);
+
+ let x_offset = (scaled_w.saturating_sub(size)) / 2;
+ let y_offset = (scaled_h.saturating_sub(size)) / 2;
+
+ let mut result = RgbaImage::new(size, size);
+ for y in 0..size {
+ for x in 0..size {
+ let src_x = x + x_offset;
+ let src_y = y + y_offset;
+ if src_x < scaled_w && src_y < scaled_h {
+ result.put_pixel(x, y, scaled.get_pixel(src_x, src_y));
+ }
+ }
+ }
+
+ Some((result.into_raw(), size, size))
+}
+
+fn load_single_item(
+ path: &PathBuf,
+ screenshots_dir: &PathBuf,
+ load_thumbnail: bool,
+) -> Option<CachedPreviousItem> {
+ if !path.is_dir() {
+ return None;
+ }
+
+ let meta = RecordingMeta::load_for_project(path).ok()?;
+ let created_at = path
+ .metadata()
+ .and_then(|m| m.created())
+ .unwrap_or(std::time::SystemTime::UNIX_EPOCH);
+
+ let is_screenshot = path.extension().and_then(|s| s.to_str()) == Some("cap")
+ && path.parent().map(|p| p == screenshots_dir).unwrap_or(false);
+
+ let (thumbnail_path, item_type) = if is_screenshot {
+ let png_path = std::fs::read_dir(path).ok().and_then(|dir| {
+ dir.flatten()
+ .find(|e| e.path().extension().and_then(|s| s.to_str()) == Some("png"))
+ .map(|e| e.path())
+ });
+ (png_path, PreviousItemType::Screenshot)
+ } else {
+ let thumb = path.join("screenshots/display.jpg");
+ let thumb_path = if thumb.exists() { Some(thumb) } else { None };
+ let item_type = match &meta.inner {
+ RecordingMetaInner::Studio(_) => PreviousItemType::StudioRecording,
+ RecordingMetaInner::Instant(_) => PreviousItemType::InstantRecording {
+ link: meta.sharing.as_ref().map(|s| s.link.clone()),
+ },
+ };
+ (thumb_path, item_type)
+ };
+
+ let (thumbnail, thumbnail_width, thumbnail_height) = if load_thumbnail {
+ thumbnail_path
+ .as_ref()
+ .and_then(load_thumbnail_data)
+ .map(|(data, w, h)| (Some(data), w, h))
+ .unwrap_or((None, 0, 0))
+ } else {
+ (None, 0, 0)
+ };
+
+ Some(CachedPreviousItem {
+ path: path.clone(),
+ pretty_name: meta.pretty_name,
+ thumbnail,
+ thumbnail_width,
+ thumbnail_height,
+ item_type,
+ created_at,
+ })
+}
+
+fn load_all_previous_items(app: &AppHandle, load_thumbnails: bool) -> Vec<CachedPreviousItem> {
+ let mut items = Vec::new();
+ let screenshots_dir = screenshots_path(app);
+
+ let recordings_dir = recordings_path(app);
+ if recordings_dir.exists() {
+ if let Ok(entries) = std::fs::read_dir(&recordings_dir) {
+ for entry in entries.flatten() {
+ if let Some(item) =
+ load_single_item(&entry.path(), &screenshots_dir, load_thumbnails)
+ {
+ items.push(item);
+ }
+ }
+ }
+ }
+
+ if screenshots_dir.exists() {
+ if let Ok(entries) = std::fs::read_dir(&screenshots_dir) {
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.extension().and_then(|s| s.to_str()) == Some("cap") {
+ if let Some(item) = load_single_item(&path, &screenshots_dir, load_thumbnails) {
+ items.push(item);
+ }
+ }
+ }
+ }
+ }
+
+ items.sort_by(|a, b| b.created_at.cmp(&a.created_at));
+ items.truncate(MAX_PREVIOUS_ITEMS);
+ items
+}
+
+fn create_previous_submenu(
+ app: &AppHandle,
+ cache: &PreviousItemsCache,
+) -> tauri::Result<Submenu<tauri::Wry>> {
+ if cache.items.is_empty() {
+ let submenu = Submenu::with_id(app, "previous", "Previous", false)?;
+ submenu.append(&MenuItem::with_id(
+ app,
+ "previous_empty",
+ "No recent items",
+ false,
+ None::<&str>,
+ )?)?;
+ return Ok(submenu);
+ }
+
+ let submenu = Submenu::with_id(app, "previous", "Previous", true)?;
+
+ for item in &cache.items {
+ let id = TrayItem::PreviousItem(item.path.to_string_lossy().to_string());
+ let title = truncate_title(&item.pretty_name);
+
+ let type_indicator = match &item.item_type {
+ PreviousItemType::StudioRecording => "🎬 ",
+ PreviousItemType::InstantRecording { .. } => "⚡ ",
+ PreviousItemType::Screenshot => "📷 ",
+ };
+ let display_title = format!("{type_indicator}{title}");
+
+ let icon = item.thumbnail.as_ref().map(|data| {
+ Image::new_owned(data.clone(), item.thumbnail_width, item.thumbnail_height)
+ });
+
+ let menu_item = IconMenuItem::with_id(app, id, display_title, true, icon, None::<&str>)?;
+ submenu.append(&menu_item)?;
+ }
+
+ Ok(submenu)
+}
+
+fn build_tray_menu(app: &AppHandle, cache: &PreviousItemsCache) -> tauri::Result<Menu<tauri::Wry>> {
+ let previous_submenu = create_previous_submenu(app, cache)?;
+
+ Menu::with_items(
app,
&[
&MenuItem::with_id(
@@ -93,17 +329,19 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {
)?,
&MenuItem::with_id(app, TrayItem::RecordArea, "Record Area", true, None::<&str>)?,
&PredefinedMenuItem::separator(app)?,
- // &MenuItem::with_id(
- // app,
- // TrayItem::TakeScreenshot,
- // "Take Screenshot",
- // true,
- // None::<&str>,
- // )?,
+ &previous_submenu,
+ &PredefinedMenuItem::separator(app)?,
&MenuItem::with_id(
app,
- TrayItem::PreviousRecordings,
- "Previous Recordings",
+ TrayItem::ViewAllRecordings,
+ "View all recordings",
+ true,
+ None::<&str>,
+ )?,
+ &MenuItem::with_id(
+ app,
+ TrayItem::ViewAllScreenshots,
+ "View all screenshots",
true,
None::<&str>,
)?,
@@ -119,9 +357,103 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {
)?,
&MenuItem::with_id(app, TrayItem::Quit, "Quit Cap", true, None::<&str>)?,
],
- )?;
+ )
+}
+
+fn add_new_item_to_cache(cache: &Arc<Mutex<PreviousItemsCache>>, app: &AppHandle, path: PathBuf) {
+ let screenshots_dir = screenshots_path(app);
+
+ let Some(new_item) = load_single_item(&path, &screenshots_dir, true) else {
+ return;
+ };
+
+ let mut cache_guard = cache.lock().unwrap();
+
+ cache_guard.items.retain(|item| item.path != path);
+
+ cache_guard.items.insert(0, new_item);
+
+ cache_guard.items.truncate(MAX_PREVIOUS_ITEMS);
+}
+
+fn refresh_tray_menu(app: &AppHandle, cache: &Arc<Mutex<PreviousItemsCache>>) {
+ let app_clone = app.clone();
+ let cache_clone = cache.clone();
+
+ let _ = app.run_on_main_thread(move || {
+ let Some(tray) = app_clone.tray_by_id("tray") else {
+ return;
+ };
+
+ let cache_guard = cache_clone.lock().unwrap();
+ if let Ok(menu) = build_tray_menu(&app_clone, &cache_guard) {
+ let _ = tray.set_menu(Some(menu));
+ }
+ });
+}
+
+fn handle_previous_item_click(app: &AppHandle, path_str: &str) {
+ let path = PathBuf::from(path_str);
+
+ let screenshots_dir = screenshots_path(app);
+ let is_screenshot = path.extension().and_then(|s| s.to_str()) == Some("cap")
+ && path.parent().map(|p| p == screenshots_dir).unwrap_or(false);
+
+ if is_screenshot {
+ let app = app.clone();
+ let screenshot_path = path;
+ tokio::spawn(async move {
+ let _ = ShowCapWindow::ScreenshotEditor {
+ path: screenshot_path,
+ }
+ .show(&app)
+ .await;
+ });
+ return;
+ }
+
+ let meta = match RecordingMeta::load_for_project(&path) {
+ Ok(m) => m,
+ Err(e) => {
+ tracing::error!("Failed to load recording meta for previous item: {e}");
+ return;
+ }
+ };
+
+ match &meta.inner {
+ RecordingMetaInner::Studio(_) => {
+ let app = app.clone();
+ let project_path = path.clone();
+ tokio::spawn(async move {
+ let _ = ShowCapWindow::Editor { project_path }.show(&app).await;
+ });
+ }
+ RecordingMetaInner::Instant(_) => {
+ if let Some(sharing) = &meta.sharing {
+ let _ = app.opener().open_url(&sharing.link, None::<String>);
+ } else {
+ let mp4_path = path.join("content/output.mp4");
+ if mp4_path.exists() {
+ let _ = app
+ .opener()
+ .open_path(mp4_path.to_str().unwrap_or_default(), None::<String>);
+ }
+ }
+ }
+ }
+}
+
+pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {
+ let items = load_all_previous_items(app, false);
+ let cache = Arc::new(Mutex::new(PreviousItemsCache { items }));
+
+ let menu = {
+ let cache_guard = cache.lock().unwrap();
+ build_tray_menu(app, &cache_guard)?
+ };
let app = app.clone();
let is_recording = Arc::new(AtomicBool::new(false));
+
let _ = TrayIconBuilder::with_id("tray")
.icon(Image::from_bytes(include_bytes!(
"../icons/tray-default-icon.png"
@@ -159,13 +491,13 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {
}
.emit(&app_handle);
}
- Ok(TrayItem::PreviousRecordings) => {
+ Ok(TrayItem::ViewAllRecordings) => {
let _ = RequestOpenSettings {
page: "recordings".to_string(),
}
.emit(&app_handle);
}
- Ok(TrayItem::PreviousScreenshots) => {
+ Ok(TrayItem::ViewAllScreenshots) => {
let _ = RequestOpenSettings {
page: "screenshots".to_string(),
}
@@ -197,6 +529,9 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {
Ok(TrayItem::Quit) => {
app.exit(0);
}
+ Ok(TrayItem::PreviousItem(path)) => {
+ handle_previous_item_click(app, &path);
+ }
_ => {}
}
})
@@ -218,6 +553,49 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {
})
.build(&app);
+ {
+ let app_clone = app.clone();
+ let cache_clone = cache.clone();
+ std::thread::spawn(move || {
+ let screenshots_dir = screenshots_path(&app_clone);
+ let items_needing_thumbnails: Vec<PathBuf> = {
+ let cache_guard = cache_clone.lock().unwrap();
+ cache_guard
+ .items
+ .iter()
+ .filter(|item| item.thumbnail.is_none())
+ .map(|item| item.path.clone())
+ .collect()
+ };
+
+ if items_needing_thumbnails.is_empty() {
+ return;
+ }
+
+ for path in items_needing_thumbnails {
+ if let Some(updated_item) = load_single_item(&path, &screenshots_dir, true) {
+ let mut cache_guard = cache_clone.lock().unwrap();
+ if let Some(existing) = cache_guard.items.iter_mut().find(|i| i.path == path) {
+ existing.thumbnail = updated_item.thumbnail;
+ existing.thumbnail_width = updated_item.thumbnail_width;
+ existing.thumbnail_height = updated_item.thumbnail_height;
+ }
+ }
+ }
+
+ let app_for_refresh = app_clone.clone();
+ let cache_for_refresh = cache_clone.clone();
+ let _ = app_clone.run_on_main_thread(move || {
+ if let Some(tray) = app_for_refresh.tray_by_id("tray") {
+ let cache_guard = cache_for_refresh.lock().unwrap();
+ if let Ok(menu) = build_tray_menu(&app_for_refresh, &cache_guard) {
+ let _ = tray.set_menu(Some(menu));
+ }
+ }
+ });
+ });
+ }
+
RecordingStarted::listen_any(&app, {
let app = app.clone();
let is_recording = is_recording.clone();
@@ -248,5 +626,31 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {
}
});
+ NewStudioRecordingAdded::listen_any(&app, {
+ let app_handle = app.clone();
+ let cache_clone = cache.clone();
+ move |event| {
+ add_new_item_to_cache(&cache_clone, &app_handle, event.payload.path.clone());
+ refresh_tray_menu(&app_handle, &cache_clone);
+ }
+ });
+
+ NewScreenshotAdded::listen_any(&app, {
+ let app_handle = app.clone();
+ let cache_clone = cache.clone();
+ move |event| {
+ let path = if event.payload.path.extension().and_then(|s| s.to_str()) == Some("png") {
+ event.payload.path.parent().map(|p| p.to_path_buf())
+ } else {
+ Some(event.payload.path.clone())
+ };
+
+ if let Some(path) = path {
+ add_new_item_to_cache(&cache_clone, &app_handle, path);
+ refresh_tray_menu(&app_handle, &cache_clone);
+ }
+ }
+ });
+
Ok(())
}