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
10 changes: 7 additions & 3 deletions crates/tinyclient/src/gui/rail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ impl Shell {
cx.notify();
}

pub(super) fn rail(&self, snapshot: &Snapshot, _window: &mut Window, cx: &mut Context<Self>) -> Stateful<Div> {
pub(super) fn rail(&self, snapshot: &Snapshot, window: &mut Window, cx: &mut Context<Self>) -> Stateful<Div> {
let mode = &self.sidebar_state.mode;
let tint = |lit: bool| if lit { theme::text() } else { theme::text_soft() };
let rule = || div().w(px(28.)).flex_none().child(divider());
Expand Down Expand Up @@ -234,19 +234,23 @@ impl Shell {
.on_click(cx.listener(move |this, _, _, cx| this.open_menu(menu.clone(), cx)))
};

// The macOS traffic lights overlap the top strip in a window. Begin the rail edge below
// them; full screen and the other platforms keep the edge along the full height.
let lights = cfg!(target_os = "macos") && !phone && !window.is_fullscreen();
div()
.id("places")
.role(gpui::Role::Navigation)
.aria_label("Places")
.relative()
.w(px(rail_width()))
.h_full()
.flex_none()
.flex()
.flex_col()
.items_center()
.bg(theme::rail())
.border_r_1()
.border_color(theme::hairline())
.pr(px(1.))
.child(div().absolute().right_0().bottom_0().top(px(if lights { TOP_BAR } else { 0. })).w(px(1.)).bg(theme::hairline()))
// On a phone the status bar takes the strip's place, and the Inbox button sits level with
// the sidebar's title: 4 above a 44 button in a 52 strip.
.child(drags_window(div().h(px(if phone { tokens::safe_top() + 4. } else { TOP_BAR })).w_full().flex_none()))
Expand Down
Binary file added docs/design/shots/rail-divider.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
32 changes: 28 additions & 4 deletions e2e/lab/platforms/mac/helper/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
// key --pid P --combo alt-down post a key press (modifiers: cmd alt ctrl shift) to P only
// click --pid P --x X --y Y post a click at X,Y points inside P's first window
// text --pid P --out F read visible text from P's first window into F
// shot --pid P --out F.png save P's first window as a PNG
import AppKit
import AVFoundation
import CoreGraphics
Expand Down Expand Up @@ -73,17 +74,22 @@ func status() {
}

@available(macOS 14.0, *)
func windowText(pid: pid_t) async throws -> [String] {
guard let target = windows(of: pid).first else { return [] }
func windowImage(pid: pid_t) async throws -> CGImage? {
guard let target = windows(of: pid).first else { return nil }
let content = try await SCShareableContent.excludingDesktopWindows(true, onScreenWindowsOnly: true)
guard let window = content.windows.first(where: { $0.windowID == target.id && $0.owningApplication?.processID == pid }) else {
return []
return nil
}
let config = SCStreamConfiguration()
config.width = Int(window.frame.width) * 2
config.height = Int(window.frame.height) * 2
let filter = SCContentFilter(desktopIndependentWindow: window)
let image = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: config)
return try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: config)
}

@available(macOS 14.0, *)
func windowText(pid: pid_t) async throws -> [String] {
guard let image = try await windowImage(pid: pid) else { return [] }
let request = VNRecognizeTextRequest()
request.usesLanguageCorrection = false
try VNImageRequestHandler(cgImage: image).perform([request])
Expand Down Expand Up @@ -307,6 +313,24 @@ case "text":
}
}
app.run()
case "shot":
guard #available(macOS 14.0, *) else { die("Window capture requires macOS 14", 77) }
guard let p = option("pid").flatMap({ Int32($0) }), let out = option("out") else { die("--pid --out", 64) }
let app = NSApplication.shared
app.setActivationPolicy(.accessory)
Task {
do {
guard CGPreflightScreenCaptureAccess() else { die("Screen Recording is not granted to TinyLabHelper", 77) }
guard let image = try await windowImage(pid: p) else { die("the app has no window") }
guard let png = NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:]) else { die("could not encode the window") }
try png.write(to: URL(fileURLWithPath: out), options: .atomic)
say("ok shot")
exit(0)
} catch {
die("could not capture the window: \(error)")
}
}
app.run()
case "key":
guard let p = option("pid").flatMap({ Int32($0) }), let combo = option("combo") else { die("--pid --combo", 64) }
guard AXIsProcessTrusted() else { die("Accessibility is not granted to TinyLabHelper", 77) }
Expand Down
4 changes: 4 additions & 0 deletions e2e/scenarios/rail-divider/drive.macos.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/bash
set -eu
HERE=$(cd "$(dirname "$0")" && pwd)
exec python3 "$HERE/drive.py"
132 changes: 132 additions & 0 deletions e2e/scenarios/rail-divider/drive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Check the rail edge in a captured window from the real macOS app."""

import json
import os
from pathlib import Path
import struct
import subprocess
import tempfile
import time

OUT = Path(os.environ["E2E_OUT"])
BIN = Path(os.environ["E2E_APP_DIR"]) / "Contents" / "MacOS"
HELPER = os.environ["E2E_HELPER"]
T0 = float(os.environ.get("E2E_T0") or time.time())


def step(words, ok, shot=None):
entry = {"t": round(time.time() - T0, 2), "step": words, "ok": bool(ok)}
if shot:
entry["shot"] = shot
with (OUT / "steps.jsonl").open("a", encoding="utf-8") as log:
log.write(json.dumps(entry) + "\n")
print(("[ok] " if ok else "[FAILED] ") + words, flush=True)
if not ok:
raise RuntimeError(words)


def stop(proc):
if proc is None or proc.poll() is not None:
return
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)


def helper(*args):
log = OUT / "helper-output.txt"
log.unlink(missing_ok=True)
subprocess.run(["open", "-W", "-n", "--stdout", str(log), "--stderr", str(log),
"-a", HELPER, "--args", *map(str, args)], check=True, timeout=30)
return log.read_text(encoding="utf-8")


def until(look, seconds=25):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
value = look()
if value:
return value
time.sleep(0.25)
return None


def pixels(path):
png = path.read_bytes()
if png[:8] != b"\x89PNG\r\n\x1a\n":
raise RuntimeError("helper did not write a PNG")
width, height = struct.unpack(">II", png[16:24])
rgb = subprocess.run([os.environ.get("E2E_FFMPEG", "ffmpeg"), "-v", "error", "-i", str(path),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Residual: this runs ffmpeg from $E2E_FFMPEG or PATH, but run-macos.sh exports no E2E_FFMPEG on macOS, so the lab Mac needs ffmpeg on the PATH of an ssh session. Same as call-video-seen, tiny-video-received and gpu-codecs-wave18; none of them has run on the lab yet.

"-f", "rawvideo", "-pix_fmt", "rgb24", "-"], check=True,
capture_output=True, timeout=20).stdout
if len(rgb) != width * height * 3:
raise RuntimeError("window image has the wrong pixel count")
return width, height, rgb


def edge_strength(rgb, width, x, y):
at = (y * width + x) * 3
beside = (y * width + x - 6) * 3
return sum(abs(rgb[at + channel] - rgb[beside + channel]) for channel in range(3))


def divider_begins_below_strip(path, window_width):
width, height, rgb = pixels(path)
scale = width / window_width
if height < 120 * scale:
raise RuntimeError("the app window is too short to inspect the rail")
# Find the one-pixel edge near the 72-point rail boundary. The comparison pixel is safely
# inside the rail. Both samples are below the traffic lights and away from rail buttons.
candidates = range(round(70 * scale), round(73 * scale))
upper = range(round(37 * scale), round(47 * scale))
lower = range(round(65 * scale), round(85 * scale))
scores = []
for x in candidates:
top = sum(edge_strength(rgb, width, x, y) for y in upper) / len(upper)
bottom = sum(edge_strength(rgb, width, x, y) for y in lower) / len(lower)
scores.append((bottom, top, x))
bottom, top, _ = max(scores)
return bottom >= 10 and top < bottom * 0.4


def run(data):
env = dict(os.environ, TINYCLIENT_DIR=str(data))
daemon = window = None
with (OUT / "app.log").open("wb") as log:
try:
daemon = subprocess.Popen([BIN / "chatd", "--seed-demo=live"], env=env, stdout=log, stderr=log)
step("demo chat service responds", until(lambda: subprocess.run(
[BIN / "tinyclient", "--text"], env=env, capture_output=True, timeout=5).returncode == 0))
window = subprocess.Popen([BIN / "tinyclient"], env=env, stdout=log, stderr=log)
(OUT / "app.pid").write_text(str(window.pid), encoding="utf-8")

def visible():
lines = helper("windows", "--pid", window.pid).splitlines()
return json.loads(lines[0]) if lines and lines[0].startswith("{") else None

info = until(visible)
step("the app window appears", info)
time.sleep(2)
shot = OUT / "rail-divider.png"
step("the lab helper captured the app window", "ok shot" in helper("shot", "--pid", window.pid, "--out", shot)
and shot.exists(), shot.name)
step("rail edge starts below the traffic lights", divider_begins_below_strip(shot, info["w"]), shot.name)
time.sleep(1)
finally:
stop(window)
stop(daemon)


if __name__ == "__main__":
OUT.mkdir(parents=True, exist_ok=True)
(OUT / "steps.jsonl").write_text("", encoding="utf-8")
try:
with tempfile.TemporaryDirectory(prefix="tiny-rail-divider-", dir="/tmp") as data_dir:
run(Path(data_dir))
except (RuntimeError, OSError, subprocess.SubprocessError) as error:
print(error, flush=True)
raise SystemExit(1)
13 changes: 13 additions & 0 deletions e2e/scenarios/rail-divider/scenario.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"id": "rail-divider",
"title": "The macOS rail divider begins below the window controls",
"platforms": ["macos"],
"not_applicable": {
"windows": "Windows has no macOS traffic lights; its rail divider remains full height.",
"linux": "Linux has no macOS traffic lights; its rail divider remains full height.",
"android": "The phone layout has no macOS window controls.",
"ios": "The phone layout has no macOS window controls."
},
"needs": [],
"release": false
}
Loading