Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions apps/desktop/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2179,11 +2179,18 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
hotkeys::init(&app);
general_settings::init(&app);
fake_window::init(&app);
app.manage(target_select_overlay::WindowFocusManager::default());
app.manage(target_select_overlay::State::default());
app.manage(EditorWindowIds::default());
#[cfg(target_os = "macos")]
app.manage(crate::platform::ScreenCapturePrewarmer::default());

tokio::spawn({
let app = app.clone();
async move {
target_select_overlay::init(&app).await;
}
});

tokio::spawn({
let camera_feed = camera_feed.clone();
let app = app.clone();
Expand Down Expand Up @@ -2351,7 +2358,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
if let Ok(CapWindowId::TargetSelectOverlay { .. }) =
CapWindowId::from_str(&id)
{
let _ = window.close();
let _ = window.hide();
}
}

Expand Down Expand Up @@ -2416,10 +2423,6 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
}
return;
}
CapWindowId::TargetSelectOverlay { display_id } => {
app.state::<target_select_overlay::WindowFocusManager>()
.destroy(&display_id, app.global_shortcut());
}
CapWindowId::Camera => {
let app = app.clone();
tokio::spawn(async move {
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop/src-tauri/src/recording.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ pub async fn start_recording(
.filter_map(|(label, win)| CapWindowId::from_str(label).ok().map(|id| (id, win)))
{
if matches!(id, CapWindowId::TargetSelectOverlay { .. }) {
win.close().ok();
win.hide().ok();
}
}
let _ = ShowCapWindow::InProgressRecording { countdown }
Expand Down
178 changes: 80 additions & 98 deletions apps/desktop/src-tauri/src/target_select_overlay.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::{
collections::HashMap,
str::FromStr,
sync::{Mutex, PoisonError},
time::Duration,
};

use base64::prelude::*;
use cap_recording::screen_capture::ScreenCaptureTarget;
use futures::future::join_all;

use crate::windows::{CapWindowId, ShowCapWindow};
use scap_targets::{
Expand All @@ -15,8 +15,8 @@ use scap_targets::{
};
use serde::Serialize;
use specta::Type;
use tauri::{AppHandle, Manager, WebviewWindow};
use tauri_plugin_global_shortcut::{GlobalShortcut, GlobalShortcutExt};
use tauri::{AppHandle, Manager};
use tauri_plugin_global_shortcut::GlobalShortcutExt;
use tauri_specta::Event;
use tokio::task::JoinHandle;
use tracing::{error, instrument};
Expand All @@ -41,22 +41,67 @@ pub struct DisplayInformation {
refresh_rate: String,
}

// We create the windows hidden at app launch so they are ready when used.
// Otherwise we have noticed they can take a while to load on first interaction (especially on Windows).
pub async fn init(app: &AppHandle) {
join_all(
scap_targets::Display::list()
.into_iter()
.map(|d| d.id())
.map(|display_id| {
let app = app.clone();

async move {
let result = ShowCapWindow::TargetSelectOverlay { display_id }
.show(&app)
.await
.map_err(|err| error!("Error initializing target select overlay: {err}"));

if let Ok(window) = result {
window.hide().ok();
}
}
}),
)
.await;
}

#[derive(Default)]
pub struct State(Mutex<Option<JoinHandle<()>>>);

#[specta::specta]
#[tauri::command]
#[instrument(skip(app, state))]
pub async fn open_target_select_overlays(
app: AppHandle,
state: tauri::State<'_, WindowFocusManager>,
state: tauri::State<'_, State>,
focused_target: Option<ScreenCaptureTarget>,
) -> Result<(), String> {
let displays = scap_targets::Display::list()
.into_iter()
.map(|d| d.id())
.collect::<Vec<_>>();
for display_id in displays {
let _ = ShowCapWindow::TargetSelectOverlay { display_id }
.show(&app)
.await;
let windows = join_all(
scap_targets::Display::list()
.into_iter()
.map(|d| d.id())
.map(|display_id| {
let app = app.clone();

async move {
ShowCapWindow::TargetSelectOverlay { display_id }
.show(&app)
.await
.map_err(|err| error!("Error initializing target select overlay: {err}"))
.ok()
}
}),
)
.await;

for window in windows {
if let Some(window) = window {
window
.show()
.map_err(|err| error!("Error showing target select overlay: {err}"))
.ok();
}
}

let handle = tokio::spawn({
Expand Down Expand Up @@ -93,7 +138,7 @@ pub async fn open_target_select_overlays(
});

if let Some(task) = state
.task
.0
.lock()
.unwrap_or_else(PoisonError::into_inner)
.replace(handle)
Expand All @@ -112,14 +157,33 @@ pub async fn open_target_select_overlays(

#[specta::specta]
#[tauri::command]
#[instrument(skip(app))]
pub async fn close_target_select_overlays(app: AppHandle) -> Result<(), String> {
#[instrument(skip(app, state))]
pub async fn close_target_select_overlays(
app: AppHandle,
state: tauri::State<'_, State>,
) -> Result<(), String> {
for (id, window) in app.webview_windows() {
if let Ok(CapWindowId::TargetSelectOverlay { .. }) = CapWindowId::from_str(&id) {
let _ = window.close();
window
.hide()
.map_err(|err| error!("Error hiding target select overlay: {err}"))
.ok();
}
}

if let Some(task) = state
.0
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
{
task.abort();
app.global_shortcut()
.unregister("Escape")
.map_err(|err| error!("Error unregistering global keyboard shortcut for Escape: {err}"))
.ok();
}

Ok(())
}

Expand Down Expand Up @@ -210,85 +274,3 @@ pub async fn focus_window(window_id: WindowId) -> Result<(), String> {

Ok(())
}

// Windows doesn't have a proper concept of window z-index's so we implement them in userspace :(
#[derive(Default)]
pub struct WindowFocusManager {
task: Mutex<Option<JoinHandle<()>>>,
tasks: Mutex<HashMap<String, JoinHandle<()>>>,
}

impl WindowFocusManager {
/// Called when a window is created to spawn it's task
pub fn spawn(&self, id: &DisplayId, window: WebviewWindow) {
let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);
tasks.insert(
id.to_string(),
tokio::spawn(async move {
let app = window.app_handle();
loop {
let cap_main = CapWindowId::Main.get(app);
let cap_settings = CapWindowId::Settings.get(app);

let has_cap_main = cap_main
.as_ref()
.and_then(|v| Some(v.is_minimized().ok()? || !v.is_visible().ok()?))
.unwrap_or(true);
let has_cap_settings = cap_settings
.and_then(|v| Some(v.is_minimized().ok()? || !v.is_visible().ok()?))
.unwrap_or(true);

// Close the overlay if the cap main and settings are not available.
if has_cap_main && has_cap_settings {
window.hide().ok();
break;
}

#[cfg(windows)]
if let Some(cap_main) = cap_main {
let should_refocus = cap_main.is_focused().ok().unwrap_or_default()
|| window.is_focused().unwrap_or_default();

// If a Cap window is not focused we know something is trying to steal the focus.
// We need to move the overlay above it. We don't use `always_on_top` on the overlay because we need the Cap window to stay above it.
if !should_refocus {
window.set_focus().ok();
}
}

tokio::time::sleep(std::time::Duration::from_millis(400)).await;
}
}),
);
}

/// Called when a specific overlay window is destroyed to cleanup it's resources
pub fn destroy<R: tauri::Runtime>(&self, id: &DisplayId, global_shortcut: &GlobalShortcut<R>) {
let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(task) = tasks.remove(&id.to_string()) {
task.abort();
}

// When all overlay windows are closed cleanup shared resources.
if tasks.is_empty() {
// Unregister keyboard shortcut
// This messes with other applications if we don't remove it.
global_shortcut
.unregister("Escape")
.map_err(|err| {
error!("Error unregistering global keyboard shortcut for Escape: {err}")
})
.ok();

// Shutdown the cursor tracking task
if let Some(task) = self
.task
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
{
task.abort();
}
}
}
}
9 changes: 0 additions & 9 deletions apps/desktop/src-tauri/src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ use crate::{
general_settings::{self, AppTheme, GeneralSettingsStore},
permissions,
recording_settings::RecordingTargetMode,
target_select_overlay::WindowFocusManager,
window_exclusion::WindowExclusion,
};

Expand Down Expand Up @@ -366,14 +365,6 @@ impl ShowCapWindow {
}
}

app.state::<WindowFocusManager>()
.spawn(display_id, window.clone());

#[cfg(target_os = "macos")]
{
crate::platform::set_window_level(window.as_ref().window(), 45);
}

window
}
Self::Settings { page } => {
Expand Down
54 changes: 54 additions & 0 deletions apps/desktop/src/routes/(window-chrome)/new-main/BaseControls.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { createMutation } from "@tanstack/solid-query";
import { onMount } from "solid-js";
import { createCameraMutation } from "~/utils/queries";
import { commands } from "~/utils/tauri";
import { useRecordingOptions } from "../OptionsContext";
import CameraSelect from "./CameraSelect";
import MicrophoneSelect from "./MicrophoneSelect";
import SystemAudio from "./SystemAudio";
import { useSystemHardwareOptions } from "./useSystemHardwareOptions";

export function BaseControls() {
const { rawOptions, setOptions } = useRecordingOptions();
const { cameras, mics, options } = useSystemHardwareOptions();

const setCamera = createCameraMutation();
const setMicInput = createMutation(() => ({
mutationFn: async (name: string | null) => {
await commands.setMicInput(name);
setOptions("micName", name);
},
}));

onMount(() => {
if (rawOptions.cameraID && "ModelID" in rawOptions.cameraID)
setCamera.mutate({ ModelID: rawOptions.cameraID.ModelID });
else if (rawOptions.cameraID && "DeviceID" in rawOptions.cameraID)
setCamera.mutate({ DeviceID: rawOptions.cameraID.DeviceID });
else setCamera.mutate(null);
});

return (
<div class="space-x-2 grid grid-cols-2">
<CameraSelect
disabled={cameras.isPending}
options={cameras.data ?? []}
value={options.camera() ?? null}
onChange={(c) => {
if (!c) setCamera.mutate(null);
else if (c.model_id) setCamera.mutate({ ModelID: c.model_id });
else setCamera.mutate({ DeviceID: c.device_id });
}}
/>
<MicrophoneSelect
disabled={mics.isPending}
options={mics.isPending ? [] : (mics.data ?? [])}
value={
mics.isPending ? rawOptions.micName : (options.micName() ?? null)
}
onChange={(v) => setMicInput.mutate(v)}
/>
{/*<SystemAudio />*/}
</div>
);
}
Loading
Loading