Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

13.6 KB
Raw Blame
/**
 * The pointer sidecar: where the pointer was and when a button went down or
 * up while recording, so the moment rules have something to anchor on.
 *
 * Each OS gets a tiny helper that uses only what ships with it, polls the
 * pointer every ~50 ms and prints one line per sample:
 *
 *   P <epoch ms> <x> <y> <buttons>     buttons: 1 left, 2 right, 4 middle
 *   S <json>                           the screens, once, at start
 *   E <message>                        the helper cannot work here
 *
 * - Linux: python3 with ctypes over libX11 (XQueryPointer). No Xlib module,
 *   xdotool or xinput needed. Coordinates are X screen pixels.
 * - macOS: osascript JXA reading NSEvent.mouseLocation and
 *   pressedMouseButtons. Coordinates are global points, top-left origin.
 * - Windows: PowerShell calling GetCursorPos and GetAsyncKeyState from a
 *   DPI-aware process. Coordinates are virtual-desktop pixels.
 *
 * Polling sees a button state, not the button event itself, so a click
 * shorter than one interval can be missed. Scroll and keys are not sampled.
 */
import { spawn, type ChildProcess } from "node:child_process";
import { trackChild } from "./children.js";
import { xEnv } from "./xauth.js";
import { createInterface } from "node:readline";
import { findExecutable } from "./proc.js";
import { encodePowerShell, LINUX_POINTER_SCRIPT, MAC_POINTER_SCRIPT, windowsPointerScript } from "./scripts.js";
import { parseScreensLine, type ScreenInfo } from "./sources.js";
import type { InteractionEvent, Platform } from "./types.js";

export const SAMPLE_INTERVAL_MS = 50;

export interface PointerSample {
  /** Epoch ms. */
  t: number;
  x: number;
  y: number;
  /** 1 left, 2 right, 4 middle. */
  buttons: number;
}

// ---------------------------------------------------------------------------
// Parsing and conversion (pure)
// ---------------------------------------------------------------------------

export function parseSampleLine(line: string): PointerSample | null {
  const m = /^P (\d+) (-?\d+(?:\.\d+)?) (-?\d+(?:\.\d+)?) (\d+)\s*$/.exec(line);
  if (!m) return null;
  return { t: Number(m[1]), x: Math.round(Number(m[2])), y: Math.round(Number(m[3])), buttons: Number(m[4]) & 7 };
}

const BUTTONS: [bit: number, button: number][] = [
  [1, 1],
  [2, 2],
  [4, 3],
];

/** One recorded stretch of a capture, between a start (or resume) and a pause (or stop). */
export interface RecordedSegment {
  /** Epoch ms when this segment's ffmpeg began recording. */
  startedAt: number;
  /** Epoch ms when it stopped; left open while the segment is still recording. */
  endedAt?: number;
  /**
   * The segment's true length in the finished video, in ms, when it is known.
   * ffmpeg can record a little past `endedAt` (it flushes a final fragment), so
   * this is preferred when placing later segments on the timeline; it falls
   * back to the wall-clock span.
   */
  videoMs?: number;
}

/** The segment's length on the video clock, or Infinity while it is still recording. */
function segmentCap(seg: RecordedSegment): number {
  if (seg.videoMs !== undefined) return Math.max(0, seg.videoMs);
  if (seg.endedAt !== undefined) return Math.max(0, seg.endedAt - seg.startedAt);
  return Infinity;
}

/**
 * Turn polled samples into interaction events on the recording clock, across
 * one or more recorded segments. A capture that was paused is several segments;
 * the pauses between them are left out, so each segment begins on the clock
 * where the previous one ended, and samples taken while paused are dropped.
 * `maxDurationMs`, when given, clamps every event to the video's length.
 *
 * - Times are ms from the first segment's start. A move is emitted only when
 *   the position changes; the position held when recording starts is emitted
 *   once at time 0.
 * - A button that goes down during a segment emits `down`, and `up` when it is
 *   released. A button already held at the first start emits nothing until it
 *   is pressed again, so every `up` has its `down`. Once the last segment has
 *   ended, any button still down gets an `up` at the end, so every `down` has
 *   an `up`.
 */
export function samplesToEventsInSegments(
  samples: readonly PointerSample[],
  segments: readonly RecordedSegment[],
  maxDurationMs?: number,
): InteractionEvent[] {
  if (segments.length === 0) return [];
  if (segments[0].endedAt !== undefined && segments[0].endedAt < segments[0].startedAt) return [];
  const sorted = [...samples].sort((a, b) => a.t - b.t);

  // Where each segment begins on the video clock (the earlier segments' lengths).
  const offsets: number[] = [0];
  for (let i = 1; i < segments.length; i++) {
    const length = segmentCap(segments[i - 1]);
    offsets.push(offsets[i - 1] + (Number.isFinite(length) ? length : 0));
  }
  const clamp = (t: number) => (maxDurationMs === undefined ? t : Math.min(t, maxDurationMs));

  const firstStart = segments[0].startedAt;
  const events: InteractionEvent[] = [];
  // The last sample before the recording places the pointer at its start,
  // even when no later sample lands inside it.
  let i = 0;
  while (i < sorted.length && sorted[i].t < firstStart) i++;
  const preStart = sorted[i - 1];
  let last: { x: number; y: number } | undefined = preStart;
  let buttons: number | undefined = preStart?.buttons;
  if (preStart) events.push({ kind: "move", time_ms: 0, x: preStart.x, y: preStart.y });
  const down = new Set<number>();
  let seg = 0;
  let pausedButtons: number | undefined;
  for (; i < sorted.length; i++) {
    const s = sorted[i];
    // Skip past any segment (and the pause after it) this sample lands beyond.
    while (seg < segments.length && segments[seg].endedAt !== undefined && s.t > segments[seg].endedAt!) seg++;
    if (seg >= segments.length) break;
    if (s.t < segments[seg].startedAt) {
      pausedButtons = s.buttons;
      continue;
    }
    buttons ??= s.buttons;
    // Cap the offset into a segment at its own length, so a sample in the tail
    // (after that segment's video ended) never spills into the next segment.
    const into = Math.min(s.t - segments[seg].startedAt, segmentCap(segments[seg]));
    const time = clamp(Math.round(offsets[seg] + into));
    if (!last || last.x !== s.x || last.y !== s.y) {
      events.push({ kind: "move", time_ms: time, x: s.x, y: s.y });
      last = { x: s.x, y: s.y };
    }
    for (const [bit, button] of BUTTONS) {
      // A press observed only while paused is already held at resume.
      // Keep pairing releases with presses recorded before the pause.
      const was = down.has(button) || ((pausedButtons ?? buttons) & bit) !== 0;
      const is = (s.buttons & bit) !== 0;
      if (!was && is) {
        events.push({ kind: "down", time_ms: time, x: s.x, y: s.y, button });
        down.add(button);
      } else if (was && !is && down.has(button)) {
        events.push({ kind: "up", time_ms: time, x: s.x, y: s.y, button });
        down.delete(button);
      }
    }
    buttons = s.buttons;
    pausedButtons = undefined;
  }
  const lastSeg = segments[segments.length - 1];
  if (lastSeg.endedAt !== undefined && down.size > 0 && last) {
    const endTime = clamp(Math.round(offsets[segments.length - 1] + segmentCap(lastSeg)));
    for (const [, button] of BUTTONS) {
      if (down.has(button)) {
        events.push({ kind: "up", time_ms: endTime, x: last.x, y: last.y, button });
      }
    }
  }
  return events;
}

/** How long before the end the samples may stop before the caller is told. */
export const POINTER_GAP_LIMIT_MS = 3000;

/**
 * A warning when the samples end well before the recording does. A helper
 * prints one every interval whether or not the pointer moves, so a long gap
 * means it stopped partway. null when the samples reach the end, or when there
 * are none (the sampler's `stop()` reports that).
 */
export function pointerGapWarning(samples: readonly PointerSample[], endedAt: number): string | null {
  if (samples.length === 0) return null;
  const gapMs = endedAt - samples.reduce((latest, s) => Math.max(latest, s.t), 0);
  if (gapMs <= POINTER_GAP_LIMIT_MS) return null;
  return `pointer positions stopped ${Math.round(gapMs / 1000)}s before the recording ended; later moves and clicks are missing`;
}

/**
 * Turn polled samples into interaction events on the recording clock of a
 * single, unpaused recording: times are ms since `startedAt`, and samples after
 * `endedAt` are dropped. See {@link samplesToEventsInSegments} for the move and
 * button rules.
 */
export function samplesToEvents(samples: readonly PointerSample[], startedAt: number, endedAt?: number): InteractionEvent[] {
  if (endedAt !== undefined && endedAt < startedAt) return [];
  return samplesToEventsInSegments(samples, [{ startedAt, endedAt }]);
}

// ---------------------------------------------------------------------------
// Running a helper
// ---------------------------------------------------------------------------

export interface PointerSampler {
  /** Screens the helper reported (empty until it prints them). */
  screens(): ScreenInfo[];
  /** Resolves once the helper printed its first line, or failed, or 3 s passed. */
  ready: Promise<void>;
  stop(): Promise<{ samples: PointerSample[]; warnings: string[] }>;
}

export interface SamplerOptions {
  xDisplay?: string;
  intervalMs?: number;
  env?: NodeJS.ProcessEnv;
}

function helperCommand(platform: Platform, intervalMs: number, env: NodeJS.ProcessEnv): { cmd: string; args: string[] } | { missing: string } {
  const seconds = (intervalMs / 1000).toFixed(3);
  if (platform === "linux") {
    const python = findExecutable("python3", platform, env);
    if (!python) return { missing: "pointer positions need python3 on Linux; recording without them" };
    return { cmd: python, args: ["-c", LINUX_POINTER_SCRIPT, seconds] };
  }
  if (platform === "darwin") {
    const osascript = findExecutable("osascript", platform, env) ?? "/usr/bin/osascript";
    return { cmd: osascript, args: ["-l", "JavaScript", "-e", MAC_POINTER_SCRIPT, seconds] };
  }
  const powershell = findExecutable("powershell.exe", platform, env) ?? findExecutable("pwsh.exe", platform, env);
  if (!powershell) return { missing: "pointer positions need PowerShell on Windows; recording without them" };
  return {
    cmd: powershell,
    args: ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encodePowerShell(windowsPointerScript(intervalMs))],
  };
}

export function startPointerSampler(platform: Platform, opts: SamplerOptions = {}): PointerSampler {
  const base = { ...(opts.env ?? process.env) };
  const env = platform === "linux" ? xEnv(base, opts.xDisplay) : base;
  const intervalMs = opts.intervalMs ?? SAMPLE_INTERVAL_MS;
  const samples: PointerSample[] = [];
  const warnings: string[] = [];
  let screens: ScreenInfo[] = [];
  const command = helperCommand(platform, intervalMs, env);
  if ("missing" in command) {
    warnings.push(command.missing);
    return { screens: () => screens, ready: Promise.resolve(), stop: async () => ({ samples, warnings }) };
  }

  let child: ChildProcess | null = null;
  let errorLine: string | null = null;
  let stderr = "";
  let markReady: () => void = () => {};
  const ready = new Promise<void>((r) => {
    markReady = r;
  });
  const readyTimer = setTimeout(() => markReady(), 3000);
  const exited = new Promise<void>((resolve) => {
    try {
      child = trackChild(spawn(command.cmd, command.args, { env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }));
    } catch (err) {
      errorLine = (err as Error).message;
      resolve();
      return;
    }
    const c = child as ChildProcess;
    let exitTimer: ReturnType<typeof setTimeout> | undefined;
    let lines: ReturnType<typeof createInterface> | undefined;
    let settled = false;
    const onStderrData = (chunk: Buffer) => {
      if (stderr.length < 4096) stderr += chunk.toString("utf8");
    };
    const finish = () => {
      if (settled) return;
      settled = true;
      if (exitTimer) clearTimeout(exitTimer);
      c.off("error", onError);
      c.off("exit", onExit);
      c.off("close", onClose);
      c.stderr?.off("data", onStderrData);
      lines?.close();
      resolve();
    };
    const onError = (err: Error) => {
      errorLine ??= err.message;
      finish();
    };
    const onExit = () => {
      exitTimer = setTimeout(() => {
        c.stdout?.destroy();
        c.stderr?.destroy();
        finish();
      }, 1000);
    };
    const onClose = () => finish();
    c.once("error", onError);
    c.once("exit", onExit);
    c.once("close", onClose);
    c.stderr?.on("data", onStderrData);
    lines = createInterface({ input: c.stdout! });
    lines.on("line", (line) => {
      markReady();
      const sample = parseSampleLine(line);
      if (sample) samples.push(sample);
      else if (line.startsWith("S ")) screens = parseScreensLine(line);
      else if (line.startsWith("E ")) errorLine ??= line.slice(2).trim();
    });
  });
  void exited.then(() => markReady());

  let stopped: Promise<{ samples: PointerSample[]; warnings: string[] }> | null = null;
  const stop = async () => {
    clearTimeout(readyTimer);
    const c = child as ChildProcess | null;
    if (c && c.exitCode === null && c.signalCode === null) {
      c.kill();
      const killTimer = setTimeout(() => c.kill("SIGKILL"), 2000);
      await exited;
      clearTimeout(killTimer);
    } else {
      await exited;
    }
    if (samples.length === 0) {
      const why = errorLine ?? stderr.trim().split("\n").pop() ?? "the helper printed nothing";
      warnings.push(`no pointer positions were recorded (${why || "the helper printed nothing"})`);
    }
    return { samples, warnings };
  };

  return {
    screens: () => screens,
    ready,
    stop() {
      stopped ??= stop();
      return stopped;
    },
  };
}