// F01 — first pixel & init cost, X11 edition (../../../features/f01-first-pixel.md).
// Derived from the X11 scaffold (../scaffold/app.d), cut down to exactly the
// init-to-first-pixel path: connect, create + map a window, allocate a MIT-SHM
// backbuffer, draw one gradient, present it, and exit as soon as the present is
// confirmed.
//
// Every initialization API call emits one `step name=<call>` line, tagged
// `rt=1` when the call blocks on a server reply (a round-trip in Xlib's
// output-buffer model) and `rt=0` when it only appends to the output buffer.
// X11 is the platform where this distinction is the finding: most of "window
// creation" is free local marshalling, and the wall-clock cost concentrates in
// the handful of reply-bearing calls (XOpenDisplay, XShmQueryExtension,
// XInternAtom, the XSetWMProtocols hidden InternAtom, and the one deliberate
// XSync in the SHM attach dance).
//
// WSI_SYNC_STEPS=1 brackets every *async* request with an XSync and logs
// `step name=XSync after=<call> us=<cost>` — measuring the
// server-side processing each fire-and-forget call hides.
// WSI_NO_SHM=1 forces the plain XPutImage fallback; first pixel is then
// only `method=XPutImage_XSync` (server *processed* the
// put — core X11 cannot confirm presentation; without the
// Present extension that caveat is structural, and with
// MIT-SHM the completion event still only means "the
// server is done *reading* the segment").
//
// After `first_pixel_presented` the demo emits one summary line:
// summary concepts=<N> loc=<N> init_to_pixel_us=<N>
// concepts = distinct platform object/handle types touched (the F01 concept
// count, itemized in ../../scaffold.md); loc = lines of this file (excluding
// instrument.d and c.c), kept in sync manually with `wc -l app.d`.
//
// Headless-safe: no reachable X server prints `SKIP:` and exits 0. Findings:
// ../../f01-first-pixel.md.
module (module) appapp;
import (module) cc; // ImportC: Xlib + Xutil + Xatom + XShm + sys/ipc + sys/shm + poll
import (module) instrumentinstrument;
import (package) corecore.(package) core.stdcstdc.(module) core.stdc.configD compatible types that correspond to various basic types in associated
C and C++ compilers.
Source
core/stdc/config.d
config : c_long;
import (package) corecore.(package) core.stdcstdc.(module) core.stdc.stdioD header file for C99 <stdio.h>
pubs.opengroup.org/onlinepubs/009695399/basedefs/stdio.h.html, stdio.h
Source
core/stdc/stdio.d
stdio : (alias) app.printf = int core.stdc.stdio.printf(scope const(char*) format, scope const ...) nothrow @nogcprintf;
import (package) corecore.(package) core.stdcstdc.(module) core.stdc.stdlibD header file for C99.
pubs.opengroup.org/onlinepubs/009695399/basedefs/stdlib.h.html, stdlib.h
Source
core/stdc/stdlib.d
stdlib : (alias) app.getenv = char* core.stdc.stdlib.getenv(scope const(char*) name) nothrow @nogcgetenv;
// Constants Xlib/glibc expose only as macros (not ImportC-able); re-declared
// per the ImportC guide, same as the scaffold.
enum : c_long
{
(enum value) app.ExposureMask = 32768LExposureMask = 1L << 15,
(enum value) app.StructureNotifyMask = 131072LStructureNotifyMask = 1L << 17,
}
enum // XEvent.type discriminators
{
(enum value) app.Expose = 12Expose = 12,
(enum value) app.MapNotify = 19MapNotify = 19,
(enum value) app.ConfigureNotify = 22ConfigureNotify = 22,
}
enum (constant) int app.ZPixmap = 2ZPixmap = 2;
enum (constant) int app.ShmCompletion = 0ShmCompletion = 0; // offset inside MIT-SHM's allocated event range
enum (constant) int app.False = 0False = 0;
enum (constant) int app.True = 1True = 1;
enum (constant) int app.POLLIN = 1POLLIN = 0x001;
enum (constant) int app.IPC_PRIVATE = 0IPC_PRIVATE = 0;
enum (constant) int app.IPC_CREAT = 512IPC_CREAT = 0x200; // 01000 octal
enum (constant) int app.IPC_RMID = 0IPC_RMID = 0;
/// This file's line count — the F01 LOC figure (excludes instrument.d / c.c).
/// Keep in sync with `wc -l app.d`.
enum (constant) int app.locCount = 359This file's line count — the F01 LOC figure (excludes instrument.d / c.c).
Keep in sync with wc -l app.d.
locCount = 359;
__gshared bool (__gshared global) bool app.g_syncStepsg_syncSteps = false;
/// `step name=<call> rt=<0|1>` — one line per init API call. `rt=1` marks a
/// call that blocked on a server reply.
void app.step``step name=<call> rt=<0|1> — one line per init API call. rt=1 marks a
call that blocked on a server reply.
step(Display* (parameter) Display* dpydpy, const(char)* name, bool roundTrip) @nogc nothrow
{
emitf("step", "name=%s rt=%d", name, cast(int) roundTrip);
}
/// WSI_SYNC_STEPS=1: bracket an async request with XSync to surface the
/// server-side cost the fire-and-forget call hides.
void app.syncPointWSI_SYNC_STEPS=1: bracket an async request with XSync to surface the
server-side cost the fire-and-forget call hides.
syncPoint(Display* (parameter) Display* dpydpy, const(char)* after) @nogc nothrow
{
if (!g_syncSteps)
return;
const _error_ t0t0 = nowUs();
XSync(dpy, False);
emitf("step", "name=XSync after=%s us=%lld", after, nowUs() - t0);
}
/// Corner-anchored diagonal gradient (the scaffold's, phase 0 — one frame).
void app.drawGradientCorner-anchored diagonal gradient (the scaffold's, phase 0 — one frame).
drawGradient(XImage* (parameter) XImage* ximgximg) @nogc nothrow
{
const _error_ ww = ximg.ximg.widthwidth, _error_ hh = ximg.ximg.heightheight;
if (ximg.bits_per_pixel != 32)
return;
foreach ((parameter) yy; 0 .. h)
{
auto _error_ rowrow = cast(uint*)(ximg.ximg.datadata + y * ximg.bytes_per_line);
const _error_ gg = cast(uint)(h > 1 ? (y * 255) / (h - 1) : 0);
foreach ((parameter) xx; 0 .. w)
{
const _error_ rr = cast(uint)(w > 1 ? (x * 255) / (w - 1) : 0);
row[x] = (r << 16) | (g << 8) | cast(uint)((x + y) & 0xff);
}
}
}
int int D main()main()
{
void instrument.initInstrument(const(char)* demoName) nothrow @nogcNames the demo, starts the monotonic clock, and emits init_start.
Call this first, before any platform API call.
initInstrument("f01_x11");
(__gshared global) bool app.g_syncStepsg_syncSteps = char* core.stdc.stdlib.getenv(scope const(char*) name) nothrow @nogcgetenv("WSI_SYNC_STEPS") !is null;
// -- 1. Connect (concept 1: Display*) — the one unavoidable round-trip:
// socket connect + authentication + the connection-setup reply.
Display* (local variable) _error_ dpydpy = XOpenDisplay(null);
if (dpy is null)
{
int core.stdc.stdio.printf(scope const(char*) format, scope const ...) nothrow @nogcprintf("SKIP: no X11 display (XOpenDisplay returned null)\n");
return 0;
}
step(dpy, "XOpenDisplay", true);
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("step", "name=XConnectionNumber fd=%d rt=0", XConnectionNumber(dpy));
const (local variable) const(_error_) screenscreen = XDefaultScreen(dpy); // local: reads connection-setup data
const (local variable) const(_error_) rootroot = XRootWindow(dpy, screen);
Visual* (local variable) _error_ visualvisual = XDefaultVisual(dpy, screen); // concept 4: Visual*
const (local variable) const(_error_) depthdepth = XDefaultDepth(dpy, screen);
step(dpy, "XDefaultScreen/Root/Visual/Depth", false);
// -- 2. MIT-SHM availability — QueryExtension is reply-bearing.
bool (local variable) bool haveShmhaveShm = XShmQueryExtension(dpy) != 0;
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("step", "name=XShmQueryExtension available=%d rt=1", cast(int) (local variable) bool haveShmhaveShm);
int (local variable) int shmCompletionTypeshmCompletionType = -1;
if ((local variable) bool haveShmhaveShm && char* core.stdc.stdlib.getenv(scope const(char*) name) nothrow @nogcgetenv("WSI_NO_SHM") !is null)
{
(local variable) bool haveShmhaveShm = false;
void instrument.emit(scope const(char)* kind) nothrow @nogcEmit an event with no key=value payload.
emit("step name=shm_fallback reason=WSI_NO_SHM");
}
else if ((local variable) bool haveShmhaveShm)
{
// Local: libXext cached the extension info during the query above.
(local variable) int shmCompletionTypeshmCompletionType = XShmGetEventBase(dpy) + ShmCompletion;
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("step", "name=XShmGetEventBase completion_event=%d rt=0", (local variable) int shmCompletionTypeshmCompletionType);
}
else
void instrument.emit(scope const(char)* kind) nothrow @nogcEmit an event with no key=value payload.
emit("step name=shm_fallback reason=extension_absent");
// -- 3. Window (concept 2: Window, an XID minted client-side) ------------
const (local variable) const(int) widthwidth = 480, (local variable) const(int) heightheight = 320;
Window (local variable) _error_ winwin = XCreateSimpleWindow(dpy, root, 0, 0, width, height, 1,
XBlackPixel(dpy, screen), XWhitePixel(dpy, screen));
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("step", "name=XCreateSimpleWindow xid=0x%lx rt=0", win);
syncPoint(dpy, "XCreateSimpleWindow");
XStoreName(dpy, win, "Sparkles · X11 F01");
step(dpy, "XStoreName", false);
syncPoint(dpy, "XStoreName");
// -- 4. Close handshake (concept 3: Atom). XInternAtom carries a reply;
// XSetWMProtocols additionally interns WM_PROTOCOLS itself — a *hidden*
// second InternAtom round-trip (xtrace-confirmed in ../../scaffold.md).
Atom (local variable) _error_ wmDeletewmDelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("step", "name=XInternAtom atom=%lu rt=1", wmDelete);
XSetWMProtocols(dpy, win, &wmDelete, 1);
void instrument.emit(scope const(char)* kind) nothrow @nogcEmit an event with no key=value payload.
emit("step name=XSetWMProtocols rt=1 note=hidden_InternAtom");
XSelectInput(dpy, win, ExposureMask | StructureNotifyMask);
step(dpy, "XSelectInput", false);
XMapWindow(dpy, win);
step(dpy, "XMapWindow", false);
syncPoint(dpy, "XMapWindow");
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("window_created", "xid=0x%lx size=%dx%d", win, (local variable) const(int) widthwidth, (local variable) const(int) heightheight);
GC (local variable) _error_ gcgc = XDefaultGC(dpy, screen); // concept 5: GC (the default one)
// -- 5. Backbuffer: concepts 6 (XImage*), 7 (ShmSeg XID), 9 (SysV shm
// segment, a kernel handle — not an X concept at all).
XImage* (local variable) _error_ ximgximg;
XShmSegmentInfo (local variable) _error_ shminfoshminfo;
bool (local variable) bool usingShmusingShm = false;
if ((local variable) bool haveShmhaveShm)
{
ximg = XShmCreateImage(dpy, visual, cast(uint) depth, ZPixmap,
null, &shminfo, width, height);
if (ximg !is null)
{
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("step", "name=XShmCreateImage size=%dx%d bpl=%d bpp=%d rt=0",
(local variable) const(int) widthwidth, (local variable) const(int) heightheight, ximg.bytes_per_line, ximg.bits_per_pixel);
const (local variable) const(_error_) nbytesnbytes = cast((alias) object.size_t = ulongsize_t)(ximg.bytes_per_line * ximg.(field) _error_ ximg.heightheight);
shminfo.shmid = shmget(IPC_PRIVATE, nbytes, IPC_CREAT | 0x180 /* 0600 */ );
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("step", "name=shmget shmid=%d bytes=%zu rt=kernel", shminfo.shmid, nbytes);
if (shminfo.shmid >= 0)
{
shminfo.shmaddr = cast(char*) shmat(shminfo.shmid, null, 0);
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("step", "name=shmat ok=%d rt=kernel",
cast(int)(shminfo.shmaddr !is cast(char*)-1));
if (shminfo.shmaddr !is cast(char*)-1)
{
ximg.ximg.datadata = shminfo.shmaddr;
shminfo.readOnly = False;
XShmAttach(dpy, &shminfo);
void instrument.emit(scope const(char)* kind) nothrow @nogcEmit an event with no key=value payload.
emit("step name=XShmAttach rt=0");
// The one deliberate round-trip of SHM setup: the server
// must have attached before we mark-for-delete, so the
// kernel reclaims the segment even if we crash.
const (local variable) const(long) t0t0 = long instrument.nowUs() nothrow @nogcMicroseconds elapsed since initInstrument.
nowUs();
XSync(dpy, False);
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("step", "name=XSync rt=1 us=%lld", long instrument.nowUs() nothrow @nogcMicroseconds elapsed since initInstrument.
nowUs() - (local variable) const(long) t0t0);
shmctl(shminfo.shmid, IPC_RMID, null);
void instrument.emit(scope const(char)* kind) nothrow @nogcEmit an event with no key=value payload.
emit("step name=shmctl_IPC_RMID rt=kernel");
(local variable) bool usingShmusingShm = true;
}
else
shmctl(shminfo.shmid, IPC_RMID, null);
}
if (!(local variable) bool usingShmusingShm)
{
ximg.f.destroy_image(ximg); // XDestroyImage is a macro
ximg = null;
}
}
if (!(local variable) bool usingShmusingShm)
void instrument.emit(scope const(char)* kind) nothrow @nogcEmit an event with no key=value payload.
emit("step name=shm_fallback reason=alloc_or_attach_failed");
}
if (!(local variable) bool usingShmusingShm)
{
import (package) corecore.(package) core.stdcstdc.(module) core.stdc.stdlibD header file for C99.
pubs.opengroup.org/onlinepubs/009695399/basedefs/stdlib.h.html, stdlib.h
Source
core/stdc/stdlib.d
stdlib : (alias) malloc = void* core.stdc.stdlib.malloc(ulong size) nothrow @nogcmalloc;
auto (local variable) char* datadata = cast(char*) void* core.stdc.stdlib.malloc(ulong size) nothrow @nogcmalloc(cast((alias) object.size_t = ulongsize_t) (local variable) const(int) widthwidth * (local variable) const(int) heightheight * 4);
ximg = XCreateImage(dpy, visual, cast(uint) depth, ZPixmap, 0, data,
width, height, 32, 0);
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("step", "name=XCreateImage size=%dx%d bpl=%d bpp=%d rt=0",
(local variable) const(int) widthwidth, (local variable) const(int) heightheight, ximg.bytes_per_line, ximg.bits_per_pixel);
}
scope (exit)
{
if ((local variable) bool usingShmusingShm)
{
XSync(dpy, False); // drain the in-flight put before detaching
XShmDetach(dpy, &shminfo);
}
ximg.f.destroy_image(ximg);
if ((local variable) bool usingShmusingShm)
shmdt(shminfo.shmaddr);
XDestroyWindow(dpy, win);
XCloseDisplay(dpy);
}
// -- 6. Wait for Expose (the server's "draw now" signal), present once,
// and wait for the confirmation event. concept 8: XEvent.
const (local variable) const(_error_) fdfd = XConnectionNumber(dpy);
bool (local variable) bool exposedexposed = false, (local variable) bool presentedpresented = false, (local variable) bool confirmedconfirmed = false;
bool (local variable) bool sawFirstConfiguresawFirstConfigure = false;
while (!(local variable) bool confirmedconfirmed)
{
while (XPending(dpy) > 0) // XPending flushes the output buffer
{
XEvent (local variable) _error_ evev;
XNextEvent(dpy, &ev);
switch (ev.type)
{
case MapNotify:
// No WM: MapNotify (not ConfigureNotify) is the first
// structure event — waiting for ConfigureNotify deadlocks.
if (!sawFirstConfigure)
{
sawFirstConfigure = true;
emitf("first_configure", "kind=MapNotify size=%dx%d", width, height);
}
else
emit("map_notify");
break;
case ConfigureNotify: // only under a WM (reparent/placement)
if (!sawFirstConfigure)
{
sawFirstConfigure = true;
emitf("first_configure", "kind=ConfigureNotify size=%dx%d send_event=%d",
ev.xconfigure.ev.xconfigure.widthwidth, ev.xconfigure.ev.xconfigure.heightheight,
cast(int) ev.xany.send_event);
}
else
emitf("configure_notify", "size=%dx%d send_event=%d",
ev.xconfigure.ev.xconfigure.widthwidth, ev.xconfigure.ev.xconfigure.heightheight,
cast(int) ev.xany.send_event);
break;
case Expose:
emitf("expose", "count=%d area=%dx%d+%d+%d", ev.xexpose.count,
ev.xexpose.ev.xexpose.widthwidth, ev.xexpose.ev.xexpose.heightheight, ev.xexpose.ev.xexpose.xx, ev.xexpose.ev.xexpose.yy);
if (ev.xexpose.count == 0)
exposed = true;
break;
default:
if (usingShm && ev.type == shmCompletionType)
{
// The server finished *reading* the segment. This is the
// strongest confirmation core X11 + MIT-SHM offers; it is
// still not "on glass" — that needs the Present extension.
const _error_ shsh = cast(const XShmCompletionEvent*)&ev;
emitf("first_pixel_presented",
"method=XShmCompletionEvent drawable=0x%lx", sh.drawable);
confirmed = true;
}
break;
}
}
if ((local variable) bool exposedexposed && !(local variable) bool presentedpresented)
{
drawGradient(ximg);
if ((local variable) bool usingShmusingShm)
{
XShmPutImage(dpy, win, gc, ximg, 0, 0, 0, 0,
width, height, True); // send_event=True -> completion event
XFlush(dpy); // push the put before sleeping in poll()
void instrument.emit(scope const(char)* kind) nothrow @nogcEmit an event with no key=value payload.
emit("step name=XShmPutImage rt=0 send_event=1");
}
else
{
XPutImage(dpy, win, gc, ximg, 0, 0, 0, 0, width, height);
void instrument.emit(scope const(char)* kind) nothrow @nogcEmit an event with no key=value payload.
emit("step name=XPutImage rt=0");
const (local variable) const(long) t0t0 = long instrument.nowUs() nothrow @nogcMicroseconds elapsed since initInstrument.
nowUs();
XSync(dpy, False); // no completion contract: round-trip instead
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("step", "name=XSync rt=1 us=%lld", long instrument.nowUs() nothrow @nogcMicroseconds elapsed since initInstrument.
nowUs() - (local variable) const(long) t0t0);
// Proves the server *processed* the put — nothing more.
void instrument.emit(scope const(char)* kind) nothrow @nogcEmit an event with no key=value payload.
emit("first_pixel_presented method=XPutImage_XSync");
(local variable) bool confirmedconfirmed = true;
}
(local variable) bool presentedpresented = true;
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("frame_callback", "t=%lld frame=1 size=%dx%d", long instrument.nowUs() nothrow @nogcMicroseconds elapsed since initInstrument.
nowUs(), (local variable) const(int) widthwidth, (local variable) const(int) heightheight);
}
if (!(local variable) bool confirmedconfirmed)
{
pollfd (local variable) _error_ pfdpfd;
pfd.pfd.fdfd = fd;
pfd.events = POLLIN;
pfd.revents = 0;
poll(&pfd, 1, 1000); // bounded: a silent server can't hang the demo
if (long instrument.nowUs() nothrow @nogcMicroseconds elapsed since initInstrument.
nowUs() > 5_000_000)
{
void instrument.emit(scope const(char)* kind) nothrow @nogcEmit an event with no key=value payload.
emit("auto_exit reason=timeout");
return 1;
}
}
}
// concepts: Display*, Window, Atom, Visual*, GC, XImage*, XEvent = 7;
// MIT-SHM adds the ShmSeg XID and the kernel shm segment = 9.
void instrument.emitf(scope const(char)* kind, scope const(char)* fmt, ...) nothrow @nogcEmit an event with a printf-formatted key=value ... payload.
emitf("summary", "concepts=%d loc=%d init_to_pixel_us=%lld",
(local variable) bool usingShmusingShm ? 9 : 7, (constant) int app.locCount = 359This file's line count — the F01 LOC figure (excludes instrument.d / c.c).
Keep in sync with wc -l app.d.
locCount, long instrument.nowUs() nothrow @nogcMicroseconds elapsed since initInstrument.
nowUs());
void instrument.emit(scope const(char)* kind) nothrow @nogcEmit an event with no key=value payload.
emit("teardown");
return 0;
}