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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions crates/compositor/build.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
use std::env;
use std::path::{Path, PathBuf};

/// Header comments are C/Doxygen source, not implicit Rust examples. Preserve
/// them as text instead of letting indentation turn prose/formulas into doctests.
#[derive(Debug)]
struct FfmpegHeaderDocs;

impl bindgen::callbacks::ParseCallbacks for FfmpegHeaderDocs {
fn process_comment(&self, comment: &str) -> Option<String> {
// A longer fence also preserves upstream comments containing Markdown.
let longest = comment.split(|c| c != '`').map(str::len).max().unwrap_or(0);
let fence = "`".repeat(3.max(longest + 1));
Some(format!("{fence}text\n{comment}\n{fence}"))
}
}

fn main() {
// La cible réelle est connue via `CARGO_CFG_TARGET_OS` (renseigné par cargo
// pour chaque build). `cfg!(target_os = "macos")` est faux ici : build.rs
Expand Down Expand Up @@ -106,6 +120,7 @@ fn main() {
// pinne ses enums/structs pour clang sur macOS, MSVC sur Windows).
let mut builder = bindgen::Builder::default()
.header(wrapper)
.parse_callbacks(Box::new(FfmpegHeaderDocs))
.clang_arg(format!("-I{}", include_dir))
.allowlist_function("av.*")
.allowlist_function("avcodec_.*")
Expand Down
40 changes: 34 additions & 6 deletions crates/compositor/src/d3d_linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,12 +286,33 @@ impl Gpu {
#[cfg(test)]
pub fn shared_for_tests() -> Option<&'static Gpu> {
static GPU: OnceLock<Option<Gpu>> = OnceLock::new();
GPU.get_or_init(|| {
Gpu::create_auto(false)
.map_err(|e| eprintln!("pas d'adaptateur Vulkan ({e:#})"))
.ok()
})
.as_ref()
let gpu = GPU
.get_or_init(|| {
Gpu::create_auto(false)
.map_err(|e| eprintln!("pas d'adaptateur Vulkan ({e:#})"))
.ok()
})
.as_ref()?;
// The GLES fallback has one adapter context with a finite lock timeout.
// Concurrent shader tests can time it out even though the device is shared.
// SAFETY: inspect only the backend kind; do not retain/destroy the HAL handle.
if unsafe {
gpu.device
.as_hal::<wgpu_hal::api::Gles, _, _>(|d| d.is_some())
} {
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
thread_local! {
// libtest gives each test its own thread. Hold through resource Drop,
// release at thread exit, and allow repeated gpu() calls in that test.
static GUARD: std::cell::OnceCell<std::sync::MutexGuard<'static, ()>> = const {
std::cell::OnceCell::new()
};
}
GUARD.with(|guard| {
guard.get_or_init(|| LOCK.lock().unwrap_or_else(|e| e.into_inner()));
});
}
Some(gpu)
}
}

Expand Down Expand Up @@ -332,6 +353,13 @@ fn any_adapter_exists() -> bool {
mod tests {
use super::*;

#[test]
fn shared_test_device_can_be_reused_on_the_same_test_thread() {
if let Some(first) = Gpu::shared_for_tests() {
assert!(std::ptr::eq(first, Gpu::shared_for_tests().unwrap()));
}
}

#[test]
fn classify_cpu_pour_lavapipe() {
let info = wgpu::AdapterInfo {
Expand Down
71 changes: 71 additions & 0 deletions crates/compositor/tests/ffi_header_docs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//! C-header prose/examples must remain visible docs, not implicit Rust examples.
use std::{
fs,
process::Command,
time::{SystemTime, UNIX_EPOCH},
};

#[test]
fn generated_header_docs_do_not_disable_real_rust_doctests() {
let bindings = include_str!(concat!(env!("OUT_DIR"), "/ffi.rs"));
let docs = bindings
.lines()
.map(str::trim_start)
.filter(|line| line.starts_with("#[doc = "))
.collect::<Vec<_>>();
assert!(docs.len() > 100, "keep upstream header documentation");
assert!(docs
.join("\n")
.contains("Return an informative version string"));
let dir = std::env::temp_dir().join(format!(
"openscreen-ffi-docs-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir(&dir).unwrap();
let fixture = dir.join("foreign_docs.rs");
fs::write(
&fixture,
format!(
"{}\npub struct ForeignHeader;\n\
/// A genuine Rust example must still execute.\n\
/// ```rust\n\
/// assert_eq!(2 + 2, 4);\n\
/// ```\n\
pub struct RustExample;\n",
docs.join("\n")
),
)
.unwrap();
let output = Command::new(std::env::var_os("RUSTDOC").unwrap_or_else(|| "rustdoc".into()))
.args(["--test", "--edition=2021"])
.arg(&fixture)
.output()
.unwrap();
let report = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert!(output.status.success(), "{report}");
assert!(report.contains("1 passed; 0 failed; 0 ignored"), "{report}");
// A broken *Rust* example must still fail: no global doctest disable/ignore.
let source = fs::read_to_string(&fixture)
.unwrap()
.replace("assert_eq!(2 + 2, 4)", "assert_eq!(2 + 2, 5)");
fs::write(&fixture, source).unwrap();
let broken = Command::new(std::env::var_os("RUSTDOC").unwrap_or_else(|| "rustdoc".into()))
.args(["--test", "--edition=2021"])
.arg(&fixture)
.output()
.unwrap();
fs::remove_dir_all(&dir).unwrap();
assert!(
!broken.status.success(),
"real Rust doctests must not be skipped"
);
assert!(String::from_utf8_lossy(&broken.stdout).contains("1 failed"));
}
143 changes: 143 additions & 0 deletions electron/ipc/browserCursorCapability.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import fs from "node:fs";
import path from "node:path";
import { runInNewContext } from "node:vm";
import ts from "typescript";
import { describe, expect, it, vi } from "vitest";
import { browserCursorCaptureError } from "../../src/lib/browserCursorCapture";

const source = fs.readFileSync(new URL("./handlers.ts", import.meta.url), "utf8");
function execute(code: string, context: object) {
runInNewContext(
ts.transpileModule(code, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
}).outputText,
context,
);
}
function stateFixture(platform = "linux") {
const start = source.indexOf('ipcMain.handle(\n\t\t"set-recording-state",');
expect(start).toBeGreaterThan(-1);
const end = source.indexOf("\n\t);", start) + 5;
const handle = vi.fn();
const context = {
ipcMain: { handle },
process: { platform },
browserCursorCaptureError,
isWindowsUpdatePending: () => false,
selectedSource: { name: "Chosen screen" },
normalizeCursorCaptureMode: (mode: string) =>
mode === "system" || mode === "editable-overlay" ? mode : undefined,
setAppRecording: vi.fn(),
startCursorRecording: vi.fn(async () => undefined),
stopCursorRecording: vi.fn(async () => undefined),
};
execute(source.slice(start, end), context);
return {
context,
invoke: handle.mock.calls[0][1] as (
...args: unknown[]
) => Promise<{ success: boolean; error?: string }>,
};
}
describe("browser cursor main-process capability boundary", () => {
it.each([
true,
false,
])("refuses an editable browser start before reservation/sampler (reserve=%s)", async (reserve) => {
const { context, invoke } = stateFixture();
expect(await invoke({}, true, 123, "editable-overlay", reserve)).toMatchObject({
success: false,
error: expect.stringContaining("native Linux capture"),
});
expect(context.setAppRecording).not.toHaveBeenCalled();
expect(context.startCursorRecording).not.toHaveBeenCalled();
expect(context.stopCursorRecording).not.toHaveBeenCalled();
});
it("does not silently treat a missing mode as a supported editable take", async () => {
const { context, invoke } = stateFixture();
expect(await invoke({}, true)).toMatchObject({ success: false });
expect(context.setAppRecording).not.toHaveBeenCalled();
});
it("still allows stop/cleanup regardless of the unsupported requested mode", async () => {
const { context, invoke } = stateFixture();
expect(await invoke({}, false, 123, "editable-overlay")).toMatchObject({ success: true });
expect(context.stopCursorRecording).toHaveBeenCalledOnce();
});
it.each([
["linux", "system"],
["win32", "editable-overlay"],
["darwin", "editable-overlay"],
])("preserves %s %s recording", async (platform, mode) => {
const { context, invoke } = stateFixture(platform);
expect(await invoke({}, true, 123, mode)).toMatchObject({ success: true });
expect(context.setAppRecording).toHaveBeenCalled();
if (mode === "system") expect(context.startCursorRecording).not.toHaveBeenCalled();
else expect(context.startCursorRecording).toHaveBeenCalledWith(123);
});
});

function storeFixture() {
const start = source.indexOf("async function storeRecordedSessionFiles(");
const end = source.indexOf('\n\tipcMain.handle("store-recorded-video"', start);
const context = {
process: { platform: "linux" },
browserCursorCaptureError,
normalizeCursorCaptureMode: (mode: string) =>
mode === "system" || mode === "editable-overlay" ? mode : undefined,
resolveRecordingOutputPath: vi.fn((name: string) => `/rec/${name}`),
finalizeRecordingFile: vi.fn(async () => false),
recordingStreams: new Map(),
stoppedBrowserCursorRecordings: new Map(),
fs: { stat: vi.fn(async () => ({ size: 4096 })), writeFile: vi.fn(async () => undefined) },
isValidDurationMs: () => false,
pendingCursorRecordingData: { samples: [{ timeMs: 10 }] },
cursorTelemetryRecordingId: 999,
finalizeBrowserCursorTelemetry: vi.fn((data: unknown) => data),
writePendingCursorTelemetry: vi.fn(async () => undefined),
setCurrentRecordingSessionState: vi.fn(),
currentProjectPath: null,
RECORDINGS_DIR: "/rec",
RECORDING_SESSION_SUFFIX: ".session.json",
path,
registerRecordingMediaLinks: vi.fn(async () => undefined),
storeRecordedSessionFiles: undefined as unknown as (
payload: object,
) => Promise<{ success: boolean; error?: string; session?: { cursorCaptureMode: string } }>,
};
execute(source.slice(start, end), context);
return context;
}
describe("browser store capability boundary", () => {
it.each([
"editable-overlay",
undefined,
"invalid",
])("rejects unsupported/ambiguous mode %s before file or ownership changes", async (mode) => {
const c = storeFixture();
const owned = c.pendingCursorRecordingData;
expect(
await c.storeRecordedSessionFiles({
screen: { fileName: "screen.webm" },
cursorCaptureMode: mode,
}),
).toMatchObject({ success: false, error: expect.stringContaining("--cursor system") });
expect(c.finalizeRecordingFile).not.toHaveBeenCalled();
expect(c.fs.writeFile).not.toHaveBeenCalled();
expect(c.setCurrentRecordingSessionState).not.toHaveBeenCalled();
expect(c.pendingCursorRecordingData).toBe(owned);
expect(c.cursorTelemetryRecordingId).toBe(999);
});
it("stores explicit system without attaching or clearing another take's pending telemetry", async () => {
const c = storeFixture();
const owned = c.pendingCursorRecordingData;
expect(
await c.storeRecordedSessionFiles({
screen: { fileName: "screen.webm" },
cursorCaptureMode: "system",
}),
).toMatchObject({ success: true, session: { cursorCaptureMode: "system" } });
expect(c.writePendingCursorTelemetry).not.toHaveBeenCalled();
expect(c.finalizeBrowserCursorTelemetry).not.toHaveBeenCalled();
expect(c.pendingCursorRecordingData).toBe(owned);
});
});
Loading
Loading