Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

wip(desktop-gpui): local onboarding, sign-in and shortcuts work from 2026-10-15

Richie McIlroy3ead838ca547
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock
index 9be0e0e0a..9738114ae 100644
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@ -1565,6 +1565,7 @@ dependencies = [
"jpeg-decoder",
"kameo",
"libc",
+ "lyon_tessellation",
"minisign-verify",
"objc2 0.5.2",
"objc2-app-kit 0.2.2",
diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml
index f0823efa0..704e3cf65 100644
--- a/apps/desktop-gpui/Cargo.toml
+++ b/apps/desktop-gpui/Cargo.toml
@@ -116,6 +116,8 @@ global-hotkey = "0.7.0"
# cap-recording's actor system; version must match its `kameo = "0.17.2"`.
kameo = "0.17.2"
flume = "0.11.0"
+# Round caps and joins for the onboarding doodles; already in the tree via gpui.
+lyon_tessellation = "1.0"
anyhow = "1"
chrono = "0.4"
# Read the Tauri app's settings store so both apps share one recordings library.
diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs
index ae2ecce79..7dabb4d08 100644
--- a/apps/desktop-gpui/src/app_windows.rs
+++ b/apps/desktop-gpui/src/app_windows.rs
@@ -1417,6 +1417,7 @@ pub fn open_onboarding(cx: &mut App) {
}
pub fn onboarding_finished(cx: &mut App) {
+ crate::permission_guide::stop(cx);
if let Some(handle) = cx.global_mut::<AppWindows>().onboarding.take() {
handle
.update(cx, |_, window, _| window.remove_window())
@@ -1436,6 +1437,7 @@ pub fn close_onboarding(cx: &mut App) {
}
pub fn onboarding_closed(cx: &mut App) {
+ crate::permission_guide::stop(cx);
cx.global_mut::<AppWindows>().onboarding.take();
crate::tray::refresh_menu(cx);
if !crate::store::should_show_onboarding() {
@@ -2291,6 +2293,17 @@ fn overlay_window_ids(cx: &mut App) -> Vec<scap_targets::WindowId> {
.collect()
}
+/// The overlay's "Sign In To Use": close the picker and put the sign-in
+/// prompt on the main window, brought forward even when the picker was opened
+/// from the tray with the main window closed.
+pub fn show_instant_sign_in(kind: crate::main_window::TargetType, cx: &mut App) {
+ dismiss_target_overlays(cx);
+ let main = cx.global::<AppWindows>().main;
+ main.update(cx, |view, _, cx| view.show_sign_in_prompt(kind, cx))
+ .ok();
+ show_main_window(cx);
+}
+
pub fn start_recording_from_overlay(target: ScreenCaptureTarget, cx: &mut App) {
let main = cx.global::<AppWindows>().main;
if RecordingSession::global(cx).read(cx).phase != Phase::Idle
diff --git a/apps/desktop-gpui/src/assets.rs b/apps/desktop-gpui/src/assets.rs
index 73e899420..1cf6aee94 100644
--- a/apps/desktop-gpui/src/assets.rs
+++ b/apps/desktop-gpui/src/assets.rs
@@ -136,8 +136,6 @@ const ICONS: &[(&str, &[u8])] = assets!("icons":
"scan-text.svg",
"screen.svg",
"screenshot.svg",
- // The onboarding permissions surface's header badge.
- "shield.svg",
"stop-circle.svg",
"search.svg",
"settings.svg",
diff --git a/apps/desktop-gpui/src/auth.rs b/apps/desktop-gpui/src/auth.rs
index 072cdab5c..f0841d6fe 100644
--- a/apps/desktop-gpui/src/auth.rs
+++ b/apps/desktop-gpui/src/auth.rs
@@ -1,10 +1,13 @@
use std::collections::HashMap;
+use std::future::Future;
use std::io::{Read, Write};
-use std::net::TcpListener;
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::{Mutex, OnceLock};
+use std::net::{TcpListener, TcpStream};
+use std::pin::pin;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
+use futures_util::future::{Either, select};
use serde_json::{Value, json};
use crate::store::{self, DEFAULT_SERVER_URL};
@@ -39,7 +42,24 @@ const CALLBACK_HTML: &str = r#"<!DOCTYPE html>
</html>
"#;
-static DEEP_LINK: OnceLock<Mutex<Option<flume::Sender<String>>>> = OnceLock::new();
+pub const SIGN_IN_TIMEOUT: Duration = Duration::from_secs(15 * 60);
+
+/// How long the loopback server keeps answering after sign-in completes. The
+/// web's desktop redirect page tries the deep link first and then navigates to
+/// the loopback URL ~1.8s later whether or not the deep link worked, so a
+/// server that closed on the deep link would leave the browser on a
+/// "connection refused" page.
+const CALLBACK_LINGER: Duration = Duration::from_secs(30);
+
+const NOT_FOUND_HTML: &str = "<!DOCTYPE html><html><body>Not found</body></html>";
+
+static DEEP_LINK: OnceLock<Mutex<Option<DeepLinkSlot>>> = OnceLock::new();
+static NEXT_SESSION_ID: AtomicU64 = AtomicU64::new(1);
+
+struct DeepLinkSlot {
+ session: u64,
+ tx: flume::Sender<String>,
+}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthParams {
@@ -85,59 +105,136 @@ impl std::fmt::Display for AuthApiError {
pub struct SignInSession {
pub url: String,
- local: flume::Receiver<Option<AuthParams>>,
+ id: u64,
+ local: Option<flume::Receiver<AuthParams>>,
deep: flume::Receiver<String>,
- cancel: ArcAtomic,
+ callback: Arc<CallbackControl>,
}
-type ArcAtomic = std::sync::Arc<AtomicBool>;
+#[derive(Default)]
+struct CallbackControl {
+ stop: AtomicBool,
+ completed: AtomicBool,
+}
-pub fn begin_sign_in(cancel: ArcAtomic) -> Result<SignInSession, String> {
- let server_url = store::GeneralSettings::load().server_url;
- let local_only = should_use_local_server_session(&server_url);
- let local = start_local_callback(cancel.clone())?;
- let (deep_tx, deep_rx) = flume::bounded(1);
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum SignInWaitError {
+ TimedOut,
+}
+
+/// Start one sign-in attempt: a loopback callback server, a deep-link slot,
+/// and the browser URL that leads back to either. Dropping the session tears
+/// both down.
+pub fn begin_sign_in() -> SignInSession {
+ let server = server_url();
+ let local_only = should_use_local_server_session(&server);
+ let id = NEXT_SESSION_ID.fetch_add(1, Ordering::Relaxed);
+ let callback = Arc::new(CallbackControl::default());
+
+ // Without a port the server redirects straight to the `cap-desktop://`
+ // deep link, so a failed bind degrades to the deep-link path instead of
+ // failing sign-in outright.
+ let local = match start_local_callback(callback.clone()) {
+ Ok(local) => Some(local),
+ Err(error) => {
+ tracing::warn!(
+ "sign-in loopback server unavailable, using the deep link only: {error}"
+ );
+ None
+ }
+ };
+
+ let (deep_tx, deep_rx) = flume::bounded(8);
*deep_link_slot()
.lock()
- .unwrap_or_else(|error| error.into_inner()) = Some(deep_tx);
-
- let mut request = format!("{server_url}/api/desktop/session/request?type=api_key");
- request.push_str(&format!("&port={}", local.port));
- request.push_str(&format!(
- "&platform={}",
- if local_only { "web" } else { "desktop" }
- ));
-
- Ok(SignInSession {
- url: request,
- local: local.complete,
+ .unwrap_or_else(|error| error.into_inner()) = Some(DeepLinkSlot {
+ session: id,
+ tx: deep_tx,
+ });
+
+ SignInSession {
+ url: sign_in_request_url(&server, local.as_ref().map(|local| local.port), local_only),
+ id,
+ local: local.map(|local| local.complete),
deep: deep_rx,
- cancel,
- })
+ callback,
+ }
+}
+
+fn sign_in_request_url(server: &str, port: Option<u16>, local_only: bool) -> String {
+ let mut url = format!("{server}/api/desktop/session/request?type=api_key");
+ if let Some(port) = port {
+ url.push_str(&format!("&port={port}"));
+ }
+ url.push_str(if local_only {
+ "&platform=web"
+ } else {
+ "&platform=desktop"
+ });
+ url
}
impl SignInSession {
- pub fn complete(self) -> Result<bool, String> {
- let result = wait_for_auth(self.local, self.deep, self.cancel.clone());
- *deep_link_slot()
+ /// Resolve with whichever callback arrives first -- the loopback request or
+ /// the `cap-desktop://` deep link -- or time out.
+ pub async fn wait(
+ &self,
+ timeout: impl Future<Output = ()>,
+ ) -> Result<AuthParams, SignInWaitError> {
+ let local = async {
+ match &self.local {
+ Some(local) => match local.recv_async().await {
+ Ok(params) => params,
+ Err(_) => std::future::pending().await,
+ },
+ None => std::future::pending().await,
+ }
+ };
+ let deep = async {
+ loop {
+ match self.deep.recv_async().await {
+ Ok(url) => {
+ if let Some(params) = parse_auth_params(&url) {
+ break params;
+ }
+ }
+ Err(_) => std::future::pending::<()>().await,
+ }
+ }
+ };
+ let local = pin!(local);
+ let deep = pin!(deep);
+ let timeout = pin!(timeout);
+ match select(select(local, deep), timeout).await {
+ Either::Left((Either::Left((params, _)) | Either::Right((params, _)), _)) => Ok(params),
+ Either::Right(_) => Err(SignInWaitError::TimedOut),
+ }
+ }
+
+ pub fn mark_completed(&self) {
+ self.callback.completed.store(true, Ordering::Release);
+ }
+}
+
+impl Drop for SignInSession {
+ fn drop(&mut self) {
+ if !self.callback.completed.load(Ordering::Acquire) {
+ self.callback.stop.store(true, Ordering::Release);
+ }
+ let mut slot = deep_link_slot()
.lock()
- .unwrap_or_else(|error| error.into_inner()) = None;
- if self.cancel.load(Ordering::Relaxed) {
- return Ok(false);
+ .unwrap_or_else(|error| error.into_inner());
+ if slot.as_ref().is_some_and(|slot| slot.session == self.id) {
+ *slot = None;
}
- let Some(params) = result? else {
- return Ok(false);
- };
- process_auth_data(params)?;
- Ok(true)
}
}
pub fn submit_deep_link(url: &str) {
let slot = deep_link_slot();
let guard = slot.lock().unwrap_or_else(|error| error.into_inner());
- if let Some(tx) = guard.as_ref() {
- let _ = tx.send(url.to_string());
+ if let Some(slot) = guard.as_ref() {
+ let _ = slot.tx.try_send(url.to_string());
}
}
@@ -290,22 +387,20 @@ pub async fn update_auth_plan() -> Result<(), AuthApiError> {
if !snapshot.signed_in() {
return Err(AuthApiError::InvalidAuthentication);
}
+ let account = auth_identity(&store::store_section("auth"));
- let mut auth = store::store_section("auth");
+ let mut plan = None;
if !snapshot.plan_manual {
match authed_request(reqwest::Method::GET, "/api/desktop/plan", None).await {
Ok(response) if response.status().is_success() => {
if let Ok(body) = response.json::<Value>().await
&& let Some(upgraded) = body.get("upgraded").and_then(Value::as_bool)
{
- auth.insert(
- "plan".into(),
- json!({
- "upgraded": upgraded,
- "manual": false,
- "last_checked": chrono::Utc::now().timestamp() as i32,
- }),
- );
+ plan = Some(json!({
+ "upgraded": upgraded,
+ "manual": false,
+ "last_checked": chrono::Utc::now().timestamp() as i32,
+ }));
}
}
Ok(response) => tracing::warn!("Plan fetch returned {}", response.status()),
@@ -313,137 +408,179 @@ pub async fn update_auth_plan() -> Result<(), AuthApiError> {
}
}
+ let mut organizations = None;
+ let mut organizations_failed = false;
match authed_request(reqwest::Method::GET, "/api/desktop/organizations", None).await {
Ok(response) if response.status().is_success() => {
if let Ok(orgs) = response.json::<Value>().await {
- auth.insert("organizations".into(), orgs);
- auth.insert(
- "organizations_updated_at".into(),
- json!(chrono::Utc::now().timestamp() as i32),
- );
+ organizations = Some(orgs);
}
}
Ok(response) => tracing::warn!("Organizations fetch returned {}", response.status()),
Err(error) => {
tracing::warn!("Failed to fetch organizations: {error}");
- if auth
+ organizations_failed = true;
+ }
+ }
+
+ // Merged into the auth section as it is on disk now, and only if it still
+ // belongs to the account these responses are for: a sign-out or account
+ // switch during the requests must not be overwritten by the old session.
+ let mut stale = false;
+ let persisted = store::update_store_section("auth", |auth| {
+ if account.is_none() || auth_identity(auth) != account {
+ stale = true;
+ return false;
+ }
+ if let Some(plan) = plan {
+ auth.insert("plan".into(), plan);
+ }
+ let now = json!(chrono::Utc::now().timestamp() as i32);
+ if let Some(orgs) = organizations {
+ auth.insert("organizations".into(), orgs);
+ auth.insert("organizations_updated_at".into(), now);
+ } else if organizations_failed
+ && auth
.get("organizations")
.and_then(Value::as_array)
.is_none_or(Vec::is_empty)
- {
- auth.insert(
- "organizations_updated_at".into(),
- json!(chrono::Utc::now().timestamp() as i32),
- );
- }
+ {
+ auth.insert("organizations_updated_at".into(), now);
}
+ true
+ });
+ if stale {
+ return Err(AuthApiError::InvalidAuthentication);
}
-
- if !store::set_auth(Some(Value::Object(auth))) {
+ if !persisted {
return Err(AuthApiError::Other("Failed to persist auth plan".into()));
}
Ok(())
}
-fn wait_for_auth(
- local: flume::Receiver<Option<AuthParams>>,
- deep: flume::Receiver<String>,
- cancel: ArcAtomic,
-) -> Result<Option<AuthParams>, String> {
- let deadline = Instant::now() + Duration::from_secs(10 * 60);
+fn auth_identity(auth: &serde_json::Map<String, Value>) -> Option<(Value, Value)> {
+ Some((auth.get("user_id")?.clone(), auth.get("secret")?.clone()))
+}
+
+struct LocalCallback {
+ port: u16,
+ complete: flume::Receiver<AuthParams>,
+}
+
+fn start_local_callback(control: Arc<CallbackControl>) -> std::io::Result<LocalCallback> {
+ let listener = TcpListener::bind("127.0.0.1:0")?;
+ listener.set_nonblocking(true)?;
+ let port = listener.local_addr()?.port();
+ let (tx, rx) = flume::bounded(1);
+ std::thread::Builder::new()
+ .name("cap-sign-in-callback".into())
+ .spawn(move || serve_local_callback(listener, port, &control, &tx))?;
+ Ok(LocalCallback { port, complete: rx })
+}
+
+fn serve_local_callback(
+ listener: TcpListener,
+ port: u16,
+ control: &CallbackControl,
+ tx: &flume::Sender<AuthParams>,
+) {
+ let started = Instant::now();
+ let mut completed_at = None;
loop {
- if cancel.load(Ordering::Relaxed) {
- return Ok(None);
+ if control.stop.load(Ordering::Acquire) {
+ return;
}
- if Instant::now() >= deadline {
- return Err("Sign in timed out".into());
+ if control.completed.load(Ordering::Acquire)
+ && completed_at.get_or_insert_with(Instant::now).elapsed() >= CALLBACK_LINGER
+ {
+ return;
}
- match local.try_recv() {
- Ok(value) => return Ok(value),
- Err(flume::TryRecvError::Disconnected) => return Ok(None),
- Err(flume::TryRecvError::Empty) => {}
+ if started.elapsed() >= SIGN_IN_TIMEOUT + CALLBACK_LINGER {
+ return;
}
- match deep.try_recv() {
- Ok(url) => {
- if let Some(params) = parse_auth_params(&url) {
- return Ok(Some(params));
+ match listener.accept() {
+ Ok((stream, _)) => {
+ let tx = tx.clone();
+ let spawned = std::thread::Builder::new()
+ .name("cap-sign-in-request".into())
+ .spawn(move || handle_callback_connection(stream, port, &tx));
+ if let Err(error) = spawned {
+ tracing::warn!("sign-in callback connection thread: {error}");
}
}
- Err(flume::TryRecvError::Disconnected) => {}
- Err(flume::TryRecvError::Empty) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ Err(error) => {
+ tracing::warn!("sign-in callback accept: {error}");
+ std::thread::sleep(Duration::from_millis(50));
+ }
}
- std::thread::sleep(Duration::from_millis(50));
}
}
-struct LocalCallback {
- port: u16,
- complete: flume::Receiver<Option<AuthParams>>,
-}
-
-fn start_local_callback(cancel: ArcAtomic) -> Result<LocalCallback, String> {
- let listener = TcpListener::bind("127.0.0.1:0").map_err(|error| error.to_string())?;
- listener
- .set_nonblocking(true)
- .map_err(|error| error.to_string())?;
- let port = listener
- .local_addr()
- .map_err(|error| error.to_string())?
- .port();
- let (tx, rx) = flume::bounded(1);
- std::thread::spawn(move || {
- let started = Instant::now();
- loop {
- if cancel.load(Ordering::Relaxed) {
- let _ = tx.send(None);
- return;
- }
- if started.elapsed() > Duration::from_secs(10 * 60) {
- let _ = tx.send(None);
- return;
- }
- match listener.accept() {
- Ok((mut stream, _)) => {
- let mut buffer = [0u8; 4096];
- let read = match stream.read(&mut buffer) {
- Ok(read) => read,
- Err(_) => continue,
- };
- let request = String::from_utf8_lossy(&buffer[..read]);
- let path = request.lines().next().and_then(|line| {
- let mut parts = line.split_whitespace();
- let _method = parts.next()?;
- parts.next()
- });
- let url = path
- .map(|path| format!("http://127.0.0.1:{port}{path}"))
- .unwrap_or_default();
- let body = CALLBACK_HTML;
- let response = format!(
- "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nCache-Control: no-store, no-cache, must-revalidate\r\nPragma: no-cache\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
- body.len()
- );
- let _ = stream.write_all(response.as_bytes());
- let _ = stream.flush();
- if url.contains("token") || url.contains("api_key") {
- let _ = tx.send(parse_auth_params(&url));
- return;
- }
- }
- Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
- std::thread::sleep(Duration::from_millis(50));
- }
- Err(_) => {
- let _ = tx.send(None);
- return;
- }
- }
+fn handle_callback_connection(mut stream: TcpStream, port: u16, tx: &flume::Sender<AuthParams>) {
+ // BSD sockets inherit O_NONBLOCK from the listener, so on macOS a stream
+ // accepted from the non-blocking listener reads WouldBlock until the
+ // browser's request bytes land. Treating that as a failed read dropped the
+ // callback and left sign-in waiting forever.
+ if stream.set_nonblocking(false).is_err()
+ || stream
+ .set_read_timeout(Some(Duration::from_secs(5)))
+ .is_err()
+ || stream
+ .set_write_timeout(Some(Duration::from_secs(5)))
+ .is_err()
+ {
+ return;
+ }
+ let Some(target) = read_request_target(&mut stream) else {
+ return;
+ };
+ let params = parse_auth_params(&format!("http://127.0.0.1:{port}{target}"));
+ let (status, body) = if params.is_some() {
+ ("200 OK", CALLBACK_HTML)
+ } else {
+ ("404 Not Found", NOT_FOUND_HTML)
+ };
+ if let Some(params) = params {
+ let _ = tx.try_send(params);
+ }
+ let response = format!(
+ "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nCache-Control: no-store, no-cache, must-revalidate\r\nPragma: no-cache\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes());
+ let _ = stream.flush();
+ let _ = stream.shutdown(std::net::Shutdown::Write);
+}
+
+/// The request target of an HTTP/1 request, after reading the whole header
+/// block: closing a socket with unread request bytes makes the kernel answer
+/// with a reset, which browsers show as an error page instead of ours.
+fn read_request_target(stream: &mut impl Read) -> Option<String> {
+ const MAX_HEADER_BYTES: usize = 32 * 1024;
+ let mut request = Vec::with_capacity(1024);
+ let mut chunk = [0u8; 4096];
+ while !request.windows(4).any(|window| window == b"\r\n\r\n") {
+ if request.len() > MAX_HEADER_BYTES {
+ return None;
}
- });
- Ok(LocalCallback { port, complete: rx })
+ match stream.read(&mut chunk) {
+ Ok(0) => break,
+ Ok(read) => request.extend_from_slice(&chunk[..read]),
+ Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
+ Err(_) => break,
+ }
+ }
+ let request = String::from_utf8_lossy(&request);
+ let mut parts = request.lines().next()?.split_whitespace();
+ let _method = parts.next()?;
+ let target = parts.next()?;
+ target.starts_with('/').then(|| target.to_string())
}
-fn deep_link_slot() -> &'static Mutex<Option<flume::Sender<String>>> {
+fn deep_link_slot() -> &'static Mutex<Option<DeepLinkSlot>> {
DEEP_LINK.get_or_init(|| Mutex::new(None))
}
@@ -531,6 +668,119 @@ mod tests {
);
}
+ fn request(port: u16, delay: Duration, request: &str) -> String {
+ let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
+ stream
+ .set_read_timeout(Some(Duration::from_secs(10)))
+ .unwrap();
+ let (head, tail) = request.split_at(request.len() / 2);
+ std::thread::sleep(delay);
+ stream.write_all(head.as_bytes()).unwrap();
+ std::thread::sleep(delay);
+ stream.write_all(tail.as_bytes()).unwrap();
+ let mut response = String::new();
+ stream.read_to_string(&mut response).unwrap();
+ response
+ }
+
+ #[test]
+ fn loopback_callback_survives_a_slow_browser_and_keeps_serving() {
+ let control = Arc::new(CallbackControl::default());
+ let local = start_local_callback(control.clone()).unwrap();
+
+ let unrelated = request(
+ local.port,
+ Duration::ZERO,
+ "GET /favicon.ico HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n",
+ );
+ assert!(unrelated.starts_with("HTTP/1.1 404"), "{unrelated}");
+ assert!(local.complete.try_recv().is_err());
+
+ let callback = request(
+ local.port,
+ Duration::from_millis(300),
+ "GET /?type=api_key&api_key=key-1&user_id=user-1 HTTP/1.1\r\nHost: 127.0.0.1\r\nAccept: text/html\r\n\r\n",
+ );
+ assert!(callback.starts_with("HTTP/1.1 200"), "{callback}");
+ assert!(callback.contains("signed in"));
+ assert_eq!(
+ local.complete.recv_timeout(Duration::from_secs(5)).unwrap(),
+ AuthParams::ApiKey {
+ api_key: "key-1".into(),
+ user_id: "user-1".into(),
+ }
+ );
+
+ control.completed.store(true, Ordering::Release);
+ let fallback = request(
+ local.port,
+ Duration::ZERO,
+ "GET /?type=api_key&api_key=key-1&user_id=user-1 HTTP/1.1\r\n\r\n",
+ );
+ assert!(fallback.starts_with("HTTP/1.1 200"), "{fallback}");
+ control.stop.store(true, Ordering::Release);
+ }
+
+ #[test]
+ fn request_target_needs_a_path() {
+ let mut ok = "GET /?api_key=k HTTP/1.1\r\nHost: x\r\n\r\n".as_bytes();
+ assert_eq!(read_request_target(&mut ok).as_deref(), Some("/?api_key=k"));
+ let mut absolute = "GET http://evil/ HTTP/1.1\r\n\r\n".as_bytes();
+ assert_eq!(read_request_target(&mut absolute), None);
+ let mut empty = "".as_bytes();
+ assert_eq!(read_request_target(&mut empty), None);
+ }
+
+ #[test]
+ fn sign_in_url_omits_a_missing_port() {
+ assert_eq!(
+ sign_in_request_url("https://cap.so", Some(4280), false),
+ "https://cap.so/api/desktop/session/request?type=api_key&port=4280&platform=desktop"
+ );
+ assert_eq!(
+ sign_in_request_url("http://localhost:3000", None, true),
+ "http://localhost:3000/api/desktop/session/request?type=api_key&platform=web"
+ );
+ }
+
+ #[test]
+ fn a_finished_session_only_clears_its_own_deep_link_slot() {
+ let (old_tx, old_rx) = flume::bounded(1);
+ let old = SignInSession {
+ url: String::new(),
+ id: u64::MAX - 1,
+ local: None,
+ deep: old_rx,
+ callback: Arc::new(CallbackControl::default()),
+ };
+ drop(old_tx);
+ let (new_tx, new_rx) = flume::bounded(1);
+ *deep_link_slot().lock().unwrap() = Some(DeepLinkSlot {
+ session: u64::MAX,
+ tx: new_tx,
+ });
+ drop(old);
+ submit_deep_link("cap-desktop://signin?api_key=k&user_id=u");
+ assert_eq!(
+ new_rx.try_recv().unwrap(),
+ "cap-desktop://signin?api_key=k&user_id=u"
+ );
+ *deep_link_slot().lock().unwrap() = None;
+ }
+
+ #[test]
+ fn plan_refresh_identity_tracks_account_and_credential() {
+ let signed_in = json!({"user_id":"u","secret":{"api_key":"k"},"plan":null});
+ let refreshed_plan =
+ json!({"user_id":"u","secret":{"api_key":"k"},"plan":{"upgraded":true}});
+ let other_key = json!({"user_id":"u","secret":{"api_key":"k2"}});
+ let identity = |value: &Value| auth_identity(value.as_object().unwrap());
+ assert!(identity(&signed_in).is_some());
+ assert_eq!(identity(&signed_in), identity(&refreshed_plan));
+ assert_ne!(identity(&signed_in), identity(&other_key));
+ assert_eq!(identity(&json!({})), None);
+ }
+
#[test]
fn ignores_unrelated_urls() {
assert!(parse_auth_params("http://127.0.0.1:1/health").is_none());
diff --git a/apps/desktop-gpui/src/camera_window.rs b/apps/desktop-gpui/src/camera_window.rs
index c76750e37..0fa15b11a 100644
--- a/apps/desktop-gpui/src/camera_window.rs
+++ b/apps/desktop-gpui/src/camera_window.rs
@@ -700,7 +700,26 @@ fn overlay_metrics(size: f32) -> OverlayMetrics {
/// `camera_preview_error_message` (`lib.rs:755-774`) plus the fixed title
/// from `emit_camera_preview_error` (`lib.rs:776-784`). The error strings
/// come from the same `cap-recording` camera errors the Tauri app matches on.
+/// The camera is waiting on the macOS prompt: asked through the pickers, or
+/// a start in flight while macOS has not decided yet.
+fn awaiting_camera_access(cx: &gpui::App) -> bool {
+ use crate::permissions::{OSPermission, OSPermissionStatus};
+ let access = crate::media_access::MediaAccess::global(cx);
+ let access = access.read(cx);
+ access.requesting(OSPermission::Camera)
+ || (access.status(OSPermission::Camera) == OSPermissionStatus::NotDetermined
+ && crate::feeds::Feeds::global(cx)
+ .read(cx)
+ .camera_input_pending())
+}
+
fn camera_issue(error: &str) -> (&'static str, &'static str) {
+ if error.contains("access is unavailable") {
+ return (
+ "Camera access needed",
+ "Click to allow Cap to use your camera in System Settings.",
+ );
+ }
let message = if error.contains("DeviceNotFound") {
"This camera is no longer available. Check that it is connected and allowed by system permissions."
} else if error.contains("CameraTimeout") {
@@ -987,7 +1006,11 @@ struct CameraPreviewView {
/// repaint the whole preview for a message that did not change.
camera_error: Option<String>,
effect_issue: Option<(&'static str, &'static str)>,
+ /// Camera access is still being asked for: the prompt is up, so the
+ /// preview says so instead of spinning with no end.
+ awaiting_access: bool,
_feeds_subscription: Subscription,
+ _access_subscription: Subscription,
}
impl CameraPreviewView {
@@ -1031,7 +1054,21 @@ impl CameraPreviewView {
.detach();
}
let retained = retained.map(|retained| retained.image);
+ let access = crate::media_access::MediaAccess::global(cx);
+ let awaiting_access = awaiting_camera_access(cx);
+ let access_subscription = cx.observe(&access, |this: &mut Self, _, cx| {
+ let awaiting = awaiting_camera_access(cx);
+ if this.awaiting_access != awaiting {
+ this.awaiting_access = awaiting;
+ cx.notify();
+ }
+ });
let feeds_subscription = cx.observe(&feeds, |this: &mut Self, feeds, cx| {
+ let awaiting = awaiting_camera_access(cx);
+ if this.awaiting_access != awaiting {
+ this.awaiting_access = awaiting;
+ cx.notify();
+ }
let feeds = feeds.read(cx);
let error = feeds.camera_error.clone();
let camera = feeds.camera.clone();
@@ -1071,7 +1108,9 @@ impl CameraPreviewView {
paints,
camera_error,
effect_issue: None,
+ awaiting_access,
_feeds_subscription: feeds_subscription,
+ _access_subscription: access_subscription,
}
}
@@ -1160,7 +1199,9 @@ impl Render for CameraPreviewView {
let radius = self.radius;
let showing_frame = self.latest_frame.is_some() || self.retained.is_some();
- let has_issue = self.camera_error.is_some() || self.effect_issue.is_some();
+ let awaiting_access = self.awaiting_access && !showing_frame && self.camera_error.is_none();
+ let has_issue =
+ self.camera_error.is_some() || self.effect_issue.is_some() || awaiting_access;
let loading = if !showing_frame {
self.loading_fade_started = None;
@@ -1288,15 +1329,32 @@ impl Render for CameraPreviewView {
// the preview with a centred, size-scaled title + message. The
// `backdrop-blur-xs` behind it has no per-element hook in this gpui
// rev (the recording overlay documents the same gap).
+ let access_issue = self
+ .camera_error
+ .as_deref()
+ .is_some_and(|error| error.contains("access is unavailable"));
if let Some((title, message)) = self
.camera_error
.as_deref()
.map(camera_issue)
.or(self.effect_issue)
+ .or(awaiting_access.then_some((
+ "Waiting for camera access",
+ "Choose Allow in the macOS prompt.",
+ )))
{
let metrics = overlay_metrics(self.size);
container = container.child(
div()
+ .id("camera-issue")
+ .when(access_issue, |overlay| {
+ overlay.cursor_pointer().on_click(|_, _, cx| {
+ let access = crate::media_access::MediaAccess::global(cx);
+ access.update(cx, |access, cx| {
+ access.request(crate::permissions::OSPermission::Camera, cx)
+ });
+ })
+ })
.absolute()
.inset_0()
.flex()
diff --git a/apps/desktop-gpui/src/doodle.rs b/apps/desktop-gpui/src/doodle.rs
new file mode 100644
index 000000000..618c79973
--- /dev/null
+++ b/apps/desktop-gpui/src/doodle.rs
@@ -0,0 +1,816 @@
+//! Hand-drawn doodles: the ink language of Cap's Chrome extension pages and
+//! the web recorder, drawn natively.
+//!
+//! The web version is inline SVG with round-capped strokes, a "boil" filter
+//! (`feTurbulence` -> `feDisplacementMap`, seed stepping through four values
+//! every 150ms) and `stroke-dashoffset` draw-on. Here the same path data is
+//! flattened once, displaced by four seeded noise fields up front, and each
+//! paint picks the variant for the current 150ms slot and trims every stroke
+//! by arc length for its draw-on progress.
+
+use std::collections::HashMap;
+use std::sync::{Mutex, OnceLock};
+use std::time::Instant;
+
+use gpui::{
+ App, Bounds, Hsla, IntoElement, PathBuilder, PathStyle, Pixels, Styled, Window, canvas, point,
+ px,
+};
+use lyon_tessellation::{LineCap, LineJoin, StrokeOptions};
+
+const BOIL_FRAME_MS: u128 = 150;
+const BOIL_VARIANTS: usize = 4;
+const BOIL_AMPLITUDE: f32 = 1.25;
+const BOIL_WAVELENGTH: f32 = 20.;
+const FLATTEN_STEP: f32 = 1.5;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Ink {
+ Line,
+ Soft,
+ Accent,
+ Red,
+ Green,
+ Track,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Motion {
+ /// Always fully drawn.
+ Still,
+ /// `stroke-dashoffset` 1 -> 0.
+ Draw { delay: u32, duration: u32 },
+ /// Opacity 0 -> 1.
+ Fade { delay: u32, duration: u32 },
+ /// Scale 0.2 -> 1.2 -> 1 around the stroke's centre, fading in.
+ Pop { delay: u32, duration: u32 },
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Stroke {
+ pub d: &'static str,
+ pub ink: Ink,
+ pub width: f32,
+ pub motion: Motion,
+ /// Filled rather than stroked (dots, lens).
+ pub fill: bool,
+ /// Marching dashes: dash 2, gap 4.2, a full cycle every 1.1s.
+ pub march: bool,
+ /// Bob 0 -> -4 -> 0 units every 1.9s.
+ pub bob: bool,
+ /// Opacity breathing 1 -> 0.3 -> 1 every 1.2s once shown.
+ pub pulse: bool,
+}
+
+impl Stroke {
+ pub const fn ink(d: &'static str) -> Self {
+ Self {
+ d,
+ ink: Ink::Line,
+ width: 4.,
+ motion: Motion::Still,
+ fill: false,
+ march: false,
+ bob: false,
+ pulse: false,
+ }
+ }
+
+ pub const fn with_ink(mut self, ink: Ink) -> Self {
+ self.ink = ink;
+ self
+ }
+
+ pub const fn width(mut self, width: f32) -> Self {
+ self.width = width;
+ self
+ }
+
+ pub const fn draw(mut self, delay: u32, duration: u32) -> Self {
+ self.motion = Motion::Draw { delay, duration };
+ self
+ }
+
+ pub const fn fade(mut self, delay: u32, duration: u32) -> Self {
+ self.motion = Motion::Fade { delay, duration };
+ self
+ }
+
+ pub const fn pop(mut self, delay: u32, duration: u32) -> Self {
+ self.motion = Motion::Pop { delay, duration };
+ self
+ }
+
+ pub const fn filled(mut self) -> Self {
+ self.fill = true;
+ self
+ }
+
+ pub const fn marching(mut self) -> Self {
+ self.march = true;
+ self
+ }
+
+ pub const fn bobbing(mut self) -> Self {
+ self.bob = true;
+ self
+ }
+
+ pub const fn pulsing(mut self) -> Self {
+ self.pulse = true;
+ self
+ }
+
+ fn settled_at(&self) -> u32 {
+ match self.motion {
+ Motion::Still => 0,
+ Motion::Draw { delay, duration }
+ | Motion::Fade { delay, duration }
+ | Motion::Pop { delay, duration } => delay + duration,
+ }
+ }
+}
+
+pub struct Doodle {
+ pub view: (f32, f32),
+ pub strokes: &'static [Stroke],
+}
+
+impl Doodle {
+ /// When every entrance has finished, in ms after the doodle appeared.
+ pub fn settled_at(&self) -> u32 {
+ self.strokes
+ .iter()
+ .map(Stroke::settled_at)
+ .max()
+ .unwrap_or(0)
+ }
+
+ fn perpetual(&self) -> bool {
+ self.strokes
+ .iter()
+ .any(|stroke| stroke.march || stroke.bob || stroke.pulse)
+ }
+}
+
+#[derive(Clone, Copy)]
+pub struct Palette {
+ pub ink: Hsla,
+ pub soft: Hsla,
+ pub accent: Hsla,
+ pub red: Hsla,
+ pub green: Hsla,
+ pub track: Hsla,
+}
+
+impl Palette {
+ fn color(&self, ink: Ink) -> Hsla {
+ match ink {
+ Ink::Line => self.ink,
+ Ink::Soft => self.soft,
+ Ink::Accent => self.accent,
+ Ink::Red => self.red,
+ Ink::Green => self.green,
+ Ink::Track => self.track,
+ }
+ }
+}
+
+type Polyline = Vec<(f32, f32)>;
+
+struct Prepared {
+ /// Per stroke, per subpath: the un-boiled points and cumulative lengths.
+ strokes: Vec<PreparedStroke>,
+}
+
+struct PreparedStroke {
+ subpaths: Vec<PreparedSubpath>,
+ length: f32,
+ centre: (f32, f32),
+}
+
+struct PreparedSubpath {
+ variants: [Polyline; BOIL_VARIANTS],
+ cumulative: Vec<f32>,
+ closed: bool,
+}
+
+/// Every doodle's flattening and boil variants, built on first paint. A
+/// doodle is a `&'static`, so its address is a stable key.
+fn prepared(doodle: &'static Doodle) -> &'static Prepared {
+ static CACHE: OnceLock<Mutex<HashMap<usize, &'static Prepared>>> = OnceLock::new();
+ let key = doodle as *const Doodle as usize;
+ let mut cache = CACHE
+ .get_or_init(Default::default)
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
+ cache
+ .entry(key)
+ .or_insert_with(|| Box::leak(Box::new(prepare(doodle))))
+}
+
+fn prepare(doodle: &Doodle) -> Prepared {
+ Prepared {
+ strokes: doodle
+ .strokes
+ .iter()
+ .enumerate()
+ .map(|(index, stroke)| {
+ let subpaths: Vec<PreparedSubpath> = parse(stroke.d)
+ .into_iter()
+ .map(|(points, closed)| {
+ let mut cumulative = Vec::with_capacity(points.len());
+ let mut total = 0.;
+ for (i, point) in points.iter().enumerate() {
+ if i > 0 {
+ total += distance(points[i - 1], *point);
+ }
+ cumulative.push(total);
+ }
+ let variants = std::array::from_fn(|variant| {
+ boil(&points, (index * BOIL_VARIANTS + variant) as u32 + 1)
+ });
+ PreparedSubpath {
+ variants,
+ cumulative,
+ closed,
+ }
+ })
+ .collect();
+ let length = subpaths
+ .iter()
+ .map(|subpath| subpath.cumulative.last().copied().unwrap_or(0.))
+ .sum();
+ let (mut sx, mut sy, mut count) = (0., 0., 0.);
+ for subpath in &subpaths {
+ for &(x, y) in &subpath.variants[0] {
+ sx += x;
+ sy += y;
+ count += 1.;
+ }
+ }
+ PreparedStroke {
+ subpaths,
+ length,
+ centre: if count > 0. {
+ (sx / count, sy / count)
+ } else {
+ (0., 0.)
+ },
+ }
+ })
+ .collect(),
+ }
+}
+
+fn distance(a: (f32, f32), b: (f32, f32)) -> f32 {
+ ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt()
+}
+
+fn hash(x: i32, y: i32, seed: u32) -> f32 {
+ let mut h = (x as u32)
+ .wrapping_mul(374_761_393)
+ .wrapping_add((y as u32).wrapping_mul(668_265_263))
+ .wrapping_add(seed.wrapping_mul(2_246_822_519));
+ h = (h ^ (h >> 13)).wrapping_mul(1_274_126_177);
+ h ^= h >> 16;
+ (h & 0x00ff_ffff) as f32 / 0x00ff_ffff as f32
+}
+
+fn value_noise(x: f32, y: f32, seed: u32) -> f32 {
+ let (x0, y0) = (x.floor(), y.floor());
+ let (fx, fy) = (x - x0, y - y0);
+ let (sx, sy) = (fx * fx * (3. - 2. * fx), fy * fy * (3. - 2. * fy));
+ let (ix, iy) = (x0 as i32, y0 as i32);
+ let top = hash(ix, iy, seed) * (1. - sx) + hash(ix + 1, iy, seed) * sx;
+ let bottom = hash(ix, iy + 1, seed) * (1. - sx) + hash(ix + 1, iy + 1, seed) * sx;
+ top * (1. - sy) + bottom * sy
+}
+
+fn boil(points: &[(f32, f32)], seed: u32) -> Polyline {
+ points
+ .iter()
+ .map(|&(x, y)| {
+ let (nx, ny) = (x / BOIL_WAVELENGTH, y / BOIL_WAVELENGTH);
+ let dx = (value_noise(nx, ny, seed) - 0.5) * 2. * BOIL_AMPLITUDE;
+ let dy = (value_noise(nx + 31.7, ny + 17.3, seed ^ 0x9e37) - 0.5) * 2. * BOIL_AMPLITUDE;
+ (x + dx, y + dy)
+ })
+ .collect()
+}
+
+/// A tiny SVG path parser: `M L H V C Q T Z`, absolute or relative, with
+/// implicit repeats. No arcs; circles are written as four cubics. Curves are
+/// flattened to [`FLATTEN_STEP`]-unit segments.
+fn parse(d: &str) -> Vec<(Polyline, bool)> {
+ let mut tokens = Tokens::new(d);
+ let mut subpaths = Vec::new();
+ let mut current: Polyline = Vec::new();
+ let mut pen = (0., 0.);
+ let mut start = (0., 0.);
+ let mut last_quad: Option<(f32, f32)> = None;
+ let mut command = 'M';
+ while let Some(next) = tokens.command_or_number() {
+ if let Some(letter) = next {
+ command = letter;
+ }
+ let relative = command.is_ascii_lowercase();
+ let base = if relative { pen } else { (0., 0.) };
+ match command.to_ascii_uppercase() {
+ 'M' => {
+ let Some(to) = tokens.pair() else { break };
+ if current.len() > 1 {
+ subpaths.push((std::mem::take(&mut current), false));
+ }
+ current.clear();
+ pen = (base.0 + to.0, base.1 + to.1);
+ start = pen;
+ current.push(pen);
+ command = if relative { 'l' } else { 'L' };
+ last_quad = None;
+ }
+ 'L' => {
+ let Some(to) = tokens.pair() else { break };
+ pen = (base.0 + to.0, base.1 + to.1);
+ push_line(&mut current, pen);
+ last_quad = None;
+ }
+ 'H' => {
+ let Some(x) = tokens.number() else { break };
+ pen = (if relative { pen.0 + x } else { x }, pen.1);
+ push_line(&mut current, pen);
+ last_quad = None;
+ }
+ 'V' => {
+ let Some(y) = tokens.number() else { break };
+ pen = (pen.0, if relative { pen.1 + y } else { y });
+ push_line(&mut current, pen);
+ last_quad = None;
+ }
+ 'C' => {
+ let (Some(c1), Some(c2), Some(to)) = (tokens.pair(), tokens.pair(), tokens.pair())
+ else {
+ break;
+ };
+ let c1 = (base.0 + c1.0, base.1 + c1.1);
+ let c2 = (base.0 + c2.0, base.1 + c2.1);
+ let to = (base.0 + to.0, base.1 + to.1);
+ flatten_cubic(&mut current, pen, c1, c2, to);
+ pen = to;
+ last_quad = None;
+ }
+ 'Q' => {
+ let (Some(c), Some(to)) = (tokens.pair(), tokens.pair()) else {
+ break;
+ };
+ let c = (base.0 + c.0, base.1 + c.1);
+ let to = (base.0 + to.0, base.1 + to.1);
+ flatten_quad(&mut current, pen, c, to);
+ pen = to;
+ last_quad = Some(c);
+ }
+ 'T' => {
+ let Some(to) = tokens.pair() else { break };
+ let c = match last_quad {
+ Some(c) => (2. * pen.0 - c.0, 2. * pen.1 - c.1),
+ None => pen,
+ };
+ let to = (base.0 + to.0, base.1 + to.1);
+ flatten_quad(&mut current, pen, c, to);
+ pen = to;
+ last_quad = Some(c);
+ }
+ 'Z' => {
+ push_line(&mut current, start);
+ pen = start;
+ if current.len() > 1 {
+ subpaths.push((std::mem::take(&mut current), true));
+ }
+ last_quad = None;
+ }
+ _ => break,
+ }
+ }
+ if !current.is_empty() {
+ if current.len() == 1 {
+ let only = current[0];
+ current.push((only.0 + 0.01, only.1));
+ }
+ subpaths.push((current, false));
+ }
+ subpaths
+}
+
+fn push_line(points: &mut Polyline, to: (f32, f32)) {
+ let Some(&from) = points.last() else {
+ points.push(to);
+ return;
+ };
+ let steps = (distance(from, to) / FLATTEN_STEP).ceil().max(1.) as usize;
+ for step in 1..=steps {
+ let t = step as f32 / steps as f32;
+ points.push((from.0 + (to.0 - from.0) * t, from.1 + (to.1 - from.1) * t));
+ }
+}
+
+fn flatten_quad(points: &mut Polyline, from: (f32, f32), c: (f32, f32), to: (f32, f32)) {
+ let estimate = distance(from, c) + distance(c, to);
+ let steps = (estimate / FLATTEN_STEP).ceil().max(2.) as usize;
+ for step in 1..=steps {
+ let t = step as f32 / steps as f32;
+ let u = 1. - t;
+ points.push((
+ u * u * from.0 + 2. * u * t * c.0 + t * t * to.0,
+ u * u * from.1 + 2. * u * t * c.1 + t * t * to.1,
+ ));
+ }
+}
+
+fn flatten_cubic(
+ points: &mut Polyline,
+ from: (f32, f32),
+ c1: (f32, f32),
+ c2: (f32, f32),
+ to: (f32, f32),
+) {
+ let estimate = distance(from, c1) + distance(c1, c2) + distance(c2, to);
+ let steps = (estimate / FLATTEN_STEP).ceil().max(2.) as usize;
+ for step in 1..=steps {
+ let t = step as f32 / steps as f32;
+ let u = 1. - t;
+ let (a, b, c, d) = (u * u * u, 3. * u * u * t, 3. * u * t * t, t * t * t);
+ points.push((
+ a * from.0 + b * c1.0 + c * c2.0 + d * to.0,
+ a * from.1 + b * c1.1 + c * c2.1 + d * to.1,
+ ));
+ }
+}
+
+struct Tokens<'a> {
+ rest: &'a str,
+}
+
+impl<'a> Tokens<'a> {
+ fn new(d: &'a str) -> Self {
+ Self { rest: d }
+ }
+
+ fn skip_separators(&mut self) {
+ self.rest = self
+ .rest
+ .trim_start_matches(|c: char| c.is_whitespace() || c == ',');
+ }
+
+ /// `Some(Some(letter))` for a command, `Some(None)` when a number follows
+ /// (an implicit repeat of the previous command), `None` at the end.
+ fn command_or_number(&mut self) -> Option<Option<char>> {
+ self.skip_separators();
+ let first = self.rest.chars().next()?;
+ if first.is_ascii_alphabetic() {
+ self.rest = &self.rest[1..];
+ Some(Some(first))
+ } else {
+ Some(None)
+ }
+ }
+
+ fn number(&mut self) -> Option<f32> {
+ self.skip_separators();
+ let bytes = self.rest.as_bytes();
+ let mut end = 0;
+ let mut seen_dot = false;
+ while end < bytes.len() {
+ let c = bytes[end] as char;
+ let sign = (c == '-' || c == '+') && end == 0;
+ let dot = c == '.' && !seen_dot;
+ if !(c.is_ascii_digit() || sign || dot) {
+ break;
+ }
+ seen_dot |= dot;
+ end += 1;
+ }
+ if end == 0 {
+ return None;
+ }
+ let value = self.rest[..end].parse().ok();
+ self.rest = &self.rest[end..];
+ value
+ }
+
+ fn pair(&mut self) -> Option<(f32, f32)> {
+ Some((self.number()?, self.number()?))
+ }
+}
+
+fn ease(t: f32) -> f32 {
+ let t = t.clamp(0., 1.);
+ 1. - (1. - t).powi(3)
+}
+
+fn progress(motion: Motion, elapsed: f32) -> f32 {
+ match motion {
+ Motion::Still => 1.,
+ Motion::Draw { delay, duration }
+ | Motion::Fade { delay, duration }
+ | Motion::Pop { delay, duration } => {
+ ((elapsed - delay as f32) / duration.max(1) as f32).clamp(0., 1.)
+ }
+ }
+}
+
+/// The variant every doodle on screen shows right now: one shared clock so
+/// all of them boil in step, like the single SVG filter does.
+fn boil_frame() -> usize {
+ static CLOCK: OnceLock<Instant> = OnceLock::new();
+ let start = CLOCK.get_or_init(Instant::now);
+ ((start.elapsed().as_millis() / BOIL_FRAME_MS) as usize) % BOIL_VARIANTS
+}
+
+/// A settled, boil-only doodle needs a repaint every 150ms, not every frame:
+/// one refresh per window per boil slot, however many doodles it shows.
+fn schedule_boil_frame(window: &mut Window, cx: &mut App) {
+ static SCHEDULED: OnceLock<Mutex<HashMap<gpui::WindowId, u128>>> = OnceLock::new();
+ static CLOCK: OnceLock<Instant> = OnceLock::new();
+ let now = CLOCK.get_or_init(Instant::now).elapsed().as_millis();
+ let slot = now / BOIL_FRAME_MS + 1;
+ let id = window.window_handle().window_id();
+ {
+ let mut scheduled = SCHEDULED
+ .get_or_init(Default::default)
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
+ if scheduled.get(&id).is_some_and(|&pending| pending >= slot) {
+ return;
+ }
+ scheduled.insert(id, slot);
+ }
+ let wait = (slot * BOIL_FRAME_MS).saturating_sub(now) as u64;
+ window
+ .spawn(cx, async move |cx| {
+ cx.background_executor()
+ .timer(std::time::Duration::from_millis(wait))
+ .await;
+ cx.update(|window, _| window.refresh()).ok();
+ })
+ .detach();
+}
+
+/// Paint a doodle into a `width x height` box, its entrance timed from
+/// `shown_at`. `still` freezes the boil and skips the entrance (reduced
+/// motion, or a window in the background).
+pub fn doodle(
+ doodle: &'static Doodle,
+ palette: Palette,
+ shown_at: Instant,
+ still: bool,
+ width: f32,
+ height: f32,
+) -> impl IntoElement {
+ canvas(
+ |_, _, _| {},
+ move |bounds: Bounds<Pixels>, _, window: &mut Window, cx: &mut App| {
+ let elapsed = if still {
+ f32::MAX
+ } else {
+ shown_at.elapsed().as_secs_f32() * 1000.
+ };
+ let frame = if still { 0 } else { boil_frame() };
+ paint(doodle, palette, bounds, elapsed, frame, window);
+ if still {
+ return;
+ }
+ if elapsed < doodle.settled_at() as f32 + 50. || doodle.perpetual() {
+ window.request_animation_frame();
+ } else {
+ schedule_boil_frame(window, cx);
+ }
+ },
+ )
+ .w(px(width))
+ .h(px(height))
+}
+
+fn paint(
+ doodle: &'static Doodle,
+ palette: Palette,
+ bounds: Bounds<Pixels>,
+ elapsed: f32,
+ frame: usize,
+ window: &mut Window,
+) {
+ let prepared = prepared(doodle);
+ let (view_w, view_h) = doodle.view;
+ let scale = (f32::from(bounds.size.width) / view_w).min(f32::from(bounds.size.height) / view_h);
+ let origin_x =
+ f32::from(bounds.origin.x) + (f32::from(bounds.size.width) - view_w * scale) / 2.;
+ let origin_y =
+ f32::from(bounds.origin.y) + (f32::from(bounds.size.height) - view_h * scale) / 2.;
+ let seconds = elapsed / 1000.;
+
+ for (stroke, shape) in doodle.strokes.iter().zip(&prepared.strokes) {
+ let t = progress(stroke.motion, elapsed);
+ if t <= 0. {
+ continue;
+ }
+ let mut alpha = 1.;
+ let mut grow = 1.;
+ let mut drawn = 1.;
+ match stroke.motion {
+ Motion::Draw { .. } => drawn = ease(t),
+ Motion::Fade { .. } => alpha = ease(t),
+ Motion::Pop { .. } => {
+ alpha = ease(t);
+ grow = if t < 0.6 {
+ 0.2 + 1.0 * (t / 0.6)
+ } else {
+ 1.2 - 0.2 * ((t - 0.6) / 0.4)
+ };
+ }
+ Motion::Still => {}
+ }
+ if stroke.pulse && elapsed.is_finite() && elapsed < f32::MAX / 2. {
+ let cycle = (seconds / 1.2).fract();
+ alpha *= 0.65 + 0.35 * (std::f32::consts::TAU * cycle).cos();
+ }
+ let bob = if stroke.bob && elapsed < f32::MAX / 2. {
+ let cycle = (seconds / 1.9).fract();
+ -4. * (0.5 - 0.5 * (std::f32::consts::TAU * cycle).cos())
+ } else {
+ 0.
+ };
+ let mut color = palette.color(stroke.ink);
+ color.a *= alpha;
+ if color.a <= 0.001 {
+ continue;
+ }
+
+ let map = |(x, y): (f32, f32)| {
+ let (cx, cy) = shape.centre;
+ let x = cx + (x - cx) * grow;
+ let y = cy + (y - cy) * grow + bob;
+ point(px(origin_x + x * scale), px(origin_y + y * scale))
+ };
+
+ let budget = shape.length * drawn;
+ let mut spent = 0.;
+ let mut builder = if stroke.fill {
+ PathBuilder::fill()
+ } else {
+ PathBuilder::stroke(px(stroke.width * scale)).with_style(PathStyle::Stroke(
+ StrokeOptions::default()
+ .with_line_width(stroke.width * scale)
+ .with_line_cap(LineCap::Round)
+ .with_line_join(LineJoin::Round),
+ ))
+ };
+ let mut any = false;
+ for subpath in &shape.subpaths {
+ if spent >= budget {
+ break;
+ }
+ let points = &subpath.variants[frame];
+ let length = subpath.cumulative.last().copied().unwrap_or(0.);
+ let allowed = (budget - spent).min(length);
+ spent += length;
+ let segments: Vec<Polyline> = if stroke.march && !stroke.fill {
+ let phase = (seconds / 1.1).fract() * 6.2;
+ dashes(points, &subpath.cumulative, allowed, 2., 4.2, phase)
+ } else {
+ vec![trim(points, &subpath.cumulative, allowed)]
+ };
+ for segment in segments {
+ if segment.len() < 2 {
+ continue;
+ }
+ builder.move_to(map(segment[0]));
+ for &p in &segment[1..] {
+ builder.line_to(map(p));
+ }
+ if stroke.fill || (subpath.closed && allowed >= length && !stroke.march) {
+ builder.close();
+ }
+ any = true;
+ }
+ }
+ if any && let Ok(path) = builder.build() {
+ window.paint_path(path, color);
+ }
+ }
+}
+
+fn trim(points: &[(f32, f32)], cumulative: &[f32], allowed: f32) -> Polyline {
+ let mut out = Vec::with_capacity(points.len());
+ for (i, &point) in points.iter().enumerate() {
+ if cumulative[i] <= allowed {
+ out.push(point);
+ continue;
+ }
+ if i > 0 {
+ let span = cumulative[i] - cumulative[i - 1];
+ let t = if span > 0. {
+ (allowed - cumulative[i - 1]) / span
+ } else {
+ 0.
+ };
+ let a = points[i - 1];
+ out.push((a.0 + (point.0 - a.0) * t, a.1 + (point.1 - a.1) * t));
+ }
+ break;
+ }
+ out
+}
+
+fn dashes(
+ points: &[(f32, f32)],
+ cumulative: &[f32],
+ allowed: f32,
+ on: f32,
+ off: f32,
+ phase: f32,
+) -> Vec<Polyline> {
+ let period = on + off;
+ let mut out = Vec::new();
+ let mut start = -phase.rem_euclid(period);
+ while start < allowed {
+ let (a, b) = (start.max(0.), (start + on).min(allowed));
+ if b > a {
+ out.push(slice(points, cumulative, a, b));
+ }
+ start += period;
+ }
+ out
+}
+
+fn slice(points: &[(f32, f32)], cumulative: &[f32], from: f32, to: f32) -> Polyline {
+ let at = |distance: f32| -> (f32, f32) {
+ let index = cumulative
+ .partition_point(|&c| c < distance)
+ .min(points.len() - 1);
+ if index == 0 {
+ return points[0];
+ }
+ let span = cumulative[index] - cumulative[index - 1];
+ let t = if span > 0. {
+ (distance - cumulative[index - 1]) / span
+ } else {
+ 0.
+ };
+ let (a, b) = (points[index - 1], points[index]);
+ (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t)
+ };
+ let mut out = vec![at(from)];
+ for (i, &c) in cumulative.iter().enumerate() {
+ if c > from && c < to {
+ out.push(points[i]);
+ }
+ }
+ out.push(at(to));
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_lines_curves_and_implicit_repeats() {
+ let subpaths = parse("M 0 0 L 10 0 10 10 Z M 0 20 q 6 -7 12 0 t 12 0");
+ assert_eq!(subpaths.len(), 2);
+ assert!(subpaths[0].1);
+ let first = &subpaths[0].0;
+ assert_eq!(first.first(), Some(&(0., 0.)));
+ assert_eq!(first.last(), Some(&(0., 0.)));
+ let wave = &subpaths[1].0;
+ let end = wave.last().unwrap();
+ assert!((end.0 - 24.).abs() < 0.01 && (end.1 - 20.).abs() < 0.01);
+ }
+
+ #[test]
+ fn a_lone_point_becomes_a_dot() {
+ let subpaths = parse("M 60 75 L 60 75");
+ assert_eq!(subpaths.len(), 1);
+ assert!(subpaths[0].0.len() >= 2);
+ }
+
+ #[test]
+ fn trim_and_dashes_respect_arc_length() {
+ let points: Polyline = (0..=10).map(|i| (i as f32, 0.)).collect();
+ let cumulative: Vec<f32> = (0..=10).map(|i| i as f32).collect();
+ let half = trim(&points, &cumulative, 5.5);
+ assert!((half.last().unwrap().0 - 5.5).abs() < 0.001);
+ let dashes = dashes(&points, &cumulative, 10., 2., 3., 0.);
+ assert_eq!(dashes.len(), 2);
+ assert!((dashes[1][0].0 - 5.).abs() < 0.001);
+ }
+
+ #[test]
+ fn boil_stays_within_amplitude_and_variants_differ() {
+ let points: Polyline = (0..50).map(|i| (i as f32 * 2., 10.)).collect();
+ let a = boil(&points, 1);
+ let b = boil(&points, 2);
+ for (original, moved) in points.iter().zip(&a) {
+ assert!(distance(*original, *moved) <= BOIL_AMPLITUDE * 1.5);
+ }
+ assert_ne!(a, b);
+ }
+}
diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rs
index abbf6d98e..2f2b10b55 100644
--- a/apps/desktop-gpui/src/editor_export.rs
+++ b/apps/desktop-gpui/src/editor_export.rs
@@ -25,6 +25,7 @@ use gpui::{
};
use crate::editor_window::EditorWindow;
+use crate::sign_in::{SignIn, SignInEvent, SignInOrigin, SignInOutcome};
use crate::store::{self, ExportPrefs};
use crate::ui;
use crate::{library, platform};
@@ -208,8 +209,11 @@ pub struct ExportUi {
pub error: Option<String>,
pub cancel: Arc<AtomicBool>,
pub export_task: Option<gpui::Task<()>>,
- pub sign_in_pending: bool,
- pub sign_in_cancel: Arc<AtomicBool>,
+ /// The server answered the last share with 401: the stored credential is
+ /// dead even though one exists, so the CTA offers sign-in again instead of
+ /// another upload that would fail the same way.
+ auth_rejected: bool,
+ sign_in_subscriptions: Option<[gpui::Subscription; 2]>,
pub organization_id: Option<String>,
pub share_link: Option<String>,
pub reuploading: bool,
@@ -230,6 +234,21 @@ const BPP_MAX: f32 = 0.5;
const BPP_STEP: f32 = 0.01;
impl ExportUi {
+ fn pick_default_organization(&mut self) {
+ let organizations = store::auth_snapshot().organizations;
+ if self
+ .organization_id
+ .as_ref()
+ .is_some_and(|id| organizations.iter().any(|org| &org.id == id))
+ {
+ return;
+ }
+ if let Some(org) = organizations.first() {
+ self.organization_id = Some(org.id.clone());
+ self.persist();
+ }
+ }
+
pub fn load() -> Self {
let prefs = store::load().export.unwrap_or(ExportPrefs {
format: "Mp4".into(),
@@ -280,8 +299,8 @@ impl ExportUi {
error: None,
cancel: Arc::new(AtomicBool::new(false)),
export_task: None,
- sign_in_pending: false,
- sign_in_cancel: Arc::new(AtomicBool::new(false)),
+ auth_rejected: false,
+ sign_in_subscriptions: None,
organization_id: prefs.organization_id,
share_link: None,
reuploading: false,
@@ -499,6 +518,7 @@ impl EditorWindow {
}
self.normalize_export_fps(&mut ui);
self.export = Some(ui);
+ self.subscribe_export_to_sign_in(window, cx);
self.refresh_export_preview(window, cx);
cx.notify();
}
@@ -511,7 +531,6 @@ impl EditorWindow {
cx.notify();
return;
}
- ui.sign_in_cancel.store(true, Ordering::Relaxed);
if let Some(image) = ui.preview.take() {
let _ = window.drop_image(image);
}
@@ -741,14 +760,13 @@ impl EditorWindow {
return;
}
if ui.destination == ExportDestination::Link {
- if ui.sign_in_pending {
- ui.sign_in_cancel.store(true, Ordering::Relaxed);
- ui.sign_in_pending = false;
- cx.notify();
+ let sign_in = SignIn::global(cx);
+ if sign_in.read(cx).is_pending() {
+ sign_in.update(cx, |sign_in, cx| sign_in.cancel(cx));
return;
}
- if !store::auth_snapshot().signed_in() {
- self.start_share_sign_in(window, cx);
+ if ui.auth_rejected || !store::auth_snapshot().signed_in() {
+ sign_in.update(cx, |sign_in, cx| sign_in.start(SignInOrigin::Editor, cx));
return;
}
self.start_link_export(window, cx);
@@ -989,76 +1007,39 @@ impl EditorWindow {
self.finish_requested_export_close(window, cx);
}
- fn start_share_sign_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- let Some(ui) = self.export.as_mut() else {
- return;
- };
- ui.sign_in_cancel.store(false, Ordering::Relaxed);
- let cancel = ui.sign_in_cancel.clone();
- ui.sign_in_pending = true;
- cx.notify();
-
- let session = match crate::auth::begin_sign_in(cancel.clone()) {
- Ok(session) => session,
- Err(error) => {
- ui.sign_in_pending = false;
- ui.error = Some(error);
- cx.notify();
- return;
- }
- };
- cx.open_url(&session.url);
-
- ui.export_task = Some(cx.spawn_in(window, async move |this, cx| {
- let signed_in = cx
- .background_executor()
- .spawn(async move { session.complete() })
- .await;
- match signed_in {
- Ok(true) => {
- if let Ok(Err(error)) =
- gpui_tokio::Tokio::spawn(cx, crate::auth::update_auth_plan()).await
- {
- tracing::warn!("updating auth plan after sign-in: {error}");
- }
- platform::activate_app();
- let _ = this.update(cx, |this, cx| {
- if let Some(ui) = this.export.as_mut() {
- ui.sign_in_pending = false;
- ui.error = None;
- if ui.organization_id.is_none() {
- ui.organization_id = store::auth_snapshot()
- .organizations
- .first()
- .map(|org| org.id.clone());
- }
- ui.persist();
- }
- cx.notify();
- });
- }
- Ok(false) => {
- let _ = this.update(cx, |this, cx| {
- if let Some(ui) = this.export.as_mut() {
- ui.sign_in_pending = false;
- }
- cx.notify();
- });
- }
- Err(error) => {
- let _ = this.update(cx, |this, cx| {
- if let Some(ui) = this.export.as_mut() {
- ui.sign_in_pending = false;
- ui.error = Some(error.clone());
+ fn subscribe_export_to_sign_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let sign_in = SignIn::global(cx);
+ let subscriptions = [
+ cx.observe(&sign_in, |_, _, cx| cx.notify()),
+ cx.subscribe_in(&sign_in, window, |this, _, event, _, cx| {
+ let Some(ui) = this.export.as_mut() else {
+ return;
+ };
+ match event {
+ SignInEvent::Finished {
+ outcome: SignInOutcome::SignedIn,
+ ..
+ } => {
+ ui.auth_rejected = false;
+ if ui.phase == ExportPhase::Failed {
+ ui.phase = ExportPhase::Idle;
}
- cx.notify();
- });
- if !cancel.load(Ordering::Relaxed) {
- platform::alert_dialog("Sign in failed", &error);
+ ui.error = None;
+ ui.pick_default_organization();
}
+ SignInEvent::Finished {
+ origin: SignInOrigin::Editor,
+ outcome: SignInOutcome::Failed(error),
+ } => ui.error = Some(error.clone()),
+ SignInEvent::Finished { .. } => {}
+ SignInEvent::AccountRefreshed => ui.pick_default_organization(),
}
- }
- }));
+ cx.notify();
+ }),
+ ];
+ if let Some(ui) = self.export.as_mut() {
+ ui.sign_in_subscriptions = Some(subscriptions);
+ }
}
fn start_link_export(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -1257,6 +1238,11 @@ impl EditorWindow {
});
}
Ok(Ok(crate::upload::UploadResult::NotAuthenticated)) => {
+ let _ = this.update(cx, |this, _| {
+ if let Some(ui) = this.export.as_mut() {
+ ui.auth_rejected = true;
+ }
+ });
show_upload_failure(
&this,
cx,
@@ -1692,11 +1678,12 @@ impl EditorWindow {
fn export_cta(&self, ui: &ExportUi, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let editor = theme.editor;
- let signed_in = store::auth_snapshot().signed_in();
+ let signed_in = !ui.auth_rejected && store::auth_snapshot().signed_in();
+ let sign_in_pending = SignIn::global(cx).read(cx).is_pending();
let (label, icon, primary) = match ui.destination {
ExportDestination::File => ("Export to File", Some("icons/folder.svg"), true),
ExportDestination::Clipboard => ("Export to Clipboard", Some("icons/copy.svg"), true),
- ExportDestination::Link if ui.sign_in_pending => ("Cancel Sign In", None, false),
+ ExportDestination::Link if sign_in_pending => ("Cancel Sign In", None, false),
ExportDestination::Link if !signed_in => {
("Sign in to share", Some("icons/link.svg"), true)
}
diff --git a/apps/desktop-gpui/src/feeds.rs b/apps/desktop-gpui/src/feeds.rs
index 39acece9f..03d5184ee 100644
--- a/apps/desktop-gpui/src/feeds.rs
+++ b/apps/desktop-gpui/src/feeds.rs
@@ -728,6 +728,12 @@ struct FeedsGlobal(Entity<Feeds>);
impl Global for FeedsGlobal {}
impl Feeds {
+ /// A camera start is in flight -- which includes waiting on the macOS
+ /// camera prompt.
+ pub fn camera_input_pending(&self) -> bool {
+ self.camera_input_pending
+ }
+
pub fn init(cx: &mut App) -> Entity<Self> {
let feeds = cx.new(|_| Self {
camera_actor: None,
@@ -1040,6 +1046,7 @@ impl Feeds {
return;
}
this.camera_input_pending = false;
+ crate::media_access::MediaAccess::refresh_global(cx);
match result {
Ok(settings) => {
this.applied_settings.camera = settings.camera;
@@ -1172,6 +1179,7 @@ impl Feeds {
return;
}
this.mic_input_pending = false;
+ crate::media_access::MediaAccess::refresh_global(cx);
match result {
Ok(settings) => this.applied_settings.microphone = settings.microphone,
Err(error) => {
diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs
index ea6403351..f26cb56de 100644
--- a/apps/desktop-gpui/src/main.rs
+++ b/apps/desktop-gpui/src/main.rs
@@ -20,6 +20,7 @@ mod deeplink;
mod dev_restore;
mod devices;
mod diagnostics;
+mod doodle;
mod editor_audio;
mod editor_canvas;
mod editor_clips;
@@ -41,10 +42,13 @@ mod import;
mod installer;
mod library;
mod main_window;
+mod media_access;
mod menus;
mod mode_select_window;
mod onboarding_audio;
+mod onboarding_doodles;
mod onboarding_window;
+mod permission_guide;
mod permissions;
mod permissions_ui;
#[cfg(test)]
@@ -62,7 +66,10 @@ mod screenshot_export;
mod session;
mod settings_pages;
mod settings_window;
+mod sign_in;
mod single_instance;
+#[cfg(debug_assertions)]
+mod snapshot;
mod store;
mod target_overlay;
mod target_thumbnails;
@@ -308,7 +315,9 @@ fn main() {
crate::theme::init(cx);
let session = RecordingSession::init(cx);
+ crate::sign_in::SignIn::init(cx);
crate::feeds::Feeds::init(cx);
+ crate::media_access::MediaAccess::init(cx);
crate::target_overlay::TargetSelect::init(cx);
let dev_restore = dev_restore::load();
@@ -587,6 +596,8 @@ fn main() {
}
permissions_ui::auto_open_from_env(cx); // `CAP_GPUI_AUTO_PERMISSIONS=1`: the permissions surface.
+ #[cfg(debug_assertions)]
+ snapshot::arm_from_env(cx);
// `CAP_GPUI_AUTO_MODE_SELECT=1`: open the 580x340 mode picker the way
// the mode dot does, main window hidden included. A mode name instead
diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs
index e28479746..c72418869 100644
--- a/apps/desktop-gpui/src/main_window.rs
+++ b/apps/desktop-gpui/src/main_window.rs
@@ -19,9 +19,12 @@ use crate::{
devices::{CameraOption, DeviceSnapshot, DisplayOption, MicrophoneOption, WindowOption},
feeds::{self, Feeds},
library::{self, RecordingItem, ScreenshotItem},
+ media_access::MediaAccess,
+ permissions::OSPermission,
recording,
session::{Phase, RecordingSession},
settings_window::Page,
+ sign_in::{SignIn, SignInEvent, SignInOrigin, SignInOutcome},
target_thumbnails,
theme::Theme,
ui,
@@ -592,6 +595,13 @@ fn save_device_format(target: &DeviceFormatTarget, format: DeviceFormat) -> bool
}
impl DeviceMenu {
+ fn permission(self) -> OSPermission {
+ match self {
+ Self::Camera => OSPermission::Camera,
+ Self::Microphone => OSPermission::Microphone,
+ }
+ }
+
fn title(self) -> &'static str {
match self {
Self::Camera => "Camera",
@@ -755,6 +765,14 @@ impl RecordingStartPermit {
}
}
+/// Instant Mode's sign-in gate, shown here when the overlay's "Sign In To
+/// Use" is pressed: the overlays close so the browser is reachable, and they
+/// re-open for `kind` once the account is signed in.
+struct SignInPrompt {
+ kind: TargetType,
+ error: Option<String>,
+}
+
struct MicrophoneWarning {
config: recording::StartConfig,
permit: RecordingStartPermit,
@@ -804,6 +822,9 @@ pub struct MainWindow {
checking_storage: bool,
deep_link_start: Option<RecordingStartPermit>,
microphone_warning: Option<MicrophoneWarning>,
+ sign_in_prompt: Option<SignInPrompt>,
+ /// The error whose text was last copied, so the button can say so.
+ copied_error: Option<String>,
/// Header recordings / screenshots panel. Scanned only while that panel
/// is open so a large library is not walked on every home paint.
library: Option<LibraryItems>,
@@ -872,6 +893,8 @@ impl MainWindow {
cx.observe_window_activation(window, |this, window, cx| {
if !window.is_window_active() {
this.clear_mode_hover();
+ } else {
+ MediaAccess::global(cx).update(cx, |access, cx| access.refresh(cx));
}
#[cfg(target_os = "windows")]
if window.is_window_active() && !this.devices.displays.is_empty() {
@@ -981,6 +1004,62 @@ impl MainWindow {
let search_input = cx.new(|cx| ui::TextInputState::single_line(window, cx));
let search_events = cx.subscribe(&search_input, Self::on_search_event);
+ let media = MediaAccess::global(cx);
+ let mut media_allowed = (
+ media.read(cx).allowed(OSPermission::Camera),
+ media.read(cx).allowed(OSPermission::Microphone),
+ );
+ cx.observe(&media, move |this: &mut Self, media, cx| {
+ let allowed = (
+ media.read(cx).allowed(OSPermission::Camera),
+ media.read(cx).allowed(OSPermission::Microphone),
+ );
+ // A grant that lands after a device was picked (the prompt
+ // answered, or the switch flipped in System Settings) retries
+ // that device instead of leaving its failed start behind.
+ if allowed.0 && !media_allowed.0 && this.camera.is_some() {
+ let (camera, id) = (this.camera.clone(), this.camera_id.clone());
+ this.apply_camera_selection(camera, id, cx);
+ }
+ if allowed.1 && !media_allowed.1 && this.microphone.is_some() {
+ let microphone = this.microphone.clone();
+ this.apply_microphone_selection(microphone, cx);
+ }
+ media_allowed = allowed;
+ cx.notify();
+ })
+ .detach();
+
+ let sign_in = SignIn::global(cx);
+ cx.observe(&sign_in, |_, _, cx| cx.notify()).detach();
+ cx.subscribe(&sign_in, |this, _, event, cx| {
+ let SignInEvent::Finished { origin, outcome } = event else {
+ return;
+ };
+ let Some(prompt) = this.sign_in_prompt.as_mut() else {
+ return;
+ };
+ match outcome {
+ SignInOutcome::SignedIn => {
+ let kind = prompt.kind;
+ this.sign_in_prompt = None;
+ let session = this.session.read(cx);
+ if session.phase == Phase::Idle && session.editor_recording_target().is_none() {
+ this.arm_overlay(kind, cx);
+ }
+ }
+ SignInOutcome::Failed(error) if matches!(origin, SignInOrigin::Overlay(_)) => {
+ prompt.error = Some(error.clone());
+ }
+ SignInOutcome::TimedOut if matches!(origin, SignInOrigin::Overlay(_)) => {
+ prompt.error = Some("Sign in timed out. Try again.".into());
+ }
+ _ => {}
+ }
+ cx.notify();
+ })
+ .detach();
+
Self {
theme,
// `rawOptions.mode` -- the recording mode is a persisted setting,
@@ -1017,6 +1096,8 @@ impl MainWindow {
checking_storage: false,
deep_link_start: None,
microphone_warning: None,
+ sign_in_prompt: None,
+ copied_error: None,
library: None,
library_task: None,
incomplete_recording: None,
@@ -2095,6 +2176,17 @@ impl MainWindow {
None => return,
}
};
+ if mode == recording::RecordingMode::Instant && !crate::store::auth_snapshot().signed_in() {
+ let kind = match &target {
+ ScreenCaptureTarget::Display { .. } => TargetType::Display,
+ ScreenCaptureTarget::Window { .. } => TargetType::Window,
+ ScreenCaptureTarget::Area { .. } => TargetType::Area,
+ ScreenCaptureTarget::CameraOnly => TargetType::CameraOnly,
+ };
+ self.show_sign_in_prompt(kind, cx);
+ cx.defer(app_windows::show_main_window);
+ return;
+ }
if matches!(target, ScreenCaptureTarget::CameraOnly) && self.camera.is_none() {
self.session.update(cx, |session, cx| {
session.error = Some("Camera-only recording requires a selected camera.".into());
@@ -2494,6 +2586,30 @@ impl MainWindow {
/// Select (or clear) the camera -- the same wiring as the camera panel's
/// rows: this window's state plus the app-scoped feed, which opens or
/// closes the preview bubble.
+ /// The pill for a picked device Cap cannot use yet, or `None` when access
+ /// is fine.
+ fn access_pill(&self, permission: OSPermission, cx: &gpui::App) -> Option<PillState> {
+ let access = MediaAccess::global(cx);
+ let access = access.read(cx);
+ if access.allowed(permission) {
+ return None;
+ }
+ Some(PillState::Access(if access.requesting(permission) {
+ "Asking…"
+ } else if access.status(permission) == crate::permissions::OSPermissionStatus::Denied {
+ "Allow in Settings"
+ } else {
+ "Allow"
+ }))
+ }
+
+ fn ensure_media_access(&mut self, permission: OSPermission, cx: &mut Context<Self>) {
+ let access = MediaAccess::global(cx);
+ if !access.read(cx).allowed(permission) {
+ access.update(cx, |access, cx| access.request(permission, cx));
+ }
+ }
+
pub fn set_camera_selection(&mut self, camera: Option<CameraOption>, cx: &mut Context<Self>) {
let id = camera.as_ref().map(|camera| {
camera
@@ -2634,6 +2750,14 @@ impl Render for MainWindow {
.when(self.microphone_warning.is_some(), |this| {
this.child(self.render_microphone_warning(cx))
})
+ .when(self.sign_in_prompt.is_some(), |this| {
+ this.child(self.render_sign_in_prompt(cx))
+ })
+ // A failed start has nowhere else to surface: the overlays are
+ // gone by then and the bar closed itself.
+ .when_some(self.idle_error(cx), |this, error| {
+ this.child(self.render_idle_error(error, cx))
+ })
.on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, _, cx| {
if event.keystroke.key == "escape" && this.dismiss_main(cx) {
cx.stop_propagation();
@@ -2734,6 +2858,276 @@ impl MainWindow {
)
}
+ pub fn show_sign_in_prompt(&mut self, kind: TargetType, cx: &mut Context<Self>) {
+ self.clear_mode_hover();
+ self.sign_in_prompt = Some(SignInPrompt { kind, error: None });
+ cx.notify();
+ }
+
+ fn dismiss_sign_in_prompt(&mut self, cx: &mut Context<Self>) {
+ if self.sign_in_prompt.take().is_none() {
+ return;
+ }
+ let sign_in = SignIn::global(cx);
+ if sign_in.read(cx).is_pending() {
+ sign_in.update(cx, |sign_in, cx| sign_in.cancel(cx));
+ }
+ cx.notify();
+ }
+
+ /// The dialog frame the sign-in prompt and the error card share: a dimmed
+ /// backdrop over the home view (clicking it dismisses), and a raised card
+ /// with an icon badge, a title and a close button.
+ fn render_modal(
+ &self,
+ id: &'static str,
+ badge: (&'static str, gpui::Rgba, gpui::Rgba),
+ title: &'static str,
+ on_dismiss: fn(&mut Self, &mut Context<Self>),
+ body: gpui::AnyElement,
+ cx: &mut Context<Self>,
+ ) -> impl IntoElement {
+ let theme = self.theme;
+ let (icon, badge_bg, badge_fg) = badge;
+ div()
+ .id(id)
+ .absolute()
+ .inset_0()
+ .when(cfg!(target_os = "windows"), |overlay| {
+ overlay.top(px(HEADER_HEIGHT))
+ })
+ .when(!cfg!(target_os = "windows"), |overlay| {
+ overlay.rounded(px(16.))
+ })
+ .occlude()
+ .flex()
+ .items_center()
+ .justify_center()
+ .p(px(14.))
+ .bg(gpui::hsla(
+ 0.,
+ 0.,
+ 0.,
+ if theme.is_dark() { 0.55 } else { 0.32 },
+ ))
+ .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
+ .on_click(cx.listener(move |this, _, _, cx| on_dismiss(this, cx)))
+ .child(
+ div()
+ .id("modal-card")
+ .relative()
+ .w_full()
+ .rounded(px(14.))
+ .border_1()
+ .border_color(theme.body_border(6))
+ .bg(theme.gray_1)
+ .shadow_lg()
+ .p(px(16.))
+ .flex()
+ .flex_col()
+ .gap(px(14.))
+ .on_click(|_, _, cx| cx.stop_propagation())
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(10.))
+ .pr(px(24.))
+ .child(
+ div()
+ .flex()
+ .flex_shrink_0()
+ .items_center()
+ .justify_center()
+ .size(px(36.))
+ .rounded_full()
+ .bg(badge_bg)
+ .child(svg().path(icon).size(px(18.)).text_color(badge_fg)),
+ )
+ .child(
+ div()
+ .text_size(px(15.))
+ .line_height(px(20.))
+ .font_weight(FontWeight::SEMIBOLD)
+ .text_color(theme.gray_12)
+ .child(title),
+ ),
+ )
+ .child(body)
+ .child(
+ div()
+ .id("modal-close")
+ .absolute()
+ .top(px(10.))
+ .right(px(10.))
+ .flex()
+ .items_center()
+ .justify_center()
+ .size(px(24.))
+ .rounded_full()
+ .cursor_pointer()
+ .hover(|style| style.bg(theme.gray_3))
+ .tooltip(move |_, cx| ui::Tooltip::new(&theme, "Close").view(cx))
+ .child(
+ svg()
+ .path("icons/x.svg")
+ .size(px(12.))
+ .text_color(theme.gray_10),
+ )
+ .on_click(cx.listener(move |this, _, _, cx| {
+ cx.stop_propagation();
+ on_dismiss(this, cx);
+ })),
+ ),
+ )
+ }
+
+ fn render_sign_in_prompt(&self, cx: &mut Context<Self>) -> impl IntoElement {
+ let theme = self.theme;
+ let pending = SignIn::global(cx).read(cx).is_pending();
+ let error = self
+ .sign_in_prompt
+ .as_ref()
+ .and_then(|prompt| prompt.error.clone())
+ .filter(|_| !pending);
+
+ let message = if pending {
+ "Finish signing in to Cap in your browser. Cap comes back here and opens the recorder when you're done."
+ } else {
+ "Instant Mode uploads while you record, so your shareable link is ready the moment you stop."
+ };
+ let primary = if pending {
+ ui::Button::plain(
+ &theme,
+ "sign-in-prompt-reopen",
+ ui::ButtonVariant::Blue,
+ ui::ButtonSize::Lg,
+ )
+ .label("Open browser again")
+ .full_width()
+ .on_click(cx.listener(|_, _, _, cx| {
+ SignIn::global(cx).update(cx, |sign_in, cx| sign_in.reopen(cx));
+ }))
+ } else {
+ ui::Button::plain(
+ &theme,
+ "sign-in-prompt-sign-in",
+ ui::ButtonVariant::Blue,
+ ui::ButtonSize::Lg,
+ )
+ .icon("icons/user-round.svg")
+ .label("Sign In")
+ .full_width()
+ .on_click(cx.listener(|this, _, _, cx| {
+ let Some(prompt) = this.sign_in_prompt.as_mut() else {
+ return;
+ };
+ prompt.error = None;
+ let origin = SignInOrigin::Overlay(prompt.kind);
+ SignIn::global(cx).update(cx, |sign_in, cx| sign_in.start(origin, cx));
+ cx.notify();
+ }))
+ };
+ let secondary = if pending {
+ div().child(
+ ui::Button::plain(
+ &theme,
+ "sign-in-prompt-cancel",
+ ui::ButtonVariant::Gray,
+ ui::ButtonSize::Lg,
+ )
+ .label("Cancel")
+ .full_width()
+ .on_click(cx.listener(|_, _, _, cx| {
+ SignIn::global(cx).update(cx, |sign_in, cx| sign_in.cancel(cx));
+ })),
+ )
+ } else {
+ div()
+ .flex()
+ .gap(px(8.))
+ .child(
+ div().flex_1().child(
+ ui::Button::plain(
+ &theme,
+ "sign-in-prompt-studio",
+ ui::ButtonVariant::Gray,
+ ui::ButtonSize::Lg,
+ )
+ .label("Use Studio")
+ .full_width()
+ .on_click(cx.listener(|this, _, _, cx| {
+ let Some(prompt) = this.sign_in_prompt.take() else {
+ return;
+ };
+ this.set_mode(Mode::Studio, cx);
+ this.arm_overlay(prompt.kind, cx);
+ })),
+ ),
+ )
+ .child(
+ div().flex_1().child(
+ ui::Button::plain(
+ &theme,
+ "sign-in-prompt-dismiss",
+ ui::ButtonVariant::Gray,
+ ui::ButtonSize::Lg,
+ )
+ .label("Not now")
+ .full_width()
+ .on_click(cx.listener(|this, _, _, cx| this.dismiss_sign_in_prompt(cx))),
+ ),
+ )
+ };
+
+ let body = div()
+ .flex()
+ .flex_col()
+ .gap(px(14.))
+ .child(
+ div()
+ .text_size(px(12.5))
+ .line_height(px(19.))
+ .text_color(theme.gray_11)
+ .child(message),
+ )
+ .when_some(error, |this, error| {
+ this.child(
+ div()
+ .rounded(px(8.))
+ .bg(theme.red_3)
+ .px(px(10.))
+ .py(px(7.))
+ .text_size(px(12.))
+ .line_height(px(16.))
+ .text_color(theme.red_11)
+ .child(error),
+ )
+ })
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(8.))
+ .child(primary)
+ .child(secondary),
+ )
+ .into_any_element();
+
+ self.render_modal(
+ "sign-in-prompt",
+ ("icons/instant.svg", theme.blue_3, theme.blue_9),
+ if pending {
+ "Waiting for your browser"
+ } else {
+ "Sign in to use Instant Mode"
+ },
+ Self::dismiss_sign_in_prompt,
+ body,
+ cx,
+ )
+ }
+
fn render_clean_capture_preflight(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
div()
@@ -3185,61 +3579,99 @@ impl MainWindow {
actions
}
+ fn idle_error(&self, cx: &gpui::App) -> Option<String> {
+ let session = self.session.read(cx);
+ session
+ .error
+ .clone()
+ .filter(|_| session.phase == Phase::Idle)
+ }
+
+ fn dismiss_idle_error(&mut self, cx: &mut Context<Self>) {
+ let Some(shown) = self.idle_error(cx) else {
+ return;
+ };
+ self.copied_error = None;
+ self.session.update(cx, |session, cx| {
+ if clear_shown_idle_error(session.phase, &mut session.error, &shown) {
+ cx.notify();
+ }
+ });
+ }
+
fn render_idle_error(&self, error: String, cx: &mut Context<Self>) -> impl IntoElement {
+ let theme = self.theme;
+ let copied = self.copied_error.as_deref() == Some(error.as_str());
let copy_error = error.clone();
- let shown_error = error.clone();
- div()
- .id("recording-error-panel")
+ let body = div()
.flex()
.flex_col()
- .flex_shrink_0()
- .min_w_0()
- .max_h(px(72.))
- .gap(px(4.))
- .overflow_hidden()
- .child(recording_error_text(error).text_color(self.theme.red_9))
+ .gap(px(14.))
+ .child(
+ recording_error_text(error)
+ .rounded(px(8.))
+ .bg(theme.gray_3)
+ .px(px(10.))
+ .py(px(8.))
+ .text_size(px(12.5))
+ .line_height(px(18.))
+ .text_color(theme.gray_12),
+ )
.child(
div()
.flex()
- .flex_shrink_0()
- .justify_end()
- .gap(px(6.))
+ .gap(px(8.))
.child(
- ui::Button::body(
- &self.theme,
- "copy-recording-error",
- ui::ButtonVariant::Gray,
- ui::ButtonSize::Xs,
- )
- .label("Copy error")
- .on_click(cx.listener(move |_, _, _, cx| {
- cx.write_to_clipboard(gpui::ClipboardItem::new_string(
- copy_error.clone(),
- ));
- })),
+ div().flex_1().child(
+ ui::Button::plain(
+ &theme,
+ "copy-recording-error",
+ ui::ButtonVariant::Gray,
+ ui::ButtonSize::Lg,
+ )
+ .icon(if copied {
+ "icons/check.svg"
+ } else {
+ "icons/copy.svg"
+ })
+ .label(if copied { "Copied" } else { "Copy error" })
+ .full_width()
+ .on_click(cx.listener(
+ move |this, _, _, cx| {
+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(
+ copy_error.clone(),
+ ));
+ this.copied_error = Some(copy_error.clone());
+ cx.notify();
+ },
+ )),
+ ),
)
.child(
- ui::Button::body(
- &self.theme,
- "dismiss-recording-error",
- ui::ButtonVariant::Gray,
- ui::ButtonSize::Xs,
- )
- .label("Dismiss")
- .on_click(cx.listener(move |this, _, _, cx| {
- this.session.update(cx, |session, cx| {
- if clear_shown_idle_error(
- session.phase,
- &mut session.error,
- &shown_error,
- ) {
- cx.notify();
- }
- });
- })),
+ div().flex_1().child(
+ ui::Button::plain(
+ &theme,
+ "dismiss-recording-error",
+ ui::ButtonVariant::Blue,
+ ui::ButtonSize::Lg,
+ )
+ .label("Dismiss")
+ .full_width()
+ .on_click(cx.listener(|this, _, _, cx| this.dismiss_idle_error(cx))),
+ ),
),
)
+ .into_any_element();
+
+ self.render_modal(
+ "recording-error-panel",
+ ("icons/triangle-alert.svg", theme.red_3, theme.red_9),
+ "Something went wrong",
+ Self::dismiss_idle_error,
+ body,
+ cx,
+ )
}
/// Page root: `px-[13px] gap-2 pb-[8px]`.
@@ -3260,32 +3692,20 @@ impl MainWindow {
// the full body, exactly as `!activeMenu() && ...` does in index.tsx.
match self.panel {
Some(panel) => root.child(self.render_panel(panel, cx)),
- None => root
- .child(self.render_logo_row(cx))
- .child(
- div()
- .id("home-scroll")
- .flex()
- .flex_col()
- .flex_1()
- .min_h_0()
- .w_full()
- .pb(px(4.))
- .gap(px(8.))
- .overflow_y_scroll()
- .child(self.render_targets(cx))
- .child(self.render_base_controls(cx)),
- )
- // A failed start has nowhere else to surface: the overlays are
- // gone by then and the bar closed itself.
- .when_some(
- self.session
- .read(cx)
- .error
- .clone()
- .filter(|_| self.session.read(cx).phase == Phase::Idle),
- |this, error| this.child(self.render_idle_error(error, cx)),
- ),
+ None => root.child(self.render_logo_row(cx)).child(
+ div()
+ .id("home-scroll")
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_h_0()
+ .w_full()
+ .pb(px(4.))
+ .gap(px(8.))
+ .overflow_y_scroll()
+ .child(self.render_targets(cx))
+ .child(self.render_base_controls(cx)),
+ ),
}
}
@@ -3578,6 +3998,10 @@ impl MainWindow {
fn dismiss_main(&mut self, cx: &mut Context<Self>) -> bool {
if self.microphone_warning.is_some() {
self.dismiss_microphone_warning(cx);
+ } else if self.sign_in_prompt.is_some() {
+ self.dismiss_sign_in_prompt(cx);
+ } else if self.idle_error(cx).is_some() {
+ self.dismiss_idle_error(cx);
} else if self.mode_hover.visible.is_some() {
self.clear_mode_hover();
cx.notify();
@@ -4590,6 +5014,8 @@ impl MainWindow {
);
}
+ let list = list.children(self.render_access_banner(menu, cx));
+
// The "none" row is always offered and is never filtered out -- it is
// how you turn the device off, not a search result.
let mut rows = vec![
@@ -4665,6 +5091,7 @@ impl MainWindow {
if !this.device_changes_allowed(cx) {
return;
}
+ this.ensure_media_access(OSPermission::Camera, cx);
this.set_camera_selection(Some(chosen.clone()), cx);
this.close_panel(cx);
}),
@@ -4725,6 +5152,7 @@ impl MainWindow {
if !this.device_changes_allowed(cx) {
return;
}
+ this.ensure_media_access(OSPermission::Microphone, cx);
this.set_microphone_selection(Some(chosen.clone()), cx);
this.close_panel(cx);
}),
@@ -5336,6 +5764,80 @@ impl MainWindow {
)
}
+ /// Above a camera/mic list Cap cannot use yet: what is wrong and the one
+ /// button that fixes it.
+ fn render_access_banner(
+ &self,
+ menu: DeviceMenu,
+ cx: &mut Context<Self>,
+ ) -> Option<gpui::AnyElement> {
+ let permission = menu.permission();
+ let access = MediaAccess::global(cx);
+ let access = access.read(cx);
+ if access.allowed(permission) {
+ return None;
+ }
+ let theme = self.theme;
+ let denied = access.status(permission) == crate::permissions::OSPermissionStatus::Denied;
+ let requesting = access.requesting(permission);
+ let noun = match menu {
+ DeviceMenu::Camera => "camera",
+ DeviceMenu::Microphone => "microphone",
+ };
+ let message = if denied {
+ format!("Cap can't use your {noun}. Turn it on in System Settings.")
+ } else if requesting {
+ "Choose Allow in the macOS prompt.".to_string()
+ } else {
+ format!("Cap needs your OK to use your {noun}.")
+ };
+ let label = if denied {
+ "Open System Settings"
+ } else if requesting {
+ "Asking…"
+ } else {
+ crate::media_access::action_label(access.status(permission))
+ };
+ Some(
+ div()
+ .flex()
+ .flex_row()
+ .items_center()
+ .gap(px(8.))
+ .w_full()
+ .px(px(10.))
+ .py(px(8.))
+ .mb(px(4.))
+ .rounded(px(10.))
+ .bg(theme.amber_3)
+ .border_1()
+ .border_color(theme.amber_6)
+ .child(
+ div()
+ .flex_1()
+ .min_w_0()
+ .text_size(px(12.))
+ .line_height(px(16.))
+ .text_color(theme.amber_11)
+ .child(message),
+ )
+ .child(
+ ui::Button::body(
+ &theme,
+ SharedString::from(format!("{noun}-access")),
+ ui::ButtonVariant::Primary,
+ ui::ButtonSize::Xs,
+ )
+ .label(label)
+ .disabled(requesting)
+ .on_click(cx.listener(move |this, _, _, cx| {
+ this.ensure_media_access(permission, cx);
+ })),
+ )
+ .into_any_element(),
+ )
+ }
+
fn render_empty_state(&self, message: impl Into<SharedString>) -> gpui::AnyElement {
div()
.py(px(24.))
@@ -5950,7 +6452,11 @@ impl MainWindow {
.as_ref()
.map(|camera| camera.label.clone())
.unwrap_or_else(|| "No Camera".into()),
- if self.camera.is_some() {
+ if self.camera.is_some()
+ && let Some(pill) = self.access_pill(OSPermission::Camera, cx)
+ {
+ pill
+ } else if self.camera.is_some() {
if self.devices.cameras.iter().any(|camera| {
Some(&camera.device_id)
== self.camera.as_ref().map(|selected| &selected.device_id)
@@ -5985,7 +6491,11 @@ impl MainWindow {
.as_ref()
.map(|mic| mic.name.clone())
.unwrap_or_else(|| "No Microphone".into()),
- if self.microphone.is_some() {
+ if self.microphone.is_some()
+ && let Some(pill) = self.access_pill(OSPermission::Microphone, cx)
+ {
+ pill
+ } else if self.microphone.is_some() {
if self.devices.microphones.iter().any(|microphone| {
Some(&microphone.name)
== self.microphone.as_ref().map(|selected| &selected.name)
@@ -6119,6 +6629,16 @@ impl MainWindow {
cx.stop_propagation();
return;
}
+ let permission = menu.permission();
+ let selected = match menu {
+ DeviceMenu::Camera => this.camera.is_some(),
+ DeviceMenu::Microphone => this.microphone.is_some(),
+ };
+ if selected && !MediaAccess::global(cx).read(cx).allowed(permission) {
+ cx.stop_propagation();
+ this.ensure_media_access(permission, cx);
+ return;
+ }
match menu {
DeviceMenu::Camera if this.camera.is_some() => {
cx.stop_propagation();
@@ -6180,6 +6700,9 @@ enum PillState {
On,
Off,
Disconnected,
+ /// The device is picked but macOS has not given Cap access: the pill is
+ /// the button that asks (or opens System Settings).
+ Access(&'static str),
}
impl PillState {
@@ -6192,6 +6715,7 @@ impl PillState {
Hsla::from(theme.gray_11),
"Not connected",
),
+ Self::Access(label) => (Hsla::from(theme.amber_3), Hsla::from(theme.amber_11), label),
};
div()
@@ -6211,13 +6735,15 @@ impl PillState {
}
}
+const ERROR_TEXT_MAX_HEIGHT: f32 = 132.;
+
fn recording_error_text(error: String) -> impl IntoElement + Styled {
div()
.id("recording-error-text")
.w_full()
.min_w_0()
.min_h_0()
- .max_h(px(48.))
+ .max_h(px(ERROR_TEXT_MAX_HEIGHT))
.text_size(px(12.))
.line_height(px(16.))
.whitespace_normal()
@@ -6598,7 +7124,10 @@ mod recording_error_panel_tests {
fn long_error_keeps_bounded_scrollable_text() {
let mut element = recording_error_text("Requested microphone unavailable. ".repeat(200));
let style = element.style();
- assert_eq!(style.max_size.height, Some(px(48.).into()));
+ assert_eq!(
+ style.max_size.height,
+ Some(px(ERROR_TEXT_MAX_HEIGHT).into())
+ );
assert_eq!(style.min_size.height, Some(px(0.).into()));
assert_eq!(style.overflow.x, Some(gpui::Overflow::Scroll));
assert_eq!(style.overflow.y, Some(gpui::Overflow::Scroll));
@@ -6608,7 +7137,10 @@ mod recording_error_panel_tests {
fn unbroken_error_keeps_both_scroll_axes() {
let mut element = recording_error_text("x".repeat(8192));
let style = element.style();
- assert_eq!(style.max_size.height, Some(px(48.).into()));
+ assert_eq!(
+ style.max_size.height,
+ Some(px(ERROR_TEXT_MAX_HEIGHT).into())
+ );
assert_eq!(style.overflow.x, Some(gpui::Overflow::Scroll));
assert_eq!(style.overflow.y, Some(gpui::Overflow::Scroll));
}
diff --git a/apps/desktop-gpui/src/media_access.rs b/apps/desktop-gpui/src/media_access.rs
new file mode 100644
index 000000000..ecc8df56f
--- /dev/null
+++ b/apps/desktop-gpui/src/media_access.rs
@@ -0,0 +1,145 @@
+//! Camera and microphone access, as every device picker sees it.
+//!
+//! Selecting a device used to be the only way to trigger the AV prompt, and
+//! a denial or an unanswered prompt surfaced nowhere: the preview spun
+//! forever and the row still said "On". This model is the one place the
+//! pickers (main window, recording overlay, camera window) read the current
+//! authorization from, and the one place that asks for it: the system prompt
+//! while undetermined, the exact System Settings pane once denied.
+//!
+//! The status is a cached preflight (`AVCaptureDevice authorizationStatus`,
+//! never prompts), refreshed when an app window activates and after every
+//! request, so renders never hit TCC.
+
+use gpui::{App, AppContext, Context, Entity, Global, Task};
+
+use crate::permissions::{self, OSPermission, OSPermissionStatus};
+
+pub struct MediaAccess {
+ camera: OSPermissionStatus,
+ microphone: OSPermissionStatus,
+ requesting: Option<OSPermission>,
+ refresh: Option<Task<()>>,
+ request: Option<Task<()>>,
+}
+
+struct MediaAccessGlobal(Entity<MediaAccess>);
+
+impl Global for MediaAccessGlobal {}
+
+impl MediaAccess {
+ pub fn init(cx: &mut App) {
+ let entity = cx.new(|cx| {
+ let mut this = Self {
+ camera: OSPermissionStatus::Granted,
+ microphone: OSPermissionStatus::Granted,
+ requesting: None,
+ refresh: None,
+ request: None,
+ };
+ this.refresh(cx);
+ this
+ });
+ cx.set_global(MediaAccessGlobal(entity));
+ }
+
+ /// Re-read the statuses from anywhere, tolerating the model not being
+ /// installed yet (feeds can finish before it is).
+ pub fn refresh_global(cx: &mut App) {
+ if let Some(global) = cx.try_global::<MediaAccessGlobal>() {
+ let entity = global.0.clone();
+ entity.update(cx, |access, cx| access.refresh(cx));
+ }
+ }
+
+ pub fn global(cx: &App) -> Entity<Self> {
+ cx.global::<MediaAccessGlobal>().0.clone()
+ }
+
+ pub fn status(&self, permission: OSPermission) -> OSPermissionStatus {
+ match permission {
+ OSPermission::Camera => self.camera,
+ OSPermission::Microphone => self.microphone,
+ OSPermission::ScreenRecording | OSPermission::Accessibility => {
+ OSPermissionStatus::NotNeeded
+ }
+ }
+ }
+
+ pub fn allowed(&self, permission: OSPermission) -> bool {
+ self.status(permission).permitted()
+ }
+
+ pub fn requesting(&self, permission: OSPermission) -> bool {
+ self.requesting == Some(permission)
+ }
+
+ /// Re-read both statuses off the main thread.
+ pub fn refresh(&mut self, cx: &mut Context<Self>) {
+ if self.refresh.is_some() {
+ return;
+ }
+ self.refresh = Some(cx.spawn(async move |this, cx| {
+ let raw = cx
+ .background_executor()
+ .spawn(async { crate::permissions_ui::sweep_raw() })
+ .await;
+ this.update(cx, |this, cx| {
+ this.refresh = None;
+ let check = permissions::classify(raw, Default::default());
+ let camera = check.get(OSPermission::Camera);
+ let microphone = check.get(OSPermission::Microphone);
+ if camera != this.camera || microphone != this.microphone {
+ this.camera = camera;
+ this.microphone = microphone;
+ cx.notify();
+ }
+ })
+ .ok();
+ }));
+ }
+
+ /// The one action a missing permission offers: the system prompt while
+ /// macOS has not asked yet, the Privacy pane once it has been denied.
+ pub fn request(&mut self, permission: OSPermission, cx: &mut Context<Self>) {
+ match self.status(permission) {
+ OSPermissionStatus::Granted | OSPermissionStatus::NotNeeded => {}
+ OSPermissionStatus::Denied => permissions::open_permission_settings(permission),
+ OSPermissionStatus::NotDetermined => {
+ if self.requesting.is_some() {
+ return;
+ }
+ self.requesting = Some(permission);
+ cx.notify();
+ self.request = Some(cx.spawn(async move |this, cx| {
+ #[cfg(target_os = "macos")]
+ {
+ let answer = gpui_tokio::Tokio::spawn(
+ cx,
+ permissions::ensure_capture_media_permission(permission),
+ )
+ .await;
+ if let Ok(Err(error)) = answer {
+ tracing::info!(?permission, "media access not granted: {error}");
+ }
+ }
+ this.update(cx, |this, cx| {
+ this.requesting = None;
+ this.request = None;
+ this.refresh(cx);
+ cx.notify();
+ })
+ .ok();
+ }));
+ }
+ }
+ }
+}
+
+/// Short action label for a missing permission: what clicking will do.
+pub fn action_label(status: OSPermissionStatus) -> &'static str {
+ match status {
+ OSPermissionStatus::Denied => "Turn on in Settings",
+ _ => "Allow access",
+ }
+}
diff --git a/apps/desktop-gpui/src/menus.rs b/apps/desktop-gpui/src/menus.rs
index 9eb4307f5..8e3996369 100644
--- a/apps/desktop-gpui/src/menus.rs
+++ b/apps/desktop-gpui/src/menus.rs
@@ -194,16 +194,17 @@ pub fn build_menus() -> Vec<Menu> {
/// update that read the handle -- the `place_overlay_panel` rule, which is also
/// why gpui's own `Window::minimize_window` is not called here.
fn with_key_native(cx: &mut App, action: fn(&platform::NativeWindow)) {
- let Some(handle) = cx.active_window() else {
- tracing::info!("window command: no key window");
- return;
- };
+ let active = cx.active_window();
// A ⌘-keystroke action arrives *inside* the key window's own dispatch,
// which holds that window's lease -- `handle.update` on the same window
// returns Err there (observed: ⌘W resolved no native handle and silently
// did nothing). Deferred, so the lease is back first. The menu-click path
// has no lease and rides the same defer unharmed.
cx.defer(move |cx| {
+ let Some(handle) = active.or_else(|| key_window(cx)) else {
+ tracing::info!("window command: no key window");
+ return;
+ };
let native = handle
.update(cx, |_, window, _| platform::native_window(window))
.ok()
@@ -246,6 +247,10 @@ pub fn close_key_window(cx: &mut App) {
// is active), so even the visibility probe's `main.update` would silently
// Err here -- the with_key_native trap, again.
cx.defer(|cx| {
+ if let Some(handle) = key_window(cx) {
+ close_window_by_handle(handle, cx);
+ return;
+ }
if !cx.has_global::<app_windows::AppWindows>() {
return;
}
@@ -262,6 +267,23 @@ pub fn close_key_window(cx: &mut App) {
});
}
+/// The key window, if it has a close button. `active_window` is AppKit's
+/// *main* window, and a `Floating` panel such as the teleprompter becomes key
+/// without becoming main, which left ⌘W hiding the main window behind it.
+/// Panels without a close button (the controls bar, camera bubble and target
+/// overlays can all be key after a click) are skipped, so ⌘W never closes
+/// them. Call it deferred: the key window's lease is held during its own
+/// dispatch.
+fn key_window(cx: &mut App) -> Option<gpui::AnyWindowHandle> {
+ cx.windows().into_iter().find(|handle| {
+ handle
+ .update(cx, |_, window, _| {
+ window.is_window_active() && platform::window_is_closable(window)
+ })
+ .unwrap_or(false)
+ })
+}
+
/// The ⌘W body, keyed by handle -- split out so the harness can close a
/// specific window without depending on focus (synthetic activation races
/// whatever the user has focused).
diff --git a/apps/desktop-gpui/src/onboarding_doodles.rs b/apps/desktop-gpui/src/onboarding_doodles.rs
new file mode 100644
index 000000000..cd6b29d53
--- /dev/null
+++ b/apps/desktop-gpui/src/onboarding_doodles.rs
@@ -0,0 +1,278 @@
+//! The permission doodles: path data in a 120x104 view (the Chrome
+//! extension's camera-permission doodle grid) unless noted.
+
+use crate::doodle::{Doodle, Ink, Stroke};
+
+pub static SCREEN: Doodle = Doodle {
+ view: (120., 104.),
+ strokes: &[
+ Stroke::ink("M 18 12 L 102 12 Q 110 12 110 20 L 110 66 Q 110 74 102 74 L 18 74 Q 10 74 10 66 L 10 20 Q 10 12 18 12 Z")
+ .draw(80, 850),
+ Stroke::ink("M 52 74 L 49 88 M 68 74 L 71 88 M 40 90 L 80 90").draw(750, 400),
+ Stroke::ink("M 24 24 L 96 24 L 96 62 L 24 62 Z")
+ .with_ink(Ink::Accent)
+ .width(2.5)
+ .marching()
+ .fade(900, 350),
+ Stroke::ink("M 33 29.5 C 35.5 29.5 37.5 31.5 37.5 34 C 37.5 36.5 35.5 38.5 33 38.5 C 30.5 38.5 28.5 36.5 28.5 34 C 28.5 31.5 30.5 29.5 33 29.5 Z")
+ .with_ink(Ink::Red)
+ .filled()
+ .pop(1100, 450)
+ .pulsing(),
+ Stroke::ink("M 72 38 L 72 56 L 76.5 51.5 L 80 59 L 83 57.6 L 79.6 50.4 L 85.5 50.4 Z")
+ .width(2.5)
+ .fade(1250, 300)
+ .bobbing(),
+ ],
+};
+
+pub static CURSOR: Doodle = Doodle {
+ view: (120., 104.),
+ strokes: &[
+ Stroke::ink("M 24 14 L 96 14 Q 104 14 104 22 L 104 74 Q 104 82 96 82 L 24 82 Q 16 82 16 74 L 16 22 Q 16 14 24 14 Z")
+ .with_ink(Ink::Accent)
+ .width(2.5)
+ .marching()
+ .fade(700, 400),
+ Stroke::ink("M 52 32 L 52 78 L 63 67 L 71 86 L 79 82.5 L 71 64 L 87 64 Z")
+ .draw(60, 800)
+ .bobbing(),
+ Stroke::ink("M 44 26 L 38 20 M 42 34 L 33 34 M 50 24 L 50 15")
+ .with_ink(Ink::Soft)
+ .width(3.)
+ .draw(850, 300),
+ ],
+};
+
+pub static MICROPHONE: Doodle = Doodle {
+ view: (120., 104.),
+ strokes: &[
+ Stroke::ink("M 48 24 Q 48 12 60 12 Q 72 12 72 24 L 72 48 Q 72 60 60 60 Q 48 60 48 48 Z")
+ .draw(60, 700),
+ Stroke::ink("M 54 26 L 66 26 M 54 34 L 66 34 M 54 42 L 66 42")
+ .with_ink(Ink::Soft)
+ .width(3.)
+ .fade(700, 300),
+ Stroke::ink("M 38 44 Q 38 72 60 72 Q 82 72 82 44").draw(600, 500),
+ Stroke::ink("M 60 72 L 60 86 M 46 88 L 74 88").draw(1000, 300),
+ Stroke::ink("M 92 30 Q 99 40 92 50")
+ .with_ink(Ink::Accent)
+ .width(3.5)
+ .pop(1200, 450)
+ .pulsing(),
+ Stroke::ink("M 28 30 Q 21 40 28 50")
+ .with_ink(Ink::Accent)
+ .width(3.5)
+ .pop(1300, 450)
+ .pulsing(),
+ Stroke::ink("M 101 22 Q 112 40 101 58")
+ .with_ink(Ink::Accent)
+ .width(3.5)
+ .pop(1400, 450),
+ Stroke::ink("M 19 22 Q 8 40 19 58")
+ .with_ink(Ink::Accent)
+ .width(3.5)
+ .pop(1500, 450),
+ ],
+};
+
+pub static CAMERA: Doodle = Doodle {
+ view: (120., 104.),
+ strokes: &[
+ Stroke::ink("M 30 36 L 44 36 L 50 26 L 70 26 L 76 36 L 90 36 Q 98 36 98 44 L 98 80 Q 98 88 90 88 L 30 88 Q 22 88 22 80 L 22 44 Q 22 36 30 36 Z")
+ .draw(150, 900),
+ Stroke::ink("M 60 47 C 68.3 47 75 53.7 75 62 C 75 70.3 68.3 77 60 77 C 51.7 77 45 70.3 45 62 C 45 53.7 51.7 47 60 47 Z")
+ .draw(900, 500),
+ Stroke::ink("M 60 56 C 63.3 56 66 58.7 66 62 C 66 65.3 63.3 68 60 68 C 56.7 68 54 65.3 54 62 C 54 58.7 56.7 56 60 56 Z")
+ .with_ink(Ink::Accent)
+ .filled()
+ .fade(1200, 300)
+ .pulsing(),
+ Stroke::ink("M 88 43.5 C 89.4 43.5 90.5 44.6 90.5 46 C 90.5 47.4 89.4 48.5 88 48.5 C 86.6 48.5 85.5 47.4 85.5 46 C 85.5 44.6 86.6 43.5 88 43.5 Z")
+ .with_ink(Ink::Accent)
+ .filled()
+ .fade(1350, 300),
+ ],
+};
+
+pub static ALL_SET: Doodle = Doodle {
+ view: (120., 104.),
+ strokes: &[
+ Stroke::ink("M 60 12 C 84 12 102 30 102 52 C 102 75 84 92 60 92 C 35 92 18 74 18 52 C 18 31 34 14 56 12.5 C 62 12 68 13 73 15")
+ .with_ink(Ink::Soft)
+ .width(3.)
+ .draw(450, 750),
+ Stroke::ink("M 38 54 L 54 70 L 84 34")
+ .with_ink(Ink::Green)
+ .width(5.5)
+ .draw(80, 500),
+ ],
+};
+
+/// Row markers, 44x44.
+pub static MARK_PENDING: Doodle = Doodle {
+ view: (44., 44.),
+ strokes: &[Stroke::ink(
+ "M 22 7 C 30.3 7 37 13.7 37 22 C 37 30.3 30.3 37 22 37 C 13.7 37 7 30.3 7 22 C 7 13.7 13.7 7 22 7 Z",
+ )
+ .with_ink(Ink::Track)
+ .width(3.)],
+};
+
+pub static MARK_ACTIVE: Doodle = Doodle {
+ view: (44., 44.),
+ strokes: &[
+ Stroke::ink(
+ "M 22 7 C 30.3 7 37 13.7 37 22 C 37 30.3 30.3 37 22 37 C 13.7 37 7 30.3 7 22 C 7 13.7 13.7 7 22 7 Z",
+ )
+ .with_ink(Ink::Accent)
+ .width(3.)
+ .draw(0, 450),
+ Stroke::ink("M 22 17 C 24.8 17 27 19.2 27 22 C 27 24.8 24.8 27 22 27 C 19.2 27 17 24.8 17 22 C 17 19.2 19.2 17 22 17 Z")
+ .with_ink(Ink::Accent)
+ .filled()
+ .pop(300, 350),
+ ],
+};
+
+pub static MARK_GRANTED: Doodle = Doodle {
+ view: (44., 44.),
+ strokes: &[
+ Stroke::ink(
+ "M 22 6.5 C 30.8 6.5 37.5 13.5 37.5 22 C 37.5 30.8 30.5 37.5 22 37.5 C 13.2 37.5 6.5 30.5 6.5 22 C 6.5 14 12.5 7.5 20 6.8 C 23 6.6 26 7.2 28.5 8.6",
+ )
+ .with_ink(Ink::Green)
+ .width(3.)
+ .draw(0, 500),
+ Stroke::ink("M 14 23 L 20 29 L 30.5 15.5")
+ .with_ink(Ink::Green)
+ .width(3.5)
+ .draw(250, 350),
+ ],
+};
+
+pub static MARK_SKIPPED: Doodle = Doodle {
+ view: (44., 44.),
+ strokes: &[
+ Stroke::ink(
+ "M 22 7 C 30.3 7 37 13.7 37 22 C 37 30.3 30.3 37 22 37 C 13.7 37 7 30.3 7 22 C 7 13.7 13.7 7 22 7 Z",
+ )
+ .with_ink(Ink::Track)
+ .width(3.),
+ Stroke::ink("M 15 22 L 29 22")
+ .with_ink(Ink::Soft)
+ .width(3.)
+ .draw(0, 300),
+ ],
+};
+
+/// The waiting squiggle, 240x26.
+pub static WAITING: Doodle = Doodle {
+ view: (240., 26.),
+ strokes: &[Stroke::ink(
+ "M 6 14 q 6 -7 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0",
+ )
+ .with_ink(Ink::Soft)
+ .width(2.5)
+ .marching()],
+};
+
+/// The drag guide's frame around the app icon, 80x80: a dashed, marching
+/// rounded square that says "pick this up".
+pub static DRAG_FRAME: Doodle = Doodle {
+ view: (80., 80.),
+ strokes: &[Stroke::ink(
+ "M 20 6 L 60 6 Q 74 6 74 20 L 74 60 Q 74 74 60 74 L 20 74 Q 6 74 6 60 L 6 20 Q 6 6 20 6 Z",
+ )
+ .with_ink(Ink::Accent)
+ .width(2.5)
+ .marching()
+ .fade(0, 300)],
+};
+
+/// The drag guide's arrow, 34x44, curling up toward the Settings list.
+pub static UP_ARROW: Doodle = Doodle {
+ view: (34., 44.),
+ strokes: &[
+ Stroke::ink("M 12 40 C 6 30 8 16 22 6")
+ .with_ink(Ink::Accent)
+ .width(3.)
+ .draw(200, 450),
+ Stroke::ink("M 12 6 L 23 5 L 22 16")
+ .with_ink(Ink::Accent)
+ .width(3.)
+ .draw(600, 250)
+ .bobbing(),
+ ],
+};
+
+/// The accent swoosh under a heading, 132x12.
+pub static UNDERLINE: Doodle = Doodle {
+ view: (132., 12.),
+ strokes: &[Stroke::ink("M 4 8 C 34 4 78 3 128 6")
+ .with_ink(Ink::Accent)
+ .width(3.5)
+ .draw(350, 650)],
+};
+
+/// Instant mode: the web recorder's upload cloud, arrow bobbing.
+pub static UPLOAD: Doodle = Doodle {
+ view: (120., 104.),
+ strokes: &[
+ Stroke::ink("M 34 58 L 88 58 C 98 58 106 50 106 41 C 106 32 98.5 25 89.5 25 C 86.5 25 84 25.7 81.8 27 C 79 16.5 69.5 9 58.5 9 C 47 9 37.5 16.8 34.8 27.5 C 25.2 28 17.5 35.4 17.5 44 C 17.5 52 24.8 58 34 58 Z")
+ .draw(60, 800),
+ Stroke::ink("M 60 94 L 60 70 M 49 80 L 60 68 L 71 80")
+ .with_ink(Ink::Accent)
+ .fade(700, 350)
+ .bobbing(),
+ ],
+};
+
+/// Studio mode: the editor's tracks with a playhead.
+pub static TRACKS: Doodle = Doodle {
+ view: (120., 104.),
+ strokes: &[
+ Stroke::ink("M 18 30 L 102 30")
+ .with_ink(Ink::Accent)
+ .width(9.)
+ .draw(60, 500),
+ Stroke::ink("M 18 52 L 84 52")
+ .with_ink(Ink::Soft)
+ .width(9.)
+ .draw(260, 500),
+ Stroke::ink("M 18 74 L 94 74")
+ .with_ink(Ink::Green)
+ .width(9.)
+ .draw(460, 500),
+ Stroke::ink("M 62 14 L 62 90")
+ .with_ink(Ink::Red)
+ .width(2.5)
+ .fade(900, 300),
+ ],
+};
+
+/// Screenshot mode: crop corners around a little landscape.
+pub static SNAP: Doodle = Doodle {
+ view: (120., 104.),
+ strokes: &[
+ Stroke::ink("M 18 30 L 18 16 L 32 16 M 88 16 L 102 16 L 102 30 M 102 74 L 102 88 L 88 88 M 32 88 L 18 88 L 18 74")
+ .draw(60, 700),
+ Stroke::ink("M 32 74 L 50 50 L 62 63 L 72 53 L 88 74")
+ .with_ink(Ink::Accent)
+ .width(3.5)
+ .draw(600, 500),
+ Stroke::ink("M 76 30 C 79.3 30 82 32.7 82 36 C 82 39.3 79.3 42 76 42 C 72.7 42 70 39.3 70 36 C 70 32.7 72.7 30 76 30 Z")
+ .with_ink(Ink::Accent)
+ .filled()
+ .pop(1000, 400),
+ ],
+};
+
+/// A small drawn tick, 24x24.
+pub static TICK: Doodle = Doodle {
+ view: (24., 24.),
+ strokes: &[Stroke::ink("M 4 13 L 9.5 18 L 20 6")
+ .with_ink(Ink::Accent)
+ .width(3.)
+ .draw(0, 300)],
+};
diff --git a/apps/desktop-gpui/src/onboarding_window.rs b/apps/desktop-gpui/src/onboarding_window.rs
index d673229c5..d17f2351f 100644
--- a/apps/desktop-gpui/src/onboarding_window.rs
+++ b/apps/desktop-gpui/src/onboarding_window.rs
@@ -14,9 +14,12 @@ use crate::{
permissions_ui::{PermissionsState, RowAction},
store,
theme::Theme,
- ui,
};
+mod stage;
+
+pub use stage::Paper;
+
pub const ONBOARDING_WIDTH: f32 = 860.;
pub const ONBOARDING_HEIGHT: f32 = 690.;
pub const ONBOARDING_HEADER_HEIGHT: f32 = 36.;
@@ -24,11 +27,6 @@ pub const ONBOARDING_HEADER_HEIGHT: f32 = 36.;
const POLL_INTERVAL: Duration = Duration::from_secs(1);
const REQUEST_GRACE: Duration = Duration::from_secs(2);
const WELCOME_EXIT: Duration = Duration::from_millis(600);
-const CARD_W: f32 = 440.;
-const ROW_PAD_X: f32 = 16.;
-const ROW_GAP: f32 = 16.;
-const ROW_ACTION_W: f32 = 112.;
-const ROW_TEXT_W: f32 = CARD_W - 2. * ROW_PAD_X - ROW_GAP - ROW_ACTION_W;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(usize)]
@@ -193,6 +191,8 @@ pub struct OnboardingWindow {
faq_open: [bool; FAQ.len()],
error: Option<String>,
focus: FocusHandle,
+ stage: stage::StageState,
+ step_at: std::time::Instant,
}
impl OnboardingWindow {
@@ -212,6 +212,7 @@ impl OnboardingWindow {
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
crate::theme::bind_window(window, cx);
+ let granted = std::array::from_fn(|i| state.status(OSPermission::ALL[i]).permitted());
let mut this = Self {
theme: Theme::for_window(window, cx, true),
step: first_step,
@@ -238,6 +239,8 @@ impl OnboardingWindow {
faq_open: [false; FAQ.len()],
error: None,
focus: cx.focus_handle(),
+ stage: stage::StageState::new(granted),
+ step_at: std::time::Instant::now(),
};
cx.observe_window_activation(window, |this: &mut Self, window, cx| {
this.animated = window.is_window_active();
@@ -256,6 +259,16 @@ impl OnboardingWindow {
cx.notify();
})
.detach();
+ #[cfg(debug_assertions)]
+ if !this.welcome
+ && !this.permissions_only
+ && let Ok(name) = std::env::var("CAP_GPUI_ONBOARDING_STEP")
+ && let Some(step) = Step::ALL
+ .into_iter()
+ .find(|step| format!("{step:?}").eq_ignore_ascii_case(&name))
+ {
+ this.step = step;
+ }
this.arm_poll(window, cx);
this.arm_demo(window, cx);
this
@@ -392,6 +405,7 @@ impl OnboardingWindow {
this.update_in(cx, |this, window, cx| {
this.welcome = false;
this.welcome_exiting = false;
+ this.step_at = std::time::Instant::now();
this.audio = None;
this.step_revision = this.step_revision.wrapping_add(1);
this.focus_root(window, cx);
@@ -417,6 +431,7 @@ impl OnboardingWindow {
-1.
};
self.step = step;
+ self.step_at = std::time::Instant::now();
self.step_revision = self.step_revision.wrapping_add(1);
self.poll = None;
self.verify = None;
@@ -439,6 +454,10 @@ impl OnboardingWindow {
if self.welcome || (self.step == Step::Permissions && !self.state.necessary_granted()) {
return;
}
+ if self.step == Step::Permissions && self.needs_relaunch() {
+ permissions::relaunch(cx);
+ return;
+ }
if self.permissions_only || self.step == Step::Faq {
self.finish(cx);
} else if let Some(next) = self
@@ -560,6 +579,7 @@ impl OnboardingWindow {
return;
}
self.pending = Some(permission);
+ self.stage.waiting_on = Some(permission);
self.verify = Some(cx.spawn_in(window, async move |this, cx| {
let raw = cx
.background_executor()
@@ -572,12 +592,29 @@ impl OnboardingWindow {
return false;
}
let action = this.state.refreshed_action(permission, raw);
+ // With the drag guide available, Screen Recording and
+ // Accessibility skip the system alert entirely: its "Open
+ // System Settings" button and the pane it opens are two
+ // more hops, and the list may not even contain Cap.
+ // The pane opens with the guide under it instead.
+ let guided = action.is_some()
+ && permission.required()
+ && crate::permission_guide::eligible(permission);
match action {
None => {
this.pending = None;
cx.notify();
false
}
+ Some(RowAction::OpenSettings) | Some(RowAction::Request) if guided => {
+ this.pending = None;
+ this.state.note_settings_opened(permission);
+ permissions::open_permission_settings(permission);
+ cx.defer(move |cx| crate::permission_guide::start(permission, cx));
+ this.arm_poll(window, cx);
+ cx.notify();
+ false
+ }
Some(RowAction::OpenSettings) => {
this.pending = None;
this.state.note_settings_opened(permission);
@@ -637,125 +674,13 @@ impl OnboardingWindow {
)
}
}
+}
- fn render_permission_row(
- &self,
- permission: OSPermission,
- status: OSPermissionStatus,
- cx: &mut Context<Self>,
- ) -> impl IntoElement {
- let theme = self.theme;
- let (success_bg, success_border, success_fg) = self.success_palette();
- let granted = status == OSPermissionStatus::Granted;
- let busy = self.pending.is_some();
-
- let action: gpui::AnyElement = if granted {
- div()
- .flex()
- .flex_row()
- .items_center()
- .gap(px(6.))
- .px(px(12.))
- .h(px(28.))
- .rounded(px(8.))
- .bg(success_bg)
- .border_1()
- .border_color(success_border)
- .text_size(px(12.))
- .font_weight(FontWeight::MEDIUM)
- .text_color(success_fg)
- .child(
- svg()
- .path("icons/check.svg")
- .size(px(12.))
- .text_color(success_fg),
- )
- .child("Granted")
- .into_any_element()
- } else {
- let label = match self.state.action(permission) {
- Some(RowAction::OpenSettings) => "Open Settings",
- _ => "Grant",
- };
- ui::Button::plain(
- &theme,
- SharedString::from(format!("perm-action-{}", permission.label())),
- ui::ButtonVariant::Gray,
- ui::ButtonSize::Sm,
- )
- .radius(px(8.))
- .label(label)
- .disabled(busy)
- .on_click(cx.listener(move |this, _, window, cx| this.act(permission, window, cx)))
- .into_any_element()
- };
-
- div()
- .flex()
- .flex_row()
- .flex_none()
- .items_center()
- .gap(px(ROW_GAP))
- .w(px(CARD_W))
- .px(px(ROW_PAD_X))
- .py(px(12.))
- .rounded(px(12.))
- .border_1()
- .border_color(theme.body_border(4))
- .bg(if theme.is_dark() {
- theme.body_fill(2)
- } else {
- gpui::white()
- })
- .child(
- div()
- .flex()
- .flex_col()
- .flex_none()
- .w(px(ROW_TEXT_W))
- .gap(px(2.))
- .child(
- div()
- .flex()
- .flex_row()
- .items_center()
- .gap(px(8.))
- .child(
- div()
- .text_size(px(13.))
- .font_weight(FontWeight::MEDIUM)
- .text_color(Hsla::from(theme.gray_12))
- .child(permission.label()),
- )
- .when(!permission.required(), |this| {
- this.child(
- div()
- .text_size(px(10.))
- .px(px(6.))
- .py(px(2.))
- .rounded_full()
- .bg(Hsla::from(theme.gray_3))
- .text_color(Hsla::from(theme.gray_10))
- .child("Optional"),
- )
- }),
- )
- .child(
- div()
- .text_size(px(11.))
- .line_height(px(15.))
- .text_color(Hsla::from(theme.gray_10))
- .child(permission.blurb()),
- ),
- )
- .child(
- div()
- .flex()
- .flex_none()
- .w(px(ROW_ACTION_W))
- .justify_end()
- .child(action),
- )
+fn mode_doodle(mode: Mode) -> &'static crate::doodle::Doodle {
+ match mode {
+ Mode::Instant => &crate::onboarding_doodles::UPLOAD,
+ Mode::Studio => &crate::onboarding_doodles::TRACKS,
+ Mode::Screenshot => &crate::onboarding_doodles::SNAP,
}
}
@@ -798,37 +723,42 @@ impl OnboardingWindow {
})
}
- fn heading(
- &self,
- title: &'static str,
- subtitle: &'static str,
- icon: Option<&'static str>,
- ) -> Div {
- let theme = self.theme;
+ fn paper_card(&self) -> Div {
+ let paper = stage::Paper::new(&self.theme);
+ div()
+ .rounded(px(20.))
+ .border(px(1.5))
+ .border_color(paper.track)
+ .bg(paper.card)
+ }
+
+ fn heading(&self, title: &'static str, subtitle: &'static str) -> Div {
+ let paper = stage::Paper::new(&self.theme);
div()
.flex()
.flex_col()
.items_center()
- .gap(px(12.))
- .max_w(px(480.))
+ .max_w(px(500.))
.text_center()
- .when_some(icon, |el, path| {
- el.child(
- self.card()
- .size(px(48.))
- .rounded(px(16.))
- .flex()
- .items_center()
- .justify_center()
- .child(glyph(path, 20., theme.gray_11)),
- )
- })
.child(
- copy(title, 24., theme.gray_12)
- .font_weight(FontWeight::BOLD)
- .line_height(px(30.)),
+ copy(title, 28., paper.ink)
+ .font_weight(FontWeight::MEDIUM)
+ .line_height(px(34.)),
+ )
+ .child(div().mt(px(4.)).child(crate::doodle::doodle(
+ &crate::onboarding_doodles::UNDERLINE,
+ paper.palette(),
+ self.step_at,
+ !self.animated,
+ 132.,
+ 12.,
+ )))
+ .child(
+ copy(subtitle, 15., paper.soft)
+ .mt(px(10.))
+ .font_weight(FontWeight::NORMAL)
+ .line_height(px(22.)),
)
- .child(copy(subtitle, 14., theme.gray_10).line_height(px(21.)))
}
fn ambient(&self, width: f32, height: f32, welcome: bool) -> AnyElement {
@@ -1131,77 +1061,16 @@ impl OnboardingWindow {
}
}
- fn render_permissions(&self, cx: &mut Context<Self>) -> AnyElement {
- let theme = self.theme;
- div()
- .flex()
- .flex_col()
- .items_center()
- .justify_center()
- .min_h_full()
- .px(px(48.))
- .py(px(24.))
- .gap(px(24.))
- .child(self.heading(
- "Permissions Required",
- "Cap needs a few permissions to record your screen and capture audio.",
- Some("icons/shield.svg"),
- ))
- .child(div().flex().flex_col().w(px(CARD_W)).gap(px(8.)).children(
- self.state.shown().map(|(permission, status)| {
- self.render_permission_row(permission, status, cx)
- .into_any_element()
- }),
- ))
- .when(self.state.relaunch_hint(), |el| {
- el.child(
- div()
- .flex()
- .items_center()
- .gap(px(12.))
- .w(px(CARD_W))
- .p(px(12.))
- .rounded(px(12.))
- .bg(theme.amber_3)
- .border_1()
- .border_color(theme.amber_6)
- .child(glyph("icons/triangle-alert.svg", 16., theme.amber_11))
- .child(
- copy(
- "Granted it in System Settings? Relaunch Cap to apply.",
- 11.,
- theme.amber_11,
- )
- .flex_1()
- .min_w_0(),
- )
- .child(
- ui::Button::plain(
- &theme,
- "perm-relaunch",
- ui::ButtonVariant::White,
- ui::ButtonSize::Sm,
- )
- .radius(px(8.))
- .icon("icons/rotate-ccw.svg")
- .label("Relaunch Cap")
- .on_click(cx.listener(|_, _, _, cx| permissions::relaunch(cx))),
- ),
- )
- })
- .into_any_element()
- }
-
fn render_overview(&self) -> AnyElement {
let theme = self.theme;
div().flex().flex_col().items_center().justify_center().min_h_full().px(px(40.)).gap(px(32.))
- .child(self.heading("One app, every workflow", "Whether you need speed, studio quality, or a quick screenshot — Cap has a mode for it.", None))
+ .child(self.heading("One app, every workflow", "Whether you need speed, studio quality, or a quick screenshot — Cap has a mode for it."))
.child(div().flex().gap(px(16.)).w_full().max_w(px(540.)).children(MODES.iter().enumerate().map(|(index, mode)| {
- let card = self.card().flex_1().min_w_0().flex().flex_col().items_center().gap(px(12.)).p(px(20.)).rounded(px(16.))
- .child(self.card().size(px(48.)).rounded(px(16.)).flex().items_center().justify_center()
- .child(glyph(mode.icon, 20., theme.gray_12)))
- .child(copy(mode.title, 14., theme.gray_12).font_weight(FontWeight::BOLD).text_center())
- .child(copy(mode.tagline, 11., theme.gray_9).line_height(px(15.)).text_center());
+ let paper = stage::Paper::new(&theme);
+ let card = self.paper_card().flex_1().min_w_0().flex().flex_col().items_center().gap(px(10.)).px(px(20.)).pt(px(22.)).pb(px(24.))
+ .child(crate::doodle::doodle(mode_doodle(mode.mode), paper.palette(), self.step_at + Duration::from_millis(index as u64 * 180), !self.animated, 96., 84.))
+ .child(copy(mode.title, 15., paper.ink).font_weight(FontWeight::MEDIUM).text_center().mt(px(4.)))
+ .child(copy(mode.tagline, 12., paper.soft).font_weight(FontWeight::NORMAL).line_height(px(16.)).text_center());
if !self.animated { return card.into_any_element(); }
card.with_animation(("overview-card", index), Animation::new(Duration::from_millis(700 + index as u64 * 100)),
|el, t| el.relative().top(px(16. * (1. - ease(t)))).opacity(ease(t))).into_any_element()
@@ -1209,7 +1078,7 @@ impl OnboardingWindow {
}
fn render_detail(&self, index: usize) -> AnyElement {
- let theme = self.theme;
+ let paper = stage::Paper::new(&self.theme);
let mode = &MODES[index];
div()
.flex()
@@ -1230,54 +1099,56 @@ impl OnboardingWindow {
.flex()
.items_center()
.gap(px(12.))
- .child(
- self.card()
- .size(px(44.))
- .flex_shrink_0()
- .flex()
- .items_center()
- .justify_center()
- .child(glyph(mode.icon, 20., theme.gray_12)),
- )
+ .child(crate::doodle::doodle(
+ mode_doodle(mode.mode),
+ paper.palette(),
+ self.step_at,
+ !self.animated,
+ 58.,
+ 50.,
+ ))
.child(
div()
.flex()
.flex_col()
.gap(px(3.))
.child(
- copy(mode.title, 18., theme.gray_12)
- .font_weight(FontWeight::BOLD),
+ copy(mode.title, 20., paper.ink)
+ .font_weight(FontWeight::MEDIUM),
)
.child(
- copy(mode.tagline, 11., theme.gray_9)
- .font_weight(FontWeight::MEDIUM),
+ copy(mode.tagline, 12., paper.soft)
+ .font_weight(FontWeight::NORMAL),
),
),
)
- .child(copy(mode.description, 13., theme.gray_10).line_height(px(20.)))
+ .child(
+ copy(mode.description, 13., paper.soft)
+ .font_weight(FontWeight::NORMAL)
+ .line_height(px(20.)),
+ )
.child(div().flex().flex_col().gap(px(10.)).children(
- mode.features.iter().map(|feature| {
+ mode.features.iter().enumerate().map(|(i, feature)| {
div()
.flex()
.items_center()
.gap(px(10.))
+ .child(crate::doodle::doodle(
+ &crate::onboarding_doodles::TICK,
+ paper.palette(),
+ self.step_at + Duration::from_millis(400 + i as u64 * 140),
+ !self.animated,
+ 18.,
+ 18.,
+ ))
.child(
- div()
- .size(px(20.))
- .rounded_full()
- .bg(theme.blue_9)
- .flex_shrink_0()
- .flex()
- .items_center()
- .justify_center()
- .child(glyph("icons/check.svg", 10., gpui::white())),
+ copy(*feature, 13., paper.ink).font_weight(FontWeight::NORMAL),
)
- .child(copy(*feature, 12., theme.gray_11))
}),
)),
)
.child(
- self.card()
+ self.paper_card()
.flex_1()
.min_w_0()
.h(px(if index == 1 { 300. } else { 288. }))
@@ -1313,7 +1184,6 @@ impl OnboardingWindow {
.child(self.heading(
"Switch modes anytime",
"Toggle between modes with a single click from the main Cap window.",
- None,
))
.child(
div()
@@ -1322,7 +1192,7 @@ impl OnboardingWindow {
.items_center()
.gap(px(20.))
.child(
- self.card()
+ self.paper_card()
.rounded_full()
.flex()
.gap(px(24.))
@@ -1392,14 +1262,14 @@ impl OnboardingWindow {
fn render_shortcuts(&self) -> AnyElement {
let theme = self.theme;
div().flex().flex_col().items_center().justify_center().min_h_full().px(px(48.)).gap(px(24.))
- .child(self.heading("Make Cap yours", "Customize everything from keyboard shortcuts to storage. Cap adapts to your workflow.", Some("icons/settings.svg")))
+ .child(self.heading("Make Cap yours", "Customize everything from keyboard shortcuts to storage. Cap adapts to your workflow."))
.child(div().flex().flex_col().w_full().max_w(px(420.)).gap(px(8.)).children([
("Keyboard Shortcuts", "Global hotkeys for recording, screenshots, and switching modes"),
("Custom S3 Storage", "Connect your own S3-compatible bucket for full control over your recordings"),
("Custom Domain", "Use your own domain for shareable links instead of cap.so"),
("Recording Preferences", "FPS, quality, countdown timer, cursor effects, and more"),
].into_iter().map(|(title, description)| {
- self.card().px(px(16.)).py(px(12.)).flex().flex_col().gap(px(4.))
+ self.paper_card().rounded(px(16.)).px(px(18.)).py(px(13.)).flex().flex_col().gap(px(4.))
.child(copy(title, 13., theme.gray_12).font_weight(FontWeight::MEDIUM))
.child(copy(description, 11., theme.gray_10).line_height(px(15.)))
})))
@@ -1421,10 +1291,9 @@ impl OnboardingWindow {
.child(self.heading(
"Frequently Asked Questions",
"Everything you need to know to get started.",
- None,
))
.child(
- self.card()
+ self.paper_card()
.w_full()
.max_w(px(480.))
.overflow_hidden()
@@ -1496,7 +1365,7 @@ impl OnboardingWindow {
}
fn render_navigation(&self, cx: &mut Context<Self>) -> AnyElement {
- let theme = self.theme;
+ let paper = stage::Paper::new(&self.theme);
let first = self.first_step as usize;
let current = self.step as usize - first;
let total = if self.permissions_only {
@@ -1506,7 +1375,10 @@ impl OnboardingWindow {
};
let disabled = self.step == Step::Permissions && !self.state.necessary_granted();
let last = self.permissions_only || self.step == Step::Faq;
- let label = if self.permissions_only {
+ let relaunch = self.step == Step::Permissions && !disabled && self.needs_relaunch();
+ let label = if relaunch {
+ "Relaunch Cap"
+ } else if self.permissions_only {
"Continue to Cap"
} else if last {
"Start Using Cap"
@@ -1517,9 +1389,9 @@ impl OnboardingWindow {
.flex()
.flex_col()
.items_center()
- .gap(px(8.))
- .px(px(32.))
- .pb(px(20.))
+ .gap(px(10.))
+ .px(px(36.))
+ .pb(px(18.))
.pt(px(8.))
.flex_shrink_0()
.child(
@@ -1530,10 +1402,10 @@ impl OnboardingWindow {
.w_full()
.child(div().flex_1().when(current > 0, |el| {
el.child(
- copy("← Back", 13., theme.gray_10)
+ copy("← Back", 13., paper.soft)
.id("onboarding-back")
.cursor_pointer()
- .hover(move |el| el.text_color(theme.gray_12))
+ .hover(move |el| el.text_color(paper.ink))
.on_click(cx.listener(|this, _, window, cx| this.back(window, cx))),
)
}))
@@ -1541,95 +1413,101 @@ impl OnboardingWindow {
div()
.flex()
.items_center()
- .gap(px(4.))
- .children((0..total).map(|index| {
- div()
- .h(px(6.))
- .w(px(if current == index { 20. } else { 6. }))
- .rounded_full()
- .bg(if current == index {
- theme.gray_12
- } else if current > index {
- theme.gray_8
- } else {
- theme.gray_5
- })
- })),
- )
- .child(
- div().flex_1().flex().justify_end().child(
- div()
- .flex()
- .flex_col()
- .items_center()
- .gap(px(6.))
- .child(
+ .gap(px(5.))
+ .when(total > 1, |el| {
+ el.children((0..total).map(|index| {
div()
- .id("onboarding-continue")
- .tab_index(0)
- .min_w(px(152.))
- .min_h(px(48.))
- .px(px(40.))
- .py(px(12.))
+ .h(px(6.))
+ .w(px(if current == index { 22. } else { 6. }))
.rounded_full()
- .flex()
- .items_center()
- .justify_center()
- .gap(px(8.))
- .bg(if disabled {
- theme.gray_6
+ .bg(if current == index {
+ paper.ink
+ } else if current > index {
+ paper.soft
} else {
- theme.gray_12
- })
- .text_color(if disabled {
- theme.gray_9
- } else {
- theme.gray_1
- })
- .when(!disabled, |el| {
- el.cursor_pointer().on_click(cx.listener(
- |this, _, window, cx| this.next(window, cx),
- ))
+ paper.track
})
- .child(
- div()
- .text_size(px(15.))
- .font_weight(FontWeight::MEDIUM)
- .child(label),
- )
- .child(glyph(
- if last {
- "icons/check.svg"
- } else {
- "icons/move-right.svg"
- },
- 16.,
- if disabled { theme.gray_9 } else { theme.gray_1 },
- )),
- )
- .when(
- self.state.necessary_granted() && !self.permissions_only,
- |el| {
- el.child(
- copy("Skip onboarding", 11., theme.gray_9)
- .id("onboarding-skip")
- .cursor_pointer()
- .on_click(
- cx.listener(|this, _, _, cx| this.finish(cx)),
- ),
+ }))
+ }),
+ )
+ .child(
+ div().flex_1().flex().justify_end().child(
+ div().flex().flex_col().items_end().gap(px(8.)).child(
+ div()
+ .id("onboarding-continue")
+ .tab_index(0)
+ .h(px(46.))
+ .px(px(26.))
+ .rounded_full()
+ .flex()
+ .items_center()
+ .justify_center()
+ .gap(px(8.))
+ .border(px(1.5))
+ .border_color(if disabled { paper.track } else { paper.ink })
+ .bg(if disabled {
+ gpui::transparent_black()
+ } else {
+ paper.ink
+ })
+ .text_color(if disabled { paper.soft } else { paper.bg })
+ .when(!disabled, |el| {
+ el.cursor_pointer().hover(|el| el.opacity(0.88)).on_click(
+ cx.listener(|this, _, window, cx| {
+ this.next(window, cx)
+ }),
)
- },
- ),
+ })
+ .child(
+ div()
+ .text_size(px(14.))
+ .font_weight(FontWeight::MEDIUM)
+ .child(label),
+ )
+ .child(glyph(
+ if relaunch {
+ "icons/rotate-ccw.svg"
+ } else if last {
+ "icons/check.svg"
+ } else {
+ "icons/move-right.svg"
+ },
+ 15.,
+ if disabled { paper.soft } else { paper.bg },
+ )),
+ ),
),
),
)
- .child(copy(
- "Press Enter ↵ or use ← → arrow keys",
- 10.,
- theme.gray_8,
- ))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(14.))
+ .child(copy(
+ if disabled {
+ "Allow the required permissions to continue"
+ } else {
+ "Press Enter ↵ or use ← → arrow keys"
+ },
+ 11.,
+ paper.soft,
+ ))
+ .when(
+ self.state.necessary_granted() && !self.permissions_only && !last,
+ |el| {
+ el.child(
+ copy("Skip the tour", 11., paper.soft)
+ .id("onboarding-skip")
+ .cursor_pointer()
+ .hover(move |el| el.text_color(paper.ink))
+ .on_click(cx.listener(|this, _, _, cx| this.finish(cx))),
+ )
+ },
+ ),
+ )
.when_some(self.error.clone(), |el, error| {
- el.child(copy(error, 12., theme.gray_12))
+ el.child(copy(error, 12., paper.red))
})
.into_any_element()
}
@@ -2474,7 +2352,11 @@ impl OnboardingWindow {
impl Render for OnboardingWindow {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.theme = Theme::for_window(window, cx, true);
+ if self.permissions_visible() {
+ self.sync_stage(window, cx);
+ }
let theme = self.theme;
+ let paper = stage::Paper::new(&theme);
let viewport = window.viewport_size();
let width = f32::from(viewport.width);
let height = (f32::from(viewport.height) - ONBOARDING_HEADER_HEIGHT).max(0.);
@@ -2509,9 +2391,11 @@ impl Render for OnboardingWindow {
.flex()
.items_center()
.justify_between()
- .bg(theme.header_bg())
- .border_b_1()
- .border_color(theme.header_border())
+ .bg(if self.welcome {
+ rgb(0x3b82f6).into()
+ } else {
+ paper.bg
+ })
.window_control_area(gpui::WindowControlArea::Drag);
#[cfg(target_os = "windows")]
let header = header.justify_end().child(ui::windows_caption_controls(
@@ -2573,9 +2457,7 @@ impl Render for OnboardingWindow {
.min_h_0()
.w_full()
.overflow_hidden()
- .when(!self.welcome, |el| {
- el.child(self.ambient(width, height, false))
- })
+ .when(!self.welcome, |el| el.bg(paper.bg))
.when(!self.welcome, |el| {
el.child(
div()
diff --git a/apps/desktop-gpui/src/onboarding_window/stage.rs b/apps/desktop-gpui/src/onboarding_window/stage.rs
new file mode 100644
index 000000000..ff7b00a12
--- /dev/null
+++ b/apps/desktop-gpui/src/onboarding_window/stage.rs
@@ -0,0 +1,835 @@
+//! The permissions step: one permission at a time on the right, the checklist
+//! on the left, in the paper-and-ink look of Cap's Chrome extension pages.
+//!
+//! Only presentation and focus live here. Requests, polling and the
+//! grant/denied classification are still `OnboardingWindow::act`, the poll
+//! task and [`PermissionsState`](crate::permissions_ui::PermissionsState).
+
+use std::time::{Duration, Instant};
+
+use gpui::{
+ AnyElement, Context, Div, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement,
+ SharedString, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px, rgb,
+ rgba,
+};
+
+use super::OnboardingWindow;
+use crate::doodle::{self, Doodle, Palette};
+use crate::onboarding_doodles as art;
+use crate::permissions::{self, OSPermission, OSPermissionStatus};
+use crate::permissions_ui::RowAction;
+use crate::theme::Theme;
+
+/// How long a freshly granted permission stays on stage, check drawn, before
+/// the next one slides in.
+const ADVANCE_AFTER: Duration = Duration::from_millis(1400);
+const LIST_W: f32 = 296.;
+const STAGE_W: f32 = 420.;
+
+#[derive(Clone, Copy)]
+pub struct Paper {
+ pub bg: Hsla,
+ pub card: Hsla,
+ pub ink: Hsla,
+ pub soft: Hsla,
+ pub accent: Hsla,
+ pub red: Hsla,
+ pub green: Hsla,
+ pub track: Hsla,
+}
+
+impl Paper {
+ pub fn new(theme: &Theme) -> Self {
+ if theme.is_dark() {
+ Self {
+ bg: rgb(0x18181b).into(),
+ card: rgba(0xffffff0d).into(),
+ ink: rgb(0xf2f2f3).into(),
+ soft: rgb(0x8e8e96).into(),
+ accent: rgb(0x4d8dff).into(),
+ red: rgb(0xff6369).into(),
+ green: rgb(0x3dd68c).into(),
+ track: rgb(0x3a3a40).into(),
+ }
+ } else {
+ Self {
+ bg: rgb(0xfbfaf7).into(),
+ card: rgba(0xffffffa6).into(),
+ ink: rgb(0x20242c).into(),
+ soft: rgb(0x8b8f98).into(),
+ accent: rgb(0x4785ff).into(),
+ red: rgb(0xe5484d).into(),
+ green: rgb(0x2f9e69).into(),
+ track: rgb(0xdcdcd4).into(),
+ }
+ }
+ }
+
+ pub fn palette(&self) -> Palette {
+ Palette {
+ ink: self.ink,
+ soft: self.soft,
+ accent: self.accent,
+ red: self.red,
+ green: self.green,
+ track: self.track,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) enum Stage {
+ Permission(OSPermission),
+ AllSet,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Mark {
+ Pending,
+ Active,
+ Granted,
+ Skipped,
+}
+
+pub(super) struct StageState {
+ /// Pinned by a row click, or by a grant landing on the permission on
+ /// stage (held for [`ADVANCE_AFTER`]). `None` follows the first
+ /// permission still to do.
+ focused: Option<OSPermission>,
+ skipped: Vec<OSPermission>,
+ /// The permission whose action was taken and is now waiting on macOS.
+ pub(super) waiting_on: Option<OSPermission>,
+ shown: Option<(Stage, bool)>,
+ shown_at: Instant,
+ marks: [(Mark, Instant); 4],
+ granted: [bool; 4],
+ page_at: Instant,
+ /// Screen Recording was already granted when Cap launched. A grant that
+ /// lands mid-session only reaches capture after a restart.
+ screen_at_launch: bool,
+ advance: Option<gpui::Task<()>>,
+}
+
+impl StageState {
+ pub(super) fn new(granted: [bool; 4]) -> Self {
+ let now = Instant::now();
+ Self {
+ focused: None,
+ skipped: Vec::new(),
+ waiting_on: None,
+ shown: None,
+ shown_at: now,
+ marks: [(Mark::Pending, now); 4],
+ granted,
+ page_at: now,
+ screen_at_launch: granted[0],
+ advance: None,
+ }
+ }
+}
+
+fn index(permission: OSPermission) -> usize {
+ OSPermission::ALL
+ .iter()
+ .position(|&candidate| candidate == permission)
+ .unwrap_or(0)
+}
+
+struct Copy {
+ title: &'static str,
+ body: &'static str,
+ done_title: &'static str,
+ done_body: &'static str,
+ allow: &'static str,
+ doodle: &'static Doodle,
+}
+
+fn copy_for(permission: OSPermission) -> Copy {
+ match permission {
+ OSPermission::ScreenRecording => Copy {
+ title: "Let Cap see your screen",
+ body: "Screen Recording lets Cap capture your displays, windows and system audio.",
+ done_title: "Screen recording is on",
+ done_body: "Cap can capture your screen.",
+ allow: "Allow screen recording",
+ doodle: &art::SCREEN,
+ },
+ OSPermission::Accessibility => Copy {
+ title: "Let Cap follow your cursor",
+ body: "Accessibility lets Cap see your clicks and cursor, on this Mac only, so auto zoom knows where to look.",
+ done_title: "Accessibility is on",
+ done_body: "Auto zoom can follow your clicks.",
+ allow: "Allow accessibility",
+ doodle: &art::CURSOR,
+ },
+ OSPermission::Microphone => Copy {
+ title: "Let Cap hear you",
+ body: "Add your voice to your recordings. You can skip this and turn it on later.",
+ done_title: "Microphone is on",
+ done_body: "Your voice can be in your recordings.",
+ allow: "Allow microphone",
+ doodle: &art::MICROPHONE,
+ },
+ OSPermission::Camera => Copy {
+ title: "Let Cap see you",
+ body: "Show yourself in a corner of your recordings. Skip it if you don't need it.",
+ done_title: "Camera is on",
+ done_body: "You can add your camera to any recording.",
+ allow: "Allow camera",
+ doodle: &art::CAMERA,
+ },
+ }
+}
+
+impl OnboardingWindow {
+ pub(super) fn needs_relaunch(&self) -> bool {
+ !self.stage.screen_at_launch
+ && self.state.status(OSPermission::ScreenRecording).permitted()
+ && self.state.status(OSPermission::ScreenRecording) != OSPermissionStatus::NotNeeded
+ }
+
+ fn is_skipped(&self, permission: OSPermission) -> bool {
+ self.stage.skipped.contains(&permission)
+ }
+
+ pub(super) fn current_stage(&self) -> Stage {
+ let shown: Vec<(OSPermission, OSPermissionStatus)> = self.state.shown().collect();
+ if let Some(focused) = self.stage.focused
+ && shown.iter().any(|(permission, _)| *permission == focused)
+ {
+ return Stage::Permission(focused);
+ }
+ shown
+ .iter()
+ .find(|(permission, status)| !status.permitted() && !self.is_skipped(*permission))
+ .map(|(permission, _)| Stage::Permission(*permission))
+ .unwrap_or(Stage::AllSet)
+ }
+
+ /// Reconcile focus, marks and entrance clocks with the latest grants.
+ /// Called from `render`, so every path that folds in a sweep is covered.
+ pub(super) fn sync_stage(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let now = Instant::now();
+ let granted: [bool; 4] =
+ std::array::from_fn(|i| self.state.status(OSPermission::ALL[i]).permitted());
+ for (i, &permission) in OSPermission::ALL.iter().enumerate() {
+ if !granted[i] || self.stage.granted[i] {
+ continue;
+ }
+ if self.stage.waiting_on == Some(permission) {
+ self.stage.waiting_on = None;
+ }
+ if self.current_stage() == Stage::Permission(permission) {
+ self.stage.focused = Some(permission);
+ self.stage.advance = Some(cx.spawn_in(window, async move |this, cx| {
+ cx.background_executor().timer(ADVANCE_AFTER).await;
+ this.update(cx, |this, cx| {
+ if this.stage.focused == Some(permission) {
+ this.stage.focused = None;
+ cx.notify();
+ }
+ this.stage.advance = None;
+ })
+ .ok();
+ }));
+ }
+ }
+ self.stage.granted = granted;
+
+ let stage = self.current_stage();
+ let stage_done = match stage {
+ Stage::Permission(permission) => granted[index(permission)],
+ Stage::AllSet => true,
+ };
+ if self.stage.shown != Some((stage, stage_done)) {
+ if self
+ .stage
+ .shown
+ .is_none_or(|(previous, _)| previous != stage)
+ {
+ self.stage.shown_at = now;
+ }
+ self.stage.shown = Some((stage, stage_done));
+ }
+ if let Stage::Permission(on_stage) = stage
+ && self
+ .stage
+ .waiting_on
+ .is_some_and(|waiting| waiting != on_stage)
+ {
+ self.stage.waiting_on = None;
+ }
+ if let Some(waiting) = self.stage.waiting_on
+ && !waiting.required()
+ && self.pending.is_none()
+ && self.state.status(waiting) == OSPermissionStatus::Denied
+ {
+ self.stage.waiting_on = None;
+ }
+ for (i, &permission) in OSPermission::ALL.iter().enumerate() {
+ let mark = if granted[i] {
+ Mark::Granted
+ } else if self.is_skipped(permission) {
+ Mark::Skipped
+ } else if stage == Stage::Permission(permission) {
+ Mark::Active
+ } else {
+ Mark::Pending
+ };
+ if self.stage.marks[i].0 != mark {
+ self.stage.marks[i] = (mark, now);
+ }
+ }
+ }
+
+ fn focus_permission(&mut self, permission: OSPermission, cx: &mut Context<Self>) {
+ self.stage.advance = None;
+ self.stage.focused = Some(permission);
+ self.stage.skipped.retain(|&skipped| skipped != permission);
+ cx.notify();
+ }
+
+ fn skip_permission(&mut self, permission: OSPermission, cx: &mut Context<Self>) {
+ if permission.required() {
+ return;
+ }
+ self.stage.advance = None;
+ if !self.is_skipped(permission) {
+ self.stage.skipped.push(permission);
+ }
+ if self.stage.focused == Some(permission) {
+ self.stage.focused = None;
+ }
+ if self.stage.waiting_on == Some(permission) {
+ self.stage.waiting_on = None;
+ }
+ cx.notify();
+ }
+
+ pub(super) fn render_permissions(&self, cx: &mut Context<Self>) -> AnyElement {
+ let paper = Paper::new(&self.theme);
+ div()
+ .flex()
+ .flex_row()
+ .items_center()
+ .justify_center()
+ .min_h_full()
+ .px(px(40.))
+ .py(px(24.))
+ .gap(px(44.))
+ .child(self.render_checklist(&paper, cx))
+ .child(self.render_stage(&paper, cx))
+ .into_any_element()
+ }
+
+ fn render_checklist(&self, paper: &Paper, cx: &mut Context<Self>) -> Div {
+ let (title, lede) = if self.permissions_only {
+ (
+ "Cap needs a permission back",
+ "Something was switched off in System Settings. Turn it back on to keep recording.",
+ )
+ } else {
+ (
+ "Let's get Cap ready",
+ "macOS asks you to OK a few things first. It only takes a minute.",
+ )
+ };
+ let stage = self.current_stage();
+ div()
+ .flex()
+ .flex_col()
+ .w(px(LIST_W))
+ .flex_none()
+ .child(
+ div()
+ .text_size(px(28.))
+ .line_height(px(34.))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(paper.ink)
+ .child(title),
+ )
+ .child(div().mt(px(2.)).child(doodle::doodle(
+ &art::UNDERLINE,
+ paper.palette(),
+ self.stage.page_at,
+ !self.animated,
+ 132.,
+ 12.,
+ )))
+ .child(
+ div()
+ .mt(px(10.))
+ .text_size(px(14.))
+ .line_height(px(21.))
+ .font_weight(FontWeight::NORMAL)
+ .text_color(paper.soft)
+ .child(lede),
+ )
+ .child(div().mt(px(26.)).flex().flex_col().gap(px(6.)).children(
+ self.state.shown().map(|(permission, status)| {
+ self.render_check_row(
+ paper,
+ permission,
+ status,
+ stage == Stage::Permission(permission),
+ cx,
+ )
+ }),
+ ))
+ }
+
+ fn render_check_row(
+ &self,
+ paper: &Paper,
+ permission: OSPermission,
+ status: OSPermissionStatus,
+ active: bool,
+ cx: &mut Context<Self>,
+ ) -> AnyElement {
+ let (mark, mark_at) = self.stage.marks[index(permission)];
+ let doodle = match mark {
+ Mark::Pending => &art::MARK_PENDING,
+ Mark::Active => &art::MARK_ACTIVE,
+ Mark::Granted => &art::MARK_GRANTED,
+ Mark::Skipped => &art::MARK_SKIPPED,
+ };
+ let (caption, caption_color) = if status.permitted() {
+ ("Allowed", paper.green)
+ } else if self.is_skipped(permission) {
+ ("Skipped for now", paper.soft)
+ } else if status == OSPermissionStatus::Denied {
+ ("Off in System Settings", paper.red)
+ } else if permission.required() {
+ ("Required", paper.soft)
+ } else {
+ ("Optional", paper.soft)
+ };
+ let paper = *paper;
+ div()
+ .id(SharedString::from(format!(
+ "perm-row-{}",
+ permission.label()
+ )))
+ .flex()
+ .flex_row()
+ .items_center()
+ .gap(px(12.))
+ .h(px(56.))
+ .px(px(12.))
+ .rounded(px(14.))
+ .border(px(1.5))
+ .border_color(if active {
+ paper.ink
+ } else {
+ gpui::transparent_black()
+ })
+ .when(active, |row| row.bg(paper.card))
+ .when(!active, |row| {
+ row.cursor_pointer()
+ .hover(move |row| row.bg(paper.card))
+ .on_click(
+ cx.listener(move |this, _, _, cx| this.focus_permission(permission, cx)),
+ )
+ })
+ .child(doodle::doodle(
+ doodle,
+ paper.palette(),
+ mark_at,
+ !self.animated,
+ 30.,
+ 30.,
+ ))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(1.))
+ .child(
+ div()
+ .text_size(px(14.))
+ .line_height(px(18.))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(paper.ink)
+ .child(permission.label()),
+ )
+ .child(
+ div()
+ .text_size(px(12.))
+ .line_height(px(16.))
+ .font_weight(FontWeight::NORMAL)
+ .text_color(caption_color)
+ .child(caption),
+ ),
+ )
+ .into_any_element()
+ }
+
+ fn render_stage(&self, paper: &Paper, cx: &mut Context<Self>) -> AnyElement {
+ let stage = self.current_stage();
+ let shown_at = self.stage.shown_at;
+ let still = !self.animated;
+ let card = div()
+ .id("perm-stage")
+ .flex()
+ .flex_col()
+ .items_center()
+ .w(px(STAGE_W))
+ .flex_none()
+ .min_h(px(420.))
+ .justify_center()
+ .px(px(36.))
+ .py(px(30.))
+ .rounded(px(24.))
+ .border(px(1.5))
+ .border_color(paper.track)
+ .bg(paper.card);
+
+ let card = match stage {
+ Stage::AllSet if self.needs_relaunch() => card
+ .child(doodle::doodle(
+ &art::ALL_SET,
+ paper.palette(),
+ shown_at,
+ still,
+ 168.,
+ 146.,
+ ))
+ .child(stage_title(paper, "One restart and you're set"))
+ .child(stage_body(
+ paper,
+ "macOS turns on screen recording once Cap restarts. You'll pick up right here.",
+ ))
+ .child(div().mt(px(24.)).child(paper_button(
+ paper,
+ "perm-relaunch-done",
+ "Relaunch Cap",
+ true,
+ true,
+ cx.listener(|_, _, _, cx| permissions::relaunch(cx)),
+ ))),
+ Stage::AllSet => card
+ .child(doodle::doodle(
+ &art::ALL_SET,
+ paper.palette(),
+ shown_at,
+ still,
+ 168.,
+ 146.,
+ ))
+ .child(stage_title(paper, "You're all set"))
+ .child(stage_body(
+ paper,
+ if self.permissions_only {
+ "Thanks. Cap can record again."
+ } else {
+ "Cap has everything it needs. Next, a quick look at what it can do."
+ },
+ )),
+ Stage::Permission(permission) => {
+ let copy = copy_for(permission);
+ let status = self.state.status(permission);
+ let granted = status.permitted();
+ let card = card
+ .child(doodle::doodle(
+ copy.doodle,
+ paper.palette(),
+ shown_at,
+ still,
+ 168.,
+ 146.,
+ ))
+ .child(stage_title(
+ paper,
+ if granted {
+ copy.done_title
+ } else if self.stage.waiting_on == Some(permission) && permission.required()
+ {
+ "Switch Cap on in System Settings"
+ } else {
+ copy.title
+ },
+ ));
+ if granted {
+ let done_body = if permission == OSPermission::ScreenRecording
+ && self.needs_relaunch()
+ {
+ "macOS applies it after Cap restarts. You can do that once you're done here."
+ } else {
+ copy.done_body
+ };
+ card.child(stage_body(paper, done_body)).child(allowed_pill(
+ paper,
+ self.stage.marks[index(permission)].1,
+ still,
+ ))
+ } else {
+ self.render_stage_actions(card, paper, permission, status, &copy, cx)
+ }
+ }
+ };
+
+ card.into_any_element()
+ }
+
+ fn render_stage_actions(
+ &self,
+ card: gpui::Stateful<Div>,
+ paper: &Paper,
+ permission: OSPermission,
+ status: OSPermissionStatus,
+ copy: &Copy,
+ cx: &mut Context<Self>,
+ ) -> gpui::Stateful<Div> {
+ let action = self.state.action(permission);
+ let busy = self.pending.is_some();
+ let waiting = self.stage.waiting_on == Some(permission);
+ let guided = crate::permission_guide::eligible(permission);
+ let waiting_required = waiting && permission.required();
+ let body = if waiting_required && guided {
+ "Drag Cap from the panel under System Settings into the list. Already listed? Just switch it on."
+ } else if waiting_required {
+ "Find Cap in the list and switch it on. If macOS asked first, choose Open System Settings."
+ } else if status == OSPermissionStatus::Denied && !permission.required() {
+ "It was turned off earlier, so switch Cap on in System Settings. Or skip it for now."
+ } else if action == Some(RowAction::OpenSettings) && permission.required() {
+ "Open System Settings, find Cap in the list and switch it on."
+ } else {
+ copy.body
+ };
+ let primary_label = if waiting_required {
+ "Open System Settings again"
+ } else {
+ match action {
+ Some(RowAction::OpenSettings) => "Open System Settings",
+ _ => copy.allow,
+ }
+ };
+ let paper_copy = *paper;
+ let card = card.child(stage_body(paper, body)).child(
+ div()
+ .mt(px(24.))
+ .flex()
+ .flex_row()
+ .items_center()
+ .justify_center()
+ .gap(px(10.))
+ .child(paper_button(
+ paper,
+ SharedString::from(format!("perm-action-{}", permission.label())),
+ primary_label,
+ true,
+ !busy,
+ cx.listener(move |this, _, window, cx| this.act(permission, window, cx)),
+ ))
+ .when(!permission.required(), |row| {
+ row.child(paper_button(
+ &paper_copy,
+ SharedString::from(format!("perm-skip-{}", permission.label())),
+ "Skip for now",
+ false,
+ true,
+ cx.listener(move |this, _, _, cx| this.skip_permission(permission, cx)),
+ ))
+ }),
+ );
+
+ // The AV request returned without macOS ever showing its prompt
+ // (still undetermined once the request settled): say so and offer
+ // the pane, instead of waiting on a dialog that is not there.
+ let no_prompt = waiting
+ && !permission.required()
+ && !busy
+ && status == OSPermissionStatus::NotDetermined;
+ let card = if no_prompt {
+ card.child(
+ div()
+ .mt(px(18.))
+ .flex()
+ .flex_col()
+ .items_center()
+ .gap(px(10.))
+ .child(
+ div()
+ .text_size(px(12.))
+ .font_weight(FontWeight::NORMAL)
+ .text_color(paper.soft)
+ .child("No prompt showed up? Switch Cap on in System Settings."),
+ )
+ .child(paper_button(
+ paper,
+ SharedString::from(format!("perm-settings-{}", permission.label())),
+ "Open System Settings",
+ false,
+ true,
+ cx.listener(move |this, _, _, cx| {
+ this.state.note_settings_opened(permission);
+ permissions::open_permission_settings(permission);
+ cx.notify();
+ }),
+ )),
+ )
+ } else if waiting {
+ let hint = if permission.required() || action == Some(RowAction::OpenSettings) {
+ "Waiting for System Settings"
+ } else {
+ "Choose Allow in the macOS prompt"
+ };
+ card.child(
+ div()
+ .mt(px(18.))
+ .flex()
+ .flex_col()
+ .items_center()
+ .gap(px(4.))
+ .child(doodle::doodle(
+ &art::WAITING,
+ paper.palette(),
+ self.stage.shown_at,
+ !self.animated,
+ 150.,
+ 16.,
+ ))
+ .child(
+ div()
+ .text_size(px(12.))
+ .font_weight(FontWeight::NORMAL)
+ .text_color(paper.soft)
+ .child(hint),
+ ),
+ )
+ } else {
+ card
+ };
+
+ if permission == OSPermission::ScreenRecording && waiting && self.state.relaunch_hint() {
+ card.child(
+ div()
+ .mt(px(18.))
+ .w_full()
+ .flex()
+ .flex_row()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(10.))
+ .rounded(px(14.))
+ .border(px(1.5))
+ .border_color(paper.track)
+ .child(
+ div()
+ .flex_1()
+ .min_w_0()
+ .text_size(px(12.))
+ .line_height(px(17.))
+ .font_weight(FontWeight::NORMAL)
+ .text_color(paper.soft)
+ .child("Switched on but still waiting? Restart Cap to apply it."),
+ )
+ .child(paper_button(
+ paper,
+ "perm-relaunch",
+ "Relaunch",
+ false,
+ true,
+ cx.listener(|_, _, _, cx| permissions::relaunch(cx)),
+ )),
+ )
+ } else {
+ card
+ }
+ }
+}
+
+fn stage_title(paper: &Paper, title: &'static str) -> Div {
+ div()
+ .mt(px(22.))
+ .text_size(px(22.))
+ .line_height(px(28.))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(paper.ink)
+ .text_center()
+ .child(title)
+}
+
+fn stage_body(paper: &Paper, body: &'static str) -> Div {
+ div()
+ .mt(px(8.))
+ .max_w(px(320.))
+ .text_size(px(14.))
+ .line_height(px(21.))
+ .font_weight(FontWeight::NORMAL)
+ .text_color(paper.soft)
+ .text_center()
+ .child(body)
+}
+
+fn allowed_pill(paper: &Paper, shown_at: Instant, still: bool) -> Div {
+ div()
+ .mt(px(24.))
+ .flex()
+ .flex_row()
+ .items_center()
+ .gap(px(6.))
+ .h(px(42.))
+ .px(px(18.))
+ .rounded_full()
+ .border(px(1.5))
+ .border_color(paper.green)
+ .text_size(px(14.))
+ .text_color(paper.green)
+ .child(doodle::doodle(
+ &art::MARK_GRANTED,
+ paper.palette(),
+ shown_at,
+ still,
+ 22.,
+ 22.,
+ ))
+ .child("Allowed")
+}
+
+/// The extension's `.cta`: an ink pill. Primary is filled; secondary is the
+/// outlined `ghost`.
+pub(super) fn paper_button(
+ paper: &Paper,
+ id: impl Into<gpui::ElementId>,
+ label: &'static str,
+ primary: bool,
+ enabled: bool,
+ on_click: impl Fn(&gpui::ClickEvent, &mut Window, &mut gpui::App) + 'static,
+) -> gpui::Stateful<Div> {
+ let paper = *paper;
+ let (bg, fg, border) = if primary {
+ (paper.ink, paper.bg, paper.ink)
+ } else {
+ (gpui::transparent_black(), paper.ink, paper.track)
+ };
+ div()
+ .id(id.into())
+ .flex()
+ .items_center()
+ .justify_center()
+ .h(px(42.))
+ .px(px(22.))
+ .rounded_full()
+ .border(px(1.5))
+ .border_color(border)
+ .bg(bg)
+ .text_size(px(14.))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(fg)
+ .child(label)
+ .when(!enabled, |button| button.opacity(0.45))
+ .when(enabled, |button| {
+ button
+ .cursor_pointer()
+ .hover(move |button| {
+ if primary {
+ button.opacity(0.88)
+ } else {
+ button.border_color(paper.soft)
+ }
+ })
+ .on_click(on_click)
+ })
+}
diff --git a/apps/desktop-gpui/src/permission_guide.rs b/apps/desktop-gpui/src/permission_guide.rs
new file mode 100644
index 000000000..b539696a8
--- /dev/null
+++ b/apps/desktop-gpui/src/permission_guide.rs
@@ -0,0 +1,407 @@
+//! The drag-to-grant helper: while System Settings is open on the Screen
+//! Recording or Accessibility pane, a small panel floats under its window
+//! with Cap's icon to drag into the list.
+//!
+//! Those two panes (macOS 13+, System Settings) add a `.app` dropped onto
+//! their list, which rescues the case where Cap is missing from the list or
+//! listed under a stale signature. Camera and Microphone lists accept no
+//! drops; they only fill in through the request API, so they get no guide.
+//!
+//! The panel is a non-activating gpui popup; the drag itself is AppKit
+//! ([`platform::begin_file_drag`]) and the Settings window is found by pid
+//! through `CGWindowListCopyWindowInfo`, which needs no Screen Recording grant.
+
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use gpui::{
+ App, AppContext, Bounds, Context, FontWeight, Global, InteractiveElement, IntoElement,
+ MouseButton, ParentElement, Render, Styled, Task, Window, WindowBounds, WindowHandle,
+ WindowKind, WindowOptions, div, img, point, px, size,
+};
+
+use crate::doodle;
+use crate::onboarding_doodles as art;
+use crate::permissions::OSPermission;
+use crate::platform;
+use crate::theme::Theme;
+
+const PANEL_W: f32 = 404.;
+const PANEL_H: f32 = 132.;
+const SHADOW_INSET: f32 = 12.;
+const TICK: Duration = Duration::from_millis(120);
+const GRANT_CHECK_EVERY: u32 = 4;
+const GIVE_UP_UNSEEN: Duration = Duration::from_secs(20);
+const GIVE_UP_AFTER_CLOSE: Duration = Duration::from_secs(8);
+const LIFETIME: Duration = Duration::from_secs(5 * 60);
+const SIDEBAR_W: f64 = 230.;
+
+const APP_ICON: &[u8] = include_bytes!("../assets/dock-icon.png");
+
+/// The `.app` to drag: the bundle this binary runs from. A bare dev binary
+/// has none -- TCC attributes it to the launching terminal anyway -- so the
+/// guide stays off unless a debug build is told to show it.
+fn app_bundle() -> Option<PathBuf> {
+ let exe = std::env::current_exe().ok()?;
+ if let Some(bundle) = exe
+ .ancestors()
+ .find(|path| path.extension().is_some_and(|ext| ext == "app"))
+ {
+ return Some(bundle.to_path_buf());
+ }
+ #[cfg(debug_assertions)]
+ if std::env::var("CAP_GPUI_FORCE_PERMISSION_GUIDE").is_ok_and(|value| value == "1") {
+ return Some(exe);
+ }
+ None
+}
+
+/// `CAP_GPUI_PERMISSION_GUIDE_PREVIEW=1` (debug builds): pretend a Settings
+/// window is up and frontmost, so the panel can be photographed.
+fn preview() -> bool {
+ cfg!(debug_assertions)
+ && std::env::var("CAP_GPUI_PERMISSION_GUIDE_PREVIEW").is_ok_and(|value| value == "1")
+}
+
+pub fn eligible(permission: OSPermission) -> bool {
+ cfg!(target_os = "macos")
+ && matches!(
+ permission,
+ OSPermission::ScreenRecording | OSPermission::Accessibility
+ )
+ && std::path::Path::new("/System/Applications/System Settings.app").exists()
+ && app_bundle().is_some()
+}
+
+#[derive(Default)]
+struct GuideGlobal {
+ handle: Option<WindowHandle<PermissionGuide>>,
+ tracker: Option<Task<()>>,
+ permission: Option<OSPermission>,
+}
+
+impl Global for GuideGlobal {}
+
+pub struct PermissionGuide {
+ theme: Theme,
+ permission: OSPermission,
+ shown_at: Instant,
+ app: PathBuf,
+ icon: Arc<gpui::Image>,
+}
+
+/// Show the guide for `permission` while the user is in System Settings.
+/// Idempotent per permission; a different permission replaces the guide.
+pub fn start(permission: OSPermission, cx: &mut App) {
+ if !eligible(permission) {
+ return;
+ }
+ let Some(app) = app_bundle() else {
+ return;
+ };
+ if cx
+ .try_global::<GuideGlobal>()
+ .is_some_and(|guide| guide.permission == Some(permission) && guide.handle.is_some())
+ {
+ return;
+ }
+ stop(cx);
+
+ let opened = cx.open_window(
+ WindowOptions {
+ window_bounds: Some(WindowBounds::Windowed(Bounds {
+ origin: point(px(0.), px(0.)),
+ size: size(px(PANEL_W), px(PANEL_H)),
+ })),
+ titlebar: None,
+ kind: WindowKind::PopUp,
+ focus: false,
+ show: false,
+ is_resizable: false,
+ is_minimizable: false,
+ window_background: gpui::WindowBackgroundAppearance::Transparent,
+ ..Default::default()
+ },
+ move |window, cx| {
+ cx.new(|cx| {
+ crate::theme::bind_window(window, cx);
+ PermissionGuide {
+ theme: Theme::for_window(window, cx, true),
+ permission,
+ shown_at: Instant::now(),
+ app,
+ icon: Arc::new(gpui::Image::from_bytes(
+ gpui::ImageFormat::Png,
+ APP_ICON.to_vec(),
+ )),
+ }
+ })
+ },
+ );
+ let handle = match opened {
+ Ok(handle) => handle,
+ Err(error) => {
+ tracing::warn!("permission guide failed to open: {error:#}");
+ return;
+ }
+ };
+ let Some(native) = handle
+ .update(cx, |_, window, _| platform::native_window(window))
+ .ok()
+ .flatten()
+ else {
+ handle
+ .update(cx, |_, window, _| window.remove_window())
+ .ok();
+ return;
+ };
+
+ let tracker = cx.spawn(async move |cx| {
+ let started = Instant::now();
+ let mut seen_at: Option<Instant> = None;
+ let mut placed: Option<(f64, f64)> = None;
+ let mut ticks = 0u32;
+ loop {
+ cx.background_executor().timer(TICK).await;
+ ticks = ticks.wrapping_add(1);
+ if ticks.is_multiple_of(GRANT_CHECK_EVERY) {
+ let granted = cx
+ .background_executor()
+ .spawn(async move { granted(permission) })
+ .await;
+ if granted {
+ tracing::info!(?permission, "permission guide: granted");
+ cx.update(stop);
+ return;
+ }
+ }
+ if started.elapsed() > LIFETIME {
+ cx.update(stop);
+ return;
+ }
+ let (frame, front) = if preview() {
+ (Some((300., 200., 900., 600.)), true)
+ } else {
+ (
+ platform::system_settings_frame(),
+ platform::system_settings_frontmost(),
+ )
+ };
+ match frame.filter(|_| front) {
+ Some(frame) => {
+ seen_at = Some(Instant::now());
+ let (x, y) = panel_origin(frame);
+ if placed != Some((x, y)) {
+ let fresh = placed.is_none();
+ placed = Some((x, y));
+ platform::place_overlay_panel(
+ &native,
+ x,
+ y,
+ PANEL_W as f64,
+ PANEL_H as f64,
+ FLOATING_LEVEL,
+ );
+ if fresh {
+ handle
+ .update(cx, |guide, _, cx| {
+ guide.shown_at = Instant::now();
+ cx.notify();
+ })
+ .ok();
+ }
+ }
+ }
+ None => {
+ if placed.take().is_some() {
+ platform::hide_native(&native);
+ }
+ let gone = match seen_at {
+ Some(at) => frame.is_none() && at.elapsed() > GIVE_UP_AFTER_CLOSE,
+ None => started.elapsed() > GIVE_UP_UNSEEN,
+ };
+ if gone {
+ cx.update(stop);
+ return;
+ }
+ }
+ }
+ }
+ });
+
+ cx.set_global(GuideGlobal {
+ handle: Some(handle),
+ tracker: Some(tracker),
+ permission: Some(permission),
+ });
+}
+
+#[cfg(debug_assertions)]
+pub fn window_handle(cx: &App) -> Option<gpui::AnyWindowHandle> {
+ cx.try_global::<GuideGlobal>()?.handle.map(Into::into)
+}
+
+/// `CAP_GPUI_PERMISSION_GUIDE_PREVIEW=1`: open the guide at launch.
+#[cfg(debug_assertions)]
+pub fn preview_from_env(cx: &mut App) {
+ if preview() {
+ start(OSPermission::ScreenRecording, cx);
+ }
+}
+
+pub fn stop(cx: &mut App) {
+ let Some(guide) = cx.try_global::<GuideGlobal>() else {
+ return;
+ };
+ if guide.handle.is_none() && guide.tracker.is_none() {
+ return;
+ }
+ let guide = std::mem::take(cx.global_mut::<GuideGlobal>());
+ drop(guide.tracker);
+ if let Some(handle) = guide.handle {
+ handle
+ .update(cx, |_, window, _| window.remove_window())
+ .ok();
+ }
+}
+
+/// `NSFloatingWindowLevel`: above System Settings, below its auth sheets.
+const FLOATING_LEVEL: isize = 3;
+
+fn granted(permission: OSPermission) -> bool {
+ let Some(raw) = crate::permissions_ui::sweep_raw() else {
+ return false;
+ };
+ match permission {
+ OSPermission::ScreenRecording => raw.screen_granted,
+ OSPermission::Accessibility => raw.accessibility_granted,
+ OSPermission::Microphone | OSPermission::Camera => true,
+ }
+}
+
+/// Under the Settings window, centred on its content pane (right of the
+/// sidebar); tucked inside the bottom edge when the screen has no room below.
+fn panel_origin((x, y, width, height): (f64, f64, f64, f64)) -> (f64, f64) {
+ let sidebar = if width > 640. { SIDEBAR_W } else { 0. };
+ let panel_w = PANEL_W as f64;
+ let panel_h = PANEL_H as f64;
+ let inset = SHADOW_INSET as f64;
+ let left = (x + sidebar + (width - sidebar - panel_w) / 2.).round();
+ let below = y + height - inset + 10.;
+ let screen_bottom = scap_targets::Display::list()
+ .into_iter()
+ .filter_map(|display| display.raw_handle().logical_bounds())
+ .find(|bounds| {
+ let (bx, by) = (bounds.position().x(), bounds.position().y());
+ let (bw, bh) = (bounds.size().width(), bounds.size().height());
+ let (cx, cy) = (x + width / 2., y + height / 2.);
+ cx >= bx && cx < bx + bw && cy >= by && cy < by + bh
+ })
+ .map(|bounds| bounds.position().y() + bounds.size().height());
+ let top = match screen_bottom {
+ Some(bottom) if below + panel_h > bottom - 4. => y + height - panel_h - 14.,
+ _ => below,
+ };
+ (left, top.round())
+}
+
+impl Render for PermissionGuide {
+ fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ self.theme = Theme::for_window(window, cx, true);
+ let paper = crate::onboarding_window::Paper::new(&self.theme);
+ let palette = paper.palette();
+ let still = false;
+ let pane = match self.permission {
+ OSPermission::Accessibility => "Accessibility",
+ _ => "Screen & System Audio Recording",
+ };
+ div()
+ .size_full()
+ .p(px(SHADOW_INSET))
+ .font_family(crate::theme::UI_FONT)
+ .child(
+ div()
+ .size_full()
+ .flex()
+ .flex_row()
+ .items_center()
+ .gap(px(14.))
+ .px(px(14.))
+ .rounded(px(20.))
+ .border(px(1.5))
+ .border_color(paper.track)
+ .bg(paper.bg)
+ .shadow_lg()
+ .child(
+ div()
+ .id("permission-guide-icon")
+ .relative()
+ .flex_none()
+ .size(px(80.))
+ .cursor_grab()
+ .on_mouse_down(
+ MouseButton::Left,
+ cx.listener(|this, _, window, _| {
+ if !platform::begin_file_drag(window, &this.app) {
+ tracing::warn!("permission guide: drag did not start");
+ }
+ }),
+ )
+ .child(
+ div().absolute().inset_0().child(doodle::doodle(
+ &art::DRAG_FRAME,
+ palette,
+ self.shown_at,
+ still,
+ 80.,
+ 80.,
+ )),
+ )
+ .child(
+ div()
+ .absolute()
+ .inset_0()
+ .flex()
+ .items_center()
+ .justify_center()
+ .child(img(self.icon.clone()).size(px(52.))),
+ ),
+ )
+ .child(
+ div()
+ .flex_1()
+ .min_w_0()
+ .flex()
+ .flex_col()
+ .gap(px(3.))
+ .child(
+ div()
+ .text_size(px(15.))
+ .line_height(px(19.))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(paper.ink)
+ .child("Drag Cap into the list"),
+ )
+ .child(
+ div()
+ .text_size(px(12.))
+ .line_height(px(17.))
+ .font_weight(FontWeight::NORMAL)
+ .text_color(paper.soft)
+ .child(format!(
+ "Drop it on the {pane} list above, then make sure its switch is on."
+ )),
+ ),
+ )
+ .child(div().flex_none().child(doodle::doodle(
+ &art::UP_ARROW,
+ palette,
+ self.shown_at,
+ still,
+ 34.,
+ 44.,
+ ))),
+ )
+ }
+}
diff --git a/apps/desktop-gpui/src/permissions.rs b/apps/desktop-gpui/src/permissions.rs
index 433a505f6..f25d0299d 100644
--- a/apps/desktop-gpui/src/permissions.rs
+++ b/apps/desktop-gpui/src/permissions.rs
@@ -54,19 +54,6 @@ impl OSPermission {
}
}
- pub fn blurb(self) -> &'static str {
- match self {
- Self::ScreenRecording => {
- "Click Grant to allow when macOS asks, or pick Cap in System Settings if needed. Restart the app after allowing screen recording."
- }
- Self::Accessibility => {
- "During recording, Cap collects mouse activity locally to generate automatic zoom in segments."
- }
- Self::Microphone => "This permission is required to record audio in your Caps.",
- Self::Camera => "This permission is required to record your camera in your Caps.",
- }
- }
-
/// Screen recording and accessibility gate the app; mic and camera are
/// optional. Same split as the Tauri app's `necessary_granted`.
pub fn required(self) -> bool {
diff --git a/apps/desktop-gpui/src/platform.rs b/apps/desktop-gpui/src/platform.rs
index 0e0944503..dc9430aaa 100644
--- a/apps/desktop-gpui/src/platform.rs
+++ b/apps/desktop-gpui/src/platform.rs
@@ -1364,6 +1364,222 @@ mod mac {
native.0.makeKeyAndOrderFront(None);
}
+ /// Start an AppKit file drag of `path` from the mouse-down being handled
+ /// right now (`NSApp.currentEvent`): what Finder hands System Settings,
+ /// which adds a dropped `.app` to a privacy list. Called from a gpui
+ /// mouse-down listener; the session runs from the event loop afterwards.
+ pub fn begin_file_drag(window: &Window, path: &std::path::Path) -> bool {
+ use objc2::{class, msg_send};
+ use objc2_foundation::{NSPoint, NSRect, NSSize, NSString};
+
+ let Some(ns) = ns_window(window) else {
+ return false;
+ };
+ let source = file_drag_source();
+ unsafe {
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
+ let event: *mut AnyObject = msg_send![app, currentEvent];
+ let view: *mut AnyObject = msg_send![&*ns, contentView];
+ if event.is_null() || view.is_null() || source.is_null() {
+ return false;
+ }
+ let path = NSString::from_str(&path.to_string_lossy());
+ let url: *mut AnyObject = msg_send![class!(NSURL), fileURLWithPath: &*path];
+ if url.is_null() {
+ return false;
+ }
+ let item: *mut AnyObject = msg_send![class!(NSDraggingItem), alloc];
+ let item: *mut AnyObject = msg_send![item, initWithPasteboardWriter: url];
+ if item.is_null() {
+ return false;
+ }
+ let workspace: *mut AnyObject = msg_send![class!(NSWorkspace), sharedWorkspace];
+ let icon: *mut AnyObject = msg_send![workspace, iconForFile: &*path];
+ let _: () = msg_send![icon, setSize: NSSize::new(64., 64.)];
+ let location: NSPoint = msg_send![event, locationInWindow];
+ let point: NSPoint = msg_send![view, convertPoint: location, fromView: std::ptr::null_mut::<AnyObject>()];
+ let frame = NSRect::new(
+ NSPoint::new(point.x - 32., point.y - 32.),
+ NSSize::new(64., 64.),
+ );
+ let _: () = msg_send![item, setDraggingFrame: frame, contents: icon];
+ let items: *mut AnyObject = msg_send![class!(NSArray), arrayWithObject: item];
+ let _: () = msg_send![item, release];
+ let session: *mut AnyObject = msg_send![
+ view,
+ beginDraggingSessionWithItems: items,
+ event: event,
+ source: source
+ ];
+ if session.is_null() {
+ return false;
+ }
+ let _: () = msg_send![session, setAnimatesToStartingPositionsOnCancelOrFail: true];
+ true
+ }
+ }
+
+ /// The `NSDraggingSource` for [`begin_file_drag`]: copy/link/generic when
+ /// the drag leaves the app, nothing inside it. One instance, never freed.
+ fn file_drag_source() -> *mut AnyObject {
+ use std::sync::OnceLock;
+
+ use objc2::runtime::{AnyProtocol, ClassBuilder, NSObject};
+ use objc2::{ClassType, msg_send, sel};
+
+ unsafe extern "C" fn operation_mask(
+ _receiver: *mut AnyObject,
+ _selector: Sel,
+ _session: *mut AnyObject,
+ context: isize,
+ ) -> usize {
+ const OUTSIDE_APPLICATION: isize = 0;
+ const COPY_LINK_GENERIC: usize = 1 | 2 | 4;
+ if context == OUTSIDE_APPLICATION {
+ COPY_LINK_GENERIC
+ } else {
+ 0
+ }
+ }
+
+ static SOURCE: OnceLock<usize> = OnceLock::new();
+ *SOURCE.get_or_init(|| {
+ let Some(mut builder) = ClassBuilder::new("CapFileDragSource", NSObject::class())
+ else {
+ return 0;
+ };
+ unsafe {
+ builder.add_method(
+ sel!(draggingSession:sourceOperationMaskForDraggingContext:),
+ operation_mask
+ as unsafe extern "C" fn(
+ *mut AnyObject,
+ Sel,
+ *mut AnyObject,
+ isize,
+ ) -> usize,
+ );
+ }
+ if let Some(protocol) = AnyProtocol::get("NSDraggingSource") {
+ builder.add_protocol(protocol);
+ }
+ let class = builder.register();
+ let instance: *mut AnyObject = unsafe { msg_send![class, new] };
+ instance as usize
+ }) as *mut AnyObject
+ }
+
+ /// System Settings' main window in CoreGraphics coordinates (global,
+ /// top-left origin) -- bounds and owner pid are readable without Screen
+ /// Recording, titles are not, so the window is found by pid and size.
+ pub fn system_settings_frame() -> Option<(f64, f64, f64, f64)> {
+ use core_foundation::array::{CFArray, CFArrayRef};
+ use core_foundation::base::{CFType, TCFType};
+ use core_foundation::dictionary::CFDictionary;
+ use core_foundation::number::CFNumber;
+ use core_foundation::string::{CFString, CFStringRef};
+ use objc2::{class, msg_send};
+ use objc2_foundation::NSString;
+
+ #[link(name = "CoreGraphics", kind = "framework")]
+ unsafe extern "C" {
+ fn CGWindowListCopyWindowInfo(option: u32, relative_to: u32) -> CFArrayRef;
+ static kCGWindowOwnerPID: CFStringRef;
+ static kCGWindowLayer: CFStringRef;
+ static kCGWindowBounds: CFStringRef;
+ }
+ const ON_SCREEN_ONLY: u32 = 1 << 0;
+ const EXCLUDE_DESKTOP_ELEMENTS: u32 = 1 << 4;
+
+ let pid: i32 = unsafe {
+ let bundle = NSString::from_str("com.apple.systempreferences");
+ let apps: *mut AnyObject = msg_send![
+ class!(NSRunningApplication),
+ runningApplicationsWithBundleIdentifier: &*bundle
+ ];
+ if apps.is_null() {
+ return None;
+ }
+ let app: *mut AnyObject = msg_send![apps, firstObject];
+ if app.is_null() {
+ return None;
+ }
+ msg_send![app, processIdentifier]
+ };
+
+ let list = unsafe {
+ let raw = CGWindowListCopyWindowInfo(ON_SCREEN_ONLY | EXCLUDE_DESKTOP_ELEMENTS, 0);
+ if raw.is_null() {
+ return None;
+ }
+ CFArray::<CFDictionary<CFString, CFType>>::wrap_under_create_rule(raw)
+ };
+ let number = |dict: &CFDictionary<CFString, CFType>, key: &CFString| -> Option<f64> {
+ dict.find(key)?.downcast::<CFNumber>()?.to_f64()
+ };
+ let (owner_key, layer_key, bounds_key) = unsafe {
+ (
+ CFString::wrap_under_get_rule(kCGWindowOwnerPID),
+ CFString::wrap_under_get_rule(kCGWindowLayer),
+ CFString::wrap_under_get_rule(kCGWindowBounds),
+ )
+ };
+ let mut best: Option<(f64, f64, f64, f64)> = None;
+ for window in list.iter() {
+ if number(&window, &owner_key) != Some(pid as f64)
+ || number(&window, &layer_key) != Some(0.)
+ {
+ continue;
+ }
+ let Some(bounds) = window
+ .find(&bounds_key)
+ .and_then(|value| value.downcast::<CFDictionary>())
+ else {
+ continue;
+ };
+ let bounds: CFDictionary<CFString, CFType> =
+ unsafe { CFDictionary::wrap_under_get_rule(bounds.as_concrete_TypeRef()) };
+ let field = |name: &'static str| number(&bounds, &CFString::from_static_string(name));
+ let (Some(x), Some(y), Some(w), Some(h)) =
+ (field("X"), field("Y"), field("Width"), field("Height"))
+ else {
+ continue;
+ };
+ if w < 320. || h < 240. {
+ continue;
+ }
+ if best.is_none_or(|(_, _, bw, bh)| w * h > bw * bh) {
+ best = Some((x, y, w, h));
+ }
+ }
+ best
+ }
+
+ /// Whether the user is in System Settings or one of the authentication
+ /// sheets a privacy-list change raises.
+ pub fn system_settings_frontmost() -> bool {
+ use objc2::{class, msg_send};
+ use objc2_foundation::NSString;
+
+ unsafe {
+ let workspace: *mut AnyObject = msg_send![class!(NSWorkspace), sharedWorkspace];
+ let app: *mut AnyObject = msg_send![workspace, frontmostApplication];
+ if app.is_null() {
+ return false;
+ }
+ let bundle: *mut NSString = msg_send![app, bundleIdentifier];
+ let Some(bundle) = bundle.as_ref() else {
+ return false;
+ };
+ matches!(
+ bundle.to_string().as_str(),
+ "com.apple.systempreferences"
+ | "com.apple.SecurityAgent"
+ | "com.apple.LocalAuthentication.UIAgent"
+ )
+ }
+ }
+
/// Close the window the way the red traffic light does: ask the
/// delegate's `windowShouldClose:` (gpui's `on_window_should_close`,
/// where every window's close bookkeeping lives), then `close`.
@@ -1690,6 +1906,19 @@ mod mac {
ns_window(window).is_some_and(|ns| ns.isVisible())
}
+ /// Whether the window has a close button (`NSWindowStyleMaskClosable`):
+ /// the windows ⌘W may close. gpui only sets it with a titlebar, so the
+ /// main window, camera bubble, controls bar and target overlays never
+ /// have it. A plain getter, so it is safe inside a gpui update.
+ pub fn window_is_closable(window: &Window) -> bool {
+ use objc2::msg_send;
+ const CLOSABLE: usize = 1 << 1;
+ ns_window(window).is_some_and(|ns| {
+ let mask: usize = unsafe { msg_send![&*ns, styleMask] };
+ mask & CLOSABLE != 0
+ })
+ }
+
/// Show without stealing key status -- `orderFrontRegardless`, what the
/// Tauri app calls on the recording controls panel.
pub fn show_window_without_focus(window: &Window) {
@@ -2376,6 +2605,15 @@ mod stub {
let _ = conn.flush();
}
pub fn hide_native(_native: &NativeWindow) {}
+ pub fn begin_file_drag(_window: &Window, _path: &std::path::Path) -> bool {
+ false
+ }
+ pub fn system_settings_frame() -> Option<(f64, f64, f64, f64)> {
+ None
+ }
+ pub fn system_settings_frontmost() -> bool {
+ false
+ }
pub fn show_native(_native: &NativeWindow) {}
#[cfg(target_os = "linux")]
@@ -2447,6 +2685,9 @@ mod stub {
pub fn window_is_visible(_window: &Window) -> bool {
false
}
+ pub fn window_is_closable(_window: &Window) -> bool {
+ false
+ }
pub fn show_window_without_focus(_window: &Window) {}
pub fn window_number(_window: &Window) -> Option<isize> {
None
diff --git a/apps/desktop-gpui/src/screenshot_editor.rs b/apps/desktop-gpui/src/screenshot_editor.rs
index 7e83655f2..ecf953bdf 100644
--- a/apps/desktop-gpui/src/screenshot_editor.rs
+++ b/apps/desktop-gpui/src/screenshot_editor.rs
@@ -2275,10 +2275,13 @@ impl ScreenshotEditorWindow {
this.update_in(cx, |this, window, cx| {
this.finish_share_error(
toast,
- "You need to sign in to create shareable links".into(),
+ "Sign in to Cap in your browser, then share again".into(),
window,
cx,
- )
+ );
+ crate::sign_in::SignIn::global(cx).update(cx, |sign_in, cx| {
+ sign_in.start(crate::sign_in::SignInOrigin::ScreenshotEditor, cx)
+ });
})
.ok();
return;
diff --git a/apps/desktop-gpui/src/settings_window.rs b/apps/desktop-gpui/src/settings_window.rs
index d473ea22e..52d2a2fd3 100644
--- a/apps/desktop-gpui/src/settings_window.rs
+++ b/apps/desktop-gpui/src/settings_window.rs
@@ -26,6 +26,7 @@ use crate::{
devices::WindowOption,
library::{self, RecordingItem, RecordingMode, ScreenshotItem},
main_window::Mode,
+ sign_in::{SignIn, SignInEvent, SignInOrigin, SignInOutcome},
store::{
self, AppTheme, DEFAULT_PROJECT_NAME_TEMPLATE, DEFAULT_SERVER_URL, GENERAL_SETTINGS,
GeneralSettings, MainWindowStartBehaviour, PostDeletionBehaviour, RECORDING_START_SAFETY,
@@ -659,9 +660,7 @@ pub struct SettingsWindow {
/// Key handling for Cmd-W lives on the root, which needs a focus handle of
/// its own so the window has something focused when nothing else does.
pub(crate) focus: FocusHandle,
- sign_in_pending: bool,
- sign_in_cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
- sign_in_task: Option<gpui::Task<()>>,
+ _sign_in_subscriptions: [gpui::Subscription; 2],
user_profile: Option<UserProfile>,
profile_image: Option<Arc<RenderImage>>,
}
@@ -728,6 +727,26 @@ impl SettingsWindow {
}),
];
+ let sign_in = SignIn::global(cx);
+ let sign_in_subscriptions = [
+ cx.observe_in(&sign_in, window, |_, _, window, cx| {
+ cx.notify();
+ window.refresh();
+ }),
+ cx.subscribe_in(&sign_in, window, |this, _, event, window, cx| match event {
+ SignInEvent::Finished {
+ outcome: SignInOutcome::SignedIn,
+ ..
+ } => this.refresh_user_profile(window, cx),
+ SignInEvent::AccountRefreshed => {
+ this.has_cap_pro = store::auth_snapshot().is_upgraded();
+ cx.notify();
+ window.refresh();
+ }
+ SignInEvent::Finished { .. } => {}
+ }),
+ ];
+
let pages = crate::settings_pages::PagesState::new(window, cx);
let page_scroll = ScrollHandle::new();
@@ -762,9 +781,7 @@ impl SettingsWindow {
slider_dragging: false,
windows: Vec::new(),
focus: cx.focus_handle(),
- sign_in_pending: false,
- sign_in_cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
- sign_in_task: None,
+ _sign_in_subscriptions: sign_in_subscriptions,
user_profile,
profile_image: None,
}
@@ -1892,7 +1909,7 @@ impl SettingsWindow {
.child(update_links)
.child({
let signed_in = store::auth_snapshot().signed_in();
- let (variant, label) = if self.sign_in_pending {
+ let (variant, label) = if SignIn::global(cx).read(cx).is_pending() {
(ui::ButtonVariant::Gray, "Cancel Sign In")
} else if signed_in {
(ui::ButtonVariant::Gray, "Sign Out")
@@ -1913,53 +1930,16 @@ impl SettingsWindow {
}
fn toggle_sign_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- use std::sync::atomic::Ordering;
-
- if self.sign_in_pending {
- self.sign_in_cancel.store(true, Ordering::Relaxed);
- self.sign_in_pending = false;
- cx.notify();
+ let sign_in = SignIn::global(cx);
+ if sign_in.read(cx).is_pending() {
+ sign_in.update(cx, |sign_in, cx| sign_in.cancel(cx));
return;
}
if store::auth_snapshot().signed_in() {
self.clear_local_auth(window, cx);
return;
}
-
- self.sign_in_cancel.store(false, Ordering::Relaxed);
- let cancel = self.sign_in_cancel.clone();
- let session = match crate::auth::begin_sign_in(cancel.clone()) {
- Ok(session) => session,
- Err(error) => {
- tracing::error!("starting sign-in: {error}");
- return;
- }
- };
- cx.open_url(&session.url);
- self.sign_in_pending = true;
- self.sign_in_task = Some(cx.spawn_in(window, async move |this, cx| {
- let signed_in = cx
- .background_executor()
- .spawn(async move { session.complete() })
- .await;
- if matches!(signed_in, Ok(true))
- && let Ok(plan) =
- gpui_tokio::Tokio::spawn(cx, crate::auth::update_auth_plan()).await
- && let Err(error) = plan
- {
- tracing::warn!("updating auth plan after sign-in: {error}");
- }
- crate::platform::activate_app();
- let _ = this.update_in(cx, |this, window, cx| {
- this.sign_in_pending = false;
- if store::auth_snapshot().signed_in() {
- this.refresh_user_profile(window, cx);
- }
- cx.notify();
- window.refresh();
- });
- }));
- cx.notify();
+ sign_in.update(cx, |sign_in, cx| sign_in.start(SignInOrigin::Settings, cx));
}
pub(crate) fn refresh_plan(&mut self, window: &mut Window, cx: &mut Context<Self>) {
diff --git a/apps/desktop-gpui/src/sign_in.rs b/apps/desktop-gpui/src/sign_in.rs
new file mode 100644
index 000000000..04b08781f
--- /dev/null
+++ b/apps/desktop-gpui/src/sign_in.rs
@@ -0,0 +1,186 @@
+//! The one sign-in flow every surface drives.
+//!
+//! Settings, the editor's share export and the recording overlay used to each
+//! run their own attempt. Two at once fought over the single deep-link slot and
+//! the loser's teardown cleared the winner's, and each surface only learned
+//! about sign-ins it had started itself. Here there is at most one attempt app
+//! wide: starting while one is pending re-opens its browser page, every window
+//! observes the same pending state, and every window hears the outcome.
+
+use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, Task};
+
+use crate::auth;
+use crate::main_window::TargetType;
+use crate::platform;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SignInOrigin {
+ Settings,
+ Editor,
+ ScreenshotEditor,
+ Overlay(TargetType),
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum SignInOutcome {
+ SignedIn,
+ Cancelled,
+ TimedOut,
+ Failed(String),
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum SignInEvent {
+ Finished {
+ origin: SignInOrigin,
+ outcome: SignInOutcome,
+ },
+ AccountRefreshed,
+}
+
+struct Attempt {
+ id: u64,
+ origin: SignInOrigin,
+ url: String,
+ task: Task<()>,
+}
+
+pub struct SignIn {
+ attempt: Option<Attempt>,
+ next_id: u64,
+}
+
+struct SignInGlobal(Entity<SignIn>);
+
+impl Global for SignInGlobal {}
+
+impl EventEmitter<SignInEvent> for SignIn {}
+
+impl SignIn {
+ pub fn init(cx: &mut App) {
+ let entity = cx.new(|_| Self {
+ attempt: None,
+ next_id: 1,
+ });
+ cx.set_global(SignInGlobal(entity));
+ }
+
+ pub fn global(cx: &App) -> Entity<Self> {
+ cx.global::<SignInGlobal>().0.clone()
+ }
+
+ pub fn is_pending(&self) -> bool {
+ self.attempt.is_some()
+ }
+
+ /// Open the browser sign-in. A second call while an attempt is pending
+ /// re-opens that attempt's page (the user may have closed the tab) and
+ /// moves the attempt to the newer origin.
+ pub fn start(&mut self, origin: SignInOrigin, cx: &mut Context<Self>) {
+ if let Some(attempt) = self.attempt.as_mut() {
+ attempt.origin = origin;
+ cx.open_url(&attempt.url);
+ cx.notify();
+ return;
+ }
+
+ let session = auth::begin_sign_in();
+ let url = session.url.clone();
+ let id = self.next_id;
+ self.next_id += 1;
+ let timeout = cx.background_executor().timer(auth::SIGN_IN_TIMEOUT);
+ let task = cx.spawn(async move |this, cx| {
+ let outcome = match session.wait(timeout).await {
+ Ok(params) => match auth::process_auth_data(params) {
+ Ok(()) => {
+ session.mark_completed();
+ SignInOutcome::SignedIn
+ }
+ Err(error) => SignInOutcome::Failed(error),
+ },
+ Err(auth::SignInWaitError::TimedOut) => SignInOutcome::TimedOut,
+ };
+ drop(session);
+
+ let Ok(Some(origin)) = this.update(cx, |this, cx| this.finish(id, outcome.clone(), cx))
+ else {
+ return;
+ };
+ // After the update, not inside it: both re-enter the run loop. The
+ // main window's prompt shows its own failures inline.
+ match &outcome {
+ SignInOutcome::SignedIn => platform::activate_app(),
+ SignInOutcome::Failed(error) if !matches!(origin, SignInOrigin::Overlay(_)) => {
+ platform::alert_dialog("Sign in failed", error)
+ }
+ _ => {}
+ }
+ if outcome != SignInOutcome::SignedIn {
+ return;
+ }
+ match gpui_tokio::Tokio::spawn(cx, auth::update_auth_plan()).await {
+ Ok(Ok(())) => {}
+ Ok(Err(error)) => tracing::warn!("updating auth plan after sign-in: {error}"),
+ Err(error) => tracing::warn!("updating auth plan after sign-in: {error}"),
+ }
+ this.update(cx, |_, cx| {
+ cx.emit(SignInEvent::AccountRefreshed);
+ cx.notify();
+ })
+ .ok();
+ });
+
+ cx.open_url(&url);
+ self.attempt = Some(Attempt {
+ id,
+ origin,
+ url,
+ task,
+ });
+ cx.notify();
+ }
+
+ pub fn reopen(&mut self, cx: &mut Context<Self>) {
+ if let Some(attempt) = &self.attempt {
+ cx.open_url(&attempt.url);
+ }
+ }
+
+ pub fn cancel(&mut self, cx: &mut Context<Self>) {
+ let Some(attempt) = self.attempt.take() else {
+ return;
+ };
+ drop(attempt.task);
+ cx.emit(SignInEvent::Finished {
+ origin: attempt.origin,
+ outcome: SignInOutcome::Cancelled,
+ });
+ cx.notify();
+ }
+
+ /// Clear a finished attempt. Its task is detached rather than dropped
+ /// because this runs from inside that task, which still has the
+ /// activation, the alert and the plan refresh to do.
+ fn finish(
+ &mut self,
+ id: u64,
+ outcome: SignInOutcome,
+ cx: &mut Context<Self>,
+ ) -> Option<SignInOrigin> {
+ if self.attempt.as_ref().map(|attempt| attempt.id) != Some(id) {
+ return None;
+ }
+ let attempt = self.attempt.take()?;
+ let origin = attempt.origin;
+ attempt.task.detach();
+ match &outcome {
+ SignInOutcome::SignedIn => tracing::info!("signed in"),
+ SignInOutcome::TimedOut => tracing::info!("sign-in timed out"),
+ SignInOutcome::Failed(error) => tracing::warn!("sign-in failed: {error}"),
+ SignInOutcome::Cancelled => {}
+ }
+ cx.emit(SignInEvent::Finished { origin, outcome });
+ cx.notify();
+ Some(origin)
+ }
+}
diff --git a/apps/desktop-gpui/src/snapshot.rs b/apps/desktop-gpui/src/snapshot.rs
new file mode 100644
index 000000000..ea53a80bf
--- /dev/null
+++ b/apps/desktop-gpui/src/snapshot.rs
@@ -0,0 +1,84 @@
+//! `CAP_GPUI_SNAPSHOT=/path/out.png[,delay_ms]`: write the onboarding window
+//! to a PNG after a delay, then quit. Debug builds only; the design loop uses
+//! it because a shell without Screen Recording cannot `screencapture`, while
+//! this binary already holds the grant.
+
+use std::time::Duration;
+
+use cap_recording::sources::screen_capture::ScreenCaptureTarget;
+use gpui::App;
+
+pub fn arm_from_env(cx: &mut App) {
+ crate::permission_guide::preview_from_env(cx);
+ let Ok(spec) = std::env::var("CAP_GPUI_SNAPSHOT") else {
+ return;
+ };
+ let mut parts = spec.split(',');
+ let Some(path) = parts
+ .next()
+ .filter(|path| !path.is_empty())
+ .map(String::from)
+ else {
+ return;
+ };
+ let delay = parts
+ .next()
+ .and_then(|value| value.parse().ok())
+ .unwrap_or(2500);
+ cx.spawn(async move |cx| {
+ cx.background_executor()
+ .timer(Duration::from_millis(delay))
+ .await;
+ let mut number = None;
+ for _ in 0..20 {
+ number = cx.update(|cx| {
+ let target = std::env::var("CAP_GPUI_SNAPSHOT_WINDOW").unwrap_or_default();
+ let handle = if target == "guide" {
+ crate::permission_guide::window_handle(cx)
+ } else if target == "main" {
+ Some(cx.global::<crate::app_windows::AppWindows>().main.into())
+ } else {
+ cx.global::<crate::app_windows::AppWindows>()
+ .onboarding
+ .map(Into::into)
+ };
+ let Some(handle) = handle else {
+ tracing::warn!("snapshot: window handle missing");
+ return None;
+ };
+ match handle.update(cx, |_, window, _| crate::platform::window_number(window)) {
+ Ok(number) => number,
+ Err(error) => {
+ tracing::warn!("snapshot: onboarding update failed: {error}");
+ None
+ }
+ }
+ });
+ if number.is_some() {
+ break;
+ }
+ cx.background_executor()
+ .timer(Duration::from_millis(100))
+ .await;
+ }
+ let Some(id) = number.and_then(|number| number.to_string().parse().ok()) else {
+ tracing::error!("snapshot: no onboarding window");
+ cx.update(|cx| cx.quit());
+ return;
+ };
+ let result = gpui_tokio::Tokio::spawn(cx, async move {
+ cap_recording::screenshot::capture_screenshot(ScreenCaptureTarget::Window { id }).await
+ })
+ .await;
+ match result {
+ Ok(Ok(image)) => match image.save(&path) {
+ Ok(()) => tracing::info!("snapshot written to {path}"),
+ Err(error) => tracing::error!("snapshot save failed: {error}"),
+ },
+ Ok(Err(error)) => tracing::error!("snapshot capture failed: {error:#}"),
+ Err(error) => tracing::error!("snapshot task failed: {error}"),
+ }
+ cx.update(|cx| cx.quit());
+ })
+ .detach();
+}
diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rs
index 52dc02a8b..2567910cc 100644
--- a/apps/desktop-gpui/src/store.rs
+++ b/apps/desktop-gpui/src/store.rs
@@ -421,37 +421,68 @@ pub fn notification_sounds_enabled() -> bool {
/// already updated its in-memory copy, which is the same optimistic order
/// `handleChange` uses in `general.tsx`.
pub fn set_store_setting(section: &str, key: &str, value: Value) -> bool {
- let path = tauri_store_path();
- let Some(mut store) = read_store(&path) else {
- return false;
- };
-
- let entry = store
- .entry(section.to_string())
- .or_insert_with(|| Value::Object(Map::new()));
- if !entry.is_object() {
- *entry = Value::Object(Map::new());
- }
- entry
- .as_object_mut()
- .expect("just replaced any non-object with an object")
- .insert(key.to_string(), value);
-
- write_store(&path, &Value::Object(store))
+ modify_store(|store| {
+ let entry = store
+ .entry(section.to_string())
+ .or_insert_with(|| Value::Object(Map::new()));
+ if !entry.is_object() {
+ *entry = Value::Object(Map::new());
+ }
+ entry
+ .as_object_mut()
+ .expect("just replaced any non-object with an object")
+ .insert(key.to_string(), value);
+ true
+ })
}
/// Replace or remove one top-level store section. `authStore.set(null)` in
/// the Tauri app drops the whole `auth` object; writing keys one at a time
/// would leave a half-signed-out session behind.
pub fn set_store_value(section: &str, value: Value) -> bool {
+ modify_store(|store| {
+ if value.is_null() {
+ store.remove(section);
+ } else {
+ store.insert(section.to_string(), value);
+ }
+ true
+ })
+}
+
+/// Replace one top-level section only if `update` agrees, deciding from the
+/// section as it is on disk at write time rather than from a copy read before
+/// a network round trip.
+pub fn update_store_section(
+ section: &str,
+ update: impl FnOnce(&mut Map<String, Value>) -> bool,
+) -> bool {
+ modify_store(|store| {
+ let mut current = match store.remove(section) {
+ Some(Value::Object(map)) => map,
+ _ => Map::new(),
+ };
+ let keep = update(&mut current);
+ store.insert(section.to_string(), Value::Object(current));
+ keep
+ })
+}
+
+/// Every write is a read-modify-write of the whole file through one temp
+/// path, so two threads writing at once (an auth write from a tokio worker and
+/// a settings toggle on the main thread) could drop one update or fail the
+/// rename. One process-wide lock serializes them.
+fn modify_store(update: impl FnOnce(&mut Map<String, Value>) -> bool) -> bool {
+ static STORE_WRITE: std::sync::Mutex<()> = std::sync::Mutex::new(());
+ let _guard = STORE_WRITE
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
let path = tauri_store_path();
let Some(mut store) = read_store(&path) else {
return false;
};
- if value.is_null() {
- store.remove(section);
- } else {
- store.insert(section.to_string(), value);
+ if !update(&mut store) {
+ return false;
}
write_store(&path, &Value::Object(store))
}
@@ -1015,36 +1046,34 @@ fn set_device_format_settings(
let Ok(Value::Object(fields)) = serde_json::to_value(settings) else {
return false;
};
- let path = tauri_store_path();
- let Some(mut store) = read_store(&path) else {
- return false;
- };
- let section = store
- .entry(RECORDING_SETTINGS.to_string())
- .or_insert_with(|| Value::Object(Map::new()));
- let Some(section) = section.as_object_mut() else {
- return false;
- };
- let map = section
- .entry(map_key.to_string())
- .or_insert_with(|| Value::Object(Map::new()));
- let Some(map) = map.as_object_mut() else {
- return false;
- };
- for key in keys {
- let entry = map.entry(key).or_insert_with(|| Value::Object(Map::new()));
- let Some(entry) = entry.as_object_mut() else {
+ modify_store(|store| {
+ let section = store
+ .entry(RECORDING_SETTINGS.to_string())
+ .or_insert_with(|| Value::Object(Map::new()));
+ let Some(section) = section.as_object_mut() else {
+ return false;
+ };
+ let map = section
+ .entry(map_key.to_string())
+ .or_insert_with(|| Value::Object(Map::new()));
+ let Some(map) = map.as_object_mut() else {
return false;
};
- for (key, value) in &fields {
- if value.is_null() {
- entry.remove(key);
- } else {
- entry.insert(key.clone(), value.clone());
+ for key in keys {
+ let entry = map.entry(key).or_insert_with(|| Value::Object(Map::new()));
+ let Some(entry) = entry.as_object_mut() else {
+ return false;
+ };
+ for (key, value) in &fields {
+ if value.is_null() {
+ entry.remove(key);
+ } else {
+ entry.insert(key.clone(), value.clone());
+ }
}
}
- }
- write_store(&path, &Value::Object(store))
+ true
+ })
}
#[derive(Clone, Debug, Default, PartialEq)]
@@ -1833,12 +1862,10 @@ pub fn set_automations(automations: &AutomationsStore) -> bool {
return false;
}
};
- let path = tauri_store_path();
- let Some(mut store) = read_store(&path) else {
- return false;
- };
- store.insert(AUTOMATIONS.to_string(), value);
- write_store(&path, &Value::Object(store))
+ modify_store(|store| {
+ store.insert(AUTOMATIONS.to_string(), value);
+ true
+ })
}
/// The preset names `applyPreset` offers -- `presetsStore.createQuery()` in
@@ -1911,6 +1938,29 @@ mod tests {
}
}
+ #[test]
+ fn section_updates_merge_into_disk_state_and_can_decline() {
+ let store = TempStore::new(
+ "section-update",
+ Some(r#"{"auth":{"user_id":"a","plan":null},"general_settings":{"x":1}}"#),
+ );
+
+ assert!(update_store_section("auth", |auth| {
+ auth.insert("organizations".into(), serde_json::json!([]));
+ true
+ }));
+ let written = store.read();
+ assert_eq!(written["auth"]["user_id"], "a");
+ assert_eq!(written["auth"]["organizations"], serde_json::json!([]));
+ assert_eq!(written["general_settings"]["x"], 1);
+
+ assert!(!update_store_section("auth", |auth| {
+ auth.insert("user_id".into(), "b".into());
+ false
+ }));
+ assert_eq!(store.read()["auth"]["user_id"], "a");
+ }
+
#[test]
fn notification_sounds_follow_tauri_settings_without_writing() {
for (contents, enabled) in [
diff --git a/apps/desktop-gpui/src/target_overlay.rs b/apps/desktop-gpui/src/target_overlay.rs
index feb0e2a44..ca1c43ac4 100644
--- a/apps/desktop-gpui/src/target_overlay.rs
+++ b/apps/desktop-gpui/src/target_overlay.rs
@@ -42,6 +42,7 @@ use crate::{
GuideAxis, NormRect, SNAP_PX, SnapGuide, build_snap_targets, snap_moving_rect,
},
main_window::{Mode, TargetType},
+ sign_in::SignIn,
theme::Theme,
};
@@ -601,6 +602,9 @@ pub struct OverlayWindow {
inline_camera_subscription: Option<gpui::Subscription>,
empty_camera_state: crate::store::CameraWindowState,
device_menu: Option<OverlayDeviceMenu>,
+ /// Cached off the store so the start pill does not re-read the settings
+ /// file every frame; refreshed whenever the shared sign-in reports.
+ signed_in: bool,
_main_subscription: Option<gpui::Subscription>,
}
@@ -608,6 +612,7 @@ pub struct OverlayWindow {
enum OverlayDeviceChoice {
Camera(Option<crate::devices::CameraOption>),
Microphone(Option<crate::devices::MicrophoneOption>),
+ Access(crate::permissions::OSPermission),
}
struct OverlayDeviceMenu {
@@ -647,6 +652,14 @@ impl OverlayWindow {
.update(cx, |_, _, cx| cx.entity())
.ok()
.map(|main| cx.observe(&main, |_, _, cx| cx.notify()));
+ let media = crate::media_access::MediaAccess::global(cx);
+ media.update(cx, |access, cx| access.refresh(cx));
+ cx.observe(&media, |_, _, cx| cx.notify()).detach();
+ cx.observe(&SignIn::global(cx), |this: &mut Self, _, cx| {
+ this.signed_in = crate::store::auth_snapshot().signed_in();
+ cx.notify();
+ })
+ .detach();
let logical = display
.logical_size()
@@ -695,6 +708,7 @@ impl OverlayWindow {
inline_camera_subscription: None,
empty_camera_state: crate::store::load().camera_window.unwrap_or_default(),
device_menu: None,
+ signed_in: crate::store::auth_snapshot().signed_in(),
_main_subscription: main_subscription,
}
}
@@ -771,6 +785,13 @@ impl OverlayWindow {
let Some(target) = self.target(cx) else {
return;
};
+ if self.needs_sign_in(self.select.read(cx).recording_mode, cx) {
+ self.signed_in = crate::store::auth_snapshot().signed_in();
+ if !self.signed_in {
+ self.start_sign_in(cx);
+ return;
+ }
+ }
if let ScreenCaptureTarget::Window { id } = &target {
let window = scap_targets::Window::from_id(id);
let expected_title = crate::main_window::auto_window_title();
@@ -809,6 +830,28 @@ impl OverlayWindow {
cx.defer(app_windows::dismiss_target_overlays);
}
+ /// Instant mode uploads as it records, so it cannot start signed out
+ /// (`target-select-overlay.tsx`'s "Sign In To Use"). The editor's record
+ /// flow always records Studio whatever the pill says.
+ fn needs_sign_in(&self, mode: Mode, cx: &App) -> bool {
+ mode == Mode::Instant
+ && !self.signed_in
+ && crate::session::RecordingSession::global(cx)
+ .read(cx)
+ .editor_recording_target()
+ .is_none()
+ }
+
+ /// The overlays sit above every app, browser included, so they step aside
+ /// for the main window's sign-in prompt, and re-open for the same target
+ /// kind once signed in.
+ fn start_sign_in(&mut self, cx: &mut Context<Self>) {
+ let Some(kind) = self.select.read(cx).mode else {
+ return;
+ };
+ cx.defer(move |cx: &mut App| app_windows::show_instant_sign_in(kind, cx));
+ }
+
fn sync_appearance(&mut self, window: &Window, cx: &gpui::App) {
self.theme.refresh(window, cx, false);
}
@@ -983,6 +1026,17 @@ impl OverlayWindow {
fn apply_device_choice(&mut self, choice: OverlayDeviceChoice, cx: &mut Context<Self>) {
self.device_menu = None;
let main = cx.global::<app_windows::AppWindows>().main;
+ let needs_access = match &choice {
+ OverlayDeviceChoice::Camera(Some(_)) => Some(crate::permissions::OSPermission::Camera),
+ OverlayDeviceChoice::Microphone(Some(_)) => {
+ Some(crate::permissions::OSPermission::Microphone)
+ }
+ OverlayDeviceChoice::Access(permission) => Some(*permission),
+ _ => None,
+ };
+ if let Some(permission) = needs_access {
+ request_media_access(permission, cx);
+ }
cx.defer(move |cx| {
if !recording_devices_available(cx) {
return;
@@ -990,6 +1044,7 @@ impl OverlayWindow {
if let Err(error) = main.update(cx, |view, _, cx| match choice {
OverlayDeviceChoice::Camera(camera) => view.set_camera_selection(camera, cx),
OverlayDeviceChoice::Microphone(mic) => view.set_microphone_selection(mic, cx),
+ OverlayDeviceChoice::Access(_) => {}
}) {
tracing::warn!(%error, "could not update the recording device");
}
@@ -1006,7 +1061,29 @@ impl OverlayWindow {
if view.is_enumerating_devices() {
return;
}
- let (items, choices) = if camera {
+ let permission = if camera {
+ crate::permissions::OSPermission::Camera
+ } else {
+ crate::permissions::OSPermission::Microphone
+ };
+ let access = crate::media_access::MediaAccess::global(cx);
+ let access_item = (!access.read(cx).allowed(permission)).then(|| {
+ let label = match (
+ camera,
+ access.read(cx).status(permission)
+ == crate::permissions::OSPermissionStatus::Denied,
+ ) {
+ (true, true) => "Turn on camera access in Settings…",
+ (true, false) => "Allow camera access…",
+ (false, true) => "Turn on microphone access in Settings…",
+ (false, false) => "Allow microphone access…",
+ };
+ (
+ crate::ui::MenuItem::new(label, false),
+ OverlayDeviceChoice::Access(permission),
+ )
+ });
+ let (mut items, mut choices) = if camera {
let mut items = vec![crate::ui::MenuItem::new(
"No Camera",
view.camera_selection().is_none(),
@@ -1037,6 +1114,10 @@ impl OverlayWindow {
}
(items, choices)
};
+ if let Some((item, choice)) = access_item {
+ items.insert(0, item);
+ choices.insert(0, choice);
+ }
self.mode_menu = None;
self.countdown_menu = None;
self.device_menu = Some(OverlayDeviceMenu {
@@ -1060,6 +1141,23 @@ impl OverlayWindow {
let enabled = selected.is_some();
let disabled = view.is_enumerating_devices() || !recording_devices_available(cx);
let theme = self.theme;
+ let permission = if camera {
+ crate::permissions::OSPermission::Camera
+ } else {
+ crate::permissions::OSPermission::Microphone
+ };
+ let access = crate::media_access::MediaAccess::global(cx);
+ let access = access.read(cx);
+ let blocked = enabled && !access.allowed(permission);
+ let pill_label = if !blocked {
+ if enabled { "On" } else { "Off" }
+ } else if access.requesting(permission) {
+ "Asking…"
+ } else if access.status(permission) == crate::permissions::OSPermissionStatus::Denied {
+ "Allow in Settings"
+ } else {
+ "Allow"
+ };
div()
.id(if camera {
"overlay-camera"
@@ -1128,24 +1226,30 @@ impl OverlayWindow {
.justify_center()
.rounded_full()
.text_size(px(11.))
- .bg(if enabled {
+ .bg(if blocked {
+ Hsla::from(theme.amber_3)
+ } else if enabled {
Hsla::from(theme.blue_9)
} else {
Hsla::from(theme.gray_5)
})
- .text_color(if enabled {
+ .text_color(if blocked {
+ Hsla::from(theme.amber_11)
+ } else if enabled {
gpui::white()
} else {
Hsla::from(theme.gray_11)
})
- .child(if enabled { "On" } else { "Off" })
+ .child(pill_label)
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(move |this, event: &gpui::ClickEvent, _, cx| {
cx.stop_propagation();
if disabled {
return;
}
- if enabled {
+ if blocked {
+ this.apply_device_choice(OverlayDeviceChoice::Access(permission), cx);
+ } else if enabled {
this.apply_device_choice(
if camera {
OverlayDeviceChoice::Camera(None)
@@ -2079,16 +2183,20 @@ impl OverlayWindow {
} else {
(theme.blue_10, theme.blue_11)
};
+ let needs_sign_in = self.needs_sign_in(mode, cx);
let label = match mode {
Mode::Screenshot => "Take Screenshot",
+ _ if needs_sign_in => "Sign In To Use",
_ => "Start Recording",
};
let icon = match mode {
+ Mode::Instant if needs_sign_in => "icons/user-round.svg",
Mode::Instant => "icons/instant.svg",
Mode::Studio => "icons/film-cut.svg",
Mode::Screenshot => "icons/camera.svg",
};
let mode_label = match mode {
+ Mode::Instant if needs_sign_in => "Instant Mode — Sign in to record instantly",
Mode::Instant => "Instant Mode — Record shareable link",
Mode::Studio => "Studio Mode — Record and edit locally",
Mode::Screenshot => "Screenshot Mode",
@@ -2408,6 +2516,27 @@ impl OverlayWindow {
}
}
+/// Ask for camera/mic access from the overlay. The macOS prompt floats above
+/// the overlays, but System Settings is an ordinary window they would cover,
+/// so a denied permission steps the picker aside before opening the pane.
+fn request_media_access(permission: crate::permissions::OSPermission, cx: &mut App) {
+ let access = crate::media_access::MediaAccess::global(cx);
+ if access.read(cx).allowed(permission) {
+ return;
+ }
+ let denied =
+ access.read(cx).status(permission) == crate::permissions::OSPermissionStatus::Denied;
+ if denied {
+ cx.defer(move |cx| {
+ app_windows::dismiss_target_overlays(cx);
+ crate::media_access::MediaAccess::global(cx)
+ .update(cx, |access, cx| access.request(permission, cx));
+ });
+ } else {
+ access.update(cx, |access, cx| access.request(permission, cx));
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;