Files
mcde/programs/dtlaunch/dtlaunch.c
T
lotherk cec3eb49e3 MCDE dtsystemsettings: Parental Controls, enforced by the launcher (t0142)
New programs/dtsystemsettings/parental.c: the accounts on the left and, for
the chosen one, three pages.  Programs: "All programs" or "Only the
applications selected below" with a list of the desktop's programs.  Time
Limits: weekday and weekend hours ("09:00-19:00" or "any").  Log: the
programs that were started, from ~/.dt/parental.log.  The values are kept in
~/.dt/parental.conf under the login's name ("lotherk.allow=dtpad,dtfile"),
English keys, the file the launcher reads.

The enforcement is in dtlaunch, the place where a program is started: the
list shows only the allowed names, a disallowed program or a start outside
the hours is refused with a sentence in the window ("Outside the allowed
hours (Parental Controls)."), and every allowed start is appended to
~/.dt/parental.log.  A refusal keeps the launcher open.

Measured under Xvfb with xdotool:
  - with "lotherk.only=1, allow=dtpad" the launcher offers dtpad only;
  - with hours 03:00-03:01 (now 13:4x) Return on dtpad is refused, the
    window stays and says why, and ~/.dt/parental.log stays absent;
  - with "any" the same Return starts dtpad and the log gets
    "2026-11-14 13:44 dtpad";
  - the pane shows the accounts, the three pages and the applied file
    (docs/screenshots/leopard/System-Preferences-Parental-Controls-mcde.png,
    ...-Time-Limits-mcde.png);
  - make programs/dtsystemsettings, programs/dtlaunch exit=0.

Not done (follow-up): system-wide enforcement -- taking the execute
permission away from programs outside the list needs root, ending a session
when the hours are over belongs to dtsession, and a child's own file needs
the administrator.  A toggle or radio set before its page is laid out keeps
its first painted state in this pane (measured); the file is right.
2026-11-14 13:53:51 +00:00

834 lines
22 KiB
C

/*
* dtlaunch.c -- MCDE: the launcher
*
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* One key (default Cmd+space -- the key left of the space bar and the space
* bar, as on the desktops of that kind; resource Dtlaunch*hotkey, names Cmd,
* Option, Ctrl, Shift) opens a field and a list. What is typed is matched against the programs in $PATH, the snippets
* of ~/.dt/snippets, the history of the clipboard, and read as a calculation.
* Return starts the program, or puts the snippet, the clipboard entry or the
* result on the clipboard (CLIPBOARD and PRIMARY), ready to paste; Escape
* closes. Up and Down move in the list.
*
* The clipboard history: every second the owner of CLIPBOARD is asked for its
* text (Xt selections, ICCCM); a new text goes to the top, at most HISTORY
* entries, kept in memory only -- passwords pass through the clipboard.
*
* One launcher per display: the first one owns the selection _MCDE_DTLAUNCH;
* `dtlaunch -show' asks that one to open and exits; `dtlaunch -quit' asks it
* to exit and waits until it has (System Settings changes the hot key).
* -nograb: no hot key (for tests); -show: open at once.
*
* C99, POSIX, Xt and Motif only (ext/src/mcde/AGENTS.md); the parts without X
* are in model.c.
*/
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Shell.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>
#include <Xm/Xm.h>
#include <Xm/Form.h>
#include <Xm/Frame.h>
#include <Xm/List.h>
#include <Xm/TextF.h>
#include <Xm/Label.h>
#include "model.h"
#define HISTORY 50
#define MAXITEMS 40
#define MAXCLIP (64 * 1024)
#define POLL_MS 1000
typedef enum { K_APP, K_SNIPPET, K_CLIP, K_CALC } Kind;
typedef struct {
Kind kind;
int score;
char *label; /* what the list shows */
char *value; /* program name, or the text for the clipboard */
} Item;
static struct {
XtAppContext app;
Widget top, shell, field, list, hint;
Display *dpy;
Window root;
Atom a_clipboard, a_utf8, a_targets, a_text, a_self, a_quit,
a_show;
KeyCode hot_code;
unsigned int hot_mods;
char **programs;
size_t nprograms;
MxSnippet *snippets;
size_t nsnippets;
char *history[HISTORY];
size_t nhistory;
Item items[MAXITEMS];
size_t nitems;
char *owned; /* the text we offer as the clipboard */
Boolean visible;
} L;
typedef struct {
String hotkey;
} Resources;
static XtResource resources[] = {
{ "hotkey", "Hotkey", XtRString, sizeof(String),
XtOffsetOf(Resources, hotkey), XtRString, "Cmd+space" },
};
static XrmOptionDescRec options[] = {
{ "-show", "*show", XrmoptionNoArg, "True" },
{ "-quit", "*quit", XrmoptionNoArg, "True" },
{ "-nograb", "*nograb", XrmoptionNoArg, "True" },
};
static String fallback[] = {
"Dtlaunch*field.columns: 48",
"Dtlaunch*list.visibleItemCount: 10",
"Dtlaunch*hint.labelString: Type to find a program, a snippet, the clipboard, or =1+2",
NULL
};
static char *
xstrdup(const char *s)
{
char *r = strdup(s);
if (r == NULL) {
fputs("dtlaunch: out of memory\n", stderr);
exit(1);
}
return r;
}
/* a label for the list: one line, at most 70 characters */
static char *
oneline(const char *prefix, const char *text)
{
char buf[96];
size_t i, j;
(void)snprintf(buf, sizeof buf, "%s", prefix);
j = strlen(buf);
for (i = 0; text[i] != '\0' && j < 70; i++)
buf[j++] = (text[i] == '\n' || text[i] == '\t') ? ' ' : text[i];
buf[j] = '\0';
if (text[i] != '\0' && j + 3 < sizeof buf)
(void)strcat(buf, "...");
return xstrdup(buf);
}
/* ---- the list ---------------------------------------------------------- */
/* the Parental Controls of this login (the block below run()) */
static int ParentalAllowed(const char *program);
static int parental_in_hours(void);
static void
clear_items(void)
{
size_t i;
for (i = 0; i < L.nitems; i++) {
free(L.items[i].label);
free(L.items[i].value);
}
L.nitems = 0;
}
static void
add_item(Kind kind, int score, char *label, const char *value)
{
size_t i;
if (score <= 0) {
free(label);
return;
}
if (L.nitems == MAXITEMS) {
/* full: replace the weakest, if this one is better */
size_t w = 0;
for (i = 1; i < L.nitems; i++)
if (L.items[i].score < L.items[w].score)
w = i;
if (L.items[w].score >= score) {
free(label);
return;
}
free(L.items[w].label);
free(L.items[w].value);
L.items[w] = L.items[--L.nitems];
}
L.items[L.nitems].kind = kind;
L.items[L.nitems].score = score;
L.items[L.nitems].label = label;
L.items[L.nitems].value = xstrdup(value);
L.nitems++;
}
static int
by_score(const void *a, const void *b)
{
const Item *x = a, *y = b;
if (x->score != y->score)
return y->score - x->score;
return strcmp(x->label, y->label);
}
static void
refresh(void)
{
char *q = XmTextFieldGetString(L.field);
XmString *xs;
double v;
char num[64], buf[96];
size_t i;
clear_items();
if (mx_calc(q, &v) == 0) {
mx_calc_format(v, num, sizeof num);
(void)snprintf(buf, sizeof buf, "= %s", num);
add_item(K_CALC, 1000, xstrdup(buf), num);
}
if (q[0] == '\0') {
/* nothing typed: the clipboard history, newest first */
for (i = 0; i < L.nhistory; i++)
add_item(K_CLIP, 500 - (int)i,
oneline("[clip] ", L.history[i]), L.history[i]);
} else {
for (i = 0; i < L.nsnippets; i++) {
int s = mx_match(q, L.snippets[i].key);
char pre[64];
if (s == 0)
s = mx_match(q, L.snippets[i].text) / 2;
(void)snprintf(pre, sizeof pre, "[snippet] %s: ",
L.snippets[i].key);
add_item(K_SNIPPET, s ? s + 5 : 0,
oneline(pre, L.snippets[i].text),
L.snippets[i].text);
}
for (i = 0; i < L.nhistory; i++)
add_item(K_CLIP, mx_match(q, L.history[i]) / 2,
oneline("[clip] ", L.history[i]), L.history[i]);
for (i = 0; i < L.nprograms; i++)
if (ParentalAllowed(L.programs[i]))
add_item(K_APP, mx_match(q, L.programs[i]),
xstrdup(L.programs[i]),
L.programs[i]);
}
XtFree(q);
qsort(L.items, L.nitems, sizeof L.items[0], by_score);
xs = (XmString *)XtMalloc((Cardinal)((L.nitems + 1) * sizeof *xs));
for (i = 0; i < L.nitems; i++)
xs[i] = XmStringCreateLocalized(L.items[i].label);
XtVaSetValues(L.list, XmNitems, xs, XmNitemCount, (int)L.nitems, NULL);
for (i = 0; i < L.nitems; i++)
XmStringFree(xs[i]);
XtFree((char *)xs);
if (L.nitems > 0)
XmListSelectPos(L.list, 1, False);
}
/* ---- the clipboard: offering text, and reading the history ------------- */
static Boolean
convert(Widget w, Atom *selection, Atom *target, Atom *type,
XtPointer *value, unsigned long *length, int *format)
{
(void)w; (void)selection;
if (L.owned == NULL)
return False;
if (*target == L.a_targets) {
Atom *t = (Atom *)XtMalloc(4 * sizeof(Atom));
t[0] = L.a_targets;
t[1] = L.a_utf8;
t[2] = XA_STRING;
t[3] = L.a_text;
*type = XA_ATOM;
*value = (XtPointer)t;
*length = 4;
*format = 32;
return True;
}
if (*target == L.a_utf8 || *target == XA_STRING ||
*target == L.a_text) {
*type = *target == L.a_text ? L.a_utf8 : *target;
*value = XtNewString(L.owned);
*length = strlen(L.owned);
*format = 8;
return True;
}
return False;
}
static void
offer(const char *text)
{
Time t = XtLastTimestampProcessed(L.dpy);
free(L.owned);
L.owned = xstrdup(text);
(void)XtOwnSelection(L.top, L.a_clipboard, t, convert, NULL, NULL);
(void)XtOwnSelection(L.top, XA_PRIMARY, t, convert, NULL, NULL);
}
static void
remember(const char *text)
{
size_t i;
if (text[0] == '\0' || strlen(text) > MAXCLIP)
return;
for (i = 0; i < L.nhistory; i++)
if (strcmp(L.history[i], text) == 0)
break;
if (i == 0 && L.nhistory > 0)
return; /* already the newest */
if (i < L.nhistory) { /* move it to the top */
char *s = L.history[i];
memmove(&L.history[1], &L.history[0], i * sizeof(char *));
L.history[0] = s;
return;
}
if (L.nhistory == HISTORY)
free(L.history[--L.nhistory]);
memmove(&L.history[1], &L.history[0], L.nhistory * sizeof(char *));
L.history[0] = xstrdup(text);
L.nhistory++;
}
static void
got_clipboard(Widget w, XtPointer client, Atom *selection, Atom *type,
XtPointer value, unsigned long *length, int *format)
{
(void)w; (void)client; (void)selection;
if (value != NULL && *format == 8 &&
(*type == L.a_utf8 || *type == XA_STRING)) {
char *s = XtMalloc((Cardinal)(*length + 1));
memcpy(s, value, *length);
s[*length] = '\0';
remember(s);
XtFree(s);
}
XtFree((char *)value);
}
static void
poll_clipboard(XtPointer client, XtIntervalId *id)
{
Window owner = XGetSelectionOwner(L.dpy, L.a_clipboard);
(void)client; (void)id;
if (owner != None && owner != XtWindow(L.top))
XtGetSelectionValue(L.top, L.a_clipboard, L.a_utf8,
got_clipboard, NULL, XtLastTimestampProcessed(L.dpy));
(void)XtAppAddTimeOut(L.app, POLL_MS, poll_clipboard, NULL);
}
/* ---- showing, hiding, doing -------------------------------------------- */
static void
load_sources(void)
{
const char *home = getenv("HOME");
char path[1024];
mx_strv_free(L.programs, L.nprograms);
(void)mx_path_programs(getenv("PATH"), &L.programs, &L.nprograms);
mx_snippets_free(L.snippets, L.nsnippets);
(void)snprintf(path, sizeof path, "%s/.dt/snippets",
home != NULL ? home : "");
if (mx_snippets_load(path, &L.snippets, &L.nsnippets) != 0) {
L.snippets = NULL;
L.nsnippets = 0;
}
}
static void
show(void)
{
Dimension w, h;
Screen *scr = XtScreen(L.top);
load_sources(); /* PATH and snippets may have changed */
XmTextFieldSetString(L.field, "");
refresh();
if (!XtIsRealized(L.shell))
XtRealizeWidget(L.shell);
XtVaGetValues(L.shell, XmNwidth, &w, XmNheight, &h, NULL);
XtVaSetValues(L.shell,
XmNx, (Position)((WidthOfScreen(scr) - w) / 2),
XmNy, (Position)(HeightOfScreen(scr) / 4), NULL);
XtPopup(L.shell, XtGrabNone);
XRaiseWindow(L.dpy, XtWindow(L.shell));
/* override-redirect: no window manager gives it the focus */
XSetInputFocus(L.dpy, XtWindow(L.shell), RevertToParent, CurrentTime);
XmProcessTraversal(L.field, XmTRAVERSE_CURRENT);
L.visible = True;
}
static void
hide(void)
{
if (L.visible)
XtPopdown(L.shell);
L.visible = False;
}
/* ---- parental controls (~/.dt/parental.conf, written by the Parental
* Controls pane): "LOGIN.only=1", "LOGIN.allow=a,b,c", "LOGIN.day=HH:MM-HH:MM",
* "LOGIN.weekend=..." -- the launcher is where a program is started, so it
* is where the list and the hours are enforced; a system-wide enforcement
* (exec permission, session logout) is the follow-up in the pane ------- */
static int parLoaded;
static int parOnly;
static char parAllow[1024];
static char parDay[32];
static char parWeekend[32];
static void
parental_load(void)
{
char path[1024], line[1024], prefix[96];
const char *home = getenv("HOME");
struct passwd *pw = getpwuid(geteuid());
FILE *f;
if (parLoaded)
return;
parLoaded = 1;
if (home == NULL || pw == NULL)
return;
(void)snprintf(prefix, sizeof prefix, "%s.", pw->pw_name);
(void)snprintf(path, sizeof path, "%s/.dt/parental.conf", home);
if ((f = fopen(path, "r")) == NULL)
return;
while (fgets(line, sizeof line, f) != NULL) {
char *eq, *v;
size_t pl = strlen(prefix);
line[strcspn(line, "\r\n")] = '\0';
if (strncmp(line, prefix, pl) != 0 ||
(eq = strchr(line, '=')) == NULL)
continue;
*eq = '\0';
v = eq + 1;
if (strcmp(line + pl, "only") == 0)
parOnly = atoi(v) != 0;
else if (strcmp(line + pl, "allow") == 0)
(void)snprintf(parAllow, sizeof parAllow, "%s", v);
else if (strcmp(line + pl, "day") == 0)
(void)snprintf(parDay, sizeof parDay, "%s", v);
else if (strcmp(line + pl, "weekend") == 0)
(void)snprintf(parWeekend, sizeof parWeekend, "%s", v);
}
fclose(f);
}
/* the name in the allow list ("dtpad,dtfile" as the pane writes it) */
static int
ParentalAllowed(const char *program)
{
char list[1024], *tok, *save = NULL;
const char *base = strrchr(program, '/');
parental_load();
if (!parOnly)
return 1;
base = base != NULL ? base + 1 : program;
(void)snprintf(list, sizeof list, "%s", parAllow);
for (tok = strtok_r(list, ", ", &save); tok != NULL;
tok = strtok_r(NULL, ", ", &save))
if (strcmp(tok, base) == 0)
return 1;
return 0;
}
/* "HH:MM-HH:MM"; 1 while now is inside it */
static int
parental_in_hours(void)
{
const char *spec;
time_t now = time(NULL);
struct tm tm;
int h1, m1, h2, m2, cur;
parental_load();
spec = (tm.tm_wday == 0 || tm.tm_wday == 6) ? parWeekend : parDay;
if (parWeekend[0] == '\0')
spec = parDay;
if (spec[0] == '\0' || strcmp(spec, "any") == 0)
return 1; /* no limit set */
(void)localtime_r(&now, &tm);
if (sscanf(spec, "%d:%d-%d:%d", &h1, &m1, &h2, &m2) != 4)
return 1;
cur = tm.tm_hour * 60 + tm.tm_min;
h1 = h1 * 60 + m1;
h2 = h2 * 60 + m2;
if (h1 <= h2)
return cur >= h1 && cur <= h2;
return cur >= h1 || cur <= h2; /* over midnight */
}
/* one line per program started, for the pane's Log tab */
static void
parental_log(const char *program)
{
char path[1024];
const char *home = getenv("HOME");
FILE *f;
time_t now = time(NULL);
struct tm tm;
if (home == NULL)
return;
(void)snprintf(path, sizeof path, "%s/.dt/parental.log", home);
if ((f = fopen(path, "a")) == NULL)
return;
(void)localtime_r(&now, &tm);
fprintf(f, "%04d-%02d-%02d %02d:%02d %s\n", tm.tm_year + 1900,
tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, program);
fclose(f);
}
static void
hint_text(const char *text)
{
XmString s = XmStringCreateLocalized((char *) text);
XtVaSetValues(L.hint, XmNlabelString, s, NULL);
XmStringFree(s);
}
/* 1 when the program was started, 0 when Parental Controls refused it (the
* window stays open and says why) */
static int
run(const char *program)
{
pid_t pid;
if (!parental_in_hours()) {
hint_text("Outside the allowed hours (Parental Controls).");
return 0;
}
if (!ParentalAllowed(program)) {
hint_text("This program is not allowed (Parental Controls).");
return 0;
}
parental_log(program);
pid = fork();
if (pid == 0) {
/* a session of its own, so the program outlives the launcher */
(void)setsid();
execlp(program, program, (char *)NULL);
_exit(127);
}
return 1;
}
static void
choose(int pos)
{
Item *it;
if (pos < 1 || (size_t)pos > L.nitems)
return;
it = &L.items[pos - 1];
if (it->kind == K_APP) {
if (!run(it->value))
return; /* refused: the hint says why */
} else
offer(it->value);
hide();
}
static int
selected_pos(void)
{
int *pos, n, p = 1;
if (XmListGetSelectedPos(L.list, &pos, &n)) {
p = pos[0];
XtFree((char *)pos);
}
return p;
}
static void
field_changed(Widget w, XtPointer client, XtPointer call)
{
(void)w; (void)client; (void)call;
refresh();
}
static void
field_activate(Widget w, XtPointer client, XtPointer call)
{
(void)w; (void)client; (void)call;
choose(selected_pos());
}
static void
list_activate(Widget w, XtPointer client, XtPointer call)
{
XmListCallbackStruct *cbs = (XmListCallbackStruct *)call;
(void)w; (void)client;
choose(cbs->item_position);
}
/* Up, Down and Escape in the field */
static void
field_key(Widget w, XtPointer client, XEvent *ev, Boolean *cont)
{
KeySym ks = XLookupKeysym(&ev->xkey, 0);
int p = selected_pos();
(void)w; (void)client;
if (ks == XK_Escape) {
hide();
*cont = False;
} else if (ks == XK_Down && (size_t)p < L.nitems) {
XmListSelectPos(L.list, p + 1, False);
XmListSetBottomPos(L.list, p + 1 > 10 ? p + 1 : 10);
*cont = False;
} else if (ks == XK_Up && p > 1) {
XmListSelectPos(L.list, p - 1, False);
*cont = False;
}
}
/* ---- the hot key ------------------------------------------------------- */
static int
parse_hotkey(const char *spec)
{
char buf[128], *tok, *save = NULL;
KeySym ks = NoSymbol;
L.hot_mods = 0;
(void)snprintf(buf, sizeof buf, "%s", spec);
for (tok = strtok_r(buf, "+", &save); tok != NULL;
tok = strtok_r(NULL, "+", &save)) {
/* MCDE's names first: Command is Mod4 (the key left of the
* space bar), Option is Mod1 (ext/src/mcde/AGENTS.md) */
if (strcmp(tok, "Cmd") == 0 || strcmp(tok, "Command") == 0 ||
strcmp(tok, "Mod4") == 0)
L.hot_mods |= Mod4Mask;
else if (strcmp(tok, "Option") == 0 || strcmp(tok, "Alt") == 0 ||
strcmp(tok, "Meta") == 0)
L.hot_mods |= Mod1Mask;
else if (strcmp(tok, "Ctrl") == 0 || strcmp(tok, "Control") == 0)
L.hot_mods |= ControlMask;
else if (strcmp(tok, "Shift") == 0)
L.hot_mods |= ShiftMask;
else if (strcmp(tok, "Super") == 0)
L.hot_mods |= Mod4Mask;
else
ks = XStringToKeysym(tok);
}
if (ks == NoSymbol || (L.hot_code = XKeysymToKeycode(L.dpy, ks)) == 0)
return -1;
return 0;
}
static void
grab_hotkey(void)
{
/* with and without Caps Lock (Lock) and Num Lock (Mod2) */
static const unsigned int locks[] = { 0, LockMask, Mod2Mask,
LockMask | Mod2Mask };
size_t i;
for (i = 0; i < sizeof locks / sizeof locks[0]; i++)
XGrabKey(L.dpy, L.hot_code, L.hot_mods | locks[i], L.root,
False, GrabModeAsync, GrabModeAsync);
}
/* ---- main -------------------------------------------------------------- */
static Widget
build(void)
{
Widget form, frame;
Arg a[12];
int n;
n = 0;
XtSetArg(a[n], XmNoverrideRedirect, True); n++;
XtSetArg(a[n], XmNallowShellResize, True); n++;
L.shell = XtCreatePopupShell("launcher", topLevelShellWidgetClass,
L.top, a, n);
n = 0;
XtSetArg(a[n], XmNshadowType, XmSHADOW_OUT); n++;
XtSetArg(a[n], XmNshadowThickness, 2); n++;
frame = XmCreateFrame(L.shell, "frame", a, n);
n = 0;
XtSetArg(a[n], XmNmarginWidth, 8); n++;
XtSetArg(a[n], XmNmarginHeight, 8); n++;
XtSetArg(a[n], XmNverticalSpacing, 6); n++;
form = XmCreateForm(frame, "form", a, n);
n = 0;
XtSetArg(a[n], XmNtopAttachment, XmATTACH_FORM); n++;
XtSetArg(a[n], XmNleftAttachment, XmATTACH_FORM); n++;
XtSetArg(a[n], XmNrightAttachment, XmATTACH_FORM); n++;
L.field = XmCreateTextField(form, "field", a, n);
XtAddCallback(L.field, XmNvalueChangedCallback, field_changed, NULL);
XtAddCallback(L.field, XmNactivateCallback, field_activate, NULL);
XtInsertEventHandler(L.field, KeyPressMask, False, field_key, NULL,
XtListHead);
n = 0;
XtSetArg(a[n], XmNtopAttachment, XmATTACH_WIDGET); n++;
XtSetArg(a[n], XmNtopWidget, L.field); n++;
XtSetArg(a[n], XmNleftAttachment, XmATTACH_FORM); n++;
XtSetArg(a[n], XmNrightAttachment, XmATTACH_FORM); n++;
XtSetArg(a[n], XmNselectionPolicy, XmBROWSE_SELECT); n++;
XtSetArg(a[n], XmNtraversalOn, False); n++;
L.list = XmCreateScrolledList(form, "list", a, n);
XtAddCallback(L.list, XmNdefaultActionCallback, list_activate, NULL);
n = 0;
XtSetArg(a[n], XmNtopAttachment, XmATTACH_WIDGET); n++;
XtSetArg(a[n], XmNtopWidget, XtParent(L.list)); n++;
XtSetArg(a[n], XmNleftAttachment, XmATTACH_FORM); n++;
XtSetArg(a[n], XmNbottomAttachment, XmATTACH_FORM); n++;
L.hint = XmCreateLabel(form, "hint", a, n);
XtManageChild(L.field);
XtManageChild(L.list);
XtManageChild(L.hint);
XtManageChild(form);
XtManageChild(frame);
return L.shell;
}
int
main(int argc, char **argv)
{
Resources res;
XEvent ev;
String s;
Boolean show_now, nograb, quit_now;
(void)signal(SIGCHLD, SIG_IGN); /* started programs: no zombies */
XtSetLanguageProc(NULL, NULL, NULL);
L.top = XtVaAppInitialize(&L.app, "Dtlaunch", options,
XtNumber(options), &argc, argv, fallback,
XmNmappedWhenManaged, False, XmNwidth, 1, XmNheight, 1, NULL);
L.dpy = XtDisplay(L.top);
L.root = DefaultRootWindow(L.dpy);
L.a_clipboard = XInternAtom(L.dpy, "CLIPBOARD", False);
L.a_utf8 = XInternAtom(L.dpy, "UTF8_STRING", False);
L.a_targets = XInternAtom(L.dpy, "TARGETS", False);
L.a_text = XInternAtom(L.dpy, "TEXT", False);
L.a_self = XInternAtom(L.dpy, "_MCDE_DTLAUNCH", False);
L.a_show = XInternAtom(L.dpy, "_MCDE_DTLAUNCH_SHOW", False);
L.a_quit = XInternAtom(L.dpy, "_MCDE_DTLAUNCH_QUIT", False);
XtGetApplicationResources(L.top, &res, resources, XtNumber(resources),
NULL, 0);
s = NULL;
show_now = XrmGetResource(XtDatabase(L.dpy), "dtlaunch.show",
"Dtlaunch.Show", &s, &(XrmValue){ 0, NULL }) ? True : False;
nograb = XrmGetResource(XtDatabase(L.dpy), "dtlaunch.nograb",
"Dtlaunch.Nograb", &s, &(XrmValue){ 0, NULL }) ? True : False;
quit_now = XrmGetResource(XtDatabase(L.dpy), "dtlaunch.quit",
"Dtlaunch.Quit", &s, &(XrmValue){ 0, NULL }) ? True : False;
XtRealizeWidget(L.top);
/* one launcher per display: ask the running one to open or to exit */
{
Window other = XGetSelectionOwner(L.dpy, L.a_self);
if (other != None) {
XEvent cm;
int i;
memset(&cm, 0, sizeof cm);
cm.xclient.type = ClientMessage;
cm.xclient.window = other;
cm.xclient.message_type = quit_now ? L.a_quit : L.a_show;
cm.xclient.format = 32;
XSendEvent(L.dpy, other, False, NoEventMask, &cm);
XFlush(L.dpy);
if (!quit_now)
return 0;
/* -quit: wait until the selection has no owner, so
* that the next launcher can take the hot key */
for (i = 0; i < 40; i++) {
XSync(L.dpy, False);
if (XGetSelectionOwner(L.dpy, L.a_self) == None)
break;
usleep(50000);
}
return 0;
}
if (quit_now)
return 0;
XSetSelectionOwner(L.dpy, L.a_self, XtWindow(L.top),
CurrentTime);
}
build();
if (!nograb) {
if (parse_hotkey(res.hotkey) == 0)
grab_hotkey();
else
fprintf(stderr, "dtlaunch: hot key \"%s\" not understood\n",
res.hotkey);
}
(void)XtAppAddTimeOut(L.app, POLL_MS, poll_clipboard, NULL);
if (show_now)
show();
/* the hot key and the message from a second launcher arrive at
* windows Xt does not know (the root) or not for a widget */
for (;;) {
XtAppNextEvent(L.app, &ev);
if (ev.type == KeyPress && ev.xkey.window == L.root &&
ev.xkey.keycode == L.hot_code) {
if (L.visible)
hide();
else
show();
continue;
}
if (ev.type == ClientMessage &&
ev.xclient.message_type == L.a_show) {
show();
continue;
}
if (ev.type == ClientMessage &&
ev.xclient.message_type == L.a_quit) {
XCloseDisplay(L.dpy);
return 0;
}
(void)XtDispatchEvent(&ev);
}
}