Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fail injection (#344)

Brendan Allanc79d008034a8
diff --git a/Cargo.lock b/Cargo.lock
index 9616d141c..1a57fd639 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -925,6 +925,7 @@ dependencies = [
"base64 0.22.1",
"cap-editor",
"cap-export",
+ "cap-fail",
"cap-flags",
"cap-media",
"cap-project",
@@ -985,6 +986,7 @@ dependencies = [
"tauri-specta",
"tempfile",
"tokio",
+ "tokio-stream",
"tracing",
"tracing-appender",
"tracing-subscriber",
@@ -1031,6 +1033,13 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "cap-fail"
+version = "0.1.0"
+dependencies = [
+ "inventory",
+]
+
[[package]]
name = "cap-flags"
version = "0.1.0"
@@ -1051,6 +1060,7 @@ name = "cap-media"
version = "0.1.0"
dependencies = [
"axum",
+ "cap-fail",
"cap-flags",
"cap-gpu-converters",
"cap-project",
@@ -3626,6 +3636,15 @@ dependencies = [
"syn 2.0.90",
]
+[[package]]
+name = "inventory"
+version = "0.3.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "54b12ebb6799019b044deaf431eadfe23245b259bba5a2c0796acec3943a3cdb"
+dependencies = [
+ "rustversion",
+]
+
[[package]]
name = "ipnet"
version = "2.9.0"
@@ -6897,6 +6916,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ccbb212565d2dc177bc15ecb7b039d66c4490da892436a4eee5b394d620c9bc"
dependencies = [
"paste",
+ "serde_json",
"specta-macros",
"thiserror 1.0.63",
"uuid",
@@ -8024,6 +8044,18 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "tokio-stream"
+version = "0.1.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+ "tokio",
+ "tokio-util",
+]
+
[[package]]
name = "tokio-tungstenite"
version = "0.24.0"
diff --git a/Cargo.toml b/Cargo.toml
index c932dd34e..b64159f08 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@ resolver = "2"
members = ["apps/cli", "apps/desktop/src-tauri", "crates/*"]
[workspace.dependencies]
-anyhow = "1.0.86"
+anyhow = { version = "1.0.86" }
# This includes a currently-unreleased fix that ensures the audio stream is actually
# stopped and released on drop on macOS
cpal = { git = "https://github.com/RustAudio/cpal", rev = "f43d36e55494993bbbde3299af0c53e5cdf4d4cf" }
@@ -18,8 +18,12 @@ tokio = { version = "1.39.3", features = [
"rt-multi-thread",
"time",
] }
-tauri = { version = "2.2.3", features = ["specta"] }
-specta = { version = "=2.0.0-rc.20", features = ["derive", "uuid"] }
+tauri = { version = "2.2.5", features = ["specta"] }
+specta = { version = "=2.0.0-rc.20", features = [
+ "derive",
+ "serde_json",
+ "uuid",
+] }
scap = { git = "https://github.com/CapSoftware/scap", rev = "58d4410bf52f" }
nokhwa = { git = "https://github.com/CapSoftware/nokhwa", rev = "e309b938ccd6", features = [
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 96cfb2e60..59f1278c4 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -12,7 +12,7 @@ name = "desktop_solid_lib"
crate-type = ["lib", "cdylib", "staticlib"]
[build-dependencies]
-tauri-build = { version = "2.0.3", features = [] }
+tauri-build = { version = "2.0.5", features = [] }
[target.'cfg(target_os = "macos")'.build-dependencies]
swift-rs = { version = "1.0.6", features = ["build"] }
@@ -41,6 +41,7 @@ tauri-plugin-oauth = { git = "https://github.com/FabianLars/tauri-plugin-oauth",
tauri-plugin-window-state = "2.2.0"
tauri-plugin-positioner = "2.2.0"
tauri-plugin-deep-link = "2.2.0"
+tauri-plugin-clipboard-manager = "2.2.1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
@@ -85,7 +86,8 @@ tracing-subscriber = "0.3.19"
tracing-appender = "0.2.3"
dirs = "6.0.0"
relative-path = "1.9.3"
-tauri-plugin-clipboard-manager = "2.2.1"
+cap-fail = { version = "0.1.0", path = "../../../crates/fail" }
+tokio-stream = { version = "0.1.17", features = ["sync"] }
[target.'cfg(target_os = "macos")'.dependencies]
core-graphics = "0.24.0"
diff --git a/apps/desktop/src-tauri/src/auth.rs b/apps/desktop/src-tauri/src/auth.rs
index ac81256c7..e35346d2b 100644
--- a/apps/desktop/src-tauri/src/auth.rs
+++ b/apps/desktop/src-tauri/src/auth.rs
@@ -38,7 +38,7 @@ impl AuthStore {
}
pub fn get<R: Runtime>(app: &AppHandle<R>) -> Result<Option<Self>, String> {
- let Some(Some(store)) = app.get_store("store").map(|s| s.get("auth")) else {
+ let Ok(Some(store)) = app.store("store").map(|s| s.get("auth")) else {
return Ok(None);
};
@@ -104,7 +104,7 @@ impl AuthStore {
}
pub fn set(app: &AppHandle, value: Option<Self>) -> Result<(), String> {
- let Some(store) = app.get_store("store") else {
+ let Ok(store) = app.store("store") else {
return Err("Store not found".to_string());
};
diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rs
index 9cb6fafa9..1af8c7ebc 100644
--- a/apps/desktop/src-tauri/src/camera.rs
+++ b/apps/desktop/src-tauri/src/camera.rs
@@ -18,7 +18,13 @@ pub async fn create_camera_preview_ws() -> (
if frame.format() != Pixel::RGBA {
let converter = match &mut converter {
- Some((format, converter)) if *format == frame.format() => converter,
+ Some((format, converter))
+ if *format == frame.format()
+ && converter.input().width == frame.width()
+ && converter.input().height == frame.height() =>
+ {
+ converter
+ }
_ => {
&mut converter
.insert((
diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rs
index 8e615db6c..09185dd9b 100644
--- a/apps/desktop/src-tauri/src/general_settings.rs
+++ b/apps/desktop/src-tauri/src/general_settings.rs
@@ -40,9 +40,9 @@ pub struct GeneralSettingsStore {
#[serde(rename_all = "camelCase")]
pub struct CommercialLicense {
license_key: String,
- expiry_date: Option<u32>,
- refresh: u32,
- activated_on: u32,
+ expiry_date: Option<f64>,
+ refresh: f64,
+ activated_on: f64,
}
impl Default for GeneralSettingsStore {
@@ -84,7 +84,7 @@ impl GeneralSettingsStore {
// Handle potential deserialization errors gracefully
match serde_json::from_value(store) {
Ok(settings) => Ok(Some(settings)),
- Err(_) => Err("Failed to deserialize general settings store".to_string()),
+ Err(e) => Err(format!("Failed to deserialize general settings store: {e}")),
}
}
_ => Ok(None),
diff --git a/apps/desktop/src-tauri/src/hotkeys.rs b/apps/desktop/src-tauri/src/hotkeys.rs
index b2d8d5f17..637248d14 100644
--- a/apps/desktop/src-tauri/src/hotkeys.rs
+++ b/apps/desktop/src-tauri/src/hotkeys.rs
@@ -58,7 +58,7 @@ pub struct HotkeysStore {
impl HotkeysStore {
pub fn get(app: &AppHandle) -> Result<Option<Self>, String> {
- let Some(Some(store)) = app.get_store("store").map(|s| s.get("hotkeys")) else {
+ let Ok(Some(store)) = app.store("store").map(|s| s.get("hotkeys")) else {
return Ok(None);
};
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 2bf46711a..40e3cd37a 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -13,6 +13,7 @@ mod audio_meter;
mod editor_window;
mod export;
mod fake_window;
+// mod live_state;
mod presets;
mod tray;
mod upload;
@@ -24,6 +25,7 @@ use auth::{AuthStore, AuthenticationInvalid, Plan};
use camera::create_camera_preview_ws;
use cap_editor::EditorInstance;
use cap_editor::EditorState;
+use cap_fail::fail;
use cap_media::feeds::RawCameraFrame;
use cap_media::feeds::{AudioInputFeed, AudioInputSamplesSender};
use cap_media::frame_ws::WSFrame;
@@ -49,6 +51,7 @@ use scap::frame::Frame;
use serde::{Deserialize, Serialize};
use serde_json::json;
use specta::Type;
+use std::collections::BTreeMap;
use std::{
collections::HashMap,
fs::File,
@@ -195,57 +198,63 @@ impl App {
_ => {}
}
- match new_options.camera_label() {
- Some(camera_label) => {
- if let Some(camera_feed) = self.camera_feed.as_ref() {
- camera_feed
- .lock()
- .await
- .switch_cameras(camera_label)
- .await
- .map_err(|e| e.to_string())?;
- } else {
- let feed = CameraFeed::init(camera_label)
- .await
- .map_err(|e| e.to_string())?;
-
+ // try update camera
+ let camera = match (new_options.camera_label(), self.camera_feed.as_ref()) {
+ (Some(camera_label), Some(camera_feed)) => camera_feed
+ .lock()
+ .await
+ .switch_cameras(camera_label)
+ .await
+ .map_err(|e| e.to_string()),
+ (Some(camera_label), None) => CameraFeed::init(camera_label)
+ .await
+ .map(|feed| {
feed.attach(self.camera_tx.clone());
-
self.camera_feed = Some(Arc::new(Mutex::new(feed)));
- }
- }
- None => {
+ })
+ .map_err(|e| e.to_string()),
+ (None, _) => {
self.camera_feed = None;
+ Ok(())
}
}
+ .inspect(|_| {
+ self.start_recording_options.camera_label = new_options.camera_label.clone();
+ });
- self.audio_input_feed = match new_options.audio_input_name() {
- Some(audio_input_name) => Some(match self.audio_input_feed.take() {
- Some(mut feed) => {
- feed.switch_input(audio_input_name)
- .await
- .map_err(|e| e.to_string())?;
-
- feed
- }
- None => {
- let feed = AudioInputFeed::init(audio_input_name)
- .await
- .map_err(|e| e.to_string())?;
-
- feed.add_sender(self.audio_input_tx.clone()).await.unwrap();
-
- feed
- }
- }),
- None => None,
- };
+ // try update microphone
+ let microphone = match (new_options.audio_input_name(), &mut self.audio_input_feed) {
+ (Some(new_input_name), v @ None) => {
+ AudioInputFeed::init(new_input_name)
+ .await
+ .map_err(|e| e.to_string())
+ .map(|feed| async {
+ feed.add_sender(self.audio_input_tx.clone()).await.unwrap();
+ *v = Some(feed);
+ })
+ .transpose_async()
+ .await
+ }
+ (Some(new_input_name), Some(feed)) => feed
+ .switch_input(new_input_name)
+ .await
+ .map_err(|e| e.to_string()),
+ (None, v) => {
+ v.take();
+ Ok(())
+ }
+ }
+ .inspect(|_| {
+ self.start_recording_options.audio_input_name = new_options.audio_input_name.clone();
+ });
- self.start_recording_options = new_options;
+ if camera.is_ok() || microphone.is_ok() {
+ self.start_recording_options.capture_target = new_options.capture_target;
- RecordingOptionsChanged.emit(&self.handle).ok();
+ RecordingOptionsChanged.emit(&self.handle).ok();
+ }
- Ok(())
+ camera.and(microphone)
}
}
@@ -437,12 +446,12 @@ async fn set_recording_options(
Ok(())
}
-type Bruh<T> = (T,);
+type SingleTuple<T> = (T,);
#[derive(Serialize, Type)]
struct JsonValue<T>(
#[serde(skip)] PhantomData<T>,
- #[specta(type = Bruh<T>)] serde_json::Value,
+ #[specta(type = SingleTuple<T>)] serde_json::Value,
);
impl<T> Clone for JsonValue<T> {
@@ -1805,6 +1814,18 @@ fn show_window(app: AppHandle, window: ShowCapWindow) {
window.show(&app).ok();
}
+#[tauri::command(async)]
+#[specta::specta]
+fn list_fails() -> Result<BTreeMap<String, bool>, ()> {
+ Ok(cap_fail::get_state())
+}
+
+#[tauri::command(async)]
+#[specta::specta]
+fn set_fail(name: String, value: bool) {
+ cap_fail::set_fail(&name, value)
+}
+
async fn check_notification_permissions(app: AppHandle) {
// Check if we've already requested permissions
let Ok(Some(settings)) = GeneralSettingsStore::get(&app) else {
@@ -1958,6 +1979,8 @@ pub async fn run() {
write_clipboard_string,
platform::perform_haptic_feedback,
get_wallpaper_path,
+ list_fails,
+ set_fail,
update_auth_plan
])
.events(tauri_specta::collect_events![
@@ -2050,17 +2073,7 @@ pub async fn run() {
})
.build(),
)
- .invoke_handler({
- let handler = specta_builder.invoke_handler();
-
- move |invoke| {
- sentry::configure_scope(|scope| {
- scope.set_tag("cmd", invoke.message.command());
- });
-
- handler(invoke)
- }
- })
+ .invoke_handler(specta_builder.invoke_handler())
.setup(move |app| {
let app = app.handle().clone();
specta_builder.mount_events(&app);
@@ -2426,3 +2439,27 @@ trait EventExt: tauri_specta::Event {
}
impl<T: tauri_specta::Event> EventExt for T {}
+
+trait TransposeAsync {
+ type Output;
+
+ fn transpose_async(self) -> impl Future<Output = Self::Output>
+ where
+ Self: Sized;
+}
+
+impl<F: Future<Output = T>, T, E> TransposeAsync for Result<F, E> {
+ type Output = Result<T, E>;
+
+ fn transpose_async(self) -> impl Future<Output = Self::Output>
+ where
+ Self: Sized,
+ {
+ async {
+ match self {
+ Ok(f) => Ok(f.await),
+ Err(e) => Err(e),
+ }
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/presets.rs b/apps/desktop/src-tauri/src/presets.rs
index 8f868b258..3b846e943 100644
--- a/apps/desktop/src-tauri/src/presets.rs
+++ b/apps/desktop/src-tauri/src/presets.rs
@@ -21,8 +21,8 @@ pub struct Preset {
impl PresetsStore {
fn get(app: &AppHandle<Wry>) -> Result<Option<Self>, String> {
- match app.get_store("store").map(|s| s.get("presets")) {
- Some(Some(store)) => {
+ match app.store("store").map(|s| s.get("presets")) {
+ Ok(Some(store)) => {
// Handle potential deserialization errors gracefully
match serde_json::from_value(store) {
Ok(settings) => Ok(Some(settings)),
@@ -46,7 +46,7 @@ impl PresetsStore {
}
pub fn update(app: &AppHandle, update: impl FnOnce(&mut Self)) -> Result<(), String> {
- let Some(store) = app.get_store("store") else {
+ let Ok(store) = app.store("store") else {
return Err("Store not found".to_string());
};
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 58b577634..951098a6d 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -14,6 +14,7 @@ use crate::{
App, CurrentRecordingChanged, MutableState, NewRecordingAdded, PreCreatedVideo,
RecordingStarted, RecordingStopped, UploadMode,
};
+use cap_fail::fail;
use cap_flags::FLAGS;
use cap_media::sources::{CaptureScreen, CaptureWindow};
use cap_media::{feeds::CameraFeed, sources::ScreenCaptureTarget};
@@ -74,26 +75,20 @@ pub async fn start_recording(
.map(|settings| settings.auto_create_shareable_link)
.unwrap_or(false);
- if auto_create_shareable_link {
- sentry::configure_scope(|scope| {
- scope.set_tag("task", "auto_create_shareable_link");
- });
-
- if let Ok(Some(auth)) = AuthStore::get(&app) {
- if auth.is_upgraded() {
- // Pre-create the video and get the shareable link
- if let Ok(s3_config) = get_s3_config(&app, false, None).await {
- let link = web_api::make_url(format!("/s/{}", s3_config.id()));
-
- state.pre_created_video = Some(PreCreatedVideo {
- id: s3_config.id().to_string(),
- link: link.clone(),
- config: s3_config,
- });
-
- println!("Pre-created shareable link: {}", link);
- };
- }
+ if let Ok(Some(auth)) = AuthStore::get(&app) {
+ if auto_create_shareable_link && auth.is_upgraded() {
+ // Pre-create the video and get the shareable link
+ if let Ok(s3_config) = get_s3_config(&app, false, None).await {
+ let link = web_api::make_url(format!("/s/{}", s3_config.id()));
+
+ state.pre_created_video = Some(PreCreatedVideo {
+ id: s3_config.id().to_string(),
+ link: link.clone(),
+ config: s3_config,
+ });
+
+ println!("Pre-created shareable link: {}", link);
+ };
}
}
diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs
index c5f32f1dc..9f55013f9 100644
--- a/apps/desktop/src-tauri/src/tray.rs
+++ b/apps/desktop/src-tauri/src/tray.rs
@@ -3,6 +3,7 @@ use crate::{
RecordingStarted, RecordingStopped, RequestNewScreenshot, RequestOpenSettings,
RequestStartRecording, RequestStopRecording,
};
+use cap_fail::fail;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tauri::menu::{MenuId, PredefinedMenuItem};
diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsx
index b92f6e3d2..296ae51b6 100644
--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx
+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx
@@ -149,6 +149,16 @@ export default function () {
/>
</button>
</Show>
+ {import.meta.env.DEV && (
+ <button
+ type="button"
+ onClick={() => {
+ new WebviewWindow("debug", { url: "/debug" });
+ }}
+ >
+ <IconLucideBug class="text-gray-400 hover:text-gray-500" />
+ </button>
+ )}
</div>
);
@@ -227,7 +237,7 @@ export default function () {
</Tooltip.Root>
</div>
</div>
- <TargetSelects options={options.data} />
+ <TargetSelects options={options.data} setOptions={setOptions} />
<CameraSelect options={options.data} setOptions={setOptions} />
<MicrophoneSelect options={options.data} setOptions={setOptions} />
<div class="w-full flex items-center space-x-1">
@@ -293,7 +303,9 @@ import {
getCurrentWebviewWindow,
WebviewWindow,
} from "@tauri-apps/api/webviewWindow";
+import { Webview } from "@tauri-apps/api/webview";
import { UnlistenFn } from "@tauri-apps/api/event";
+import { isDev } from "solid-js/web";
let hasChecked = false;
function createUpdateCheck() {
@@ -322,6 +334,7 @@ function createUpdateCheck() {
function TargetSelects(props: {
options: ReturnType<typeof createOptionsQuery>["options"]["data"];
+ setOptions: ReturnType<typeof createOptionsQuery>["setOptions"];
}) {
const screens = createQuery(() => listScreens);
const windows = createQuery(() => listWindows);
@@ -533,8 +546,10 @@ function TargetSelects(props: {
placeholder="Screen"
optionsEmptyText="No screens found"
selected={isTargetScreenOrArea()}
+ disabled={props.setOptions.isPending}
/>
<TargetSelect<CaptureWindow>
+ disabled={props.setOptions.isPending}
options={windows.data ?? []}
onChange={(value) => {
if (!value || !props.options) return;
@@ -713,17 +728,13 @@ function MicrophoneSelect(props: {
type Option = { name: string; deviceId: string };
- const [loading, setLoading] = createSignal(false);
const handleMicrophoneChange = async (item: Option | null) => {
if (!item || !props.options) return;
- setLoading(true);
- await props.setOptions
- .mutateAsync({
- ...props.options,
- audioInputName: item.deviceId !== "" ? item.name : null,
- })
- .finally(() => setLoading(false));
+ await props.setOptions.mutateAsync({
+ ...props.options,
+ audioInputName: item.deviceId !== "" ? item.name : null,
+ });
if (!item.deviceId) setDbs();
trackEvent("microphone_selected", {
@@ -798,7 +809,7 @@ function MicrophoneSelect(props: {
}}
>
<KSelect.Trigger
- disabled={loading()}
+ disabled={props.setOptions.isPending}
class="relative flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-200 w-full disabled:text-gray-400 transition-colors KSelect overflow-hidden z-10"
>
<Show when={dbs()}>
@@ -865,15 +876,15 @@ function TargetSelect<T extends { id: number; name: string }>(props: {
NonNullable<SelectRootProps<T | null>["itemComponent"]>
>[0]
) => JSX.Element;
+ disabled?: boolean;
}) {
- createEffect(() => {
+ const value = () => {
const v = props.value;
- if (!v) return;
+ if (!v) return null;
- if (!props.options.some((o) => o.id === v.id)) {
- props.onChange(props.options[0] ?? null);
- }
- });
+ if (props.options.some((o) => o.id === v.id)) return props.value;
+ else return props.options[0];
+ };
return (
<KSelect<T | null>
@@ -889,13 +900,13 @@ function TargetSelect<T extends { id: number; name: string }>(props: {
</MenuItem>
)}
placement="bottom"
- class="max-w-[50%] w-full z-10"
+ class="max-w-[50%] w-full z-10 disabled:text-opacity-80"
placeholder={props.placeholder}
onChange={(value) => {
if (!value) return;
props.onChange(value);
}}
- value={props.value}
+ value={value()}
>
<KSelect.Trigger<ValidComponent>
as={
@@ -913,7 +924,8 @@ function TargetSelect<T extends { id: number; name: string }>(props: {
)
: 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"
+ class="flex-1 text-gray-400 py-1 z-10 data-[selected='true']:text-gray-500 disabled:text-gray-400 peer focus:outline-none transition-colors duration-100 w-full text-nowrap overflow-hidden px-2 flex gap-2 items-center justify-center"
+ disabled={props.disabled}
data-selected={props.selected}
onClick={(e) => {
if (props.options.length === 1) {
diff --git a/apps/desktop/src/routes/debug.tsx b/apps/desktop/src/routes/debug.tsx
new file mode 100644
index 000000000..4fde59818
--- /dev/null
+++ b/apps/desktop/src/routes/debug.tsx
@@ -0,0 +1,44 @@
+import { createQuery } from "@tanstack/solid-query";
+import { createUniqueId, For } from "solid-js";
+import { commands } from "~/utils/tauri";
+
+export default function Debug() {
+ const fails = createQuery(() => ({
+ queryKey: ["fails"],
+ queryFn: () => commands.listFails(),
+ }));
+
+ const orderedFails = () => Object.entries(fails.data ?? {});
+
+ return (
+ <main class="w-full h-full bg-gray-100 text-[--text-primary] p-4">
+ <h2 class="text-2xl font-bold">Fail Points</h2>
+ <ul class="p-2">
+ <For each={orderedFails()}>
+ {(fail) => {
+ const id = createUniqueId();
+
+ return (
+ <li class="flex flex-row items-center gap-2">
+ <input
+ class="size-4"
+ id={id}
+ type="checkbox"
+ checked={fail[1]}
+ value={fail[1].toString()}
+ onClick={(e) => {
+ e.preventDefault();
+ commands
+ .setFail(fail[0], !fail[1])
+ .then(() => fails.refetch());
+ }}
+ />
+ <label for={id}>{fail[0]}</label>
+ </li>
+ );
+ }}
+ </For>
+ </ul>
+ </main>
+ );
+}
diff --git a/apps/desktop/src/store.ts b/apps/desktop/src/store.ts
index f4d81d340..0a5a75db0 100644
--- a/apps/desktop/src/store.ts
+++ b/apps/desktop/src/store.ts
@@ -1,4 +1,4 @@
-import { createQuery, queryOptions } from "@tanstack/solid-query";
+import { createQuery } from "@tanstack/solid-query";
import { Store } from "@tauri-apps/plugin-store";
import { onCleanup } from "solid-js";
@@ -7,6 +7,7 @@ import {
type PresetsStore,
type HotkeysStore,
type GeneralSettingsStore,
+ commands,
} from "~/utils/tauri";
let _store: Promise<Store> | undefined;
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index fe2a1c72d..7d892d4f3 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -164,6 +164,12 @@ async performHapticFeedback(pattern: HapticPattern | null, time: HapticPerforman
async getWallpaperPath(filename: string) : Promise<string> {
return await TAURI_INVOKE("get_wallpaper_path", { filename });
},
+async listFails() : Promise<{ [key in string]: boolean }> {
+ return await TAURI_INVOKE("list_fails");
+},
+async setFail(name: string, value: boolean) : Promise<void> {
+ await TAURI_INVOKE("set_fail", { name, value });
+},
async updateAuthPlan() : Promise<void> {
await TAURI_INVOKE("update_auth_plan");
}
diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml
index d1e701c67..129905ae6 100644
--- a/crates/export/Cargo.toml
+++ b/crates/export/Cargo.toml
@@ -17,5 +17,4 @@ image = "0.25.2"
mp4 = "0.14.0"
thiserror.workspace = true
futures = "0.3.31"
-# tauri = { workspace = true }
ffmpeg = { workspace = true }
diff --git a/crates/fail/Cargo.toml b/crates/fail/Cargo.toml
new file mode 100644
index 000000000..cd994fb23
--- /dev/null
+++ b/crates/fail/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "cap-fail"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+inventory = "0.3.19"
diff --git a/crates/fail/src/lib.rs b/crates/fail/src/lib.rs
new file mode 100644
index 000000000..8c3efc7f9
--- /dev/null
+++ b/crates/fail/src/lib.rs
@@ -0,0 +1,76 @@
+use std::collections::BTreeMap;
+use std::sync::LazyLock;
+use std::sync::{Arc, RwLock};
+
+#[derive(Debug)]
+pub struct Fail {
+ pub name: &'static str,
+}
+
+inventory::collect!(Fail);
+
+static FAILS: LazyLock<Arc<RwLock<BTreeMap<String, bool>>>> = LazyLock::new(|| {
+ Arc::new(RwLock::new(if cfg!(debug_assertions) {
+ BTreeMap::from_iter(inventory::iter::<Fail>().map(|fail| (fail.name.to_string(), false)))
+ } else {
+ BTreeMap::new()
+ }))
+});
+
+#[macro_export]
+macro_rules! fail {
+ ($name:literal) => {
+ #[cfg(debug_assertions)]
+ {
+ $crate::private::inventory::submit! {
+ $crate::Fail { name: $name }
+ }
+
+ let name: &str = $name;
+ let should_fail = $crate::private::should_fail(name);
+
+ if should_fail {
+ panic!("Purposely panicked at '{name}'")
+ }
+ }
+ };
+}
+
+#[macro_export]
+macro_rules! fail_err {
+ ($name:literal, $value:expr) => {
+ #[cfg(debug_assertions)]
+ {
+ $crate::private::inventory::submit! {
+ $crate::Fail { name: $name }
+ }
+
+ let name: &str = $name;
+ let should_fail = $crate::private::should_fail(name);
+
+ if should_fail {
+ eprintln!("Purposely Err'd at '{name}'");
+ Err($value)?;
+ }
+ }
+ };
+}
+
+#[doc(hidden)]
+pub mod private {
+ use super::*;
+
+ pub use inventory;
+
+ pub fn should_fail(name: &str) -> bool {
+ FAILS.read().unwrap().get(name).cloned().unwrap_or_default()
+ }
+}
+
+pub fn get_state() -> BTreeMap<String, bool> {
+ FAILS.read().unwrap().clone()
+}
+
+pub fn set_fail(name: impl Into<String>, should_fail: bool) {
+ FAILS.write().unwrap().insert(name.into(), should_fail);
+}
diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml
index f28c35ebc..094edfb21 100644
--- a/crates/media/Cargo.toml
+++ b/crates/media/Cargo.toml
@@ -30,6 +30,7 @@ tracing = { version = "0.1", features = ["release_max_level_info"] }
futures = "0.3.31"
axum = { version = "0.7.9", features = ["macros", "ws"] }
tokio.workspace = true
+cap-fail = { version = "0.1.0", path = "../fail" }
[target.'cfg(target_os = "macos")'.dependencies]
cidre = { workspace = true, default-features = false, features = [
diff --git a/crates/media/src/encoders/h264.rs b/crates/media/src/encoders/h264.rs
index 7e5231229..d728775e5 100644
--- a/crates/media/src/encoders/h264.rs
+++ b/crates/media/src/encoders/h264.rs
@@ -57,7 +57,11 @@ impl H264Encoder {
format,
)
.map_err(|e| {
- tracing::error!("Failed to create converter from {:?} to YUV420P: {:?}", config.pixel_format, e);
+ tracing::error!(
+ "Failed to create converter from {:?} to YUV420P: {:?}",
+ config.pixel_format,
+ e
+ );
MediaError::Any("Failed to create frame converter")
})?,
),
@@ -105,9 +109,13 @@ impl H264Encoder {
Ok(_) => {
new_frame.set_pts(frame.pts());
new_frame
- },
+ }
Err(e) => {
- tracing::error!("Failed to convert frame: {:?} from format {:?} to YUV420P", e, frame.format());
+ tracing::error!(
+ "Failed to convert frame: {:?} from format {:?} to YUV420P",
+ e,
+ frame.format()
+ );
// Return early as we can't process this frame
return;
}
diff --git a/crates/media/src/encoders/opus.rs b/crates/media/src/encoders/opus.rs
index 193878c3d..40655a663 100644
--- a/crates/media/src/encoders/opus.rs
+++ b/crates/media/src/encoders/opus.rs
@@ -1,5 +1,6 @@
use std::{collections::VecDeque, path::PathBuf};
+use cap_fail::fail;
use ffmpeg::{
codec::{context, encoder},
format::{self, sample::Type, Sample},
@@ -254,6 +255,8 @@ impl PipelineSinkTask<FFAudio> for OggFile {
ready_signal.send(Ok(())).unwrap();
while let Ok(frame) = input.recv() {
+ fail!("media::encoder::opus::run");
+
self.queue_frame(frame);
}
}
diff --git a/crates/media/src/feeds/audio_input.rs b/crates/media/src/feeds/audio_input.rs
index 318e76ae7..5b59f13d2 100644
--- a/crates/media/src/feeds/audio_input.rs
+++ b/crates/media/src/feeds/audio_input.rs
@@ -1,3 +1,4 @@
+use cap_fail::{fail, fail_err};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{Device, InputCallbackInfo, SampleFormat, StreamConfig, SupportedStreamConfig};
use flume::{Receiver, Sender, TrySendError};
@@ -60,6 +61,8 @@ impl AudioInputFeed {
trace!("Initializing audio input feed with device");
debug!(selected_input);
+ fail_err!("media::feeds::audio_input::init", MediaError::Any(""));
+
let (device, config) = Self::list_devices()
.swap_remove_entry(selected_input)
.map(|(device_name, (device, config))| {
@@ -157,6 +160,11 @@ impl AudioInputFeed {
}
pub async fn switch_input(&mut self, name: &str) -> Result<(), MediaError> {
+ fail_err!(
+ "media::feeds::audio_input::switch_input",
+ MediaError::Any("")
+ );
+
let (tx, rx) = flume::bounded(1);
self.control_tx
diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rs
index 2c1fd413f..1b45624d6 100644
--- a/crates/media/src/feeds/camera.rs
+++ b/crates/media/src/feeds/camera.rs
@@ -1,3 +1,4 @@
+use cap_fail::{fail, fail_err};
use cap_gpu_converters::{NV12Input, NV12ToRGBA, UYVYToRGBA};
use ffmpeg::{format::Pixel, software::scaling};
use flume::{Receiver, Sender, TryRecvError, TrySendError};
@@ -53,6 +54,8 @@ impl CameraFeed {
pub async fn init(selected_camera: &str) -> Result<CameraFeed, MediaError> {
trace!("Initializing camera feed for: {}", selected_camera);
+ fail_err!("media::feeds::camera::init", MediaError::Any("forced fail"));
+
let camera_info = find_camera(selected_camera)?;
let (control, control_receiver) = flume::bounded(1);
@@ -89,6 +92,11 @@ impl CameraFeed {
}
pub async fn switch_cameras(&mut self, camera_name: &str) -> Result<(), MediaError> {
+ fail_err!(
+ "media::feeds::camera::switch_cameras",
+ MediaError::Any("forced fail")
+ );
+
let current_camera_name = self.camera_info.human_name();
if camera_name != &current_camera_name {
let (result_tx, result_rx) = flume::bounded::<CameraSwitchResult>(1);
@@ -201,6 +209,8 @@ fn run_camera_feed(
control: Receiver<CameraControl>,
ready_signal: Sender<Result<VideoInfo, MediaError>>,
) {
+ fail!("media::feeds::camera::run panic");
+
let mut camera = match create_camera(&camera_info) {
Ok(cam) => cam,
Err(error) => {
@@ -231,20 +241,24 @@ fn run_camera_feed(
FrameFormat::GRAY => Pixel::GRAY8,
FrameFormat::YUYV => {
let pix_fmt = if cfg!(windows) {
- tracing::debug!("Using YUYV422 format for Windows camera in buffer_to_ffvideo");
- Pixel::YUYV422 // This is correct for Windows
+ tracing::debug!(
+ "Using YUYV422 format for Windows camera in buffer_to_ffvideo"
+ );
+ Pixel::YUYV422 // This is correct for Windows
} else {
// let bytes = buffer.buffer().len() as f32;
// let ratio = bytes / (buffer.resolution().x() * buffer.resolution().y()) as f32;
// if ratio == 2.0
// nokhwa merges yuvu420 and uyvy422 into the same format, we should probably distinguish them with the frame size
- tracing::debug!("Using UYVY422 format for non-Windows camera in buffer_to_ffvideo");
+ tracing::debug!(
+ "Using UYVY422 format for non-Windows camera in buffer_to_ffvideo"
+ );
Pixel::UYVY422
};
pix_fmt
- },
+ }
},
camera_format.width(),
camera_format.height(),
@@ -292,13 +306,13 @@ fn run_camera_feed(
FrameFormat::YUYV => {
let pix_fmt = if cfg!(windows) {
tracing::debug!("Using YUYV422 format for Windows camera in buffer_to_ffvideo");
- Pixel::YUYV422 // This is correct for Windows
+ Pixel::YUYV422 // This is correct for Windows
} else {
tracing::debug!("Using UYVY422 format for non-Windows camera in buffer_to_ffvideo");
Pixel::UYVY422
};
pix_fmt
- },
+ }
},
camera_format.width(),
camera_format.height(),
@@ -397,14 +411,16 @@ fn buffer_to_ffvideo(buffer: nokhwa::Buffer) -> FFVideo {
// nokhwa moment
let pix_fmt = if cfg!(windows) {
tracing::debug!("Using YUYV422 format for Windows camera in buffer_to_ffvideo");
- Pixel::YUYV422 // This is correct for Windows
+ Pixel::YUYV422 // This is correct for Windows
} else {
// let bytes = buffer.buffer().len() as f32;
// let ratio = bytes / (buffer.resolution().x() * buffer.resolution().y()) as f32;
// if ratio == 2.0
// nokhwa merges yuvu420 and uyvy422 into the same format, we should probably distinguish them with the frame size
- tracing::debug!("Using UYVY422 format for non-Windows camera in buffer_to_ffvideo");
+ tracing::debug!(
+ "Using UYVY422 format for non-Windows camera in buffer_to_ffvideo"
+ );
Pixel::UYVY422
};
diff --git a/crates/media/src/sources/audio_input.rs b/crates/media/src/sources/audio_input.rs
index 132102f5f..7a8be608c 100644
--- a/crates/media/src/sources/audio_input.rs
+++ b/crates/media/src/sources/audio_input.rs
@@ -1,3 +1,4 @@
+use cap_fail::fail;
use cpal::{Device, StreamInstant, SupportedStreamConfig};
use flume::{Receiver, Sender};
use indexmap::IndexMap;
@@ -94,6 +95,8 @@ impl PipelineSourceTask for AudioInputSource {
let mut samples_rx: Option<Receiver<AudioInputSamples>> = None;
ready_signal.send(Ok(())).unwrap();
+ fail!("media::sources::audio_input::run");
+
loop {
match control_signal.last() {
Some(Control::Play) => {
diff --git a/crates/project/Cargo.toml b/crates/project/Cargo.toml
index c5a9435a2..ba6556061 100644
--- a/crates/project/Cargo.toml
+++ b/crates/project/Cargo.toml
@@ -10,5 +10,3 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1.0.127"
either = "1.13.0"
relative-path = { version = "1.9.3", features = ["serde"] }
-# tauri = { workspace = true }
-# tauri-plugin-store = "2.0.0-rc.4"
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index 0c96131ea..086236c63 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -51,6 +51,7 @@ declare global {
const IconHugeiconsEaseCurveControlPoints: typeof import('~icons/hugeicons/ease-curve-control-points.jsx')['default']
const IconIcRoundSearch: typeof import('~icons/ic/round-search.jsx')['default']
const IconLucideBell: typeof import('~icons/lucide/bell.jsx')['default']
+ const IconLucideBug: typeof import('~icons/lucide/bug.jsx')['default']
const IconLucideCamera: typeof import('~icons/lucide/camera.jsx')['default']
const IconLucideCheck: typeof import('~icons/lucide/check.jsx')['default']
const IconLucideChevronDown: typeof import('~icons/lucide/chevron-down.jsx')['default']