Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: multiple screen selection (#118)

Swaroop1ac5ee485e18
diff --git a/Cargo.lock b/Cargo.lock
index 8124b5f5d..26746b63d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -739,6 +739,9 @@ dependencies = [
"indexmap 2.5.0",
"nokhwa",
"nokhwa-bindings-macos",
+ "objc",
+ "objc-foundation",
+ "objc2-foundation",
"scap 0.0.5 (git+https://github.com/filleduchaos/scap?rev=8eb00ce1b9bcf)",
"serde",
"specta",
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index c5dad46f9..1becb8df3 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -15,6 +15,7 @@ mod upload;
mod web_api;
mod windows;
+use cap_media::sources::CaptureScreen;
use audio::AppSounds;
use auth::AuthStore;
use cap_editor::{AudioData, EditorState, ProjectRecordings};
@@ -35,7 +36,7 @@ use image::{ImageBuffer, Rgba};
use mp4::Mp4Reader;
use num_traits::ToBytes;
use png::{ColorType, Encoder};
-use recording::{list_cameras, list_capture_windows, InProgressRecording, FPS};
+use recording::{list_cameras, list_capture_windows, list_capture_screens, InProgressRecording, FPS};
use scap::capturer::Capturer;
use scap::frame::Frame;
use serde::{Deserialize, Serialize};
@@ -2251,6 +2252,7 @@ pub async fn run() {
take_screenshot,
list_cameras,
list_capture_windows,
+ list_capture_screens,
list_audio_devices,
show_previous_recordings_window,
close_previous_recordings_window,
@@ -2372,7 +2374,7 @@ pub async fn run() {
camera_ws_port,
camera_feed: None,
start_recording_options: RecordingOptions {
- capture_target: ScreenCaptureTarget::Screen,
+ capture_target: ScreenCaptureTarget::Screen(CaptureScreen { id: 1, name: "Default".to_string() }),
camera_label: None,
audio_input_name: None,
},
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index af4ac383d..4c7ab84f3 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -16,6 +16,12 @@ use crate::RecordingOptions;
// TODO: Hacky, please fix
pub const FPS: u32 = 30;
+#[tauri::command(async)]
+#[specta::specta]
+pub fn list_capture_screens() -> Vec<CaptureScreen> {
+ ScreenCaptureSource::list_screens()
+}
+
#[tauri::command(async)]
#[specta::specta]
pub fn list_capture_windows() -> Vec<CaptureWindow> {
@@ -173,7 +179,8 @@ pub async fn start(
let mut audio_output_path = None;
let mut camera_output_path = None;
- let screen_source = ScreenCaptureSource::init(&recording_options.capture_target, None, None);
+ let screen_source =
+ ScreenCaptureSource::init(dbg!(&recording_options.capture_target), None, None);
let screen_config = screen_source.info();
let output_config = screen_config.scaled(1920, 30);
let screen_filter = VideoFilter::init("screen", screen_config, output_config)?;
diff --git a/apps/desktop/src-tauri/src/web_api.rs b/apps/desktop/src-tauri/src/web_api.rs
index d2e6055a6..2a83fdec8 100644
--- a/apps/desktop/src-tauri/src/web_api.rs
+++ b/apps/desktop/src-tauri/src/web_api.rs
@@ -5,7 +5,7 @@ use tauri_specta::Event;
use crate::auth::{AuthStore, AuthenticationInvalid};
pub fn make_url(pathname: impl AsRef<str>) -> String {
- let server_url_base = dotenvy_macro::dotenv!("NEXT_PUBLIC_URL");
+ let server_url_base = "http://localhost:3000"; //dotenvy_macro::dotenv!("NEXT_PUBLIC_URL");
format!("{server_url_base}{}", pathname.as_ref())
}
diff --git a/apps/desktop/src/routes/(window-chrome)/index.tsx b/apps/desktop/src/routes/(window-chrome)/index.tsx
index a1d31348b..1f94382e2 100644
--- a/apps/desktop/src/routes/(window-chrome)/index.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/index.tsx
@@ -1,6 +1,5 @@
import { Button, SwitchTab } from "@cap/ui-solid";
import { Select as KSelect } from "@kobalte/core/select";
-import { createEventListener } from "@solid-primitives/event-listener";
import { cache, createAsync, redirect, useNavigate } from "@solidjs/router";
import { createMutation, createQuery } from "@tanstack/solid-query";
import { getVersion } from "@tauri-apps/api/app";
@@ -25,8 +24,14 @@ import {
listAudioDevices,
getPermissions,
createVideoDevicesQuery,
+ listScreens,
} from "~/utils/queries";
-import { type CaptureWindow, commands, events } from "~/utils/tauri";
+import {
+ CaptureScreen,
+ type CaptureWindow,
+ commands,
+ events,
+} from "~/utils/tauri";
import {
MenuItem,
MenuItemList,
@@ -46,13 +51,13 @@ export const route = {
};
export default function () {
+ const screens = createQuery(() => listScreens);
const { options, setOptions } = createOptionsQuery();
const windows = createQuery(() => listWindows);
const videoDevices = createVideoDevicesQuery();
const audioDevices = createQuery(() => listAudioDevices);
const currentRecording = createCurrentRecordingQuery();
- const [windowSelectOpen, setWindowSelectOpen] = createSignal(false);
const permissions = createQuery(() => getPermissions);
const [microphoneSelectOpen, setMicrophoneSelectOpen] = createSignal(false);
@@ -77,15 +82,7 @@ export default function () {
},
}));
- createEventListener(window, "mousedown", (e: MouseEvent) => {
- if (windowSelectOpen()) {
- const target = e.target as HTMLElement;
- if (!target.closest(".KSelect")) {
- setWindowSelectOpen(false);
- }
- }
- });
-
+ // important for sign in redirect, trust me
createAsync(() => getAuth());
createUpdateCheck();
@@ -142,12 +139,6 @@ export default function () {
}
};
- const selectedWindow = () => {
- const d = options.data?.captureTarget;
- if (d?.variant !== "window") return;
- return windows.data?.find((data) => data.id === d.id);
- };
-
const audioDevice = () =>
audioDevices?.data?.find(
(d) => d.name === options.data?.audioInputName
@@ -235,98 +226,57 @@ export default function () {
<IconCapSettings class="w-[1.25rem] h-[1.25rem] text-gray-400 hover:text-gray-500" />
</button>
</div>
- <KSelect<CaptureWindow | null>
- options={windows.data ?? []}
- optionValue="id"
- optionTextValue="name"
- placeholder="Window"
- gutter={8}
- open={windowSelectOpen()}
- onOpenChange={(o: boolean) => {
- // prevents tab onChange from interfering with dropdown trigger click
- if (o === false && options.data?.captureTarget.variant === "screen")
- return;
- setWindowSelectOpen(o);
- }}
- itemComponent={(props: { item: any }) => (
- <MenuItem<typeof KSelect.Item> as={KSelect.Item} item={props.item}>
- <KSelect.ItemLabel class="flex-1">
- {props.item.rawValue?.name}
- </KSelect.ItemLabel>
- </MenuItem>
- )}
- value={selectedWindow() ?? null}
- onChange={(d: CaptureWindow | null) => {
- if (!d || !options.data) return;
- setOptions({
- ...options.data,
- captureTarget: { variant: "window", ...d },
- });
- setWindowSelectOpen(false);
- }}
- placement="top-end"
- >
- <SwitchTab
- value={options.data?.captureTarget.variant}
- disabled={isRecording()}
- onChange={(s) => {
- if (!options.data) return;
- if (options.data?.captureTarget.variant === s) {
- setWindowSelectOpen(false);
- return;
- }
- if (s === "screen") {
- setOptions({
- ...options.data,
- captureTarget: { variant: "screen" },
- });
- setWindowSelectOpen(false);
- } else if (s === "window") {
- if (windowSelectOpen()) {
- setWindowSelectOpen(false);
- } else {
- setWindowSelectOpen(true);
- }
- }
+ <div class="flex flex-row items-center rounded-[0.5rem] relative border">
+ <div
+ class="w-1/2 absolute flex p-px inset-0 transition-transform peer-focus-visible:outline outline-2 outline-blue-300 outline-offset-2 rounded-[0.6rem] overflow-hidden"
+ style={{
+ transform:
+ options.data?.captureTarget.variant === "window"
+ ? "translateX(100%)"
+ : undefined,
}}
>
- <SwitchTab.List>
- <SwitchTab.Trigger value="screen">Screen</SwitchTab.Trigger>
- <SwitchTab.Trigger<ValidComponent>
- as={(p) => <KSelect.Trigger<ValidComponent> {...p} />}
- value="window"
- class="w-full text-nowrap overflow-hidden px-2 group KSelect"
- >
- <KSelect.Value<CaptureWindow> class="flex flex-row items-center justify-center">
- {(item) => (
- <>
- <span class="flex-1 truncate">
- {item.selectedOption()?.name ?? "Select Window"}
- </span>
-
- <IconCapChevronDown class="size-4 shrink-0 ui-group-expanded:-rotate-180 transform transition-transform" />
- </>
- )}
- </KSelect.Value>
- </SwitchTab.Trigger>
- </SwitchTab.List>
- </SwitchTab>
- <KSelect.Portal>
- <PopperContent<typeof KSelect.Content>
- as={KSelect.Content}
- class={topRightAnimateClasses}
- >
- <Show
- when={(windows.data ?? []).length > 0}
- fallback={
- <div class="p-2 text-gray-500">No windows available</div>
- }
- >
- <KSelect.Listbox class="max-h-52 max-w-64" as={MenuItemList} />
- </Show>
- </PopperContent>
- </KSelect.Portal>
- </KSelect>
+ <div class="bg-gray-100 flex-1" />
+ </div>
+ <TargetSelect<CaptureScreen>
+ options={screens.data ?? []}
+ onChange={(value) => {
+ if (!value || !options.data) return;
+
+ commands.setRecordingOptions({
+ ...options.data,
+ captureTarget: { ...value, variant: "screen" },
+ });
+ }}
+ value={
+ options.data?.captureTarget.variant === "screen"
+ ? options.data.captureTarget
+ : null
+ }
+ placeholder="Screen"
+ optionsEmptyText="No screens found"
+ selected={options.data?.captureTarget.variant === "screen"}
+ />
+ <TargetSelect<CaptureWindow>
+ options={windows.data ?? []}
+ onChange={(value) => {
+ if (!options.data) return;
+
+ commands.setRecordingOptions({
+ ...options.data,
+ captureTarget: { ...value, variant: "window" },
+ });
+ }}
+ value={
+ options.data?.captureTarget.variant === "window"
+ ? options.data.captureTarget
+ : null
+ }
+ placeholder="Window"
+ optionsEmptyText="No windows found"
+ selected={options.data?.captureTarget.variant === "window"}
+ />
+ </div>
<div class="flex flex-col gap-[0.25rem] items-stretch">
<label class="text-gray-400 text-[0.875rem]">Camera</label>
<Show when>
@@ -571,6 +521,7 @@ export default function () {
import * as dialog from "@tauri-apps/plugin-dialog";
import * as updater from "@tauri-apps/plugin-updater";
import { makePersisted } from "@solid-primitives/storage";
+import { createEventListener } from "@solid-primitives/event-listener";
let hasChecked = false;
function createUpdateCheck() {
@@ -597,7 +548,85 @@ function createUpdateCheck() {
});
}
-function dbg<T>(v: T) {
- console.log(v);
- return v;
+function TargetSelect<T extends { id: number; name: string }>(props: {
+ options: Array<T>;
+ onChange: (value: T) => void;
+ value: T | null;
+ selected: boolean;
+ optionsEmptyText: string;
+ placeholder: string;
+}) {
+ return (
+ <KSelect<T | null>
+ options={props.options ?? []}
+ optionValue="id"
+ optionTextValue="name"
+ gutter={8}
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item> as={KSelect.Item} item={props.item}>
+ <KSelect.ItemLabel class="flex-1">
+ {props.item.rawValue?.name}
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ placement="bottom"
+ class="max-w-[50%] w-full z-10"
+ placeholder={props.placeholder}
+ onChange={(value) => {
+ if (!value) return;
+ props.onChange(value);
+ }}
+ value={props.value}
+ >
+ <KSelect.Trigger<ValidComponent>
+ as={
+ props.options.length === 1
+ ? (p) => (
+ <button
+ onClick={() => {
+ props.onChange(props.options[0]);
+ }}
+ data-selected={props.selected}
+ class={p.class}
+ >
+ <span class="truncate">{props.options[0].name}</span>
+ </button>
+ )
+ : undefined
+ }
+ class="flex-1 text-gray-400 py-1 z-10 data-[selected='true']:text-gray-500 peer focus:outline-none transition-colors duration-100 w-full text-nowrap overflow-hidden px-2 flex gap-2 items-center justify-center"
+ data-selected={props.selected}
+ onClick={(e) => {
+ if (props.options.length === 1) {
+ e.preventDefault();
+ props.onChange(props.options[0]);
+ }
+ }}
+ >
+ <KSelect.Value<CaptureScreen | undefined> class="truncate">
+ {(value) => value.selectedOption()?.name}
+ </KSelect.Value>
+ {props.options.length > 1 && (
+ <KSelect.Icon class="ui-expanded:-rotate-180 transition-transform">
+ <IconCapChevronDown class="size-4 shrink-0 transform transition-transform" />
+ </KSelect.Icon>
+ )}
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={topRightAnimateClasses}
+ >
+ <Show
+ when={props.options.length > 0}
+ fallback={
+ <div class="p-2 text-gray-500">{props.optionsEmptyText}</div>
+ }
+ >
+ <KSelect.Listbox class="max-h-52 max-w-64" as={MenuItemList} />
+ </Show>
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ );
}
diff --git a/apps/desktop/src/utils/queries.ts b/apps/desktop/src/utils/queries.ts
index 2c5f48fa6..9d8b0f60c 100644
--- a/apps/desktop/src/utils/queries.ts
+++ b/apps/desktop/src/utils/queries.ts
@@ -13,6 +13,13 @@ export const listWindows = queryOptions({
refetchInterval: 1000,
});
+export const listScreens = queryOptions({
+ queryKey: ["capture", "screens"] as const,
+ queryFn: () => commands.listCaptureScreens(),
+ reconcile: "id",
+ refetchInterval: 1000,
+});
+
const getOptions = queryOptions({
queryKey: ["recordingOptions"] as const,
queryFn: async () => {
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index f02b8f207..8075c1f99 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -67,6 +67,9 @@ async listCameras() : Promise<string[]> {
async listCaptureWindows() : Promise<CaptureWindow[]> {
return await TAURI_INVOKE("list_capture_windows");
},
+async listCaptureScreens() : Promise<CaptureScreen[]> {
+ return await TAURI_INVOKE("list_capture_screens");
+},
async listAudioDevices() : Promise<Result<string[], null>> {
try {
return { status: "ok", data: await TAURI_INVOKE("list_audio_devices") };
@@ -369,6 +372,7 @@ export type CameraMeta = { path: string }
export type CameraPosition = { x: CameraXPosition; y: CameraYPosition }
export type CameraXPosition = "left" | "center" | "right"
export type CameraYPosition = "top" | "bottom"
+export type CaptureScreen = { id: number; name: string }
export type CaptureWindow = { id: number; name: string; bounds: Bounds }
export type Crop = { position: XY<number>; size: XY<number> }
export type CurrentRecordingChanged = JsonValue<InProgressRecording | null>
@@ -407,7 +411,7 @@ export type RequestRestartRecording = null
export type RequestStartRecording = null
export type RequestStopRecording = null
export type S3UploadMeta = { id: string; user_id: string; aws_region: string; aws_bucket: string }
-export type ScreenCaptureTarget = ({ variant: "window" } & CaptureWindow) | { variant: "screen" }
+export type ScreenCaptureTarget = ({ variant: "window" } & CaptureWindow) | ({ variant: "screen" } & CaptureScreen)
export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordings; path: string; prettyName: string }
export type SharingMeta = { id: string; link: string }
export type ShowCapturesPanel = null
diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml
index bbc1d6da4..cb2946239 100644
--- a/crates/media/Cargo.toml
+++ b/crates/media/Cargo.toml
@@ -28,4 +28,7 @@ tracing = "0.1"
cocoa = "0.26.0"
core-graphics = "0.24.0"
core-foundation = "0.10.0"
+objc = "0.2.7"
+objc-foundation = "0.1.1"
+objc2-foundation = { version = "0.2.2", features = ["NSValue"] }
nokhwa-bindings-macos = { git = "https://github.com/filleduchaos/nokhwa", rev = "408354f6bcdd" }
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index baac0c3ea..882d03ea0 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -1,3 +1,4 @@
+use cocoa::{base::id, foundation::NSDictionary};
use flume::Sender;
use scap::{
capturer::{get_output_frame_size, Area, Capturer, Options, Point, Resolution, Size},
@@ -6,7 +7,7 @@ use scap::{
};
use serde::{Deserialize, Serialize};
use specta::Type;
-use std::collections::HashMap;
+use std::{collections::HashMap, ffi::c_char};
use crate::pipeline::{clock::*, control::Control, task::PipelineSourceTask};
use crate::{
@@ -28,11 +29,17 @@ pub struct CaptureWindow {
pub bounds: Bounds,
}
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+pub struct CaptureScreen {
+ pub id: u32,
+ pub name: String,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", tag = "variant")]
pub enum ScreenCaptureTarget {
Window(CaptureWindow),
- Screen,
+ Screen(CaptureScreen),
}
impl PartialEq<Target> for ScreenCaptureTarget {
@@ -41,8 +48,11 @@ impl PartialEq<Target> for ScreenCaptureTarget {
(Self::Window(capture_window), Target::Window(window)) => {
window.id == capture_window.id
}
- (Self::Screen, Target::Display(_)) => true,
- _ => false,
+ (ScreenCaptureTarget::Screen(capture_screen), Target::Display(display)) => {
+ display.id == capture_screen.id
+ }
+ (&ScreenCaptureTarget::Window(_), &scap::Target::Display(_))
+ | (&ScreenCaptureTarget::Screen(_), &scap::Target::Window(_)) => todo!(),
}
}
}
@@ -63,10 +73,10 @@ impl ScreenCaptureSource {
) -> Self {
let fps = fps.unwrap_or(Self::DEFAULT_FPS);
let output_resolution = resolution.unwrap_or(Resolution::Captured);
- let targets = scap::get_all_targets();
+ let targets = dbg!(scap::get_all_targets());
let excluded_targets: Vec<scap::Target> = targets
- .into_iter()
+ .iter()
.filter(|target| match target {
Target::Window(scap_window)
if EXCLUDED_WINDOWS.contains(&scap_window.title.as_str()) =>
@@ -75,6 +85,7 @@ impl ScreenCaptureSource {
}
_ => false,
})
+ .map(|t| t.clone())
.collect();
let crop_area = match capture_target {
@@ -88,7 +99,18 @@ impl ScreenCaptureSource {
y: capture_window.bounds.y,
},
}),
- ScreenCaptureTarget::Screen => None,
+ ScreenCaptureTarget::Screen(_capture_screen) => None,
+ };
+
+ let target = match capture_target {
+ ScreenCaptureTarget::Window(w) => None,
+ ScreenCaptureTarget::Screen(capture_screen) => targets
+ .iter()
+ .find(|t| match t {
+ Target::Display(display) => display.id == capture_screen.id,
+ _ => false,
+ })
+ .cloned(),
};
let options = Options {
@@ -99,6 +121,7 @@ impl ScreenCaptureSource {
output_type: FrameType::BGRAFrame,
output_resolution,
crop_area,
+ target,
..Default::default()
};
@@ -111,6 +134,70 @@ impl ScreenCaptureSource {
}
}
+ pub fn list_screens() -> Vec<CaptureScreen> {
+ if !scap::has_permission() {
+ return vec![];
+ }
+
+ let mut targets = vec![];
+ let screens = scap::get_all_targets().into_iter().filter_map(|t| match t {
+ Target::Display(screen) => Some(screen),
+ _ => None,
+ });
+
+ #[cfg(target_os = "macos")]
+ let names = {
+ use cocoa::appkit::NSScreen;
+ use cocoa::base::nil;
+ use cocoa::foundation::{NSArray, NSString};
+ use objc::{msg_send, *};
+ use std::ffi::CStr;
+
+ unsafe {
+ let screens = NSScreen::screens(nil);
+ let screen_count = NSArray::count(screens);
+
+ let mut names = HashMap::new();
+
+ for i in 0..screen_count {
+ let screen: *mut objc::runtime::Object = screens.objectAtIndex(i);
+
+ let name: id = msg_send![screen, localizedName];
+ let name = CStr::from_ptr(NSString::UTF8String(name))
+ .to_string_lossy()
+ .to_string();
+
+ let device_description = NSScreen::deviceDescription(screen);
+ let num = NSDictionary::valueForKey_(
+ device_description,
+ NSString::alloc(nil).init_str("NSScreenNumber"),
+ ) as id;
+ let num: *const objc2_foundation::NSNumber = num.cast();
+ let num = { &*num };
+ let num = num.as_u32();
+
+ names.insert(num, name);
+ }
+
+ names
+ }
+ };
+ #[cfg(not(target_os = "macos"))]
+ let names = HashMap::new();
+
+ for (idx, screen) in screens.into_iter().enumerate() {
+ // Handle Target::Screen variant (assuming this is how it's structured in scap)
+ targets.push(CaptureScreen {
+ id: screen.id as u32,
+ name: names
+ .get(&screen.raw_handle.id)
+ .cloned()
+ .unwrap_or_else(|| format!("Screen {}", idx + 1)),
+ });
+ }
+ targets
+ }
+
pub fn list_targets() -> Vec<CaptureWindow> {
if !scap::has_permission() {
return vec![];
@@ -165,7 +252,7 @@ impl PipelineSourceTask for ScreenCaptureSource {
ScreenCaptureTarget::Window(window) => Some(window.id),
_ => None,
};
- let mut capturer = Capturer::new(self.options.clone());
+ let mut capturer = Capturer::new(dbg!(self.options.clone()));
let mut capturing = false;
let _ = ready_signal.send(Ok(())).unwrap();