Files
mcde/programs/dttoolbox/dttoolbox.c
T
lotherkandClaude Sonnet 5.5 1ea27d7b8d MCDE dttoolbox: told of the published menu, not polling every 500 ms; the rebuild no longer crashes (t0080)
The menu the desktop publishes (_SGI_MENU_Selected on the window named by the
root property _SGI__MENU_WINDOW) was read on a 500 ms timer, two atom lookups and
two property reads each time.  main now looks at PropertyNotify itself (Xt
routes no event for a foreign window to a widget; dtlaunch's loop does the
same) and selects the menu window's property events before reading the text.

Measured: idle writes to the X socket in 10 s (strace) 20 before, 0 after; the
publisher scenario (2, 3, then 1 entries) is reported at 0.01 s, 3.001 s and
7.001 s.

Two defects of the old code, found by the control run: (1) the third change of
a menu with children died with SIGSEGV in XtDestroyWidget -- the loop walked the
parent's own XmNchildren array while every destroy shortened it; the list is
copied first.  (2) A rebuild deferred because the menu was open recorded the
text as seen and never built it; the text is forgotten now and one 1 s timer
retries, only while that waits.  The deferred path is not exercised by the
harness.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 23:08:18 +00:00

653 lines
17 KiB
C

/*
* dttoolbox.c -- MCDE: the toolchest
*
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* The chest of the IRIX desktop: a window of menus, read from a chestrc file
* (docs/MCDE-PROGRAMS.md, B1-B5). Stage T1: the parser of the useful
* subset, the window, and the dynamic menus over the desktop's rendezvous:
* the root window's _SGI__MENU_WINDOW carries a property _SGI_MENU_<name>
* with the menu text; this program owns _SGI_TOOLCHEST_WINDOW and reads
* _SGI_TOOLCHEST_CONFIG ClientMessages (research/notes/TOOLCHEST_PROTOCOL.md).
*
* Grammar read: "Menu NAME [dynamic] {", entries "LABEL f.menu NAME",
* "LABEL f.exec \"command\"", "LABEL f.checkexec.sh \"command\"",
* "no-label f.separator", "}" and # comments; "sinclude"/"include" are
* skipped (a note goes to stderr), as the reference's extra chests are not
* shipped yet.
*
* C99 and POSIX, Motif and Xlib.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <Xm/Xm.h>
#include <Xm/CascadeB.h>
#include <Xm/PushB.h>
#include <Xm/RowColumn.h>
#include <Xm/Separator.h>
#define MAXMENU 64
#define MAXENTRY 64
enum { E_EXEC, E_MENU, E_SEP };
typedef struct {
char label[128];
int type;
char value[512]; /* command or menu name */
} Entry;
typedef struct {
char name[64];
int dynamic;
int n;
Entry e[MAXENTRY];
} Menu;
static Menu menus[MAXMENU];
static int nmenus;
static Display *dpy;
static Widget top, chest, selectedSub;
static Atom aMenuWindow, aChestWindow, aConfig, aDesk, aSelected;
static Window watchedMenu; /* the menu window whose property events we get */
static int dynamicOn = 1;
static char chestFile[512];
static char lastSelected[4096];
static Menu *
FindMenu(const char *name)
{
int i;
for (i = 0; i < nmenus; i++)
if (strcmp(menus[i].name, name) == 0)
return &menus[i];
return NULL;
}
static Menu *
NewMenu(const char *name)
{
static Menu spill; /* past MAXMENU: filled, never shown */
Menu *m;
if ((m = FindMenu(name)) != NULL)
return m;
if (nmenus >= MAXMENU) {
memset(&spill, 0, sizeof spill);
return &spill;
}
m = &menus[nmenus++];
memset(m, 0, sizeof *m);
snprintf(m->name, sizeof m->name, "%s", name);
return m;
}
static void
Trim(char *p)
{
size_t n = strlen(p);
while (n > 0 && (p[n - 1] == '\n' || p[n - 1] == '\r' ||
p[n - 1] == ' ' || p[n - 1] == '\t'))
p[--n] = '\0';
}
/* the label of an entry: quoted, or the first word */
static char *
TakeLabel(char **pp, char *out, size_t size)
{
char *p = *pp;
while (*p == ' ' || *p == '\t')
p++;
if (*p == '"') {
char *q = ++p;
while (*q != '\0' && *q != '"')
q++;
snprintf(out, size, "%.*s", (int) (q - p), p);
if (*q == '"')
q++;
*pp = q;
} else {
char *q = p;
while (*q != '\0' && *q != ' ' && *q != '\t')
q++;
snprintf(out, size, "%.*s", (int) (q - p), p);
*pp = q;
}
return out;
}
/* the quoted command after the function word */
static void
TakeCommand(char **pp, char *out, size_t size)
{
char *p = *pp, *q;
if ((q = strchr(p, '"')) == NULL) {
out[0] = '\0';
return;
}
q++;
p = q;
while (*q != '\0' && *q != '"')
q++;
snprintf(out, size, "%.*s", (int) (q - p), p);
}
static void
AddEntry(Menu *m, const char *label, int type, const char *value)
{
Entry *e;
if (m->n >= MAXENTRY)
return;
e = &m->e[m->n++];
snprintf(e->label, sizeof e->label, "%s", label);
e->type = type;
snprintf(e->value, sizeof e->value, "%s", value ? value : "");
}
/* one line of a menu body, for the chestrc and for a published menu */
static void
ParseEntry(Menu *m, char *line)
{
char label[128] = "", *p = line;
Trim(p);
if (*p == '\0' || *p == '#' || *p == '{' || *p == '}')
return;
if (strncmp(p, "no-label", 8) == 0) {
AddEntry(m, "", E_SEP, NULL);
return;
}
if (strncmp(p, "sinclude", 8) == 0 || strncmp(p, "include", 7) == 0) {
fprintf(stderr, "dttoolbox: %s is not read yet: %s\n",
strncmp(p, "sinclude", 8) == 0 ? "sinclude" : "include", p);
return;
}
TakeLabel(&p, label, sizeof label);
if (strstr(p, "f.menu") != NULL) {
char *q = strstr(p, "f.menu") + 6, name[64];
int n = 0;
while (*q == ' ' || *q == '\t')
q++;
while (*q != '\0' && *q != ' ' && *q != '\t' && n < 63)
name[n++] = *q++;
name[n] = '\0';
AddEntry(m, label, E_MENU, name);
} else if (strstr(p, "f.exec") != NULL ||
strstr(p, "f.checkexec") != NULL) {
char cmd[512];
TakeCommand(&p, cmd, sizeof cmd);
AddEntry(m, label, E_EXEC, cmd);
} else if (*p == '\0') {
AddEntry(m, label, E_EXEC, "");
}
}
static int
ReadChest(const char *path)
{
FILE *f;
char line[1024];
Menu *cur = NULL;
int inblock = 0;
if ((f = fopen(path, "r")) == NULL)
return -1;
while (fgets(line, sizeof line, f) != NULL) {
char *p = line;
while (*p == ' ' || *p == '\t')
p++;
Trim(p);
if (*p == '\0' || *p == '#')
continue;
if (strncmp(p, "Menu ", 5) == 0) {
char name[64], *q = p + 5;
int n = 0;
while (*q != '\0' && *q != ' ' && *q != '\t' && n < 63)
name[n++] = *q++;
name[n] = '\0';
cur = NewMenu(name);
while (*q == ' ' || *q == '\t')
q++;
if (strncmp(q, "dynamic", 7) == 0)
cur->dynamic = 1;
inblock = 0;
continue;
}
if (*p == '{') {
inblock = 1;
continue;
}
if (*p == '}') {
inblock = 0;
cur = NULL;
continue;
}
if (inblock && cur != NULL)
ParseEntry(cur, p);
}
fclose(f);
return 0;
}
/* ------------------------------------------------------------------ build */
static void RunCommand(char *cmd);
static void
EntryCallback(Widget w, XtPointer data, XtPointer call)
{
(void) w; (void) call;
RunCommand((char *) data);
}
static void BuildMenuWidget(Widget parent, const char *name, int depth);
static void
AddWidgets(Widget shell, Menu *m, int depth)
{
int i;
for (i = 0; i < m->n; i++) {
Entry *e = &m->e[i];
Widget b;
if (e->type == E_SEP) {
XtVaCreateManagedWidget("sep", xmSeparatorWidgetClass,
shell, NULL);
continue;
}
if (e->type == E_MENU) {
Widget sub = XmCreatePulldownMenu(shell,
(char *) e->label, NULL, 0);
XtVaCreateManagedWidget(e->label,
xmCascadeButtonWidgetClass, shell,
XmNsubMenuId, sub, NULL);
BuildMenuWidget(sub, e->value, depth + 1);
continue;
}
b = XtVaCreateManagedWidget(e->label, xmPushButtonWidgetClass,
shell, NULL);
XtAddCallback(b, XmNactivateCallback, EntryCallback, e->value);
}
}
static Menu *published;
static void
BuildMenuWidget(Widget shell, const char *name, int depth)
{
Menu *m;
if (depth > 6)
return;
m = FindMenu(name);
if (m == NULL) {
/* a dynamic menu that nothing has published yet */
if (published == NULL || strcmp(published->name, name) != 0) {
published = NewMenu(name);
published->dynamic = 1;
}
m = published;
}
AddWidgets(shell, m, depth);
}
/* the children are not waited for: SIGCHLD is ignored from the start
* (main), so none stays a zombie -- set after the first fork it missed
* the first child */
static void
RunCommand(char *cmd)
{
if (cmd == NULL || *cmd == '\0')
return;
fprintf(stderr, "dttoolbox: %s\n", cmd);
if (fork() == 0) {
setsid();
execl("/bin/sh", "sh", "-c", cmd, (char *) NULL);
_exit(127);
}
}
/* ------------------------------------------------ dynamic menus (events) */
/*
* The desktop publishes a menu as a string property on the menu window:
* _SGI_MENU_Selected, with chestrc lines. It was read on a timer, every
* 500 ms for good: two atom lookups and two property reads each time, because
* a property event for a foreign window is not routed through Xt. Now the
* main loop (main) looks at PropertyNotify itself, as dtlaunch's does, and calls
* this when the desktop names another menu window (root property) or changes
* the text (property of the menu window, whose events it asks for here): idle,
* the toolbox sends nothing (tasksd t0080). Only the Selected menu is
* published today; the others are their chestrc.
*/
static void RetryUpdate(XtPointer data, XtIntervalId *id);
static void
UpdateSelected(void)
{
Window root = DefaultRootWindow(dpy), menuWin = None;
Atom aWin = aMenuWindow;
Atom aSel = aSelected;
Atom type;
int format;
unsigned long n, after;
unsigned char *data2 = NULL;
if (!dynamicOn || selectedSub == NULL)
return;
if (XGetWindowProperty(dpy, root, aWin, 0, 1, False,
AnyPropertyType, &type, &format, &n, &after, &data2) == Success &&
data2 != NULL) {
if (format == 32 && n >= 1 &&
(type == XA_WINDOW || type == XA_CARDINAL))
menuWin = *(Window *) data2;
XFree(data2);
data2 = NULL;
}
/* ask for its property events BEFORE reading the text: a change between
* the two would be lost */
if (menuWin != None && menuWin != watchedMenu) {
XSelectInput(dpy, menuWin, PropertyChangeMask);
watchedMenu = menuWin;
}
if (getenv("DTTB_DEBUG") != NULL)
fprintf(stderr, "dttoolbox: update menuWin=%lx sub=%p\n",
(unsigned long) menuWin, (void *) selectedSub);
if (menuWin != None &&
XGetWindowProperty(dpy, menuWin, aSel, 0, 4096, False,
AnyPropertyType, &type, &format, &n, &after, &data2) == Success &&
data2 != NULL && n > 0) {
char *text = (char *) data2;
if (strcmp(text, lastSelected) != 0) {
Menu *m = FindMenu("Selected");
char *line, *save = NULL;
Widget *kids = NULL;
Cardinal nk = 0;
if (m == NULL)
m = NewMenu("Selected");
m->n = 0;
/* kept before strtok_r cuts the text into lines: kept
* after, it held the first line only and every poll
* rebuilt the menu */
snprintf(lastSelected, sizeof lastSelected, "%s", text);
for (line = strtok_r(text, "\n", &save); line != NULL;
line = strtok_r(NULL, "\n", &save))
ParseEntry(m, line);
if (XtIsManaged(selectedSub) &&
XtParent(selectedSub) != NULL &&
XtIsManaged(XtParent(selectedSub))) {
fprintf(stderr,
"dttoolbox: Selected is open, deferred\n");
/* the text is forgotten, not kept as seen: no
* event would come to build it once the menu is
* closed. One timer, only while this waits. */
lastSelected[0] = '\0';
XtAppAddTimeOut(XtWidgetToApplicationContext(top),
1000, RetryUpdate, NULL);
} else {
Cardinal i;
Widget *copy;
if (XmIsRowColumn(selectedSub))
XtUnmanageChild(selectedSub);
kids = NULL;
nk = 0;
XtVaGetValues(selectedSub, XmNchildren, &kids,
XmNnumChildren, &nk, NULL);
/* a copy of the list: XtDestroyWidget takes a child
* out of the parent's own array at once (no event is
* being dispatched here), so walking that array
* skipped and then freed widgets -- the third change
* of a menu with children crashed dttoolbox
* (measured: SIGSEGV in XtDestroyWidget) */
if (nk > 0 && (copy = (Widget *)malloc(nk *
sizeof *copy)) != NULL) {
memcpy(copy, kids, nk * sizeof *copy);
for (i = 0; i < nk; i++)
XtDestroyWidget(copy[i]);
free(copy);
}
AddWidgets(selectedSub, m, 1);
fprintf(stderr,
"dttoolbox: menu Selected published (%d entries)\n",
m->n);
}
}
XFree(data2);
}
}
static void
RetryUpdate(XtPointer data, XtIntervalId *id)
{
(void) data; (void) id;
UpdateSelected();
}
/* ------------------------------------------------------------------- main */
static Widget
BuildChest(void)
{
Widget row;
Menu *root = FindMenu("ToolChest");
int i;
row = XtVaCreateManagedWidget("chest", xmRowColumnWidgetClass, top,
XmNorientation, XmVERTICAL, XmNpacking, XmPACK_COLUMN,
XmNnumColumns, 1, XmNmarginWidth, 4, XmNmarginHeight, 4,
XmNspacing, 2, NULL);
if (root != NULL) {
for (i = 0; i < root->n; i++) {
Entry *e = &root->e[i];
if (e->type == E_SEP) {
XtVaCreateManagedWidget("sep", xmSeparatorWidgetClass,
row, NULL);
continue;
}
if (e->type == E_MENU) {
Widget sub = XmCreatePulldownMenu(row, e->label,
NULL, 0);
XtVaCreateManagedWidget(e->label,
xmCascadeButtonWidgetClass, row,
XmNsubMenuId, sub, NULL);
if (strcmp(e->value, "Selected") == 0)
selectedSub = sub;
BuildMenuWidget(sub, e->value, 1);
} else {
Widget b = XtVaCreateManagedWidget(e->label,
xmPushButtonWidgetClass, row, NULL);
XtAddCallback(b, XmNactivateCallback,
EntryCallback, e->value);
}
}
} else {
Widget b = XtVaCreateManagedWidget("No ToolChest menu",
xmPushButtonWidgetClass, row, NULL);
(void) b;
}
return row;
}
/* dynamic menus: the root property _SGI_MENU_<name> holds chestrc lines */
static void
ReadPublished(Window root, const char *name)
{
Menu *m;
Atom atom;
Atom type;
int format;
unsigned long n, after;
unsigned char *data = NULL;
Window menuWin = None;
m = FindMenu(name);
if (m == NULL) {
m = NewMenu(name);
m->dynamic = 1;
}
/* the text lives on the _SGI__MENU_WINDOW, else on the root */
atom = XInternAtom(dpy, "_SGI__MENU_WINDOW", False);
if (XGetWindowProperty(dpy, root, atom, 0, 1, False, XA_WINDOW,
&type, &format, &n, &after, &data) == Success && data != NULL) {
menuWin = *(Window *) data;
XFree(data);
data = NULL;
}
if (menuWin == None)
return;
snprintf(m->name, sizeof m->name, "%s", name);
(void) atom;
{
char prop[64];
snprintf(prop, sizeof prop, "_SGI_MENU_%s", name);
atom = XInternAtom(dpy, prop, False);
}
if (XGetWindowProperty(dpy, menuWin, atom, 0, 8192, False, XA_STRING,
&type, &format, &n, &after, &data) != Success || data == NULL)
return;
m->n = 0;
{
char *text = (char *) data, *line, *save = NULL;
for (line = strtok_r(text, "\n", &save); line != NULL;
line = strtok_r(NULL, "\n", &save))
ParseEntry(m, line);
}
XFree(data);
fprintf(stderr, "dttoolbox: menu %s published (%d entries)\n",
name, m->n);
}
static void
RootEvent(Widget w, XtPointer data, XEvent *ev, Boolean *keep)
{
(void) w; (void) data; (void) keep;
if (ev->type == PropertyNotify) {
char *name = XGetAtomName(dpy, ev->xproperty.atom);
if (name != NULL &&
strncmp(name, "_SGI_MENU_", 10) == 0)
ReadPublished(ev->xproperty.window,
name + 10);
if (name != NULL)
XFree(name);
}
}
static void
ChestEvent(Widget w, XtPointer data, XEvent *ev, Boolean *keep)
{
(void) w; (void) data; (void) keep;
if (ev->type == ClientMessage &&
ev->xclient.message_type == aConfig) {
dynamicOn = ev->xclient.data.b[0] != 0;
fprintf(stderr, "dttoolbox: dynamic menus %s\n",
dynamicOn ? "on" : "off");
}
}
int
main(int argc, char **argv)
{
XtAppContext app;
Window root;
const char *home;
signal(SIGCHLD, SIG_IGN);
top = XtVaAppInitialize(&app, "Dttoolbox", NULL, 0, &argc, argv, NULL,
NULL);
dpy = XtDisplay(top);
root = DefaultRootWindow(dpy);
if ((home = getenv("DTTB_CHESTRC")) != NULL) {
snprintf(chestFile, sizeof chestFile, "%s", home);
} else if ((home = getenv("HOME")) != NULL) {
char p[512];
snprintf(p, sizeof p, "%s/.chestrc", home);
if (access(p, R_OK) == 0)
snprintf(chestFile, sizeof chestFile, "%s", p);
}
if (chestFile[0] == '\0') {
snprintf(chestFile, sizeof chestFile, "%s",
CDE_INSTALLATION_TOP "/share/toolchest/system.chestrc");
if (access(chestFile, R_OK) != 0)
snprintf(chestFile, sizeof chestFile, "system.chestrc");
}
if (ReadChest(chestFile) != 0)
fprintf(stderr, "dttoolbox: cannot read %s\n", chestFile);
aMenuWindow = XInternAtom(dpy, "_SGI__MENU_WINDOW", False);
aChestWindow = XInternAtom(dpy, "_SGI_TOOLCHEST_WINDOW", False);
aConfig = XInternAtom(dpy, "_SGI_TOOLCHEST_CONFIG", False);
aDesk = XInternAtom(dpy, "_SGI_DESKS_DESKTOP_WINDOW", False);
aSelected = XInternAtom(dpy, "_SGI_MENU_Selected", False);
chest = BuildChest();
XtVaSetValues(top, XmNtitle, "ToolChest", NULL);
XtRealizeWidget(top);
XSetSelectionOwner(dpy, aChestWindow, XtWindow(top), CurrentTime);
XSelectInput(dpy, root, PropertyChangeMask);
XtAddEventHandler(top, PropertyChangeMask, False, RootEvent, NULL);
XtAddEventHandler(top, NoEventMask, True, ChestEvent, NULL);
fprintf(stderr, "dttoolbox: %d menus from %s\n", nmenus, chestFile);
UpdateSelected(); /* what is published already */
/* XtAppMainLoop with a look at the events Xt has no widget for: the
* desktop names another menu window (a property of the root), or changes
* the text of the one it named (a property of that window) */
for (;;) {
XEvent ev;
XtAppNextEvent(app, &ev);
if (ev.type == PropertyNotify &&
((ev.xproperty.window == root &&
ev.xproperty.atom == aMenuWindow) ||
(ev.xproperty.window == watchedMenu &&
ev.xproperty.atom == aSelected))) {
UpdateSelected();
continue;
}
XtDispatchEvent(&ev);
/* dynamic menus switched on: what was published meanwhile */
if (ev.type == ClientMessage &&
ev.xclient.message_type == aConfig)
UpdateSelected();
}
return 0;
}