From d41ebfa4516aafc7ca2a09984b42599c2fa48820 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sat, 21 Nov 2026 20:15:43 +0000 Subject: [PATCH 01/22] mcde: one window size for System Settings, tabs that are one of many, icons that exist - dtsystemsettings: the shell is 1022x550 and stays so (min/max equal); every pane lives in it instead of growing the window (thirteen per-pane XtVaSetValues(shell, width, height) calls are gone), and a taller pane scrolls (the pages sit in an XmScrolledWindow with XmAUTOMATIC). - panes.c: CDs & DVDs had no icon (Dtmedia.m.pm does not exist) - it shows IrixCD.m.pm; Energy Saver shows SDtpowermgr.m.pm; Accounts had the same icon as Startup (DtStart.pm) and shows McdeUser.t.pm. The "Startup Disk" entry and the disabled "Dock" entry (no icon, PANE_LATER) are removed. - McdePrefs: the tab strip is one of many (XmNradioBehavior, XmNradioAlwaysOne). Without it every visited tab stayed pressed (measured 2026-11-21: Keyboard, Mouse and Shortcuts all down at once). - dttoolbox: the window title is "dttoolchest" (msg 1 of the catalog). - McdeSys: mcde_sys_keyboard_is_mac asks the machine (hw.model "Mac...") before usbdevs. At session start the internal keyboard may not be enumerated yet, so dtkeys took a MacBook for a PC keyboard and exchanged Alt and Command (_MCDE_KEYS said "pc", measured 2026-11-21). Measured on the MacBook: keyboard _MCDE_KEYS "pc" with an Apple Internal Keyboard / Trackpad on usb1 port 2 addr 7. --- lib/DtWidget/McdePrefs.c | 5 +++++ lib/McdeSys/netbsd.c | 11 +++++++++ programs/dtsystemsettings/main.c | 37 +++++++++++++++---------------- programs/dtsystemsettings/panes.c | 12 ++++------ programs/dttoolbox/dttoolbox.msg | 2 +- 5 files changed, 39 insertions(+), 28 deletions(-) diff --git a/lib/DtWidget/McdePrefs.c b/lib/DtWidget/McdePrefs.c index f9212fc4..b883d052 100644 --- a/lib/DtWidget/McdePrefs.c +++ b/lib/DtWidget/McdePrefs.c @@ -223,8 +223,13 @@ McdePrefsCreate(Widget parent, const char *prog) xmRowColumnWidgetClass, p->shell, XmNorientation, XmVERTICAL, XmNspacing, 6, XmNmarginWidth, 8, XmNmarginHeight, 8, XmNwidth, 560, NULL); + /* the tabs are one of many: a toggle stays pressed only when it is the + * chosen page. Without the radio behaviour every tab that was visited + * stayed pressed (measured 2026-11-21: Keyboard, Mouse and Shortcuts + * were all down at once). */ p->tabs = XtVaCreateManagedWidget("prefsTabs", xmRowColumnWidgetClass, p->box, XmNorientation, XmHORIZONTAL, + XmNradioBehavior, True, XmNradioAlwaysOne, True, XmNspacing, 4, XmNmarginWidth, 0, XmNentryAlignment, XmALIGNMENT_CENTER, NULL); p->pages = XtVaCreateManagedWidget("prefsPages", diff --git a/lib/McdeSys/netbsd.c b/lib/McdeSys/netbsd.c index 357a9d38..9f637937 100644 --- a/lib/McdeSys/netbsd.c +++ b/lib/McdeSys/netbsd.c @@ -288,6 +288,17 @@ mcde_sys_keyboard_is_mac(void) if (uname(&u) == 0 && strcmp(u.machine, "macppc") == 0) return 1; + /* The machine itself: a MacBook's internal keyboard IS Apple's, and + * usbdevs may not have enumerated it yet when the session starts + * (measured 2026-11-21: _MCDE_KEYS said "pc" on a MacBook, so dtkeys + * exchanged Alt and Command). hw.model is there from boot. */ + { + char model[64]; + + if (Sysctl("hw.model", model, sizeof model) && + strncmp(model, "Mac", 3) == 0) + return 1; + } if (mcde_sys_capture(argv, out, sizeof out) != MCDE_SYS_OK) return 0; for (line = strtok_r(out, "\n", &last); line != NULL; diff --git a/programs/dtsystemsettings/main.c b/programs/dtsystemsettings/main.c index ffada0a9..3f2a3755 100644 --- a/programs/dtsystemsettings/main.c +++ b/programs/dtsystemsettings/main.c @@ -118,7 +118,8 @@ CatName(int c) categoryNames[0]; } -static Widget shell, title, showAll, overview, paneArea, current; +static Widget shell, title, showAll, overview, paneScroll, paneArea, + current; static Widget backBtn, forwardBtn, searchField; static Widget ovButton[64], ovLabel[64]; /* the overview's items */ static char *history[16]; /* the panes shown, by id */ @@ -1082,7 +1083,7 @@ ShowOverview(void) current = NULL; } shown = NULL; - XtUnmanageChild(paneArea); + XtUnmanageChild(paneScroll); XtManageChild(overview); SetText(title, Msg(31, "System Settings")); XtVaSetValues(shell, XmNtitle, Msg(31, "System Settings"), NULL); @@ -1107,39 +1108,30 @@ ShowPane(const Pane *p) w = MakeSound(paneArea); else if (strcmp(p->id, "printers") == 0) { w = MakePrinters(paneArea); - XtVaSetValues(shell, XmNheight, 640, XmNwidth, 760, NULL); } else if (strcmp(p->id, "startupdisk") == 0) { w = MakeStartupDisk(paneArea); - XtVaSetValues(shell, XmNheight, 560, XmNwidth, 680, NULL); } else if (strcmp(p->id, "sysinfo") == 0) { w = MakeSysinfo(paneArea); - XtVaSetValues(shell, XmNheight, 520, XmNwidth, 700, NULL); } else if (strcmp(p->id, "defaults") == 0) { w = MakeDefaults(paneArea); - XtVaSetValues(shell, XmNheight, 560, XmNwidth, 640, NULL); } else if (strcmp(p->id, "internet") == 0) { w = MakeInternet(paneArea); - XtVaSetValues(shell, XmNheight, 560, XmNwidth, 640, NULL); } else if (strcmp(p->id, "energy") == 0) { w = MakeEnergy(paneArea); - XtVaSetValues(shell, XmNheight, 520, XmNwidth, 720, NULL); } else if (strcmp(p->id, "cds") == 0) { w = MakeCDs(paneArea); - XtVaSetValues(shell, XmNheight, 500, XmNwidth, 700, NULL); } else if (strcmp(p->id, "parental") == 0) { w = MakeParental(paneArea); - XtVaSetValues(shell, XmNheight, 640, XmNwidth, 780, NULL); } else if (strcmp(p->id, "security") == 0) { w = MakeSecurity(paneArea); - XtVaSetValues(shell, XmNheight, 620, XmNwidth, 700, NULL); } else if (strcmp(p->id, "network") == 0) w = MakeNetwork(paneArea); @@ -1149,13 +1141,9 @@ ShowPane(const Pane *p) w = MakeAppearance(paneArea); /* palette, the four groups and the fonts need more room than * the overview */ - XtVaSetValues(shell, XmNheight, 720, XmNwidth, 780, NULL); } else if (strcmp(p->id, "datetime") == 0) { w = MakeDateTime(paneArea); - /* calendar, clock and the two tabs need more room than the - * overview's height; this pane brings its own */ - XtVaSetValues(shell, XmNheight, 660, NULL); } else if (strcmp(p->id, "about") == 0) w = MakeAbout(paneArea); @@ -1173,13 +1161,11 @@ ShowPane(const Pane *p) strcmp(p->id, "screensaver") == 0) { w = MakeDesktopPane(paneArea, strcmp(p->id, "screensaver") == 0); - XtVaSetValues(shell, XmNheight, 660, XmNwidth, 800, NULL); } else if (strcmp(p->id, "keyboardmouse") == 0 || strcmp(p->id, "keyboard") == 0 || strcmp(p->id, "mouse") == 0 || strcmp(p->id, "shortcuts") == 0) { w = MakeInput(paneArea, p->id); - XtVaSetValues(shell, XmNheight, 660, XmNwidth, 760, NULL); } else if (strcmp(p->id, "displays") == 0) w = MakeDisplays(paneArea); @@ -1191,6 +1177,7 @@ ShowPane(const Pane *p) shown = p; XtManageChild(w); XtUnmanageChild(overview); + XtManageChild(paneScroll); XtManageChild(paneArea); SetText(title, PaneLabel(p)); XtVaSetValues(shell, XmNtitle, PaneLabel(p), NULL); @@ -1533,15 +1520,27 @@ main(int argc, char **argv) XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, bar, XmNleftAttachment, XmATTACH_FORM, XmNrightAttachment, XmATTACH_FORM, NULL); + /* One size for the whole program (Konrad, 2026-11-21): every pane + * lives in this window, and a pane taller than it scrolls instead of + * making the window grow. The overview and the pages share it. */ + XtVaSetValues(shell, XmNwidth, 1022, XmNheight, 550, + XmNminWidth, 1022, XmNmaxWidth, 1022, + XmNminHeight, 550, XmNmaxHeight, 550, NULL); overview = MakeOverview(form); XtVaSetValues(overview, XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, sep, XmNleftAttachment, XmATTACH_FORM, XmNrightAttachment, XmATTACH_FORM, XmNbottomAttachment, XmATTACH_FORM, NULL); - paneArea = XtVaCreateWidget("paneArea", xmRowColumnWidgetClass, form, + paneScroll = XtVaCreateWidget("paneScroll", xmScrolledWindowWidgetClass, + form, XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, sep, XmNleftAttachment, XmATTACH_FORM, XmNrightAttachment, XmATTACH_FORM, - XmNbottomAttachment, XmATTACH_FORM, NULL); + XmNbottomAttachment, XmATTACH_FORM, + XmNscrollingPolicy, XmAUTOMATIC, + XmNscrollBarDisplayPolicy, XmAS_NEEDED, + XmNvisualPolicy, XmVARIABLE, NULL); + paneArea = XtVaCreateWidget("paneArea", xmRowColumnWidgetClass, + paneScroll, NULL); XtManageChild(overview); XtSetSensitive(showAll, False); XtRealizeWidget(shell); diff --git a/programs/dtsystemsettings/panes.c b/programs/dtsystemsettings/panes.c index 5c5b981a..2deec0af 100644 --- a/programs/dtsystemsettings/panes.c +++ b/programs/dtsystemsettings/panes.c @@ -29,9 +29,7 @@ const Pane panes[] = { "screensaver screen saver bildschirmschoner" }, { "language", "Language", CAT_PERSONAL, "DtI18N.pm", PANE_OWN, NULL, "language sprache locale region formats datum" }, - { "dock", "Dock", CAT_PERSONAL, "DtPanel.m.pm", PANE_LATER, NULL, - "dock leiste panel front panel" }, - { "security", "Security", CAT_PERSONAL, "McdeLock.pm", PANE_OWN, NULL, + { "security", "Security", CAT_PERSONAL, "McdeLock.pm", PANE_OWN, NULL, "security sicherheit firewall lock sperre password passwort " "encryption verschluesselung cgd swap virtual memory npf" }, @@ -49,9 +47,9 @@ const Pane panes[] = { "printers drucker print cups queues warteschlange" }, { "bluetooth", "Bluetooth", CAT_HARDWARE, "McdeBluetooth.m.pm", PANE_OWN, NULL, "bluetooth" }, - { "cds", "CDs & DVDs", CAT_HARDWARE, "Dtmedia.m.pm", PANE_OWN, NULL, + { "cds", "CDs & DVDs", CAT_HARDWARE, "IrixCD.m.pm", PANE_OWN, NULL, "cds dvds medien media einlegen audio video picture blank" }, - { "energy", "Energy Saver", CAT_HARDWARE, "Dtbattery.m.pm", PANE_OWN, + { "energy", "Energy Saver", CAT_HARDWARE, "SDtpowermgr.m.pm", PANE_OWN, NULL, "energy energie sleep ruhezustand strom display disks" }, { "internet", "Internet Accounts", CAT_NETWORK, "Dtmail.t.pm", @@ -72,14 +70,12 @@ const Pane panes[] = { { "parental", "Parental Controls", CAT_SYSTEM, "McdeUser.t.pm", PANE_OWN, NULL, "parental controls kinderschutz limits hours " "programs erlaubte programme" }, - { "accounts", "Accounts", CAT_SYSTEM, "DtStart.pm", PANE_OWN, NULL, + { "accounts", "Accounts", CAT_SYSTEM, "McdeUser.t.pm", PANE_OWN, NULL, "accounts benutzer users password passwort" }, { "update", "Software Update", CAT_SYSTEM, "Dtstyle.m.pm", PANE_OWN, NULL, "update software aktualisierung pakete packages" }, { "backup", "Backup", CAT_SYSTEM, "DtSystem.m.pm", PANE_OWN, NULL, "backup sicherung" }, - { "startupdisk", "Startup Disk", CAT_SYSTEM, "Dtdisk.m.pm", PANE_OWN, - NULL, "startup disk startvolume boot volume" }, { "accessibility", "Accessibility", CAT_SYSTEM, "Dtmouse.m.pm", PANE_LATER, NULL, "accessibility bedienungshilfen" }, { "about", "About", CAT_SYSTEM, "MakronixDtlogo.m.pm", PANE_OWN, NULL, diff --git a/programs/dttoolbox/dttoolbox.msg b/programs/dttoolbox/dttoolbox.msg index a666fd19..f335d569 100644 --- a/programs/dttoolbox/dttoolbox.msg +++ b/programs/dttoolbox/dttoolbox.msg @@ -2,5 +2,5 @@ $ MCDE dttoolbox message catalog (set 1) -- English is the source; a locale's co $ $set 1 -1 ToolChest +1 dttoolchest 2 No ToolChest menu From ae38eccebecee3483c646e8e79d6f0d1fc3da2a0 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sat, 21 Nov 2026 21:42:34 +0000 Subject: [PATCH 02/22] MCDE dtpaint: the review's defects -- crash, undo, menus, save, i18n, speed (t0704) Review of programs/dtpaint found and this fixes: - Picker crash: a click in the grey strip below the image reached XGetImage outside the pixmap (BadMatch, X_GetImage). The canvas is now a drawing area of exactly the image size inside a scrolled window, and CanvasInput bounds-checks; large BMPs scroll instead of being clipped. - Undo: one snapshot taken before every image-changing operation (pencil, brush, eraser, fill, shapes, invert, flip, clear) and refreshed after a load; previously only shape tools snapshotted and OpenBMP left snap uninitialized, so Undo after Open turned the image black. - Menus: Clear Selection and Edit Colors were wired to Clear Image and About; they are now insensitive until D3/D4. Help Topics is real. Accelerator text shown; Clear Image uses 'Ctrl ShiftN' (the old 'CtrlShiftN' never fired). - Save remembers the path and title, asks before New/Open/Exit when dirty (Discard/Keep), and reports open/save errors in a dialog instead of stderr; the per-tool-change stderr debug is gone. - Colour model: fg/bg are pixels (picker takes any colour, right button sets background) with a drawn fg/bg indicator; toolbox is radio with the indicator hidden (one sunken tool); swatches are 16x16. - Open/Save/Invert no longer do one X round trip per pixel: TrueColor converts through the visual's masks, other visuals batch the distinct colours. Measured on a 1024x768 BMP: open 18.3 s -> 0.02 s, invert 14.9 s -> 0.05 s, save 6.3 s -> 0.23 s. - FloodFill is scanline with a growing seed stack, not 4 neighbours per pixel; XmString leaks freed; message dialogs destroy their shell. - Catalog grows to 34 messages; the German copy transliterates umlauts (core font has no UTF-8 rendition), re-measured under de_DE.UTF-8. -selftest now also checks the BMP round trip and double invert/flip: PASS. Builds clean under -Wall -Wextra -Werror; PLIST gate ok (3714 installed). Left column is a Form so the colour box never overlaps the canvas. --- AGENTS.md | 15 +- programs/dtpaint/dtpaint.c | 1129 +++++++++++++---- programs/dtpaint/dtpaint.msg | 11 + .../localized/de_DE.UTF-8/msg/dtpaint.msg | 22 +- 4 files changed, 924 insertions(+), 253 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1d89be92..efb1fffe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,9 +69,18 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt status lines and the open/save errors) keeps its menus as the reference's (`dtphoto.menu`, docs/reference/photoshop-ui.csv) -- they are the look of the program, not its sentences. dtpaint builds its menus in code and its - labels are catalogued (`dtpaint.msg`, 23 messages); the program has no - render table, so its German strings avoid umlauts (a UTF-8 `ü` came out - as two latin-1 characters under the core font, measured 2026-11-16). + labels are catalogued (`dtpaint.msg`, 34 messages: menus, the file/error/ + discard dialogs, Help and About); the program has no render table, so its + German strings avoid umlauts (a UTF-8 `ü` came out as two latin-1 + characters under the core font, measured 2026-11-16; the German copy + transliterates ae/oe/ue throughout, re-measured 2026-11-21). Its canvas + is a drawing area of exactly the image size inside a scrolled window (a + click outside the image must never reach XGetImage -- the picker crashed + there), undo is one snapshot taken before every image-changing operation + and refreshed after a load, and Open/Save/Invert convert colours through + the visual's masks on TrueColor (or in batches otherwise), never one X + round trip per pixel (measured 2026-11-21: open 18.3 s -> 0.02 s, invert + 14.9 s -> 0.05 s, save 6.3 s -> 0.23 s on a 1024x768 BMP). McdeSys has a catalog too (`lib/McdeSys/mcdesys.msg`, `lib/McdeSys/ text.c`, `mcde_sys_msg`): common.c's tool errors ask it for their sentence (messages 1-9: not there, cannot start, failed with status, no pipe, no diff --git a/programs/dtpaint/dtpaint.c b/programs/dtpaint/dtpaint.c index 780c855e..ec319d18 100644 --- a/programs/dtpaint/dtpaint.c +++ b/programs/dtpaint/dtpaint.c @@ -5,12 +5,21 @@ * * The standard, simple drawing program of MCDE: toolbox, colour box, canvas * and status line, the sixteen tools and the six menus of the reference - * (docs/MCDE-PROGRAMS.md, C4; provenance in section 8 there). + * (docs/MCDE-PROGRAMS.md, C3; provenance in section 8 there). * * Working in this first stage: pencil, brush, eraser, fill, pick colour, * line, rectangle, ellipse, rounded rectangle, undo, invert, flip, new, * open and save as BMP. Select, text, curve, polygon, airbrush and zoom - * are in the toolbox and in the menus but do nothing yet. + * are in the toolbox but do nothing yet; their menu entries that need them + * (Clear Selection, Edit Colors) are insensitive until they exist. + * + * The canvas is a drawing area of exactly the image size inside a scrolled + * window, so a large image scrolls instead of being clipped, and a click + * outside the image can never reach XGetImage (the picker used to crash + * there). Undo is one step: a snapshot is taken before every operation + * that changes the image, and refreshed after a load. Open/Save/Invert + * convert colours in batches (or directly through the visual's masks on a + * TrueColor display), never one X round trip per pixel. * * C99 and POSIX, Motif and Xlib. */ @@ -22,6 +31,7 @@ #include #include #include +#include #include #include @@ -36,11 +46,13 @@ #include #include #include +#include #include #include /* dtpaint's message catalog (programs/dtpaint/dtpaint.msg, the locale's copy - * in programs/localized//msg, under lib/nls/msg) */ + * in programs/localized//msg, under lib/nls/msg). The core font has + * no UTF-8 rendition, so the German copy transliterates umlauts. */ static nl_catd cat = (nl_catd) -1; static const char * @@ -58,6 +70,13 @@ PaintMsg(int n, const char *text) return catgets(cat, 1, n, text); } +/* a catalog sentence as a compound string (XmStringCreateLocalized copies) */ +static XmString +Msg(int n, const char *text) +{ + return XmStringCreateLocalized((String) PaintMsg(n, text)); +} + #define PAL_COLS 14 #define PAL_ROWS 2 #define PAL_N (PAL_COLS * PAL_ROWS) @@ -85,50 +104,163 @@ static const char *const toolNames[] = { }; static Display *dpy; -static Widget top, mainw, menubar, form, canvas, colorbox, toolbox; -static Widget statusHelp, statusPos; +static Screen *scr; +static Visual *vis; +static Colormap cmap; +static int depth; +static int truecolor; +static unsigned long rmask, gmask, bmask; +static int rshift, gshift, bshift; +static unsigned long rmax, gmax, bmax; +static Widget top, mainw, form, scroll, canvas, colorbox, toolbox, leftcol; +static Widget statusHelp, statusPos, fgbg; static Pixmap pix, snap; static GC gc; static int imgW = 640, imgH = 480; static int tool = T_PENCIL; -static int fg = 0, bg = 14; +static unsigned long fgPix, bgPix; static XColor palette[PAL_N]; static int drawing, sx, sy, lx, ly; -static int curx, cury; static int toolsShown = 1, colorsShown = 1, statusShown = 1; +static char curPath[512]; +static int dirty; +static int pendingAction; -/* ------------------------------------------------------------------ files */ +/* ------------------------------------------------------------------ colour */ static int -PixelRGB(unsigned long pixel, unsigned char *r, unsigned char *g, unsigned char *b) +ShiftOf(unsigned long mask) +{ + int s = 0; + + if (mask == 0) + return 0; + while ((mask & 1) == 0) { + mask >>= 1; + s++; + } + return s; +} + +static void +InitColor(void) +{ + scr = XtScreen(top); + vis = DefaultVisualOfScreen(scr); + cmap = DefaultColormapOfScreen(scr); + depth = DefaultDepthOfScreen(scr); + rmask = vis->red_mask; + gmask = vis->green_mask; + bmask = vis->blue_mask; + rshift = ShiftOf(rmask); + gshift = ShiftOf(gmask); + bshift = ShiftOf(bmask); + rmax = rmask >> rshift; + gmax = gmask >> gshift; + bmax = bmask >> bshift; + truecolor = (vis->class == TrueColor || vis->class == DirectColor); +} + +/* RGB (0..255) to a pixel. On TrueColor/DirectColor this is arithmetic on + * the visual's masks -- no server round trip. Otherwise one XAllocColor. */ +static unsigned long +RGBToPixel(unsigned r, unsigned g, unsigned b) { - static unsigned long cachePixel[PAL_N + 8]; - static unsigned char cacheRGB[PAL_N + 8][3]; - static int ncache; - int i; XColor c; - for (i = 0; i < ncache; i++) - if (cachePixel[i] == pixel) { - *r = cacheRGB[i][0]; *g = cacheRGB[i][1]; *b = cacheRGB[i][2]; - return 0; - } - c.pixel = pixel; - if (!XQueryColor(dpy, DefaultColormap(dpy, 0), &c)) - return -1; - *r = (unsigned char) (c.red >> 8); - *g = (unsigned char) (c.green >> 8); - *b = (unsigned char) (c.blue >> 8); - if (ncache < PAL_N + 8) { - cachePixel[ncache] = pixel; - cacheRGB[ncache][0] = *r; - cacheRGB[ncache][1] = *g; - cacheRGB[ncache][2] = *b; - ncache++; - } - return 0; + if (truecolor) + return ((unsigned long) (r * rmax / 255) << rshift) | + ((unsigned long) (g * gmax / 255) << gshift) | + ((unsigned long) (b * bmax / 255) << bshift); + c.red = (unsigned short) (r * 257); + c.green = (unsigned short) (g * 257); + c.blue = (unsigned short) (b * 257); + c.flags = DoRed | DoGreen | DoBlue; + if (!XAllocColor(dpy, cmap, &c)) + return 0; + return c.pixel; } +static void +PixelToRGB(unsigned long p, unsigned *r, unsigned *g, unsigned *b) +{ + XColor c; + + if (truecolor) { + *r = (unsigned) (((p & rmask) >> rshift) * 255 / rmax); + *g = (unsigned) (((p & gmask) >> gshift) * 255 / gmax); + *b = (unsigned) (((p & bmask) >> bshift) * 255 / bmax); + return; + } + c.pixel = p; + if (!XQueryColor(dpy, cmap, &c)) { + *r = *g = *b = 0; + return; + } + *r = c.red >> 8; + *g = c.green >> 8; + *b = c.blue >> 8; +} + +static int +CmpUL(const void *a, const void *b) +{ + unsigned long x = *(const unsigned long *) a; + unsigned long y = *(const unsigned long *) b; + + return (x < y) ? -1 : (x > y) ? 1 : 0; +} + +/* Batch pixel->RGB for a non-TrueColor visual: one XQueryColors for the + * distinct pixels instead of one XQueryColor per image pixel. */ +static void +BatchQuery(unsigned long *pix, int n, unsigned char *rgb) +{ + XColor *cols; + int i; + + cols = malloc(sizeof(XColor) * (size_t) n); + if (cols == NULL) + return; + for (i = 0; i < n; i++) + cols[i].pixel = pix[i]; + if (!XQueryColors(dpy, cmap, cols, n)) { + free(cols); + return; + } + for (i = 0; i < n; i++) { + rgb[i * 3] = (unsigned char) (cols[i].red >> 8); + rgb[i * 3 + 1] = (unsigned char) (cols[i].green >> 8); + rgb[i * 3 + 2] = (unsigned char) (cols[i].blue >> 8); + } + free(cols); +} + +/* Batch RGB->pixel for a non-TrueColor visual. Xlib has no plural alloc, + * but a PseudoColor colormap holds at most a few hundred cells, so one + * XAllocColor per *distinct* colour is bounded and cheap -- unlike one per + * image pixel. */ +static void +BatchAlloc(const unsigned char *rgb, int n, unsigned long *pix) +{ + XColor c; + int i; + + for (i = 0; i < n; i++) { + c.red = (unsigned short) (rgb[i * 3] * 257); + c.green = (unsigned short) (rgb[i * 3 + 1] * 257); + c.blue = (unsigned short) (rgb[i * 3 + 2] * 257); + c.flags = DoRed | DoGreen | DoBlue; + c.pixel = 0; + if (XAllocColor(dpy, cmap, &c)) + pix[i] = c.pixel; + else + pix[i] = 0; + } +} + +/* ------------------------------------------------------------------ files */ + static void PutLE(unsigned char *p, unsigned long v, int n) { @@ -145,6 +277,9 @@ SaveBMP(const char *path) FILE *f; int row = ((imgW * 3 + 3) / 4) * 4; unsigned char *data; + unsigned long *keys = NULL; + unsigned char *krgb = NULL; + int nkeys = 0; int x, y; unsigned long size = (unsigned long) row * imgH; @@ -154,15 +289,57 @@ SaveBMP(const char *path) XDestroyImage(im); return -1; } + if (!truecolor) { + /* gather the distinct pixels, query them in one round trip */ + keys = malloc(sizeof(unsigned long) * (size_t) imgW * imgH); + if (keys != NULL) { + for (y = 0; y < imgH; y++) + for (x = 0; x < imgW; x++) + keys[nkeys++] = XGetPixel(im, x, y); + qsort(keys, (size_t) nkeys, sizeof(unsigned long), CmpUL); + { + int i, j = 0; + + for (i = 0; i < nkeys; i++) + if (i == 0 || keys[i] != keys[i - 1]) + keys[j++] = keys[i]; + nkeys = j; + } + krgb = malloc((size_t) nkeys * 3); + if (krgb != NULL) + BatchQuery(keys, nkeys, krgb); + } + } for (y = 0; y < imgH; y++) for (x = 0; x < imgW; x++) { - unsigned char r, g, b; + unsigned r, g, b; unsigned char *p = data + (size_t) (imgH - 1 - y) * row + x * 3; + unsigned long px = XGetPixel(im, x, y); - if (PixelRGB(XGetPixel(im, x, y), &r, &g, &b) < 0) - continue; - p[0] = b; p[1] = g; p[2] = r; + if (truecolor) { + PixelToRGB(px, &r, &g, &b); + } else if (keys != NULL && krgb != NULL) { + unsigned long *hit = bsearch(&px, keys, (size_t) nkeys, + sizeof(unsigned long), CmpUL); + + if (hit == NULL) + continue; + { + size_t idx = (size_t) (hit - keys); + + r = krgb[idx * 3]; + g = krgb[idx * 3 + 1]; + b = krgb[idx * 3 + 2]; + } + } else { + PixelToRGB(px, &r, &g, &b); + } + p[0] = (unsigned char) b; + p[1] = (unsigned char) g; + p[2] = (unsigned char) r; } + free(keys); + free(krgb); XDestroyImage(im); if ((f = fopen(path, "wb")) == NULL) { free(data); @@ -183,10 +360,21 @@ SaveBMP(const char *path) PutLE(hdr + 34, size, 4); PutLE(hdr + 38, 2835, 4); PutLE(hdr + 42, 2835, 4); - fwrite(hdr, 1, sizeof hdr, f); + if (fwrite(hdr, 1, sizeof hdr, f) != sizeof hdr) { + fclose(f); + free(data); + return -1; + } + } + if (fwrite(data, 1, (size_t) size, f) != (size_t) size) { + fclose(f); + free(data); + return -1; + } + if (fclose(f) != 0) { + free(data); + return -1; } - fwrite(data, 1, (size_t) size, f); - fclose(f); free(data); return 0; } @@ -207,10 +395,12 @@ OpenBMP(const char *path) fclose(f); return -1; } - off = hdr[10] | (hdr[11] << 8) | (hdr[12] << 16) | (hdr[13] << 24); - w = hdr[18] | (hdr[19] << 8) | (hdr[20] << 16) | (hdr[21] << 24); - h = hdr[22] | (hdr[23] << 8) | (hdr[24] << 16) | (hdr[25] << 24); - if (hdr[28] != 24 || w == 0 || h == 0 || w > 4096 || h > 4096) { + off = hdr[10] | (hdr[11] << 8) | (hdr[12] << 16) | ((unsigned long) hdr[13] << 24); + w = hdr[18] | (hdr[19] << 8) | (hdr[20] << 16) | ((unsigned long) hdr[21] << 24); + h = hdr[22] | (hdr[23] << 8) | (hdr[24] << 16) | ((unsigned long) hdr[25] << 24); + /* a 40-byte BITMAPINFOHEADER, 24-bit, uncompressed, bottom-up */ + if ((hdr[14] | (hdr[15] << 8)) != 40 || hdr[28] != 24 || + hdr[30] != 0 || w == 0 || h == 0 || w > 4096 || h > 4096) { fclose(f); return -1; } @@ -219,8 +409,8 @@ OpenBMP(const char *path) fclose(f); return -1; } - fseek(f, (long) off, SEEK_SET); - if (fread(data, 1, row * h, f) != row * h) { + if (fseek(f, (long) off, SEEK_SET) != 0 || + fread(data, 1, row * h, f) != row * h) { free(data); fclose(f); return -1; @@ -228,23 +418,34 @@ OpenBMP(const char *path) fclose(f); if ((int) w != imgW || (int) h != imgH) { + Pixmap np, ns; + imgW = (int) w; imgH = (int) h; + np = XCreatePixmap(dpy, RootWindowOfScreen(scr), imgW, imgH, depth); + ns = XCreatePixmap(dpy, RootWindowOfScreen(scr), imgW, imgH, depth); + if (np == None || ns == None) { + if (np != None) + XFreePixmap(dpy, np); + if (ns != None) + XFreePixmap(dpy, ns); + free(data); + return -1; + } if (pix != None) XFreePixmap(dpy, pix); - pix = XCreatePixmap(dpy, DefaultRootWindow(dpy), imgW, imgH, - DefaultDepth(dpy, 0)); if (snap != None) XFreePixmap(dpy, snap); - snap = XCreatePixmap(dpy, DefaultRootWindow(dpy), imgW, imgH, - DefaultDepth(dpy, 0)); - XtVaSetValues(canvas, XmNwidth, imgW, XmNheight, imgH, NULL); + pix = np; + snap = ns; + if (canvas != NULL) + XtVaSetValues(canvas, XmNwidth, imgW, XmNheight, imgH, NULL); } - XSetForeground(dpy, gc, palette[bg].pixel); + XSetForeground(dpy, gc, bgPix); XFillRectangle(dpy, pix, gc, 0, 0, imgW, imgH); /* draw through an XImage so that the colours stay exact */ - im = XCreateImage(dpy, DefaultVisual(dpy, 0), DefaultDepth(dpy, 0), - ZPixmap, 0, NULL, (unsigned int) w, (unsigned int) h, 32, 0); + im = XCreateImage(dpy, vis, depth, ZPixmap, 0, NULL, + (unsigned int) w, (unsigned int) h, 32, 0); if (im == NULL) { free(data); return -1; @@ -255,19 +456,74 @@ OpenBMP(const char *path) XDestroyImage(im); return -1; } - for (y = 0; y < (int) h; y++) - for (x = 0; x < (int) w; x++) { - unsigned char *p = data + (size_t) (h - 1 - y) * row + x * 3; - XColor c; + if (truecolor) { + for (y = 0; y < (int) h; y++) + for (x = 0; x < (int) w; x++) { + unsigned char *p = data + (size_t) (h - 1 - y) * row + x * 3; - c.red = (unsigned short) (p[2] << 8); - c.green = (unsigned short) (p[1] << 8); - c.blue = (unsigned short) (p[0] << 8); - c.flags = DoRed | DoGreen | DoBlue; - if (!XAllocColor(dpy, DefaultColormap(dpy, 0), &c)) - continue; - XPutPixel(im, x, y, c.pixel); + XPutPixel(im, x, y, RGBToPixel(p[2], p[1], p[0])); + } + } else { + /* distinct colours, one XAllocColors for all of them */ + unsigned long *keys = malloc(sizeof(unsigned long) * (size_t) w * h); + unsigned long *kpix = NULL; + int nkeys = 0; + + if (keys != NULL) { + for (y = 0; y < (int) h; y++) + for (x = 0; x < (int) w; x++) { + unsigned char *p = data + (size_t) (h - 1 - y) * row + x * 3; + + keys[nkeys++] = ((unsigned long) p[2] << 16) | + ((unsigned long) p[1] << 8) | p[0]; + } + qsort(keys, (size_t) nkeys, sizeof(unsigned long), CmpUL); + { + int i, j = 0; + + for (i = 0; i < nkeys; i++) + if (i == 0 || keys[i] != keys[i - 1]) + keys[j++] = keys[i]; + nkeys = j; + } + kpix = malloc(sizeof(unsigned long) * (size_t) nkeys); + if (kpix != NULL) { + unsigned char *krgb = malloc((size_t) nkeys * 3); + + if (krgb != NULL) { + int i; + + for (i = 0; i < nkeys; i++) { + krgb[i * 3] = (unsigned char) (keys[i] >> 16); + krgb[i * 3 + 1] = (unsigned char) (keys[i] >> 8); + krgb[i * 3 + 2] = (unsigned char) keys[i]; + } + BatchAlloc(krgb, nkeys, kpix); + free(krgb); + } + } } + for (y = 0; y < (int) h; y++) + for (x = 0; x < (int) w; x++) { + unsigned char *p = data + (size_t) (h - 1 - y) * row + x * 3; + unsigned long key = ((unsigned long) p[2] << 16) | + ((unsigned long) p[1] << 8) | p[0]; + unsigned long px = 0; + + if (keys != NULL && kpix != NULL) { + unsigned long *hit = bsearch(&key, keys, (size_t) nkeys, + sizeof(unsigned long), CmpUL); + + if (hit != NULL) + px = kpix[hit - keys]; + } else { + px = RGBToPixel(p[2], p[1], p[0]); + } + XPutPixel(im, x, y, px); + } + free(keys); + free(kpix); + } XPutImage(dpy, pix, gc, im, 0, 0, 0, 0, (unsigned int) w, (unsigned int) h); XDestroyImage(im); @@ -278,9 +534,15 @@ OpenBMP(const char *path) /* --------------------------------------------------------------- drawing */ static void -SetFg(int color) +SetFg(unsigned long color) { - XSetForeground(dpy, gc, palette[color].pixel); + XSetForeground(dpy, gc, color); +} + +static void +Snapshot(void) +{ + XCopyArea(dpy, pix, snap, gc, 0, 0, imgW, imgH, 0, 0); } static void @@ -290,7 +552,7 @@ RestoreSnap(void) } static void -DrawDab(int x, int y, int radius, int color) +DrawDab(int x, int y, int radius, unsigned long color) { SetFg(color); XFillArc(dpy, pix, gc, x - radius, y - radius, radius * 2 + 1, @@ -298,14 +560,14 @@ DrawDab(int x, int y, int radius, int color) } static void -DrawLineTo(int x0, int y0, int x1, int y1, int color) +DrawLineTo(int x0, int y0, int x1, int y1, unsigned long color) { SetFg(color); XDrawLine(dpy, pix, gc, x0, y0, x1, y1); } static void -DrawShape(int x0, int y0, int x1, int y1, int color) +DrawShape(int x0, int y0, int x1, int y1, unsigned long color) { int x = x0 < x1 ? x0 : x1; int y = y0 < y1 ? y0 : y1; @@ -339,37 +601,82 @@ DrawShape(int x0, int y0, int x1, int y1, int color) } } +/* Scanline flood fill: the stack holds one seed per run, not four neighbours + * per pixel, so its size follows the shape's perimeter, not its area. */ +struct Seed { int x, y; }; + static void -FloodFill(int x, int y, int color) +FloodFill(int x, int y, unsigned long color) { XImage *im; unsigned long old; - int *stack, sp = 0, max = imgW * imgH; + struct Seed *stack; + int sp = 0, cap = 256; if (x < 0 || y < 0 || x >= imgW || y >= imgH) return; if ((im = XGetImage(dpy, pix, 0, 0, imgW, imgH, AllPlanes, ZPixmap)) == NULL) return; old = XGetPixel(im, x, y); - if (old == palette[color].pixel) { + if (old == color) { XDestroyImage(im); return; } - if ((stack = malloc(sizeof(int) * (size_t) max * 4)) == NULL) { + stack = malloc(sizeof(*stack) * (size_t) cap); + if (stack == NULL) { XDestroyImage(im); return; } - stack[sp++] = y * imgW + x; + stack[sp].x = x; + stack[sp].y = y; + sp++; while (sp > 0) { - int p = stack[--sp], px = p % imgW, py = p / imgW; + int cx, cy, x1, x2, i, dy; - if (XGetPixel(im, px, py) != old) + sp--; + cx = stack[sp].x; + cy = stack[sp].y; + if (XGetPixel(im, cx, cy) != old) continue; - XPutPixel(im, px, py, palette[color].pixel); - if (px > 0) stack[sp++] = p - 1; - if (px < imgW - 1) stack[sp++] = p + 1; - if (py > 0) stack[sp++] = p - imgW; - if (py < imgH - 1) stack[sp++] = p + imgW; + x1 = cx; + while (x1 > 0 && XGetPixel(im, x1 - 1, cy) == old) + x1--; + x2 = cx; + while (x2 < imgW - 1 && XGetPixel(im, x2 + 1, cy) == old) + x2++; + for (i = x1; i <= x2; i++) + XPutPixel(im, i, cy, color); + for (dy = -1; dy <= 1; dy += 2) { + int ny = cy + dy; + int inrun = 0; + + if (ny < 0 || ny >= imgH) + continue; + for (i = x1; i <= x2; i++) { + if (XGetPixel(im, i, ny) == old) { + if (!inrun) { + if (sp == cap) { + struct Seed *ns; + + cap *= 2; + ns = realloc(stack, sizeof(*stack) * (size_t) cap); + if (ns == NULL) { + free(stack); + XDestroyImage(im); + return; + } + stack = ns; + } + stack[sp].x = i; + stack[sp].y = ny; + sp++; + inrun = 1; + } + } else { + inrun = 0; + } + } + } } free(stack); XPutImage(dpy, pix, gc, im, 0, 0, 0, 0, imgW, imgH); @@ -384,20 +691,65 @@ InvertImage(void) if ((im = XGetImage(dpy, pix, 0, 0, imgW, imgH, AllPlanes, ZPixmap)) == NULL) return; - for (y = 0; y < imgH; y++) - for (x = 0; x < imgW; x++) { - unsigned char r, g, b; - XColor c; + if (truecolor) { + for (y = 0; y < imgH; y++) + for (x = 0; x < imgW; x++) { + unsigned r, g, b; - if (PixelRGB(XGetPixel(im, x, y), &r, &g, &b) < 0) - continue; - c.red = (unsigned short) ((255 - r) << 8); - c.green = (unsigned short) ((255 - g) << 8); - c.blue = (unsigned short) ((255 - b) << 8); - c.flags = DoRed | DoGreen | DoBlue; - if (XAllocColor(dpy, DefaultColormap(dpy, 0), &c)) - XPutPixel(im, x, y, c.pixel); + PixelToRGB(XGetPixel(im, x, y), &r, &g, &b); + XPutPixel(im, x, y, RGBToPixel(255 - r, 255 - g, 255 - b)); + } + } else { + unsigned long *keys = malloc(sizeof(unsigned long) * (size_t) imgW * imgH); + unsigned char *krgb = NULL; + unsigned long *knew = NULL; + int nkeys = 0; + + if (keys != NULL) { + for (y = 0; y < imgH; y++) + for (x = 0; x < imgW; x++) + keys[nkeys++] = XGetPixel(im, x, y); + qsort(keys, (size_t) nkeys, sizeof(unsigned long), CmpUL); + { + int i, j = 0; + + for (i = 0; i < nkeys; i++) + if (i == 0 || keys[i] != keys[i - 1]) + keys[j++] = keys[i]; + nkeys = j; + } + krgb = malloc((size_t) nkeys * 3); + knew = malloc(sizeof(unsigned long) * (size_t) nkeys); + if (krgb != NULL && knew != NULL) { + int i; + + BatchQuery(keys, nkeys, krgb); + for (i = 0; i < nkeys * 3; i++) + krgb[i] = (unsigned char) (255 - krgb[i]); + BatchAlloc(krgb, nkeys, knew); + } } + for (y = 0; y < imgH; y++) + for (x = 0; x < imgW; x++) { + unsigned long px = XGetPixel(im, x, y); + + if (keys != NULL && knew != NULL) { + unsigned long *hit = bsearch(&px, keys, (size_t) nkeys, + sizeof(unsigned long), CmpUL); + + if (hit != NULL) + XPutPixel(im, x, y, knew[hit - keys]); + } else { + unsigned r, g, b; + + PixelToRGB(px, &r, &g, &b); + XPutPixel(im, x, y, RGBToPixel(255 - r, 255 - g, 255 - b)); + } + } + free(keys); + free(krgb); + free(knew); + } XPutImage(dpy, pix, gc, im, 0, 0, 0, 0, imgW, imgH); XDestroyImage(im); } @@ -405,26 +757,55 @@ InvertImage(void) static void FlipHorizontal(void) { - Pixmap tmp = XCreatePixmap(dpy, DefaultRootWindow(dpy), imgW, imgH, - DefaultDepth(dpy, 0)); + Pixmap tmp = XCreatePixmap(dpy, RootWindowOfScreen(scr), imgW, imgH, depth); + int x; + if (tmp == None) + return; XCopyArea(dpy, pix, tmp, gc, 0, 0, imgW, imgH, 0, 0); - { - int x; - - for (x = 0; x < imgW; x++) - XCopyArea(dpy, tmp, pix, gc, x, 0, 1, imgH, imgW - 1 - x, 0); - } + for (x = 0; x < imgW; x++) + XCopyArea(dpy, tmp, pix, gc, x, 0, 1, imgH, imgW - 1 - x, 0); XFreePixmap(dpy, tmp); } +static void +Redraw(void) +{ + if (canvas != NULL && XtWindow(canvas) != None) + XClearArea(dpy, XtWindow(canvas), 0, 0, imgW, imgH, True); +} + +static void +SetTitle(void) +{ + char title[600]; + const char *name = curPath[0] ? strrchr(curPath, '/') : NULL; + + name = (name != NULL) ? name + 1 : (curPath[0] ? curPath : PaintMsg(24, "untitled")); + snprintf(title, sizeof title, "%s - dtpaint", name); + XtVaSetValues(top, XmNtitle, title, NULL); +} + static void NewImage(void) { - XSetForeground(dpy, gc, palette[bg].pixel); + XSetForeground(dpy, gc, bgPix); XFillRectangle(dpy, pix, gc, 0, 0, imgW, imgH); - XCopyArea(dpy, pix, snap, gc, 0, 0, imgW, imgH, 0, 0); - XClearArea(dpy, XtWindow(canvas), 0, 0, imgW, imgH, True); + Snapshot(); + dirty = 0; + curPath[0] = '\0'; + SetTitle(); + Redraw(); +} + +static void +ClearImage(void) +{ + Snapshot(); + XSetForeground(dpy, gc, bgPix); + XFillRectangle(dpy, pix, gc, 0, 0, imgW, imgH); + dirty = 1; + Redraw(); } /* ----------------------------------------------------------------- events */ @@ -433,10 +814,37 @@ static void StatusPos(int x, int y) { char buf[96]; + XmString s; snprintf(buf, sizeof buf, "%d,%d", x, y); - XtVaSetValues(statusPos, XmNlabelString, - XmStringCreateLocalized(buf), NULL); + s = XmStringCreateLocalized(buf); + XtVaSetValues(statusPos, XmNlabelString, s, NULL); + XmStringFree(s); +} + +/* the foreground/background indicator: fg square in front, bg behind */ +static void +FgBgExpose(Widget w, XtPointer cd, XtPointer call) +{ + XmDrawingAreaCallbackStruct *c = (XmDrawingAreaCallbackStruct *) call; + + (void) cd; + if (c->reason != XmCR_EXPOSE) + return; + XSetForeground(dpy, gc, bgPix); + XFillRectangle(dpy, XtWindow(w), gc, 14, 14, 18, 18); + XSetForeground(dpy, gc, fgPix); + XFillRectangle(dpy, XtWindow(w), gc, 2, 2, 18, 18); + XSetForeground(dpy, gc, BlackPixelOfScreen(scr)); + XDrawRectangle(dpy, XtWindow(w), gc, 2, 2, 17, 17); + XDrawRectangle(dpy, XtWindow(w), gc, 14, 14, 17, 17); +} + +static void +ShowColors(void) +{ + if (fgbg != NULL && XtWindow(fgbg) != None) + XClearArea(dpy, XtWindow(fgbg), 0, 0, 34, 34, True); } static void @@ -453,24 +861,30 @@ CanvasExpose(Widget w, XtPointer cd, XtPointer call) static void CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) { - int color, x, y; + unsigned long color; + int x, y; (void) w; (void) cd; (void) keep; switch (ev->type) { case ButtonPress: if (ev->xbutton.button != Button1 && ev->xbutton.button != Button3) return; - color = (ev->xbutton.button == Button3) ? bg : fg; x = ev->xbutton.x; y = ev->xbutton.y; + /* the drawing area is exactly the image; a click outside it + * must never reach XGetImage/XDraw* on the pixmap */ + if (x < 0 || y < 0 || x >= imgW || y >= imgH) + return; + color = (ev->xbutton.button == Button3) ? bgPix : fgPix; sx = lx = x; sy = ly = y; - curx = x; cury = y; StatusPos(x, y); drawing = 1; switch (tool) { case T_FILL: + Snapshot(); FloodFill(x, y, color); + dirty = 1; drawing = 0; break; case T_PICK: @@ -480,62 +894,76 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) if (im != NULL) { unsigned long p = XGetPixel(im, 0, 0); - int i; - for (i = 0; i < PAL_N; i++) - if (palette[i].pixel == p) - fg = i; + if (ev->xbutton.button == Button3) + bgPix = p; + else + fgPix = p; + ShowColors(); XDestroyImage(im); } } drawing = 0; break; case T_ERASER: - DrawDab(x, y, 4, bg); + Snapshot(); + DrawDab(x, y, 4, bgPix); + dirty = 1; break; case T_BRUSH: + Snapshot(); DrawDab(x, y, 3, color); + dirty = 1; break; case T_PENCIL: + Snapshot(); SetFg(color); XDrawPoint(dpy, pix, gc, x, y); + dirty = 1; break; default: - XCopyArea(dpy, pix, snap, gc, 0, 0, imgW, imgH, 0, 0); + Snapshot(); break; } break; case MotionNotify: x = ev->xmotion.x; y = ev->xmotion.y; - curx = x; cury = y; StatusPos(x, y); if (!drawing) return; - color = (ev->xmotion.state & Button3Mask) ? bg : fg; + if (x < 0) x = 0; + if (y < 0) y = 0; + if (x >= imgW) x = imgW - 1; + if (y >= imgH) y = imgH - 1; + color = (ev->xmotion.state & Button3Mask) ? bgPix : fgPix; switch (tool) { case T_PENCIL: DrawLineTo(lx, ly, x, y, color); + dirty = 1; break; case T_BRUSH: DrawDab(x, y, 3, color); + dirty = 1; break; case T_ERASER: - DrawDab(x, y, 4, bg); + DrawDab(x, y, 4, bgPix); + dirty = 1; break; case T_LINE: case T_RECT: case T_ELLIPSE: case T_ROUNDRECT: RestoreSnap(); DrawShape(sx, sy, x, y, color); + dirty = 1; break; default: break; } lx = x; ly = y; - XClearArea(dpy, XtWindow(canvas), 0, 0, imgW, imgH, True); + Redraw(); break; case ButtonRelease: drawing = 0; - XClearArea(dpy, XtWindow(canvas), 0, 0, imgW, imgH, True); + Redraw(); break; default: break; @@ -546,10 +974,8 @@ static void ToolChanged(Widget w, XtPointer data, XtPointer call) { (void) call; - if (XmToggleButtonGetState(w)) { + if (XmToggleButtonGetState(w)) tool = (int) (long) data; - fprintf(stderr, "dtpaint: tool %s\n", toolNames[tool]); - } } static void @@ -561,16 +987,18 @@ SwatchPress(Widget w, XtPointer data, XEvent *ev, Boolean *keep) if (ev->type != ButtonPress) return; if (ev->xbutton.button == Button1) - fg = idx; + fgPix = palette[idx].pixel; else if (ev->xbutton.button == Button3) - bg = idx; + bgPix = palette[idx].pixel; + ShowColors(); } static void SwatchActivate(Widget w, XtPointer data, XtPointer call) { (void) w; (void) call; - fg = (int) (long) data; + fgPix = palette[(int) (long) data].pixel; + ShowColors(); } /* ------------------------------------------------------------------ menus */ @@ -578,51 +1006,175 @@ SwatchActivate(Widget w, XtPointer data, XtPointer call) enum { C_NEW, C_OPEN, C_SAVE, C_SAVEAS, C_EXIT, C_UNDO, C_CLEAR, C_INVERT, C_FLIP, - C_TOOLS, C_COLORS, C_STATUS, C_ABOUT + C_TOOLS, C_COLORS, C_STATUS, C_HELP, C_ABOUT }; +enum { A_NEW, A_OPEN, A_EXIT }; + static void FileDialog(int save); +static void PerformAction(int action); + +/* OK on a message dialog: destroy the whole dialog shell. */ +static void +DestroyDialog(Widget w, XtPointer data, XtPointer call) +{ + Widget sh = w; + + (void) data; (void) call; + while (sh != NULL && !XtIsShell(sh)) + sh = XtParent(sh); + if (sh != NULL) + XtDestroyWidget(sh); +} + +static void +ShowError(int msgid, const char *path) +{ + char buf[700]; + Widget d; + XmString s; + + snprintf(buf, sizeof buf, PaintMsg(msgid, "%s"), path); + d = XmCreateErrorDialog(top, "error", NULL, 0); + s = XmStringCreateLocalized(buf); + XtVaSetValues(d, XmNmessageString, s, NULL); + XmStringFree(s); + XtUnmanageChild(XmMessageBoxGetChild(d, XmDIALOG_CANCEL_BUTTON)); + XtUnmanageChild(XmMessageBoxGetChild(d, XmDIALOG_HELP_BUTTON)); + XtAddCallback(d, XmNokCallback, DestroyDialog, NULL); + XtManageChild(d); +} + +static void +ShowInfo(int bodyId, const char *bodyFb, int titleId, const char *titleFb) +{ + Widget d = XmCreateInformationDialog(top, "info", NULL, 0); + XmString s = Msg(bodyId, bodyFb); + + XtVaSetValues(d, XmNmessageString, s, NULL); + XmStringFree(s); + s = Msg(titleId, titleFb); + XtVaSetValues(d, XmNdialogTitle, s, NULL); + XmStringFree(s); + XtUnmanageChild(XmMessageBoxGetChild(d, XmDIALOG_CANCEL_BUTTON)); + XtUnmanageChild(XmMessageBoxGetChild(d, XmDIALOG_HELP_BUTTON)); + XtAddCallback(d, XmNokCallback, DestroyDialog, NULL); + XtManageChild(d); +} + +/* Ask before throwing away unsaved work (New / Open / Exit). */ +static void +DiscardAnswer(Widget w, XtPointer data, XtPointer call) +{ + XmAnyCallbackStruct *c = (XmAnyCallbackStruct *) call; + + (void) data; + if (c->reason == XmCR_OK) + PerformAction(pendingAction); + DestroyDialog(w, NULL, NULL); +} + +static void +MaybeDiscard(int action) +{ + Widget d; + XmString s; + char buf[700]; + const char *name = curPath[0] ? strrchr(curPath, '/') : NULL; + + if (!dirty) { + PerformAction(action); + return; + } + pendingAction = action; + name = (name != NULL) ? name + 1 : (curPath[0] ? curPath : PaintMsg(24, "untitled")); + snprintf(buf, sizeof buf, PaintMsg(28, "Save changes to \"%s\"?"), name); + d = XmCreateQuestionDialog(top, "discard", NULL, 0); + s = XmStringCreateLocalized(buf); + XtVaSetValues(d, XmNmessageString, s, NULL); + XmStringFree(s); + s = Msg(29, "Discard"); + XtVaSetValues(d, XmNokLabelString, s, NULL); + XmStringFree(s); + s = Msg(30, "Keep"); + XtVaSetValues(d, XmNcancelLabelString, s, NULL); + XmStringFree(s); + XtUnmanageChild(XmMessageBoxGetChild(d, XmDIALOG_HELP_BUTTON)); + XtAddCallback(d, XmNokCallback, DiscardAnswer, NULL); + XtAddCallback(d, XmNcancelCallback, DiscardAnswer, NULL); + XtManageChild(d); +} + +static void +DoSave(const char *path) +{ + if (SaveBMP(path) == 0) { + snprintf(curPath, sizeof curPath, "%s", path); + dirty = 0; + SetTitle(); + } else { + ShowError(27, path); + } +} + +static void +PerformAction(int action) +{ + switch (action) { + case A_NEW: + NewImage(); + break; + case A_OPEN: + FileDialog(0); + break; + case A_EXIT: + exit(0); + break; + } +} static void Command(Widget w, XtPointer data, XtPointer call) { - char path[512]; - (void) w; (void) call; switch ((int) (long) data) { case C_NEW: - NewImage(); + MaybeDiscard(A_NEW); break; case C_OPEN: - FileDialog(0); + MaybeDiscard(A_OPEN); break; case C_SAVE: - snprintf(path, sizeof path, "%s/dtpaint.bmp", - getenv("HOME") ? getenv("HOME") : "."); - if (SaveBMP(path) == 0) - fprintf(stderr, "dtpaint: saved %s\n", path); + if (curPath[0]) + DoSave(curPath); else - fprintf(stderr, "dtpaint: cannot save %s\n", path); + FileDialog(1); break; case C_SAVEAS: FileDialog(1); break; case C_EXIT: - exit(0); + MaybeDiscard(A_EXIT); + break; case C_UNDO: RestoreSnap(); - XClearArea(dpy, XtWindow(canvas), 0, 0, imgW, imgH, True); + dirty = 1; + Redraw(); break; case C_CLEAR: - NewImage(); + ClearImage(); break; case C_INVERT: + Snapshot(); InvertImage(); - XClearArea(dpy, XtWindow(canvas), 0, 0, imgW, imgH, True); + dirty = 1; + Redraw(); break; case C_FLIP: + Snapshot(); FlipHorizontal(); - XClearArea(dpy, XtWindow(canvas), 0, 0, imgW, imgH, True); + dirty = 1; + Redraw(); break; case C_TOOLS: toolsShown = !toolsShown; @@ -644,18 +1196,16 @@ Command(Widget w, XtPointer data, XtPointer call) XtUnmanageChild(statusPos); } break; + case C_HELP: + ShowInfo(34, + "Pick a tool on the left and a colour below it, then draw on " + "the canvas. The left button draws with the foreground " + "colour, the right button with the background colour. " + "Ctrl+Z undoes the last step.", + 33, "Help Topics"); + break; case C_ABOUT: - { - Widget d = XmCreateInformationDialog(top, "about", NULL, 0); - - XtVaSetValues(d, XmNmessageString, - XmStringCreateLocalized("dtpaint\nMCDE"), - XmNdialogTitle, - XmStringCreateLocalized(PaintMsg(22, "About dtpaint")), NULL); - XtUnmanageChild(XmMessageBoxGetChild(d, - XmDIALOG_CANCEL_BUTTON)); - XtManageChild(d); - } + ShowInfo(25, "dtpaint - MCDE", 22, "About dtpaint"); break; } } @@ -668,15 +1218,20 @@ FileOk(Widget w, XtPointer data, XtPointer call) if (XmStringGetLtoR(((XmFileSelectionBoxCallbackStruct *) call)->value, XmSTRING_DEFAULT_CHARSET, &path) && path != NULL) { - if (save ? (SaveBMP(path) == 0) : (OpenBMP(path) == 0)) - fprintf(stderr, "dtpaint: %s %s\n", - save ? "saved" : "opened", path); - else - fprintf(stderr, "dtpaint: cannot %s %s\n", - save ? "save" : "open", path); + if (save) { + DoSave(path); + } else { + if (OpenBMP(path) == 0) { + snprintf(curPath, sizeof curPath, "%s", path); + dirty = 0; + Snapshot(); + SetTitle(); + Redraw(); + } else { + ShowError(26, path); + } + } XtFree(path); - if (!save) - XClearArea(dpy, XtWindow(canvas), 0, 0, imgW, imgH, True); } XtDestroyWidget(XtParent(w)); } @@ -692,55 +1247,63 @@ static void FileDialog(int save) { Widget d = XmCreateFileSelectionDialog(top, "file", NULL, 0); + XmString s; XtAddCallback(d, XmNokCallback, FileOk, (XtPointer) (long) save); XtAddCallback(d, XmNcancelCallback, FileCancel, NULL); XtVaSetValues(d, XmNfileTypeMask, XmFILE_REGULAR, NULL); + s = Msg(save ? 32 : 31, save ? "Save As" : "Open"); + XtVaSetValues(d, XmNdialogTitle, s, NULL); + XmStringFree(s); + XtUnmanageChild(XmFileSelectionBoxGetChild(d, XmDIALOG_HELP_BUTTON)); XtManageChild(d); } - static Widget AddMenu(Widget bar, const char *name) { Widget shell = XmCreatePulldownMenu(bar, (char *) name, NULL, 0); - XtVaCreateManagedWidget(name, xmCascadeButtonWidgetClass, bar, + XtVaCreateManagedWidget((char *) name, xmCascadeButtonWidgetClass, bar, XmNsubMenuId, shell, NULL); return shell; } static void -AddItem(Widget shell, const char *label, const char *accel, int cmd, int sep) +AddItem(Widget shell, const char *label, const char *accel, + const char *accelText, int cmd, int sep, int sensitive) { + Widget b; + if (sep) { XtVaCreateManagedWidget("sep", xmSeparatorWidgetClass, shell, NULL); return; } - { - Widget b = XtVaCreateManagedWidget(label, xmPushButtonWidgetClass, - shell, NULL); + b = XtVaCreateManagedWidget((char *) label, xmPushButtonWidgetClass, shell, + XmNsensitive, sensitive, NULL); + XtAddCallback(b, XmNactivateCallback, Command, (XtPointer) (long) cmd); + if (accel != NULL) + XtVaSetValues(b, XmNaccelerator, accel, NULL); + if (accelText != NULL) { + XmString s = XmStringCreateLocalized((String) accelText); - XtAddCallback(b, XmNactivateCallback, Command, - (XtPointer) (long) cmd); - if (accel != NULL) - XtVaSetValues(b, XmNaccelerator, accel, NULL); + XtVaSetValues(b, XmNacceleratorText, s, NULL); + XmStringFree(s); } } /* ------------------------------------------------------------------ icons */ static void -Glyph(Display *d, Pixmap p, int t) +Glyph(Display *d, Pixmap p, int t, unsigned long bg) { XGCValues gv; GC k; - gv.foreground = BlackPixel(d, 0); + gv.foreground = bg; k = XCreateGC(d, p, GCForeground, &gv); - XSetForeground(d, k, WhitePixel(d, 0)); XFillRectangle(d, p, k, 0, 0, 16, 16); - XSetForeground(d, k, BlackPixel(d, 0)); + XSetForeground(d, k, BlackPixelOfScreen(scr)); switch (t) { case T_FREESEL: XDrawLine(d, p, k, 3, 4, 8, 2); @@ -821,13 +1384,13 @@ main(int argc, char **argv) { /* before the first PaintMsg(): the catalog is opened for the locale */ (void) setlocale(LC_ALL, ""); - /* the compound strings of the menus carry UTF-8 (ü in "Menü") */ XtSetLanguageProc(NULL, NULL, NULL); XtAppContext app; Widget menubarW; XGCValues gv; char hex[8]; int i, selftest = 0; + unsigned long toolbg; for (i = 1; i < argc; i++) if (strcmp(argv[i], "-selftest") == 0) @@ -835,45 +1398,82 @@ main(int argc, char **argv) top = XtVaAppInitialize(&app, "Dtpaint", NULL, 0, &argc, argv, NULL, NULL); dpy = XtDisplay(top); + InitColor(); for (i = 0; i < PAL_N; i++) { XColor c; snprintf(hex, sizeof hex, "#%s", palHex[i]); - if (!XParseColor(dpy, DefaultColormap(dpy, 0), hex, &c) || - !XAllocColor(dpy, DefaultColormap(dpy, 0), &c)) { - c.pixel = (i == 0) ? BlackPixel(dpy, 0) : WhitePixel(dpy, 0); + if (!XParseColor(dpy, cmap, hex, &c) || + !XAllocColor(dpy, cmap, &c)) { + c.pixel = (i == 0) ? BlackPixelOfScreen(scr) : WhitePixelOfScreen(scr); } palette[i] = c; } - pix = XCreatePixmap(dpy, DefaultRootWindow(dpy), imgW, imgH, - DefaultDepth(dpy, 0)); - snap = XCreatePixmap(dpy, DefaultRootWindow(dpy), imgW, imgH, - DefaultDepth(dpy, 0)); - gv.foreground = palette[0].pixel; - gv.background = palette[14].pixel; + fgPix = palette[0].pixel; + bgPix = palette[14].pixel; + pix = XCreatePixmap(dpy, RootWindowOfScreen(scr), imgW, imgH, depth); + snap = XCreatePixmap(dpy, RootWindowOfScreen(scr), imgW, imgH, depth); + if (pix == None || snap == None) { + fprintf(stderr, "dtpaint: cannot create the image pixmap\n"); + return 1; + } + gv.foreground = fgPix; + gv.background = bgPix; gc = XCreateGC(dpy, pix, GCForeground | GCBackground, &gv); if (selftest) { - XSetForeground(dpy, gc, palette[14].pixel); - XFillRectangle(dpy, pix, gc, 0, 0, imgW, imgH); - DrawLineTo(10, 10, 40, 10, 0); - FloodFill(20, 40, 16); - { - XImage *im = XGetImage(dpy, pix, 0, 0, imgW, imgH, - AllPlanes, ZPixmap); - unsigned long line = XGetPixel(im, 20, 10); - unsigned long area = XGetPixel(im, 20, 40); + char tmp[128]; + XImage *a, *b; + int x, y, ok = 1; - XDestroyImage(im); - if (line == palette[0].pixel && - area == palette[16].pixel) { - printf("dtpaint selftest: PASS\n"); - return 0; - } - printf("dtpaint selftest: FAIL\n"); + XSetForeground(dpy, gc, bgPix); + XFillRectangle(dpy, pix, gc, 0, 0, imgW, imgH); + DrawLineTo(10, 10, 40, 10, fgPix); + FloodFill(20, 40, palette[16].pixel); + a = XGetImage(dpy, pix, 0, 0, imgW, imgH, AllPlanes, ZPixmap); + if (a == NULL) { + printf("dtpaint selftest: FAIL image\n"); return 1; } + if (XGetPixel(a, 20, 10) != fgPix || + XGetPixel(a, 20, 40) != palette[16].pixel) + ok = 0; + /* the D2 criterion: a BMP round trip without loss */ + snprintf(tmp, sizeof tmp, "/tmp/dtpaint-selftest-%d.bmp", (int) getpid()); + if (SaveBMP(tmp) != 0 || OpenBMP(tmp) != 0) { + ok = 0; + } else { + b = XGetImage(dpy, pix, 0, 0, imgW, imgH, AllPlanes, ZPixmap); + if (b == NULL) { + ok = 0; + } else { + for (y = 0; y < imgH && ok; y += 37) + for (x = 0; x < imgW; x += 41) + if (XGetPixel(a, x, y) != XGetPixel(b, x, y)) + ok = 0; + XDestroyImage(b); + } + } + unlink(tmp); + /* invert and flip twice return to the original */ + InvertImage(); + InvertImage(); + FlipHorizontal(); + FlipHorizontal(); + b = XGetImage(dpy, pix, 0, 0, imgW, imgH, AllPlanes, ZPixmap); + if (b == NULL) { + ok = 0; + } else { + for (y = 0; y < imgH && ok; y += 37) + for (x = 0; x < imgW; x += 41) + if (XGetPixel(a, x, y) != XGetPixel(b, x, y)) + ok = 0; + XDestroyImage(b); + } + XDestroyImage(a); + printf("dtpaint selftest: %s\n", ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; } mainw = XmCreateMainWindow(top, "main", NULL, 0); @@ -884,82 +1484,107 @@ main(int argc, char **argv) { Widget m = AddMenu(menubarW, PaintMsg(1, "File")); - AddItem(m, PaintMsg(7, "New"), "CtrlN", C_NEW, 0); - AddItem(m, PaintMsg(8, "Open..."), "CtrlO", C_OPEN, 0); - AddItem(m, PaintMsg(9, "Save"), "CtrlS", C_SAVE, 0); - AddItem(m, PaintMsg(10, "Save As..."), NULL, C_SAVEAS, 0); - AddItem(m, NULL, NULL, 0, 1); - AddItem(m, PaintMsg(11, "Exit"), "AltF4", C_EXIT, 0); + AddItem(m, PaintMsg(7, "New"), "CtrlN", "Ctrl+N", C_NEW, 0, True); + AddItem(m, PaintMsg(8, "Open..."), "CtrlO", "Ctrl+O", C_OPEN, 0, True); + AddItem(m, PaintMsg(9, "Save"), "CtrlS", "Ctrl+S", C_SAVE, 0, True); + AddItem(m, PaintMsg(10, "Save As..."), NULL, NULL, C_SAVEAS, 0, True); + AddItem(m, NULL, NULL, NULL, 0, 1, True); + AddItem(m, PaintMsg(11, "Exit"), "AltF4", "Alt+F4", C_EXIT, 0, True); m = AddMenu(menubarW, PaintMsg(2, "Edit")); - AddItem(m, PaintMsg(12, "Undo"), "CtrlZ", C_UNDO, 0); - AddItem(m, NULL, NULL, 0, 1); - AddItem(m, PaintMsg(13, "Clear Selection"), NULL, C_CLEAR, 0); + AddItem(m, PaintMsg(12, "Undo"), "CtrlZ", "Ctrl+Z", C_UNDO, 0, True); + AddItem(m, NULL, NULL, NULL, 0, 1, True); + /* needs the selection tool (D3); insensitive until it exists */ + AddItem(m, PaintMsg(13, "Clear Selection"), NULL, NULL, C_CLEAR, 0, False); m = AddMenu(menubarW, PaintMsg(3, "View")); - AddItem(m, PaintMsg(14, "Tool Box"), "CtrlT", C_TOOLS, 0); - AddItem(m, PaintMsg(15, "Color Box"), "CtrlL", C_COLORS, 0); - AddItem(m, PaintMsg(16, "Status Bar"), NULL, C_STATUS, 0); + AddItem(m, PaintMsg(14, "Tool Box"), "CtrlT", "Ctrl+T", C_TOOLS, 0, True); + AddItem(m, PaintMsg(15, "Color Box"), "CtrlL", "Ctrl+L", C_COLORS, 0, True); + AddItem(m, PaintMsg(16, "Status Bar"), NULL, NULL, C_STATUS, 0, True); m = AddMenu(menubarW, PaintMsg(4, "Image")); - AddItem(m, PaintMsg(17, "Flip Horizontal"), NULL, C_FLIP, 0); - AddItem(m, PaintMsg(18, "Invert Colors"), "CtrlI", C_INVERT, 0); - AddItem(m, PaintMsg(19, "Clear Image"), "CtrlShiftN", C_CLEAR, 0); + AddItem(m, PaintMsg(17, "Flip Horizontal"), NULL, NULL, C_FLIP, 0, True); + AddItem(m, PaintMsg(18, "Invert Colors"), "CtrlI", "Ctrl+I", C_INVERT, 0, True); + AddItem(m, PaintMsg(19, "Clear Image"), "Ctrl ShiftN", "Ctrl+Shift+N", C_CLEAR, 0, True); m = AddMenu(menubarW, PaintMsg(5, "Colors")); - AddItem(m, PaintMsg(20, "Edit Colors..."), NULL, C_ABOUT, 0); + /* needs the colour editor (D4); insensitive until it exists */ + AddItem(m, PaintMsg(20, "Edit Colors..."), NULL, NULL, C_ABOUT, 0, False); m = AddMenu(menubarW, PaintMsg(6, "Help")); - AddItem(m, PaintMsg(21, "About dtpaint..."), NULL, C_ABOUT, 0); + AddItem(m, PaintMsg(33, "Help Topics"), "CtrlF1", "Ctrl+F1", C_HELP, 0, True); + AddItem(m, NULL, NULL, NULL, 0, 1, True); + AddItem(m, PaintMsg(21, "About dtpaint..."), NULL, NULL, C_ABOUT, 0, True); } form = XtVaCreateManagedWidget("form", xmFormWidgetClass, mainw, - XmNfractionBase, 100, XmNwidth, 730, XmNheight, 540, NULL); + XmNfractionBase, 100, XmNwidth, 920, XmNheight, 560, NULL); - /* toolbox on the left, two columns of eight */ - toolbox = XtVaCreateManagedWidget("tools", xmRowColumnWidgetClass, form, - XmNleftAttachment, XmATTACH_FORM, XmNtopAttachment, XmATTACH_FORM, - XmNorientation, XmVERTICAL, XmNnumColumns, 2, - XmNpacking, XmPACK_COLUMN, XmNspacing, 1, - XmNmarginWidth, 2, XmNmarginHeight, 2, NULL); + /* a left column holds the toolbox and, below it, the colour box; the + * canvas starts to the right of the wider of the two so they never + * overlap the image */ + { + Widget left = XtVaCreateManagedWidget("left", xmFormWidgetClass, + form, XmNleftAttachment, XmATTACH_FORM, + XmNtopAttachment, XmATTACH_FORM, + XmNmarginWidth, 0, XmNmarginHeight, 0, NULL); + + toolbox = XtVaCreateManagedWidget("tools", xmRowColumnWidgetClass, left, + XmNleftAttachment, XmATTACH_FORM, XmNtopAttachment, XmATTACH_FORM, + XmNorientation, XmVERTICAL, XmNnumColumns, 2, + XmNpacking, XmPACK_COLUMN, XmNspacing, 1, + XmNmarginWidth, 2, XmNmarginHeight, 2, + XmNradioBehavior, True, XmNradioAlwaysOne, True, NULL); + leftcol = left; + } + XtVaGetValues(toolbox, XmNbackground, &toolbg, NULL); for (i = 0; i < T_NONE; i++) { Widget b; - Pixmap p = XCreatePixmap(dpy, DefaultRootWindow(dpy), 16, 16, - DefaultDepth(dpy, 0)); + Pixmap p = XCreatePixmap(dpy, RootWindowOfScreen(scr), 16, 16, depth); - Glyph(dpy, p, i); + Glyph(dpy, p, i, toolbg); b = XtVaCreateManagedWidget(toolNames[i], xmToggleButtonWidgetClass, toolbox, XmNlabelType, XmPIXMAP, XmNlabelPixmap, p, - XmNindicatorType, XmN_OF_MANY, XmNshadowThickness, 1, + XmNindicatorOn, False, XmNshadowThickness, 1, XmNmarginWidth, 1, XmNmarginHeight, 1, - XmNwidth, 24, XmNheight, 24, NULL); + XmNwidth, 24, XmNheight, 24, XmNrecomputeSize, False, NULL); XtAddCallback(b, XmNvalueChangedCallback, ToolChanged, (XtPointer) (long) i); if (i == T_PENCIL) XmToggleButtonSetState(b, True, False); } - /* colour box under the toolbox: two rows of fourteen */ - colorbox = XtVaCreateManagedWidget("colors", xmRowColumnWidgetClass, form, + /* colour box under the toolbox: the fg/bg indicator at the left, then + * two rows of fourteen 16x16 swatches */ + colorbox = XtVaCreateManagedWidget("colors", xmRowColumnWidgetClass, leftcol, XmNleftAttachment, XmATTACH_FORM, XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, toolbox, - XmNorientation, XmVERTICAL, XmNspacing, 1, + XmNtopOffset, 4, + XmNorientation, XmHORIZONTAL, XmNspacing, 4, XmNmarginWidth, 2, XmNmarginHeight, 2, NULL); + fgbg = XtVaCreateManagedWidget("fgbg", xmDrawingAreaWidgetClass, + colorbox, XmNwidth, 34, XmNheight, 34, XmNrecomputeSize, False, + XmNmarginWidth, 0, XmNmarginHeight, 0, NULL); + XtAddCallback(fgbg, XmNexposeCallback, FgBgExpose, NULL); { + Widget rows = XtVaCreateManagedWidget("rows", xmRowColumnWidgetClass, + colorbox, XmNorientation, XmVERTICAL, XmNspacing, 1, NULL); int r, c; for (r = 0; r < PAL_ROWS; r++) { Widget row = XtVaCreateManagedWidget("row", - xmRowColumnWidgetClass, colorbox, XmNorientation, + xmRowColumnWidgetClass, rows, XmNorientation, XmHORIZONTAL, XmNspacing, 1, NULL); for (c = 0; c < PAL_COLS; c++) { Widget b; int idx = r * PAL_COLS + c; + XmString empty = XmStringCreateLocalized(""); b = XtVaCreateManagedWidget("swatch", xmPushButtonWidgetClass, row, XmNbackground, palette[idx].pixel, XmNwidth, 16, XmNheight, 16, + XmNrecomputeSize, False, XmNshadowThickness, 1, XmNmarginWidth, 0, XmNmarginHeight, 0, - XmNlabelString, - XmStringCreateLocalized(""), NULL); + XmNlabelString, empty, NULL); + XmStringFree(empty); XtAddCallback(b, XmNactivateCallback, SwatchActivate, (XtPointer) (long) idx); XtAddEventHandler(b, ButtonPressMask, False, @@ -968,28 +1593,42 @@ main(int argc, char **argv) } } - /* status line at the bottom, canvas between toolbox and right edge */ + /* status line at the bottom; the canvas scrolls between toolbox and the + * right edge so a large image is reachable, not clipped */ statusHelp = XtVaCreateManagedWidget("help", xmLabelWidgetClass, form, XmNbottomAttachment, XmATTACH_FORM, XmNleftAttachment, XmATTACH_FORM, XmNalignment, XmALIGNMENT_BEGINNING, NULL); - XtVaSetValues(statusHelp, XmNlabelString, XmStringCreateLocalized( - PaintMsg(23, "For Help, click Help Topics on the Help Menu.")), NULL); + { + XmString s = Msg(23, "For Help, click Help Topics on the Help Menu."); + + XtVaSetValues(statusHelp, XmNlabelString, s, NULL); + XmStringFree(s); + } statusPos = XtVaCreateManagedWidget("pos", xmLabelWidgetClass, form, XmNbottomAttachment, XmATTACH_FORM, XmNrightAttachment, XmATTACH_FORM, - XmNalignment, XmALIGNMENT_END, NULL); - XtVaSetValues(statusPos, XmNlabelString, - XmStringCreateLocalized("0,0"), NULL); + XmNalignment, XmALIGNMENT_END, XmNrecomputeSize, False, + XmNwidth, 90, NULL); + { + XmString s = XmStringCreateLocalized("0,0"); - canvas = XtVaCreateManagedWidget("canvas", xmDrawingAreaWidgetClass, + XtVaSetValues(statusPos, XmNlabelString, s, NULL); + XmStringFree(s); + } + + scroll = XtVaCreateManagedWidget("scroll", xmScrolledWindowWidgetClass, form, XmNtopAttachment, XmATTACH_FORM, - XmNleftAttachment, XmATTACH_WIDGET, XmNleftWidget, toolbox, + XmNleftAttachment, XmATTACH_WIDGET, XmNleftWidget, leftcol, XmNbottomAttachment, XmATTACH_WIDGET, XmNbottomWidget, statusHelp, - XmNwidth, imgW, XmNheight, imgH, NULL); + XmNrightAttachment, XmATTACH_FORM, + XmNscrollingPolicy, XmAUTOMATIC, + XmNscrollBarDisplayPolicy, XmAS_NEEDED, NULL); + canvas = XtVaCreateManagedWidget("canvas", xmDrawingAreaWidgetClass, + scroll, XmNwidth, imgW, XmNheight, imgH, NULL); XtAddCallback(canvas, XmNexposeCallback, CanvasExpose, NULL); XtAddEventHandler(canvas, ButtonPressMask | ButtonReleaseMask | PointerMotionMask | ButtonMotionMask, False, CanvasInput, NULL); - XtVaSetValues(top, XmNtitle, "untitled - dtpaint", NULL); + SetTitle(); XtRealizeWidget(top); NewImage(); XtAppMainLoop(app); diff --git a/programs/dtpaint/dtpaint.msg b/programs/dtpaint/dtpaint.msg index d79dacbc..8f1f233f 100644 --- a/programs/dtpaint/dtpaint.msg +++ b/programs/dtpaint/dtpaint.msg @@ -25,3 +25,14 @@ $set 1 21 About dtpaint... 22 About dtpaint 23 For Help, click Help Topics on the Help Menu. +24 untitled +25 dtpaint - MCDE +26 Cannot open %s. +27 Cannot save %s. +28 Save changes to "%s"? +29 Discard +30 Keep +31 Open +32 Save As +33 Help Topics +34 Pick a tool on the left and a colour below it, then draw on the canvas. The left button draws with the foreground colour, the right button with the background colour. Ctrl+Z undoes the last step. diff --git a/programs/localized/de_DE.UTF-8/msg/dtpaint.msg b/programs/localized/de_DE.UTF-8/msg/dtpaint.msg index 9d35c5fc..87f104f5 100644 --- a/programs/localized/de_DE.UTF-8/msg/dtpaint.msg +++ b/programs/localized/de_DE.UTF-8/msg/dtpaint.msg @@ -1,4 +1,5 @@ -$ MCDE dtpaint message catalog, German. +$ MCDE dtpaint message catalog, German. The core font has no UTF-8 rendition, +$ so umlauts are transliterated (ae/oe/ue), as in the other MCDE catalogs. $ $set 1 @@ -9,11 +10,11 @@ $set 1 5 Farben 6 Hilfe 7 Neu -8 Öffnen... +8 Oeffnen... 9 Speichern 10 Speichern unter... 11 Beenden -12 Rückgängig +12 Rueckgaengig 13 Auswahl aufheben 14 Werkzeuge 15 Farbpalette @@ -22,6 +23,17 @@ $set 1 18 Farben umkehren 19 Bild leeren 20 Farben bearbeiten... -21 Über dtpaint... -22 Über dtpaint +21 Ueber dtpaint... +22 Ueber dtpaint 23 Hilfe: Hilfe-Themen im Hilfe-Menue. +24 unbenannt +25 dtpaint - MCDE +26 %s kann nicht geoeffnet werden. +27 %s kann nicht gespeichert werden. +28 Aenderungen an "%s" speichern? +29 Verwerfen +30 Behalten +31 Oeffnen +32 Speichern unter +33 Hilfe-Themen +34 Waehlen Sie links ein Werkzeug und darunter eine Farbe, dann zeichnen Sie auf der Flaeche. Die linke Taste zeichnet mit der Vordergrundfarbe, die rechte mit der Hintergrundfarbe. Strg+Z macht den letzten Schritt rueckgaengig. From f5999063111718dd9d8fbe0de9f4bf78c839b69b Mon Sep 17 00:00:00 2001 From: lotherk Date: Sat, 21 Nov 2026 21:42:46 +0000 Subject: [PATCH 03/22] mcde dtsystemsettings: include ScrolledW.h (missing, broke every full build) main.c uses xmScrolledWindowWidgetClass (paneScroll, added in ad02893dde) but never included , so any full make install / the MCDE PLIST gate died at dtsystemsettings-main.o with 'xmScrolledWindowWidgetClass undeclared'. One include, alphabetical among the Xm headers. Found while running the PLIST gate for the dtpaint review (t0704); -fsyntax-only clean. --- programs/dtsystemsettings/main.c | 1 + 1 file changed, 1 insertion(+) diff --git a/programs/dtsystemsettings/main.c b/programs/dtsystemsettings/main.c index 3f2a3755..ca16cccb 100644 --- a/programs/dtsystemsettings/main.c +++ b/programs/dtsystemsettings/main.c @@ -36,6 +36,7 @@ #include #include #include +#include #include #include #include From fd66cdb200c6cba27d17d6b1d57eb7ddb63deae2 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 05:50:22 +0000 Subject: [PATCH 04/22] MCDE dtpaint: Ctrl+S kept the path and title (t0704 follow-up) DoSave(curPath) passed curPath as both the destination and the source of snprintf, which is undefined; glibc emptied it, so after Ctrl+S the title fell back to 'untitled' and the next Save opened Save As again. Copy only when the pointers differ. Found while verifying the PseudoColor path on Xvfb depth 8 (4-colour BMP round trip exact, selftest PASS); recorded in AGENTS.md. --- AGENTS.md | 5 ++++- programs/dtpaint/dtpaint.c | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index efb1fffe..f8e8b6a4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,7 +80,10 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt and refreshed after a load, and Open/Save/Invert convert colours through the visual's masks on TrueColor (or in batches otherwise), never one X round trip per pixel (measured 2026-11-21: open 18.3 s -> 0.02 s, invert - 14.9 s -> 0.05 s, save 6.3 s -> 0.23 s on a 1024x768 BMP). + 14.9 s -> 0.05 s, save 6.3 s -> 0.23 s on a 1024x768 BMP; PseudoColor + measured 2026-11-22 on Xvfb depth 8: 4-colour BMP round trip exact, + selftest PASS -- a picture with more colours than the 256-cell colormap + holds loses the excess, as any 8-bit paint must). McdeSys has a catalog too (`lib/McdeSys/mcdesys.msg`, `lib/McdeSys/ text.c`, `mcde_sys_msg`): common.c's tool errors ask it for their sentence (messages 1-9: not there, cannot start, failed with status, no pipe, no diff --git a/programs/dtpaint/dtpaint.c b/programs/dtpaint/dtpaint.c index ec319d18..9c0d819b 100644 --- a/programs/dtpaint/dtpaint.c +++ b/programs/dtpaint/dtpaint.c @@ -1109,7 +1109,10 @@ static void DoSave(const char *path) { if (SaveBMP(path) == 0) { - snprintf(curPath, sizeof curPath, "%s", path); + /* C_SAVE passes curPath itself; snprintf onto the same buffer + * is undefined and emptied it (the title fell back to untitled) */ + if (path != curPath) + snprintf(curPath, sizeof curPath, "%s", path); dirty = 0; SetTitle(); } else { From 6fb09e6d9d9b73dfb737d6bf667de2f33ed6640d Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 06:51:21 +0000 Subject: [PATCH 05/22] MCDE dtpaint: zoom 1x/2x/4x/8x (D3) The magnifier cycles the factor (left up, right down); View > Normal Size (Ctrl+PgUp) and Large Size (Ctrl+PgDn) set 1x and 4x. The canvas grows to image*zoom inside the scrolled window; Expose samples only the exposed rectangle into an XImage (nearest pixel), and pointer events divide by the factor, so drawing and the status line stay in image coordinates. Measured under Xvfb: 1x 640x480 -> 2x 1280x960 -> 4x 2560x1920, a line drawn at 4x appears at the same image coordinates at 1x. --- programs/dtpaint/dtpaint.c | 112 ++++++++++++++++-- programs/dtpaint/dtpaint.msg | 2 + .../localized/de_DE.UTF-8/msg/dtpaint.msg | 2 + 3 files changed, 106 insertions(+), 10 deletions(-) diff --git a/programs/dtpaint/dtpaint.c b/programs/dtpaint/dtpaint.c index 9c0d819b..d3675f52 100644 --- a/programs/dtpaint/dtpaint.c +++ b/programs/dtpaint/dtpaint.c @@ -117,6 +117,7 @@ static Widget statusHelp, statusPos, fgbg; static Pixmap pix, snap; static GC gc; static int imgW = 640, imgH = 480; +static int zoom = 1; /* 1, 2, 4 or 8 */ static int tool = T_PENCIL; static unsigned long fgPix, bgPix; static XColor palette[PAL_N]; @@ -439,7 +440,8 @@ OpenBMP(const char *path) pix = np; snap = ns; if (canvas != NULL) - XtVaSetValues(canvas, XmNwidth, imgW, XmNheight, imgH, NULL); + XtVaSetValues(canvas, XmNwidth, imgW * zoom, + XmNheight, imgH * zoom, NULL); } XSetForeground(dpy, gc, bgPix); XFillRectangle(dpy, pix, gc, 0, 0, imgW, imgH); @@ -768,11 +770,32 @@ FlipHorizontal(void) XFreePixmap(dpy, tmp); } +static void +SetCanvasSize(void) +{ + if (canvas != NULL) + XtVaSetValues(canvas, XmNwidth, imgW * zoom, + XmNheight, imgH * zoom, NULL); +} + static void Redraw(void) { if (canvas != NULL && XtWindow(canvas) != None) - XClearArea(dpy, XtWindow(canvas), 0, 0, imgW, imgH, True); + XClearArea(dpy, XtWindow(canvas), 0, 0, + imgW * zoom, imgH * zoom, True); +} + +static void +SetZoom(int z) +{ + if (z < 1) + z = 1; + if (z > 8) + z = 8; + zoom = z; + SetCanvasSize(); + Redraw(); } static void @@ -847,15 +870,69 @@ ShowColors(void) XClearArea(dpy, XtWindow(fgbg), 0, 0, 34, 34, True); } +/* draw the exposed part of the image at the current zoom (nearest pixel) */ +static void +ShowZoomed(int rx, int ry, int rw, int rh) +{ + XImage *src, *dst; + int x, y; + + if (rw <= 0 || rh <= 0) + return; + if (zoom == 1) { + XCopyArea(dpy, pix, XtWindow(canvas), gc, rx, ry, (unsigned) rw, + (unsigned) rh, rx, ry); + return; + } + if ((src = XGetImage(dpy, pix, 0, 0, imgW, imgH, AllPlanes, ZPixmap)) == NULL) + return; + dst = XCreateImage(dpy, vis, depth, ZPixmap, 0, NULL, + (unsigned) rw, (unsigned) rh, 32, 0); + if (dst == NULL) { + XDestroyImage(src); + return; + } + dst->data = calloc(1, (size_t) dst->bytes_per_line * rh); + if (dst->data == NULL) { + XDestroyImage(dst); + XDestroyImage(src); + return; + } + for (y = 0; y < rh; y++) + for (x = 0; x < rw; x++) { + int sx = (rx + x) / zoom; + int sy = (ry + y) / zoom; + + if (sx >= imgW) sx = imgW - 1; + if (sy >= imgH) sy = imgH - 1; + XPutPixel(dst, x, y, XGetPixel(src, sx, sy)); + } + XPutImage(dpy, XtWindow(canvas), gc, dst, 0, 0, rx, ry, + (unsigned) rw, (unsigned) rh); + XDestroyImage(src); + XDestroyImage(dst); +} + static void CanvasExpose(Widget w, XtPointer cd, XtPointer call) { XmDrawingAreaCallbackStruct *c = (XmDrawingAreaCallbackStruct *) call; + XRectangle r; - (void) cd; + (void) w; (void) cd; if (c->reason != XmCR_EXPOSE) return; - XCopyArea(dpy, pix, XtWindow(w), gc, 0, 0, imgW, imgH, 0, 0); + r.x = c->event->xexpose.x; + r.y = c->event->xexpose.y; + r.width = (unsigned short) c->event->xexpose.width; + r.height = (unsigned short) c->event->xexpose.height; + if (r.x >= imgW * zoom || r.y >= imgH * zoom) + return; + if (r.x + r.width > imgW * zoom) + r.width = (unsigned short) (imgW * zoom - r.x); + if (r.y + r.height > imgH * zoom) + r.height = (unsigned short) (imgH * zoom - r.y); + ShowZoomed(r.x, r.y, r.width, r.height); } static void @@ -869,8 +946,8 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) case ButtonPress: if (ev->xbutton.button != Button1 && ev->xbutton.button != Button3) return; - x = ev->xbutton.x; - y = ev->xbutton.y; + x = ev->xbutton.x / zoom; + y = ev->xbutton.y / zoom; /* the drawing area is exactly the image; a click outside it * must never reach XGetImage/XDraw* on the pixmap */ if (x < 0 || y < 0 || x >= imgW || y >= imgH) @@ -921,14 +998,20 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) XDrawPoint(dpy, pix, gc, x, y); dirty = 1; break; + case T_ZOOM: + SetZoom(ev->xbutton.button == Button3 ? + (zoom > 1 ? zoom / 2 : 8) : + (zoom < 8 ? zoom * 2 : 1)); + drawing = 0; + break; default: Snapshot(); break; } break; case MotionNotify: - x = ev->xmotion.x; - y = ev->xmotion.y; + x = ev->xmotion.x / zoom; + y = ev->xmotion.y / zoom; StatusPos(x, y); if (!drawing) return; @@ -1006,7 +1089,7 @@ SwatchActivate(Widget w, XtPointer data, XtPointer call) enum { C_NEW, C_OPEN, C_SAVE, C_SAVEAS, C_EXIT, C_UNDO, C_CLEAR, C_INVERT, C_FLIP, - C_TOOLS, C_COLORS, C_STATUS, C_HELP, C_ABOUT + C_TOOLS, C_COLORS, C_STATUS, C_HELP, C_ABOUT, C_ZNORMAL, C_ZLARGE }; enum { A_NEW, A_OPEN, A_EXIT }; @@ -1199,6 +1282,12 @@ Command(Widget w, XtPointer data, XtPointer call) XtUnmanageChild(statusPos); } break; + case C_ZNORMAL: + SetZoom(1); + break; + case C_ZLARGE: + SetZoom(4); + break; case C_HELP: ShowInfo(34, "Pick a tool on the left and a colour below it, then draw on " @@ -1502,6 +1591,9 @@ main(int argc, char **argv) AddItem(m, PaintMsg(14, "Tool Box"), "CtrlT", "Ctrl+T", C_TOOLS, 0, True); AddItem(m, PaintMsg(15, "Color Box"), "CtrlL", "Ctrl+L", C_COLORS, 0, True); AddItem(m, PaintMsg(16, "Status Bar"), NULL, NULL, C_STATUS, 0, True); + AddItem(m, NULL, NULL, NULL, 0, 1, True); + AddItem(m, PaintMsg(35, "Normal Size"), "CtrlPrior", "Ctrl+PgUp", C_ZNORMAL, 0, True); + AddItem(m, PaintMsg(36, "Large Size"), "CtrlNext", "Ctrl+PgDn", C_ZLARGE, 0, True); m = AddMenu(menubarW, PaintMsg(4, "Image")); AddItem(m, PaintMsg(17, "Flip Horizontal"), NULL, NULL, C_FLIP, 0, True); AddItem(m, PaintMsg(18, "Invert Colors"), "CtrlI", "Ctrl+I", C_INVERT, 0, True); @@ -1626,7 +1718,7 @@ main(int argc, char **argv) XmNscrollingPolicy, XmAUTOMATIC, XmNscrollBarDisplayPolicy, XmAS_NEEDED, NULL); canvas = XtVaCreateManagedWidget("canvas", xmDrawingAreaWidgetClass, - scroll, XmNwidth, imgW, XmNheight, imgH, NULL); + scroll, XmNwidth, imgW * zoom, XmNheight, imgH * zoom, NULL); XtAddCallback(canvas, XmNexposeCallback, CanvasExpose, NULL); XtAddEventHandler(canvas, ButtonPressMask | ButtonReleaseMask | PointerMotionMask | ButtonMotionMask, False, CanvasInput, NULL); diff --git a/programs/dtpaint/dtpaint.msg b/programs/dtpaint/dtpaint.msg index 8f1f233f..41644552 100644 --- a/programs/dtpaint/dtpaint.msg +++ b/programs/dtpaint/dtpaint.msg @@ -36,3 +36,5 @@ $set 1 32 Save As 33 Help Topics 34 Pick a tool on the left and a colour below it, then draw on the canvas. The left button draws with the foreground colour, the right button with the background colour. Ctrl+Z undoes the last step. +35 Normal Size +36 Large Size diff --git a/programs/localized/de_DE.UTF-8/msg/dtpaint.msg b/programs/localized/de_DE.UTF-8/msg/dtpaint.msg index 87f104f5..dff2373e 100644 --- a/programs/localized/de_DE.UTF-8/msg/dtpaint.msg +++ b/programs/localized/de_DE.UTF-8/msg/dtpaint.msg @@ -37,3 +37,5 @@ $set 1 32 Speichern unter 33 Hilfe-Themen 34 Waehlen Sie links ein Werkzeug und darunter eine Farbe, dann zeichnen Sie auf der Flaeche. Die linke Taste zeichnet mit der Vordergrundfarbe, die rechte mit der Hintergrundfarbe. Strg+Z macht den letzten Schritt rueckgaengig. +35 Normale Groesse +36 Grosse Darstellung From e987e0379fe6f596ce165ce66586064de7797b7a Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 06:56:08 +0000 Subject: [PATCH 06/22] MCDE dtpaint: airbrush and text tools (D3) Airbrush sprays random foreground/background dots in a 15-pixel square while dragging; Text opens a prompt dialog, then fills the text box with the background colour and draws the string in the foreground colour with the GC's font (the image stays 1:1 at any zoom). The prompt's OK button is a gadget whose callback widget is the SelectionBox itself, so the text field is found there, not under XtParent. Measured under Xvfb: spray dots on the canvas; 'Hello dtpaint' appears at the clicked point. --- programs/dtpaint/dtpaint.c | 101 ++++++++++++++++++ programs/dtpaint/dtpaint.msg | 1 + .../localized/de_DE.UTF-8/msg/dtpaint.msg | 1 + 3 files changed, 103 insertions(+) diff --git a/programs/dtpaint/dtpaint.c b/programs/dtpaint/dtpaint.c index d3675f52..65a0a9f9 100644 --- a/programs/dtpaint/dtpaint.c +++ b/programs/dtpaint/dtpaint.c @@ -47,7 +47,9 @@ #include #include #include +#include #include +#include #include /* dtpaint's message catalog (programs/dtpaint/dtpaint.msg, the locale's copy @@ -127,6 +129,8 @@ static char curPath[512]; static int dirty; static int pendingAction; +static void DestroyDialog(Widget w, XtPointer data, XtPointer call); + /* ------------------------------------------------------------------ colour */ static int @@ -833,6 +837,85 @@ ClearImage(void) /* ----------------------------------------------------------------- events */ +static void +Spray(int x, int y, unsigned long color) +{ + int i; + + for (i = 0; i < 14; i++) { + int px = x + (rand() % 15) - 7; + int py = y + (rand() % 15) - 7; + + if (px < 0 || py < 0 || px >= imgW || py >= imgH) + continue; + SetFg(color); + XDrawPoint(dpy, pix, gc, px, py); + } +} + +static int textX = 100, textY = 100; +static unsigned long textColor; + +static void +TextOk(Widget w, XtPointer cd, XtPointer call) +{ + /* the OK button of a SelectionBox is a gadget: the callback's + * widget is the SelectionBox itself, not the button */ + Widget text = XmSelectionBoxGetChild(w, XmDIALOG_TEXT); + char *s = (text != NULL) ? XmTextGetString(text) : NULL; + + (void) cd; (void) call; + if (s != NULL) { + if (s[0] != '\0') { + XFontStruct *font = XQueryFont(dpy, XGContextFromGC(gc)); + + if (font != NULL) { + int width = XTextWidth(font, s, (int) strlen(s)); + + SetFg(bgPix); + XFillRectangle(dpy, pix, gc, textX, + textY - font->ascent, (unsigned) width, + (unsigned) (font->ascent + font->descent)); + SetFg(textColor); + XDrawString(dpy, pix, gc, textX, textY, s, + (int) strlen(s)); + XFreeFontInfo(NULL, font, 1); + dirty = 1; + Redraw(); + } + } + XtFree(s); + } + DestroyDialog(w, NULL, NULL); +} + +static void +TextCancel(Widget w, XtPointer cd, XtPointer call) +{ + (void) cd; (void) call; + DestroyDialog(w, NULL, NULL); +} + +static void +TextDialog(void) +{ + Widget d = XmCreatePromptDialog(top, "text", NULL, 0); + Widget help, text; + XmString s = Msg(37, "Text:"); + + XtVaSetValues(d, XmNselectionLabelString, s, NULL); + XmStringFree(s); + help = XmSelectionBoxGetChild(d, XmDIALOG_HELP_BUTTON); + if (help != NULL) + XtUnmanageChild(help); + XtAddCallback(d, XmNokCallback, TextOk, NULL); + XtAddCallback(d, XmNcancelCallback, TextCancel, NULL); + XtManageChild(d); + text = XmSelectionBoxGetChild(d, XmDIALOG_TEXT); + if (text != NULL) + XmProcessTraversal(text, XmTRAVERSE_CURRENT); +} + static void StatusPos(int x, int y) { @@ -992,6 +1075,19 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) DrawDab(x, y, 3, color); dirty = 1; break; + case T_AIRBRUSH: + Snapshot(); + Spray(x, y, color); + dirty = 1; + break; + case T_TEXT: + Snapshot(); + textX = x; + textY = y; + textColor = color; + TextDialog(); + drawing = 0; + break; case T_PENCIL: Snapshot(); SetFg(color); @@ -1033,6 +1129,10 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) DrawDab(x, y, 4, bgPix); dirty = 1; break; + case T_AIRBRUSH: + Spray(x, y, color); + dirty = 1; + break; case T_LINE: case T_RECT: case T_ELLIPSE: case T_ROUNDRECT: RestoreSnap(); DrawShape(sx, sy, x, y, color); @@ -1490,6 +1590,7 @@ main(int argc, char **argv) top = XtVaAppInitialize(&app, "Dtpaint", NULL, 0, &argc, argv, NULL, NULL); dpy = XtDisplay(top); + (void) srand((unsigned) getpid()); InitColor(); for (i = 0; i < PAL_N; i++) { diff --git a/programs/dtpaint/dtpaint.msg b/programs/dtpaint/dtpaint.msg index 41644552..93c4a967 100644 --- a/programs/dtpaint/dtpaint.msg +++ b/programs/dtpaint/dtpaint.msg @@ -38,3 +38,4 @@ $set 1 34 Pick a tool on the left and a colour below it, then draw on the canvas. The left button draws with the foreground colour, the right button with the background colour. Ctrl+Z undoes the last step. 35 Normal Size 36 Large Size +37 Text: diff --git a/programs/localized/de_DE.UTF-8/msg/dtpaint.msg b/programs/localized/de_DE.UTF-8/msg/dtpaint.msg index dff2373e..1dd6fe4e 100644 --- a/programs/localized/de_DE.UTF-8/msg/dtpaint.msg +++ b/programs/localized/de_DE.UTF-8/msg/dtpaint.msg @@ -39,3 +39,4 @@ $set 1 34 Waehlen Sie links ein Werkzeug und darunter eine Farbe, dann zeichnen Sie auf der Flaeche. Die linke Taste zeichnet mit der Vordergrundfarbe, die rechte mit der Hintergrundfarbe. Strg+Z macht den letzten Schritt rueckgaengig. 35 Normale Groesse 36 Grosse Darstellung +37 Text: From ffbf8c7f2deb45c097ee968c3d8d94027879125b Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 06:59:01 +0000 Subject: [PATCH 07/22] MCDE dtpaint: curve and polygon tools (D3) Curve is the reference's two-phase tool: drag the two end points, release, then move to bend the quadratic Bezier and click to commit. Polygon adds a vertex per left click, previews the open outline with a rubber line to the pointer, and closes on a right click or a double click; leaving the tool restores the snapshot. Both keep the one-step undo (snapshot at the first press). Measured under Xvfb: a bent curve from (300,200) to (500,300) through (400,150); a closed quadrilateral; Undo removes the polygon and keeps the earlier curve. --- programs/dtpaint/dtpaint.c | 153 ++++++++++++++++++++++++++++++++++++- 1 file changed, 150 insertions(+), 3 deletions(-) diff --git a/programs/dtpaint/dtpaint.c b/programs/dtpaint/dtpaint.c index 65a0a9f9..c6f78fad 100644 --- a/programs/dtpaint/dtpaint.c +++ b/programs/dtpaint/dtpaint.c @@ -124,12 +124,21 @@ static int tool = T_PENCIL; static unsigned long fgPix, bgPix; static XColor palette[PAL_N]; static int drawing, sx, sy, lx, ly; +static int curveState; /* 0 idle, 1 drag ends, 2 bend */ +static int curveX0, curveY0, curveX1, curveY1; +static unsigned long curveColor; +#define POLY_MAX 128 +static int polyActive, polyN, polyX[POLY_MAX], polyY[POLY_MAX]; +static unsigned long polyColor; +static int polyLastX, polyLastY; +static Time polyLastTime; static int toolsShown = 1, colorsShown = 1, statusShown = 1; static char curPath[512]; static int dirty; static int pendingAction; static void DestroyDialog(Widget w, XtPointer data, XtPointer call); +static void Redraw(void); /* ------------------------------------------------------------------ colour */ @@ -607,6 +616,62 @@ DrawShape(int x0, int y0, int x1, int y1, unsigned long color) } } +/* quadratic Bezier P0 -> control -> P1, sampled into short line segments */ +static void +DrawCurve(int x0, int y0, int cx, int cy, int x1, int y1, unsigned long color) +{ + double px = x0, py = y0; + int i; + + SetFg(color); + for (i = 1; i <= 64; i++) { + double t = i / 64.0, u = 1.0 - t; + double x = u * u * x0 + 2.0 * u * t * cx + t * t * x1; + double y = u * u * y0 + 2.0 * u * t * cy + t * t * y1; + + XDrawLine(dpy, pix, gc, (int) (px + 0.5), (int) (py + 0.5), + (int) (x + 0.5), (int) (y + 0.5)); + px = x; + py = y; + } +} + +/* the polygon so far plus a rubber line to the pointer, over the snapshot */ +static void +DrawPolyPreview(int curx, int cury) +{ + int i; + + RestoreSnap(); + SetFg(polyColor); + for (i = 1; i < polyN; i++) + XDrawLine(dpy, pix, gc, polyX[i - 1], polyY[i - 1], + polyX[i], polyY[i]); + if (polyN > 0) + XDrawLine(dpy, pix, gc, polyX[polyN - 1], polyY[polyN - 1], + curx, cury); +} + +static void +ClosePolygon(void) +{ + int i; + + RestoreSnap(); + SetFg(polyColor); + if (polyN >= 2) { + for (i = 1; i < polyN; i++) + XDrawLine(dpy, pix, gc, polyX[i - 1], polyY[i - 1], + polyX[i], polyY[i]); + XDrawLine(dpy, pix, gc, polyX[polyN - 1], polyY[polyN - 1], + polyX[0], polyY[0]); + dirty = 1; + } + polyActive = 0; + drawing = 0; + Redraw(); +} + /* Scanline flood fill: the stack holds one seed per run, not four neighbours * per pixel, so its size follows the shape's perimeter, not its area. */ struct Seed { int x, y; }; @@ -1094,6 +1159,54 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) XDrawPoint(dpy, pix, gc, x, y); dirty = 1; break; + case T_CURVE: + if (curveState == 2) { + /* the preview is the result */ + curveState = 0; + drawing = 0; + dirty = 1; + Redraw(); + } else if (curveState == 0) { + Snapshot(); + curveX0 = curveX1 = x; + curveY0 = curveY1 = y; + curveColor = color; + curveState = 1; + drawing = 1; + } else { + drawing = 0; + } + break; + case T_POLYGON: + if (polyActive && ev->xbutton.button == Button3) { + ClosePolygon(); + break; + } + if (ev->xbutton.button != Button1) { + drawing = 0; + break; + } + if (!polyActive) { + Snapshot(); + polyActive = 1; + polyN = 0; + polyColor = color; + } else if (ev->xbutton.time - polyLastTime < 300 && + abs(x - polyLastX) < 4 && abs(y - polyLastY) < 4) { + ClosePolygon(); + break; + } + if (polyN < POLY_MAX) { + polyX[polyN] = x; + polyY[polyN] = y; + polyN++; + } + polyLastX = x; + polyLastY = y; + polyLastTime = ev->xbutton.time; + DrawPolyPreview(x, y); + drawing = 0; + break; case T_ZOOM: SetZoom(ev->xbutton.button == Button3 ? (zoom > 1 ? zoom / 2 : 8) : @@ -1109,7 +1222,8 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) x = ev->xmotion.x / zoom; y = ev->xmotion.y / zoom; StatusPos(x, y); - if (!drawing) + if (!drawing && !(tool == T_CURVE && curveState == 2) && + !(tool == T_POLYGON && polyActive)) return; if (x < 0) x = 0; if (y < 0) y = 0; @@ -1133,6 +1247,18 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) Spray(x, y, color); dirty = 1; break; + case T_CURVE: + RestoreSnap(); + if (curveState == 1) + DrawLineTo(curveX0, curveY0, x, y, curveColor); + else if (curveState == 2) + DrawCurve(curveX0, curveY0, x, y, curveX1, + curveY1, curveColor); + break; + case T_POLYGON: + if (polyActive) + DrawPolyPreview(x, y); + break; case T_LINE: case T_RECT: case T_ELLIPSE: case T_ROUNDRECT: RestoreSnap(); DrawShape(sx, sy, x, y, color); @@ -1145,6 +1271,17 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) Redraw(); break; case ButtonRelease: + if (tool == T_CURVE && curveState == 1) { + x = ev->xbutton.x / zoom; + y = ev->xbutton.y / zoom; + if (x < 0) x = 0; + if (y < 0) y = 0; + if (x >= imgW) x = imgW - 1; + if (y >= imgH) y = imgH - 1; + curveX1 = x; + curveY1 = y; + curveState = 2; + } drawing = 0; Redraw(); break; @@ -1157,8 +1294,18 @@ static void ToolChanged(Widget w, XtPointer data, XtPointer call) { (void) call; - if (XmToggleButtonGetState(w)) - tool = (int) (long) data; + if (!XmToggleButtonGetState(w)) + return; + if (curveState != 0) { + RestoreSnap(); + curveState = 0; + } + if (polyActive) { + RestoreSnap(); + polyActive = 0; + } + tool = (int) (long) data; + Redraw(); } static void From d224248651fb451c52a31a2e7c26d1dd0bd1d695 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 07:05:29 +0000 Subject: [PATCH 08/22] MCDE dtpaint: rectangular and free-form selection (D3) Select drags a box, Free-Form Select traces a lasso; both draw an XOR marquee (scaled with the zoom), keep the pixels, and can be dragged to move them: the snapshot is the undo base, the selected pixels float in a pixmap, and a 1-bit polygon mask clips clear/paste for the lasso. Edit > Clear Selection (Del) clears the selected pixels and deselects; Edit > Select All (Ctrl+A) selects the whole image; the Clear Selection item is sensitive only while a selection exists. A non-selection tool's click deselects, as in the reference. Measured under Xvfb: box marquee, move of a scribble (outside pixels stay), Delete clears it, lasso marquee around a dot and Delete clears just that dot, Ctrl+A marks the image and enables the menu item. --- programs/dtpaint/dtpaint.c | 379 +++++++++++++++++- programs/dtpaint/dtpaint.msg | 1 + .../localized/de_DE.UTF-8/msg/dtpaint.msg | 1 + 3 files changed, 375 insertions(+), 6 deletions(-) diff --git a/programs/dtpaint/dtpaint.c b/programs/dtpaint/dtpaint.c index c6f78fad..dfba4baa 100644 --- a/programs/dtpaint/dtpaint.c +++ b/programs/dtpaint/dtpaint.c @@ -132,6 +132,17 @@ static int polyActive, polyN, polyX[POLY_MAX], polyY[POLY_MAX]; static unsigned long polyColor; static int polyLastX, polyLastY; static Time polyLastTime; + +#define SELPT_MAX 1024 +static int selActive, selFree, selDefining, selMoving; +static int selBX, selBY, selBW, selBH; /* selection box, image coords */ +static int selStartX, selStartY; /* press / last pointer */ +static int selLastX = -1, selLastY = -1; +static int selDX, selDY; /* current move offset */ +static Pixmap selMaskPix, selFloat; +static int selPts; +static int selPX[SELPT_MAX], selPY[SELPT_MAX]; +static Widget clearSelItem; static int toolsShown = 1, colorsShown = 1, statusShown = 1; static char curPath[512]; static int dirty; @@ -139,6 +150,9 @@ static int pendingAction; static void DestroyDialog(Widget w, XtPointer data, XtPointer call); static void Redraw(void); +static void UpdateSelUI(void); +static void DrawMarquee(void); +static void Deselect(void); /* ------------------------------------------------------------------ colour */ @@ -881,6 +895,7 @@ SetTitle(void) static void NewImage(void) { + Deselect(); XSetForeground(dpy, gc, bgPix); XFillRectangle(dpy, pix, gc, 0, 0, imgW, imgH); Snapshot(); @@ -893,6 +908,7 @@ NewImage(void) static void ClearImage(void) { + Deselect(); Snapshot(); XSetForeground(dpy, gc, bgPix); XFillRectangle(dpy, pix, gc, 0, 0, imgW, imgH); @@ -1018,6 +1034,245 @@ ShowColors(void) XClearArea(dpy, XtWindow(fgbg), 0, 0, 34, 34, True); } +/* ------------------------------------------------------------- selection */ + +static void +UpdateSelUI(void) +{ + if (clearSelItem != NULL) + XtSetSensitive(clearSelItem, selActive); +} + +static void +FreeSelMask(void) +{ + if (selMaskPix != None) { + XFreePixmap(dpy, selMaskPix); + selMaskPix = None; + } + if (selFloat != None) { + XFreePixmap(dpy, selFloat); + selFloat = None; + } +} + +static void +Deselect(void) +{ + selActive = 0; + selFree = 0; + selDefining = 0; + selMoving = 0; + FreeSelMask(); + UpdateSelUI(); +} + +/* clear the selected pixels of the box at x,y (the mask is box-relative) */ +static void +SelClearArea(int x, int y, int w, int h) +{ + int cx = x, cy = y, cw = w, ch = h; + + if (cx < 0) { cw += cx; cx = 0; } + if (cy < 0) { ch += cy; cy = 0; } + if (cx + cw > imgW) cw = imgW - cx; + if (cy + ch > imgH) ch = imgH - cy; + if (cw <= 0 || ch <= 0) + return; + XSetForeground(dpy, gc, bgPix); + if (selMaskPix != None) { + XSetClipMask(dpy, gc, selMaskPix); + XSetClipOrigin(dpy, gc, x, y); + } + XFillRectangle(dpy, pix, gc, cx, cy, (unsigned) cw, (unsigned) ch); + if (selMaskPix != None) { + XSetClipMask(dpy, gc, None); + XSetClipOrigin(dpy, gc, 0, 0); + } +} + +/* paste the floating box at x,y, clipped by the mask when there is one */ +static void +SelPaste(int x, int y) +{ + if (selFloat == None) + return; + if (selMaskPix != None) { + XSetClipMask(dpy, gc, selMaskPix); + XSetClipOrigin(dpy, gc, x, y); + } + XCopyArea(dpy, selFloat, pix, gc, 0, 0, (unsigned) selBW, + (unsigned) selBH, x, y); + if (selMaskPix != None) { + XSetClipMask(dpy, gc, None); + XSetClipOrigin(dpy, gc, 0, 0); + } +} + +static void +StartMove(int x, int y) +{ + Snapshot(); + selFloat = XCreatePixmap(dpy, RootWindowOfScreen(scr), (unsigned) selBW, + (unsigned) selBH, depth); + if (selFloat == None) + return; + XSetForeground(dpy, gc, bgPix); + XFillRectangle(dpy, selFloat, gc, 0, 0, (unsigned) selBW, + (unsigned) selBH); + if (selMaskPix != None) { + XSetClipMask(dpy, gc, selMaskPix); + XSetClipOrigin(dpy, gc, 0, 0); + } + XCopyArea(dpy, pix, selFloat, gc, selBX, selBY, (unsigned) selBW, + (unsigned) selBH, 0, 0); + if (selMaskPix != None) { + XSetClipMask(dpy, gc, None); + XSetClipOrigin(dpy, gc, 0, 0); + } + SelClearArea(selBX, selBY, selBW, selBH); + selStartX = x; + selStartY = y; + selDX = selDY = 0; + selMoving = 1; +} + +static void +FinishMove(void) +{ + selBX += selDX; + selBY += selDY; + selDX = selDY = 0; + selMoving = 0; + if (selFloat != None) { + XFreePixmap(dpy, selFloat); + selFloat = None; + } +} + +static void +SelectAll(void) +{ + Deselect(); + selFree = 0; + selActive = 1; + selBX = 0; + selBY = 0; + selBW = imgW; + selBH = imgH; + UpdateSelUI(); + Redraw(); +} + +static void +ClearSelection(void) +{ + if (!selActive) + return; + Snapshot(); + SelClearArea(selBX, selBY, selBW, selBH); + dirty = 1; + Deselect(); + Redraw(); +} + +/* a 1-bit mask from the free-form path; points become box-relative */ +static void +BuildSelMask(void) +{ + XGCValues gv; + GC g1; + XPoint *pts; + int i, x0 = selPX[0], y0 = selPY[0], x1 = x0, y1 = y0; + + for (i = 1; i < selPts; i++) { + if (selPX[i] < x0) x0 = selPX[i]; + if (selPY[i] < y0) y0 = selPY[i]; + if (selPX[i] > x1) x1 = selPX[i]; + if (selPY[i] > y1) y1 = selPY[i]; + } + selBX = x0; + selBY = y0; + selBW = x1 - x0 + 1; + selBH = y1 - y0 + 1; + if (selBW < 2 || selBH < 2) + return; + selMaskPix = XCreatePixmap(dpy, RootWindowOfScreen(scr), + (unsigned) selBW, (unsigned) selBH, 1); + if (selMaskPix == None) + return; + gv.foreground = 0; + gv.background = 0; + g1 = XCreateGC(dpy, selMaskPix, GCForeground | GCBackground, &gv); + XFillRectangle(dpy, selMaskPix, g1, 0, 0, (unsigned) selBW, + (unsigned) selBH); + XSetForeground(dpy, g1, 1); + pts = malloc(sizeof(XPoint) * (size_t) selPts); + if (pts != NULL) { + for (i = 0; i < selPts; i++) { + pts[i].x = (short) (selPX[i] - selBX); + pts[i].y = (short) (selPY[i] - selBY); + } + XFillPolygon(dpy, selMaskPix, g1, pts, selPts, Complex, + CoordModeOrigin); + free(pts); + } + XFreeGC(dpy, g1); + for (i = 0; i < selPts; i++) { + selPX[i] -= selBX; + selPY[i] -= selBY; + } +} + +static void +DrawMarquee(void) +{ + int x, y, w, h, i; + XPoint pts[SELPT_MAX + 1]; + + if (!selActive && !selDefining) + return; + XSetFunction(dpy, gc, GXxor); + XSetForeground(dpy, gc, WhitePixelOfScreen(scr)); + XSetLineAttributes(dpy, gc, 1, LineOnOffDash, CapButt, JoinMiter); + if (selDefining && !selFree) { + x = selStartX < selLastX ? selStartX : selLastX; + y = selStartY < selLastY ? selStartY : selLastY; + w = abs(selLastX - selStartX); + h = abs(selLastY - selStartY); + XDrawRectangle(dpy, XtWindow(canvas), gc, x * zoom, y * zoom, + (unsigned) (w * zoom), (unsigned) (h * zoom)); + } else if (selDefining) { + for (i = 0; i < selPts; i++) { + pts[i].x = (short) (selPX[i] * zoom); + pts[i].y = (short) (selPY[i] * zoom); + } + if (selPts > 0) { + pts[selPts].x = (short) (selLastX * zoom); + pts[selPts].y = (short) (selLastY * zoom); + XDrawLines(dpy, XtWindow(canvas), gc, pts, selPts + 1, + CoordModeOrigin); + } + } else if (selFree) { + for (i = 0; i < selPts; i++) { + pts[i].x = (short) ((selBX + selDX + selPX[i]) * zoom); + pts[i].y = (short) ((selBY + selDY + selPY[i]) * zoom); + } + if (selPts > 0) { + pts[selPts] = pts[0]; + XDrawLines(dpy, XtWindow(canvas), gc, pts, selPts + 1, + CoordModeOrigin); + } + } else { + XDrawRectangle(dpy, XtWindow(canvas), gc, + (selBX + selDX) * zoom, (selBY + selDY) * zoom, + (unsigned) (selBW * zoom), (unsigned) (selBH * zoom)); + } + XSetLineAttributes(dpy, gc, 0, LineSolid, CapButt, JoinMiter); + XSetFunction(dpy, gc, GXcopy); + XSetForeground(dpy, gc, fgPix); +} + /* draw the exposed part of the image at the current zoom (nearest pixel) */ static void ShowZoomed(int rx, int ry, int rw, int rh) @@ -1081,6 +1336,7 @@ CanvasExpose(Widget w, XtPointer cd, XtPointer call) if (r.y + r.height > imgH * zoom) r.height = (unsigned short) (imgH * zoom - r.y); ShowZoomed(r.x, r.y, r.width, r.height); + DrawMarquee(); } static void @@ -1100,6 +1356,30 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) * must never reach XGetImage/XDraw* on the pixmap */ if (x < 0 || y < 0 || x >= imgW || y >= imgH) return; + if (tool == T_SEL || tool == T_FREESEL) { + if (selActive && x >= selBX && y >= selBY && + x < selBX + selBW && y < selBY + selBH) { + StartMove(x, y); + } else { + Deselect(); + selDefining = 1; + selFree = (tool == T_FREESEL); + selStartX = selLastX = x; + selStartY = selLastY = y; + if (selFree) { + selPts = 1; + selPX[0] = x; + selPY[0] = y; + } + } + drawing = 0; + Redraw(); + return; + } + if (selActive) { + Deselect(); + Redraw(); + } color = (ev->xbutton.button == Button3) ? bgPix : fgPix; sx = lx = x; sy = ly = y; @@ -1223,12 +1503,35 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) y = ev->xmotion.y / zoom; StatusPos(x, y); if (!drawing && !(tool == T_CURVE && curveState == 2) && - !(tool == T_POLYGON && polyActive)) + !(tool == T_POLYGON && polyActive) && + !selDefining && !selMoving) return; if (x < 0) x = 0; if (y < 0) y = 0; if (x >= imgW) x = imgW - 1; if (y >= imgH) y = imgH - 1; + if (selDefining) { + selLastX = x; + selLastY = y; + if (selFree && selPts < SELPT_MAX && + (abs(x - selPX[selPts - 1]) + + abs(y - selPY[selPts - 1]) >= 2)) { + selPX[selPts] = x; + selPY[selPts] = y; + selPts++; + } + Redraw(); + return; + } + if (selMoving) { + selDX = x - selStartX; + selDY = y - selStartY; + RestoreSnap(); + SelClearArea(selBX, selBY, selBW, selBH); + SelPaste(selBX + selDX, selBY + selDY); + Redraw(); + return; + } color = (ev->xmotion.state & Button3Mask) ? bgPix : fgPix; switch (tool) { case T_PENCIL: @@ -1271,6 +1574,59 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) Redraw(); break; case ButtonRelease: + if (selDefining) { + x = ev->xbutton.x / zoom; + y = ev->xbutton.y / zoom; + if (x < 0) x = 0; + if (y < 0) y = 0; + if (x >= imgW) x = imgW - 1; + if (y >= imgH) y = imgH - 1; + if (selFree) { + if (selPts >= 3 && + (abs(x - selPX[selPts - 1]) + + abs(y - selPY[selPts - 1]) >= 2)) { + if (selPts < SELPT_MAX) { + selPX[selPts] = x; + selPY[selPts] = y; + selPts++; + } + } + selMaskPix = None; + if (selPts >= 3) + BuildSelMask(); + selActive = (selMaskPix != None); + selFree = selActive; + } else { + int x0 = selStartX < x ? selStartX : x; + int y0 = selStartY < y ? selStartY : y; + int w = abs(x - selStartX); + int h = abs(y - selStartY); + + if (w >= 2 && h >= 2) { + selBX = x0; + selBY = y0; + selBW = w; + selBH = h; + selActive = 1; + selFree = 0; + } else { + Deselect(); + } + } + selDefining = 0; + if (!selActive) + Deselect(); + UpdateSelUI(); + drawing = 0; + Redraw(); + break; + } + if (selMoving) { + FinishMove(); + drawing = 0; + Redraw(); + break; + } if (tool == T_CURVE && curveState == 1) { x = ev->xbutton.x / zoom; y = ev->xbutton.y / zoom; @@ -1335,7 +1691,7 @@ SwatchActivate(Widget w, XtPointer data, XtPointer call) enum { C_NEW, C_OPEN, C_SAVE, C_SAVEAS, C_EXIT, - C_UNDO, C_CLEAR, C_INVERT, C_FLIP, + C_UNDO, C_CLEAR, C_CLEARSEL, C_SELALL, C_INVERT, C_FLIP, C_TOOLS, C_COLORS, C_STATUS, C_HELP, C_ABOUT, C_ZNORMAL, C_ZLARGE }; @@ -1490,6 +1846,7 @@ Command(Widget w, XtPointer data, XtPointer call) MaybeDiscard(A_EXIT); break; case C_UNDO: + Deselect(); RestoreSnap(); dirty = 1; Redraw(); @@ -1497,6 +1854,12 @@ Command(Widget w, XtPointer data, XtPointer call) case C_CLEAR: ClearImage(); break; + case C_CLEARSEL: + ClearSelection(); + break; + case C_SELALL: + SelectAll(); + break; case C_INVERT: Snapshot(); InvertImage(); @@ -1563,6 +1926,7 @@ FileOk(Widget w, XtPointer data, XtPointer call) if (OpenBMP(path) == 0) { snprintf(curPath, sizeof curPath, "%s", path); dirty = 0; + Deselect(); Snapshot(); SetTitle(); Redraw(); @@ -1608,7 +1972,7 @@ AddMenu(Widget bar, const char *name) return shell; } -static void +static Widget AddItem(Widget shell, const char *label, const char *accel, const char *accelText, int cmd, int sep, int sensitive) { @@ -1616,7 +1980,7 @@ AddItem(Widget shell, const char *label, const char *accel, if (sep) { XtVaCreateManagedWidget("sep", xmSeparatorWidgetClass, shell, NULL); - return; + return NULL; } b = XtVaCreateManagedWidget((char *) label, xmPushButtonWidgetClass, shell, XmNsensitive, sensitive, NULL); @@ -1629,6 +1993,7 @@ AddItem(Widget shell, const char *label, const char *accel, XtVaSetValues(b, XmNacceleratorText, s, NULL); XmStringFree(s); } + return b; } /* ------------------------------------------------------------------ icons */ @@ -1833,8 +2198,10 @@ main(int argc, char **argv) m = AddMenu(menubarW, PaintMsg(2, "Edit")); AddItem(m, PaintMsg(12, "Undo"), "CtrlZ", "Ctrl+Z", C_UNDO, 0, True); AddItem(m, NULL, NULL, NULL, 0, 1, True); - /* needs the selection tool (D3); insensitive until it exists */ - AddItem(m, PaintMsg(13, "Clear Selection"), NULL, NULL, C_CLEAR, 0, False); + clearSelItem = AddItem(m, PaintMsg(13, "Clear Selection"), + "Delete", "Del", C_CLEARSEL, 0, False); + AddItem(m, PaintMsg(38, "Select All"), "CtrlA", "Ctrl+A", + C_SELALL, 0, True); m = AddMenu(menubarW, PaintMsg(3, "View")); AddItem(m, PaintMsg(14, "Tool Box"), "CtrlT", "Ctrl+T", C_TOOLS, 0, True); AddItem(m, PaintMsg(15, "Color Box"), "CtrlL", "Ctrl+L", C_COLORS, 0, True); diff --git a/programs/dtpaint/dtpaint.msg b/programs/dtpaint/dtpaint.msg index 93c4a967..d566364b 100644 --- a/programs/dtpaint/dtpaint.msg +++ b/programs/dtpaint/dtpaint.msg @@ -39,3 +39,4 @@ $set 1 35 Normal Size 36 Large Size 37 Text: +38 Select All diff --git a/programs/localized/de_DE.UTF-8/msg/dtpaint.msg b/programs/localized/de_DE.UTF-8/msg/dtpaint.msg index 1dd6fe4e..158ef773 100644 --- a/programs/localized/de_DE.UTF-8/msg/dtpaint.msg +++ b/programs/localized/de_DE.UTF-8/msg/dtpaint.msg @@ -40,3 +40,4 @@ $set 1 35 Normale Groesse 36 Grosse Darstellung 37 Text: +38 Alles auswaehlen From a196caf47b556c0171f5a6ba2f497d50f200b9ec Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 07:13:48 +0000 Subject: [PATCH 09/22] MCDE dtpaint: image attributes and colour editor (D4) Image > Attributes... (Ctrl+E) asks width and height (1..4096), builds a new pixmap filled with the background, copies the overlap and discards the selection; the resize is a document operation, so undo starts fresh after it. Colors > Edit Colors... opens three RGB scales initialised from the current foreground; OK allocates the colour and updates the fg square. Both dialogs are FormDialogs with OK/Cancel from the catalog; the form size is set after popup so the shell does not shrink to its children. Measured under Xvfb: 640x480 -> 300x300 canvas; Red 255 + OK draws a red line and turns the fg indicator red. --- programs/dtpaint/dtpaint.c | 244 +++++++++++++++++- programs/dtpaint/dtpaint.msg | 11 + .../localized/de_DE.UTF-8/msg/dtpaint.msg | 11 + 3 files changed, 263 insertions(+), 3 deletions(-) diff --git a/programs/dtpaint/dtpaint.c b/programs/dtpaint/dtpaint.c index dfba4baa..20fd0078 100644 --- a/programs/dtpaint/dtpaint.c +++ b/programs/dtpaint/dtpaint.c @@ -46,10 +46,12 @@ #include #include #include +#include #include #include #include #include +#include #include /* dtpaint's message catalog (programs/dtpaint/dtpaint.msg, the locale's copy @@ -143,6 +145,7 @@ static Pixmap selMaskPix, selFloat; static int selPts; static int selPX[SELPT_MAX], selPY[SELPT_MAX]; static Widget clearSelItem; +static Widget attrW, attrH, colRS, colGS, colBS; static int toolsShown = 1, colorsShown = 1, statusShown = 1; static char curPath[512]; static int dirty; @@ -1692,7 +1695,8 @@ SwatchActivate(Widget w, XtPointer data, XtPointer call) enum { C_NEW, C_OPEN, C_SAVE, C_SAVEAS, C_EXIT, C_UNDO, C_CLEAR, C_CLEARSEL, C_SELALL, C_INVERT, C_FLIP, - C_TOOLS, C_COLORS, C_STATUS, C_HELP, C_ABOUT, C_ZNORMAL, C_ZLARGE + C_TOOLS, C_COLORS, C_STATUS, C_HELP, C_ABOUT, C_ZNORMAL, C_ZLARGE, + C_ATTR, C_EDITCOLORS }; enum { A_NEW, A_OPEN, A_EXIT }; @@ -1748,6 +1752,233 @@ ShowInfo(int bodyId, const char *bodyFb, int titleId, const char *titleFb) XtManageChild(d); } +/* ------------------------------------------------- image size and colours */ + +static void +ResizeImage(int nw, int nh) +{ + Pixmap np, ns; + + if (nw < 1 || nh < 1 || nw > 4096 || nh > 4096) + return; + np = XCreatePixmap(dpy, RootWindowOfScreen(scr), (unsigned) nw, + (unsigned) nh, depth); + ns = XCreatePixmap(dpy, RootWindowOfScreen(scr), (unsigned) nw, + (unsigned) nh, depth); + if (np == None || ns == None) { + if (np != None) + XFreePixmap(dpy, np); + if (ns != None) + XFreePixmap(dpy, ns); + return; + } + Deselect(); + XSetForeground(dpy, gc, bgPix); + XFillRectangle(dpy, np, gc, 0, 0, (unsigned) nw, (unsigned) nh); + XCopyArea(dpy, pix, np, gc, 0, 0, + (unsigned) (imgW < nw ? imgW : nw), + (unsigned) (imgH < nh ? imgH : nh), 0, 0); + XFreePixmap(dpy, pix); + XFreePixmap(dpy, snap); + pix = np; + snap = ns; + imgW = nw; + imgH = nh; + XCopyArea(dpy, pix, snap, gc, 0, 0, imgW, imgH, 0, 0); + dirty = 1; + SetCanvasSize(); + Redraw(); +} + +static void +AttrOk(Widget w, XtPointer cd, XtPointer call) +{ + char *sw = XmTextFieldGetString(attrW); + char *sh = XmTextFieldGetString(attrH); + long nw = (sw != NULL) ? strtol(sw, NULL, 10) : 0; + long nh = (sh != NULL) ? strtol(sh, NULL, 10) : 0; + + (void) cd; (void) call; + if (sw != NULL) + XtFree(sw); + if (sh != NULL) + XtFree(sh); + if (nw < 1 || nw > 4096 || nh < 1 || nh > 4096) { + ShowInfo(42, "Width and height must be between 1 and 4096.", + 43, "Attributes"); + return; + } + ResizeImage((int) nw, (int) nh); + DestroyDialog(w, NULL, NULL); +} + +static void +AttrDialog(void) +{ + Widget form = XmCreateFormDialog(top, "attributes", NULL, 0); + Widget shell, lw, lh, buttons, ok, cancel; + XmString s; + char buf[32]; + + if (form == NULL) + return; + shell = XtParent(form); + XtVaSetValues(shell, + XmNtitle, (String) PaintMsg(43, "Attributes"), + XmNwidth, 280, XmNheight, 190, + XmNdeleteResponse, XmDESTROY, + XmNdialogStyle, XmDIALOG_APPLICATION_MODAL, NULL); + + lw = XmCreateLabel(form, "widthLabel", NULL, 0); + s = Msg(40, "Width:"); + XtVaSetValues(lw, XmNlabelString, s, + XmNtopAttachment, XmATTACH_FORM, XmNleftAttachment, XmATTACH_FORM, + XmNtopOffset, 12, XmNleftOffset, 10, NULL); + XmStringFree(s); + XtManageChild(lw); + + attrW = XmCreateTextField(form, "width", NULL, 0); + snprintf(buf, sizeof buf, "%d", imgW); + XmTextFieldSetString(attrW, buf); + XtVaSetValues(attrW, + XmNtopAttachment, XmATTACH_FORM, XmNleftAttachment, XmATTACH_WIDGET, + XmNleftWidget, lw, XmNrightAttachment, XmATTACH_FORM, + XmNtopOffset, 8, XmNleftOffset, 8, XmNrightOffset, 10, NULL); + XtManageChild(attrW); + + lh = XmCreateLabel(form, "heightLabel", NULL, 0); + s = Msg(41, "Height:"); + XtVaSetValues(lh, XmNlabelString, s, + XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, attrW, + XmNleftAttachment, XmATTACH_FORM, + XmNtopOffset, 10, XmNleftOffset, 10, NULL); + XmStringFree(s); + XtManageChild(lh); + + attrH = XmCreateTextField(form, "height", NULL, 0); + snprintf(buf, sizeof buf, "%d", imgH); + XmTextFieldSetString(attrH, buf); + XtVaSetValues(attrH, + XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, attrW, + XmNleftAttachment, XmATTACH_WIDGET, XmNleftWidget, lh, + XmNrightAttachment, XmATTACH_FORM, + XmNtopOffset, 6, XmNleftOffset, 8, XmNrightOffset, 10, NULL); + XtManageChild(attrH); + + buttons = XmCreateRowColumn(form, "buttons", NULL, 0); + XtVaSetValues(buttons, XmNorientation, XmHORIZONTAL, + XmNpacking, XmPACK_TIGHT, XmNspacing, 8, + XmNbottomAttachment, XmATTACH_FORM, + XmNrightAttachment, XmATTACH_FORM, + XmNbottomOffset, 10, XmNrightOffset, 10, NULL); + ok = XmCreatePushButton(buttons, "ok", NULL, 0); + XtAddCallback(ok, XmNactivateCallback, AttrOk, NULL); + s = Msg(48, "OK"); + XtVaSetValues(ok, XmNlabelString, s, NULL); + XmStringFree(s); + XtManageChild(ok); + cancel = XmCreatePushButton(buttons, "cancel", NULL, 0); + XtAddCallback(cancel, XmNactivateCallback, DestroyDialog, NULL); + s = Msg(49, "Cancel"); + XtVaSetValues(cancel, XmNlabelString, s, NULL); + XmStringFree(s); + XtManageChild(cancel); + XtManageChild(buttons); + XtVaSetValues(form, XmNwidth, 280, XmNheight, 190, + XmNresizePolicy, XmRESIZE_NONE, NULL); + XtManageChild(form); + XtPopup(shell, XtGrabNone); + XtVaSetValues(shell, XmNwidth, 280, XmNheight, 190, NULL); +} + +static void +ColorOk(Widget w, XtPointer cd, XtPointer call) +{ + int r, g, b; + + (void) cd; (void) call; + XmScaleGetValue(colRS, &r); + XmScaleGetValue(colGS, &g); + XmScaleGetValue(colBS, &b); + fgPix = RGBToPixel((unsigned) r, (unsigned) g, (unsigned) b); + ShowColors(); + DestroyDialog(w, NULL, NULL); +} + +static Widget +ColorRow(Widget parent, const char *name, const char *label, int value) +{ + Widget row = XmCreateRowColumn(parent, (char *) name, NULL, 0); + Widget lab, sc; + XmString s = XmStringCreateLocalized((String) label); + + XtVaSetValues(row, XmNorientation, XmHORIZONTAL, XmNspacing, 6, + XmNpacking, XmPACK_TIGHT, NULL); + lab = XmCreateLabel(row, "label", NULL, 0); + XtVaSetValues(lab, XmNlabelString, s, XmNwidth, 55, + XmNrecomputeSize, False, NULL); + XmStringFree(s); + XtManageChild(lab); + sc = XmCreateScale(row, "scale", NULL, 0); + XtVaSetValues(sc, XmNminimum, 0, XmNmaximum, 255, XmNvalue, value, + XmNorientation, XmHORIZONTAL, XmNshowValue, True, + XmNwidth, 220, NULL); + XtManageChild(sc); + XtManageChild(row); + return sc; +} + +static void +ColorDialog(void) +{ + Widget form = XmCreateFormDialog(top, "editcolors", NULL, 0); + Widget shell, rc, buttons, ok, cancel; + XmString s; + unsigned r, g, b; + + if (form == NULL) + return; + shell = XtParent(form); + XtVaSetValues(shell, + XmNtitle, (String) PaintMsg(44, "Edit Colors"), + XmNwidth, 330, XmNheight, 230, + XmNdeleteResponse, XmDESTROY, + XmNdialogStyle, XmDIALOG_APPLICATION_MODAL, NULL); + PixelToRGB(fgPix, &r, &g, &b); + + rc = XmCreateRowColumn(form, "rc", NULL, 0); + XtVaSetValues(rc, XmNorientation, XmVERTICAL, XmNspacing, 8, + XmNtopAttachment, XmATTACH_FORM, XmNleftAttachment, XmATTACH_FORM, + XmNrightAttachment, XmATTACH_FORM, + XmNtopOffset, 12, XmNleftOffset, 12, XmNrightOffset, 12, NULL); + colRS = ColorRow(rc, "red", PaintMsg(45, "Red:"), (int) r); + colGS = ColorRow(rc, "green", PaintMsg(46, "Green:"), (int) g); + colBS = ColorRow(rc, "blue", PaintMsg(47, "Blue:"), (int) b); + + buttons = XmCreateRowColumn(rc, "buttons", NULL, 0); + XtVaSetValues(buttons, XmNorientation, XmHORIZONTAL, + XmNpacking, XmPACK_TIGHT, XmNspacing, 8, NULL); + ok = XmCreatePushButton(buttons, "ok", NULL, 0); + XtAddCallback(ok, XmNactivateCallback, ColorOk, NULL); + s = Msg(48, "OK"); + XtVaSetValues(ok, XmNlabelString, s, NULL); + XmStringFree(s); + XtManageChild(ok); + cancel = XmCreatePushButton(buttons, "cancel", NULL, 0); + XtAddCallback(cancel, XmNactivateCallback, DestroyDialog, NULL); + s = Msg(49, "Cancel"); + XtVaSetValues(cancel, XmNlabelString, s, NULL); + XmStringFree(s); + XtManageChild(cancel); + XtManageChild(buttons); + XtManageChild(rc); + XtVaSetValues(form, XmNwidth, 330, XmNheight, 230, + XmNresizePolicy, XmRESIZE_NONE, NULL); + XtManageChild(form); + XtPopup(shell, XtGrabNone); + XtVaSetValues(shell, XmNwidth, 330, XmNheight, 230, NULL); +} + /* Ask before throwing away unsaved work (New / Open / Exit). */ static void DiscardAnswer(Widget w, XtPointer data, XtPointer call) @@ -1898,6 +2129,12 @@ Command(Widget w, XtPointer data, XtPointer call) case C_ZLARGE: SetZoom(4); break; + case C_ATTR: + AttrDialog(); + break; + case C_EDITCOLORS: + ColorDialog(); + break; case C_HELP: ShowInfo(34, "Pick a tool on the left and a colour below it, then draw on " @@ -2213,9 +2450,10 @@ main(int argc, char **argv) AddItem(m, PaintMsg(17, "Flip Horizontal"), NULL, NULL, C_FLIP, 0, True); AddItem(m, PaintMsg(18, "Invert Colors"), "CtrlI", "Ctrl+I", C_INVERT, 0, True); AddItem(m, PaintMsg(19, "Clear Image"), "Ctrl ShiftN", "Ctrl+Shift+N", C_CLEAR, 0, True); + AddItem(m, NULL, NULL, NULL, 0, 1, True); + AddItem(m, PaintMsg(39, "Attributes..."), "CtrlE", "Ctrl+E", C_ATTR, 0, True); m = AddMenu(menubarW, PaintMsg(5, "Colors")); - /* needs the colour editor (D4); insensitive until it exists */ - AddItem(m, PaintMsg(20, "Edit Colors..."), NULL, NULL, C_ABOUT, 0, False); + AddItem(m, PaintMsg(20, "Edit Colors..."), NULL, NULL, C_EDITCOLORS, 0, True); m = AddMenu(menubarW, PaintMsg(6, "Help")); AddItem(m, PaintMsg(33, "Help Topics"), "CtrlF1", "Ctrl+F1", C_HELP, 0, True); AddItem(m, NULL, NULL, NULL, 0, 1, True); diff --git a/programs/dtpaint/dtpaint.msg b/programs/dtpaint/dtpaint.msg index d566364b..8872bb6b 100644 --- a/programs/dtpaint/dtpaint.msg +++ b/programs/dtpaint/dtpaint.msg @@ -40,3 +40,14 @@ $set 1 36 Large Size 37 Text: 38 Select All +39 Attributes... +40 Width: +41 Height: +42 Width and height must be between 1 and 4096. +43 Attributes +44 Edit Colors +45 Red: +46 Green: +47 Blue: +48 OK +49 Cancel diff --git a/programs/localized/de_DE.UTF-8/msg/dtpaint.msg b/programs/localized/de_DE.UTF-8/msg/dtpaint.msg index 158ef773..8aff9038 100644 --- a/programs/localized/de_DE.UTF-8/msg/dtpaint.msg +++ b/programs/localized/de_DE.UTF-8/msg/dtpaint.msg @@ -41,3 +41,14 @@ $set 1 36 Grosse Darstellung 37 Text: 38 Alles auswaehlen +39 Attribute... +40 Breite: +41 Hoehe: +42 Breite und Hoehe muessen zwischen 1 und 4096 liegen. +43 Attribute +44 Farben bearbeiten +45 Rot: +46 Gruen: +47 Blau: +48 OK +49 Abbrechen From fa06dc280adb5edd5866731ec9d6f79c3b435ace Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 07:18:21 +0000 Subject: [PATCH 10/22] MCDE dtpaint: 8-bit BMP (incl. RLE8) and ICO read (D4) OpenBMP now dispatches on the file: 24-bit BMP keeps the proven path (OpenBMP24), 8-bit palette BMP decodes uncompressed and RLE8 (count/value, end-of-line, end-of-bitmap, delta, absolute runs with word padding, top-down and bottom-up), and the first image of a .ico decodes 1/4/8/24/32 bpp (BGRA with alpha 0 composited onto the background; PNG-compressed icons are refused because there is no PNG decoder). All three go through one RGB buffer and SetImageRGB, which allocates distinct colours in one batch on PseudoColor. Measured under Xvfb: ImageMagick's RLE8 160x100 gradient opens and shows the gradient; a 64x64 32-bpp ICO opens with its four colours; 24-bit -selftest still passes. --- programs/dtpaint/dtpaint.c | 455 ++++++++++++++++++++++++++++++++++++- 1 file changed, 454 insertions(+), 1 deletion(-) diff --git a/programs/dtpaint/dtpaint.c b/programs/dtpaint/dtpaint.c index 20fd0078..a099f886 100644 --- a/programs/dtpaint/dtpaint.c +++ b/programs/dtpaint/dtpaint.c @@ -411,7 +411,7 @@ SaveBMP(const char *path) } static int -OpenBMP(const char *path) +OpenBMP24(const char *path) { FILE *f; unsigned char hdr[54]; @@ -563,6 +563,459 @@ OpenBMP(const char *path) return 0; } +/* ---------------------------------------------------------- more formats */ + +static unsigned +LE16(const unsigned char *p) +{ + return (unsigned) (p[0] | (p[1] << 8)); +} + +static unsigned long +LE32(const unsigned char *p) +{ + return (unsigned long) p[0] | ((unsigned long) p[1] << 8) | + ((unsigned long) p[2] << 16) | ((unsigned long) p[3] << 24); +} + +/* install a top-down RGB buffer as the document (owner keeps the buffer) */ +static int +SetImageRGB(const unsigned char *rgb, int w, int h) +{ + Pixmap np, ns; + XImage *im; + int x, y; + unsigned long *keys = NULL, *kpix = NULL; + int nkeys = 0; + + if (w < 1 || h < 1 || w > 4096 || h > 4096) + return -1; + np = XCreatePixmap(dpy, RootWindowOfScreen(scr), (unsigned) w, + (unsigned) h, depth); + ns = XCreatePixmap(dpy, RootWindowOfScreen(scr), (unsigned) w, + (unsigned) h, depth); + if (np == None || ns == None) { + if (np != None) + XFreePixmap(dpy, np); + if (ns != None) + XFreePixmap(dpy, ns); + return -1; + } + if (pix != None) + XFreePixmap(dpy, pix); + if (snap != None) + XFreePixmap(dpy, snap); + pix = np; + snap = ns; + imgW = w; + imgH = h; + if (canvas != NULL) + XtVaSetValues(canvas, XmNwidth, imgW * zoom, + XmNheight, imgH * zoom, NULL); + XSetForeground(dpy, gc, bgPix); + XFillRectangle(dpy, pix, gc, 0, 0, (unsigned) w, (unsigned) h); + im = XCreateImage(dpy, vis, depth, ZPixmap, 0, NULL, + (unsigned) w, (unsigned) h, 32, 0); + if (im == NULL) + return -1; + im->data = calloc(1, (size_t) im->bytes_per_line * h); + if (im->data == NULL) { + XDestroyImage(im); + return -1; + } + if (truecolor) { + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + const unsigned char *p = + rgb + ((size_t) y * w + x) * 3; + + XPutPixel(im, x, y, RGBToPixel(p[0], p[1], p[2])); + } + } else { + keys = malloc(sizeof(unsigned long) * (size_t) w * h); + if (keys != NULL) { + int i; + + for (i = 0; i < w * h; i++) + keys[i] = ((unsigned long) rgb[i * 3] << 16) | + ((unsigned long) rgb[i * 3 + 1] << 8) | + rgb[i * 3 + 2]; + qsort(keys, (size_t) (w * h), sizeof(unsigned long), + CmpUL); + nkeys = 0; + for (i = 0; i < w * h; i++) + if (i == 0 || keys[i] != keys[i - 1]) + keys[nkeys++] = keys[i]; + kpix = malloc(sizeof(unsigned long) * (size_t) nkeys); + if (kpix != NULL) { + unsigned char *krgb = + malloc((size_t) nkeys * 3); + + if (krgb != NULL) { + for (i = 0; i < nkeys; i++) { + krgb[i * 3] = + (unsigned char) (keys[i] >> 16); + krgb[i * 3 + 1] = + (unsigned char) (keys[i] >> 8); + krgb[i * 3 + 2] = + (unsigned char) keys[i]; + } + BatchAlloc(krgb, nkeys, kpix); + free(krgb); + } + } + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + const unsigned char *p = + rgb + ((size_t) y * w + x) * 3; + unsigned long key = + ((unsigned long) p[0] << 16) | + ((unsigned long) p[1] << 8) | p[2]; + unsigned long px = 0; + + if (keys != NULL && kpix != NULL) { + unsigned long *hit = bsearch(&key, keys, + (size_t) nkeys, sizeof(unsigned long), + CmpUL); + + if (hit != NULL) + px = kpix[hit - keys]; + } else { + px = RGBToPixel(p[0], p[1], p[2]); + } + XPutPixel(im, x, y, px); + } + free(keys); + free(kpix); + } + XPutImage(dpy, pix, gc, im, 0, 0, 0, 0, (unsigned) w, (unsigned) h); + XDestroyImage(im); + return 0; +} + +/* 8-bit palette BMP, uncompressed or RLE8 (the 24-bit path is OpenBMP24) */ +static int +LoadBMP8(FILE *f) +{ + unsigned char fh[14], ih[40], pal[256][3], *raw, *rgb, *idx; + unsigned long off, row, size; + long w, h, hs; + int bpp, comp, ncolors, i, y, x, topdown = 0; + + if (fread(fh, 1, 14, f) != 14 || fh[0] != 'B' || fh[1] != 'M') + return -1; + if (fread(ih, 1, 40, f) != 40) + return -1; + if (LE32(ih) != 40 || LE16(ih + 12) != 1) + return -1; + bpp = (int) LE16(ih + 14); + comp = (int) LE32(ih + 16); + if (bpp != 8 || (comp != 0 && comp != 1)) + return -1; + w = (long) LE32(ih + 4); + hs = (long) (int) LE32(ih + 8); + if (hs < 0) { + topdown = 1; + h = -hs; + } else { + h = hs; + } + if (w < 1 || h < 1 || w > 4096 || h > 4096) + return -1; + off = LE32(fh + 10); + ncolors = (int) LE32(ih + 32); + if (ncolors == 0) + ncolors = 256; + if (ncolors > 256) + ncolors = 256; + memset(pal, 0, sizeof pal); + if (fseek(f, 14 + 40, SEEK_SET) != 0) + return -1; + for (i = 0; i < ncolors; i++) { + unsigned char e[4]; + + if (fread(e, 1, 4, f) != 4) + return -1; + pal[i][0] = e[2]; + pal[i][1] = e[1]; + pal[i][2] = e[0]; + } + idx = calloc((size_t) w * h, 1); + if (idx == NULL) + return -1; + + if (comp == 0) { + row = (((unsigned long) w * 8 + 31) / 32) * 4; + raw = malloc((size_t) row * h); + if (raw == NULL) { + free(idx); + return -1; + } + if (fseek(f, (long) off, SEEK_SET) != 0 || + fread(raw, 1, (size_t) row * h, f) != (size_t) row * h) { + free(raw); + free(idx); + return -1; + } + for (y = 0; y < h; y++) { + unsigned char *src = + raw + (topdown ? y : (h - 1 - y)) * row; + + memcpy(idx + (size_t) y * w, src, (size_t) w); + } + free(raw); + } else { + /* RLE8: count/value pairs, 00 00 end of line, 00 01 end of + * bitmap, 00 02 dx dy delta, 00 n literals (padded to word) */ + FILE *g = f; + long beg, end; + unsigned char *rl; + size_t p = 0; + + if (fseek(g, 0, SEEK_END) != 0 || + (end = ftell(g)) < 0 || + fseek(g, (long) off, SEEK_SET) != 0) { + free(idx); + return -1; + } + beg = (long) off; + size = (unsigned long) (end - beg); + if (size > 64UL * 1024 * 1024) { + free(idx); + return -1; + } + rl = malloc((size_t) size); + if (rl == NULL || fread(rl, 1, (size_t) size, g) != (size_t) size) { + free(rl); + free(idx); + return -1; + } + x = 0; + y = topdown ? 0 : (int) h - 1; + while (p + 1 < size) { + int cnt = rl[p], val = rl[p + 1]; + + p += 2; + if (cnt > 0) { + int k; + + for (k = 0; k < cnt; k++) { + if (x < w && y >= 0 && y < h) + idx[(size_t) y * w + x] = + (unsigned char) val; + x++; + } + } else if (val == 0) { + x = 0; + y += topdown ? 1 : -1; + } else if (val == 1) { + break; + } else if (val == 2) { + int dx, dy; + + if (p + 1 >= size) + break; + dx = rl[p++]; + dy = rl[p++]; + x += dx; + y += topdown ? dy : -dy; + } else { + int k; + + for (k = 0; k < val && p < size; k++) { + if (x < w && y >= 0 && y < h) + idx[(size_t) y * w + x] = rl[p]; + x++; + p++; + } + if (val & 1) + p++; + } + } + free(rl); + } + + rgb = malloc((size_t) w * h * 3); + if (rgb == NULL) { + free(idx); + return -1; + } + for (i = 0; i < w * h; i++) { + unsigned char c = idx[i]; + + if (c >= ncolors) { + rgb[i * 3] = rgb[i * 3 + 1] = rgb[i * 3 + 2] = 0; + } else { + rgb[i * 3] = pal[c][0]; + rgb[i * 3 + 1] = pal[c][1]; + rgb[i * 3 + 2] = pal[c][2]; + } + } + free(idx); + i = SetImageRGB(rgb, (int) w, (int) h); + free(rgb); + return i; +} + +/* the first image of a Windows .ico (1, 4, 8, 24 or 32 bpp; PNG icons are + * refused because the program has no PNG decoder) */ +static int +LoadICO(FILE *f) +{ + unsigned char dir[6], ent[16], ih[40], pal[256][3], *raw, *rgb; + unsigned long off, row; + long w, h, hs; + int bpp, ncolors, i, y, x; + unsigned br, bg, bb; + + if (fread(dir, 1, 6, f) != 6 || LE16(dir) != 0 || LE16(dir + 2) != 1) + return -1; + if (LE16(dir + 4) < 1) + return -1; + if (fread(ent, 1, 16, f) != 16) + return -1; + off = LE32(ent + 12); + if (off < 22) + return -1; + if (fseek(f, (long) off, SEEK_SET) != 0) + return -1; + if (fread(ih, 1, 40, f) != 40) + return -1; + if (ih[0] == 0x89 && ih[1] == 'P' && ih[2] == 'N' && ih[3] == 'G') + return -1; + if (LE32(ih) != 40 || LE16(ih + 12) != 1 || LE32(ih + 16) != 0) + return -1; + w = (long) LE32(ih + 4); + hs = (long) (int) LE32(ih + 8); + if (hs <= 0 || (hs % 2) != 0) + return -1; + h = hs / 2; + if (w < 1 || h < 1 || w > 4096 || h > 4096) + return -1; + bpp = (int) LE16(ih + 14); + if (bpp != 1 && bpp != 4 && bpp != 8 && bpp != 24 && bpp != 32) + return -1; + ncolors = 0; + if (bpp <= 8) { + ncolors = (int) LE32(ih + 32); + if (ncolors == 0) + ncolors = 1 << bpp; + if (ncolors > 256) + ncolors = 256; + } + memset(pal, 0, sizeof pal); + for (i = 0; i < ncolors; i++) { + unsigned char e[4]; + + if (fread(e, 1, 4, f) != 4) + return -1; + pal[i][0] = e[2]; + pal[i][1] = e[1]; + pal[i][2] = e[0]; + } + row = (((unsigned long) w * bpp + 31) / 32) * 4; + raw = malloc((size_t) row * h); + if (raw == NULL) + return -1; + if (fread(raw, 1, (size_t) row * h, f) != (size_t) row * h) { + free(raw); + return -1; + } + rgb = malloc((size_t) w * h * 3); + if (rgb == NULL) { + free(raw); + return -1; + } + PixelToRGB(bgPix, &br, &bg, &bb); + for (y = 0; y < h; y++) { + unsigned char *src = raw + (h - 1 - y) * row; + + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + + if (bpp == 32) { + unsigned a = src[x * 4 + 3]; + + d[0] = src[x * 4 + 2]; + d[1] = src[x * 4 + 1]; + d[2] = src[x * 4]; + if (a == 0) { + d[0] = (unsigned char) br; + d[1] = (unsigned char) bg; + d[2] = (unsigned char) bb; + } + } else if (bpp == 24) { + d[0] = src[x * 3 + 2]; + d[1] = src[x * 3 + 1]; + d[2] = src[x * 3]; + } else { + int idx; + + if (bpp == 8) + idx = src[x]; + else if (bpp == 4) + idx = (x & 1) ? (src[x / 2] & 15) : + (src[x / 2] >> 4); + else + idx = (src[x / 8] >> (7 - (x & 7))) & 1; + if (idx >= ncolors) { + d[0] = d[1] = d[2] = 0; + } else { + d[0] = pal[idx][0]; + d[1] = pal[idx][1]; + d[2] = pal[idx][2]; + } + } + } + } + free(raw); + i = SetImageRGB(rgb, (int) w, (int) h); + free(rgb); + return i; +} + +/* Open a BMP (24 or 8 bit) or the first image of an ICO. */ +static int +OpenBMP(const char *path) +{ + FILE *f; + unsigned char m[6], hdr[54]; + int bpp; + + if ((f = fopen(path, "rb")) == NULL) + return -1; + if (fread(m, 1, 6, f) != 6) { + fclose(f); + return -1; + } + if (m[0] == 'B' && m[1] == 'M') { + fseek(f, 0, SEEK_SET); + if (fread(hdr, 1, 54, f) != 54 || LE32(hdr + 14) != 40) { + fclose(f); + return -1; + } + bpp = (int) LE16(hdr + 28); + if (bpp == 24) { + fclose(f); + return OpenBMP24(path); + } + if (bpp == 8) { + fseek(f, 0, SEEK_SET); + bpp = LoadBMP8(f); + fclose(f); + return bpp; + } + } else if (m[0] == 0 && m[1] == 0 && m[2] == 1 && m[3] == 0) { + fseek(f, 0, SEEK_SET); + bpp = LoadICO(f); + fclose(f); + return bpp; + } + fclose(f); + return -1; +} + /* --------------------------------------------------------------- drawing */ static void From 7c0281f48a7be1a6f9019fe9e021e82679575081 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 07:23:33 +0000 Subject: [PATCH 11/22] MCDE: print a file through McdeSys; dtpaint Print... (D4) McdeSys gains mcde_sys_print_file(path, printer): it looks for lp(1) (/usr/bin, /usr/local/bin, /usr/sbin, pkg prefix; MCDE_PRINT_COMMAND overrides it for tests), passes -d PRINTER when one is named, and runs it as the existing job (fd into the event loop, finish/cancel). dtpaint links libMcdeSys, adds File > Print... (Ctrl+P): it picks the default queue from mcde_sys_printers (or the first), writes the image to /tmp/dtpaint-PID.bmp, starts the job and removes the file when the job ends; errors and 'no printer is set up' go to the information dialog. Measured under Xvfb with MCDE_PRINT_COMMAND=fake lp: argv '-d HP_LaserJet_M110w_CC1016 /tmp/dtpaint-3543226.bmp', the fake copied a valid 640x480 BMP and the temporary file was gone; no physical page was printed (the real queue is the user's step). --- include/Mcde/McdeSys.h | 5 ++ lib/McdeSys/printers.c | 33 ++++++++ programs/dtpaint/Makefile.am | 2 +- programs/dtpaint/dtpaint.c | 77 ++++++++++++++++++- programs/dtpaint/dtpaint.msg | 3 + .../localized/de_DE.UTF-8/msg/dtpaint.msg | 3 + 6 files changed, 119 insertions(+), 4 deletions(-) diff --git a/include/Mcde/McdeSys.h b/include/Mcde/McdeSys.h index 53c1fb81..d65d97f5 100644 --- a/include/Mcde/McdeSys.h +++ b/include/Mcde/McdeSys.h @@ -732,6 +732,11 @@ int mcde_sys_printers(McdeSysPrinter *list, size_t max); /* the default queue for new jobs (root: needs the administrator) */ int mcde_sys_printer_default(const char *name); +/* Spool PATH to PRINTER (NULL or "" = the default queue) with lp(1), as a + * job for the event loop (mcde_sys_job_fd/_finish/_cancel). MCDE_PRINT_COMMAND + * names the tool instead, for tests with a fake lp. */ +McdeSysJob *mcde_sys_print_file(const char *path, const char *printer); + /* a queue for URI with the driverless model (lpadmin -p NAME -E -v URI -m * everywhere); root, a name without spaces or slashes, an ipp:// URI */ int mcde_sys_printer_add(const char *name, const char *uri); diff --git a/lib/McdeSys/printers.c b/lib/McdeSys/printers.c index 4a9dc86f..909fff99 100644 --- a/lib/McdeSys/printers.c +++ b/lib/McdeSys/printers.c @@ -142,6 +142,39 @@ mcde_sys_printer_default(const char *name) return MCDE_SYS_OK; } +McdeSysJob * +mcde_sys_print_file(const char *path, const char *printer) +{ + static const char *const where[] = { "/usr/bin/lp", + "/usr/local/bin/lp", "/usr/sbin/lp", MCDE_PKG_PREFIX "/bin/lp", + NULL }; + const char *lp = getenv("MCDE_PRINT_COMMAND"); + char *argv[5]; + int n = 0; + + if (path == NULL || path[0] == '\0' || access(path, R_OK) != 0) { + (void) mcde_sys_fail(MCDE_SYS_ENOTSUP, + mcde_sys_msg(MSG_NOT_THERE, "%s is not there."), + path != NULL ? path : ""); + return NULL; + } + if (lp == NULL) + lp = Tool(where); + if (lp == NULL) { + (void) mcde_sys_fail(MCDE_SYS_ENOTSUP, + mcde_sys_msg(MSG_NOT_THERE, "%s is not there."), "lp"); + return NULL; + } + argv[n++] = (char *) lp; + if (printer != NULL && printer[0] != '\0') { + argv[n++] = (char *) "-d"; + argv[n++] = (char *) printer; + } + argv[n++] = (char *) path; + argv[n] = NULL; + return mcde_sys_job_start(argv, NULL); +} + /* the checks every name and URI pass before they reach a command line */ static int NameOk(const char *name) diff --git a/programs/dtpaint/Makefile.am b/programs/dtpaint/Makefile.am index cd9b2359..c574bf77 100644 --- a/programs/dtpaint/Makefile.am +++ b/programs/dtpaint/Makefile.am @@ -5,7 +5,7 @@ bin_PROGRAMS = dtpaint dtpaint_CPPFLAGS = -I$(top_srcdir)/include \ -DCDE_INSTALLATION_TOP=\"$(CDE_INSTALLATION_TOP)\" -dtpaint_LDADD = $(DTCLIENTLIBS) $(XTOOLLIB) +dtpaint_LDADD = $(LIBMCDESYS) $(DTCLIENTLIBS) $(XTOOLLIB) if SOLARIS dtpaint_LDADD += -lintl diff --git a/programs/dtpaint/dtpaint.c b/programs/dtpaint/dtpaint.c index a099f886..c4b9ec74 100644 --- a/programs/dtpaint/dtpaint.c +++ b/programs/dtpaint/dtpaint.c @@ -36,6 +36,8 @@ #include #include +#include + #include #include #include @@ -108,6 +110,7 @@ static const char *const toolNames[] = { }; static Display *dpy; +static XtAppContext appctx; static Screen *scr; static Visual *vis; static Colormap cmap; @@ -2146,7 +2149,7 @@ SwatchActivate(Widget w, XtPointer data, XtPointer call) /* ------------------------------------------------------------------ menus */ enum { - C_NEW, C_OPEN, C_SAVE, C_SAVEAS, C_EXIT, + C_NEW, C_OPEN, C_SAVE, C_SAVEAS, C_PRINT, C_EXIT, C_UNDO, C_CLEAR, C_CLEARSEL, C_SELALL, C_INVERT, C_FLIP, C_TOOLS, C_COLORS, C_STATUS, C_HELP, C_ABOUT, C_ZNORMAL, C_ZLARGE, C_ATTR, C_EDITCOLORS @@ -2189,10 +2192,10 @@ ShowError(int msgid, const char *path) } static void -ShowInfo(int bodyId, const char *bodyFb, int titleId, const char *titleFb) +ShowText(const char *body, int titleId, const char *titleFb) { Widget d = XmCreateInformationDialog(top, "info", NULL, 0); - XmString s = Msg(bodyId, bodyFb); + XmString s = XmStringCreateLocalized((String) body); XtVaSetValues(d, XmNmessageString, s, NULL); XmStringFree(s); @@ -2205,6 +2208,68 @@ ShowInfo(int bodyId, const char *bodyFb, int titleId, const char *titleFb) XtManageChild(d); } +static void +ShowInfo(int bodyId, const char *bodyFb, int titleId, const char *titleFb) +{ + ShowText(PaintMsg(bodyId, bodyFb), titleId, titleFb); +} + +/* ---------------------------------------------------------------- printing */ + +static McdeSysJob *printJob; +static char printPath[256]; + +static void +PrintDone(XtPointer cd, int *fd, XtInputId *id) +{ + McdeSysJob *job = (McdeSysJob *) cd; + int rc = mcde_sys_job_finish(job); + + (void) fd; + XtRemoveInput(*id); + if (rc != MCDE_SYS_OK) + ShowText(mcde_sys_error(), 51, "Print"); + unlink(printPath); + printJob = NULL; +} + +static void +PrintImage(void) +{ + McdeSysPrinter list[32]; + const char *printer = NULL; + int n, i; + + if (printJob != NULL) + return; + n = mcde_sys_printers(list, 32); + if (n <= 0) { + ShowInfo(50, "No printer is set up.", 51, "Print"); + return; + } + for (i = 0; i < n; i++) + if (list[i].is_default) { + printer = list[i].name; + break; + } + if (printer == NULL) + printer = list[0].name; + snprintf(printPath, sizeof printPath, "/tmp/dtpaint-%d.bmp", + (int) getpid()); + if (SaveBMP(printPath) != 0) { + ShowError(27, printPath); + return; + } + printJob = mcde_sys_print_file(printPath, printer); + if (printJob == NULL) { + unlink(printPath); + ShowText(mcde_sys_error(), 51, "Print"); + return; + } + XtAppAddInput(appctx, mcde_sys_job_fd(printJob), + (XtPointer) XtInputReadMask, PrintDone, printJob); +} + /* ------------------------------------------------- image size and colours */ static void @@ -2526,6 +2591,9 @@ Command(Widget w, XtPointer data, XtPointer call) case C_SAVEAS: FileDialog(1); break; + case C_PRINT: + PrintImage(); + break; case C_EXIT: MaybeDiscard(A_EXIT); break; @@ -2791,6 +2859,7 @@ main(int argc, char **argv) selftest = 1; top = XtVaAppInitialize(&app, "Dtpaint", NULL, 0, &argc, argv, NULL, NULL); + appctx = app; dpy = XtDisplay(top); (void) srand((unsigned) getpid()); InitColor(); @@ -2884,6 +2953,8 @@ main(int argc, char **argv) AddItem(m, PaintMsg(9, "Save"), "CtrlS", "Ctrl+S", C_SAVE, 0, True); AddItem(m, PaintMsg(10, "Save As..."), NULL, NULL, C_SAVEAS, 0, True); AddItem(m, NULL, NULL, NULL, 0, 1, True); + AddItem(m, PaintMsg(53, "Print..."), "CtrlP", "Ctrl+P", + C_PRINT, 0, True); AddItem(m, PaintMsg(11, "Exit"), "AltF4", "Alt+F4", C_EXIT, 0, True); m = AddMenu(menubarW, PaintMsg(2, "Edit")); AddItem(m, PaintMsg(12, "Undo"), "CtrlZ", "Ctrl+Z", C_UNDO, 0, True); diff --git a/programs/dtpaint/dtpaint.msg b/programs/dtpaint/dtpaint.msg index 8872bb6b..10b0964b 100644 --- a/programs/dtpaint/dtpaint.msg +++ b/programs/dtpaint/dtpaint.msg @@ -51,3 +51,6 @@ $set 1 47 Blue: 48 OK 49 Cancel +50 No printer is set up. +51 Print +53 Print... diff --git a/programs/localized/de_DE.UTF-8/msg/dtpaint.msg b/programs/localized/de_DE.UTF-8/msg/dtpaint.msg index 8aff9038..c89b23af 100644 --- a/programs/localized/de_DE.UTF-8/msg/dtpaint.msg +++ b/programs/localized/de_DE.UTF-8/msg/dtpaint.msg @@ -52,3 +52,6 @@ $set 1 47 Blau: 48 OK 49 Abbrechen +50 Es ist kein Drucker eingerichtet. +51 Drucken +53 Drucken... From 5ee5dfcb0a9f5e30778cf46bcb2d460dfe0d4573 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 07:31:31 +0000 Subject: [PATCH 12/22] docs: dtpaint D3/D4 (tools, formats, print) recorded C3's status gains the 2026-11-22 paragraph: airbrush/text/curve/polygon, rect/free selection with XOR marquee, move and Delete/Select All, zoom 1x-8x, Attributes, Edit Colors, 8-bit BMP (uncompressed and RLE8) and ICO read, 24-bit BMP save, and Print through mcde_sys_print_file with the temporary file removed when the job ends. The physical page on the HP printer stays the user's step; the spool path is verified with a fake lp. AGENTS.md: the same in the dtpaint paragraph and the catalog count (51 messages, 52 free). --- AGENTS.md | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f8e8b6a4..532237a1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,8 +69,9 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt status lines and the open/save errors) keeps its menus as the reference's (`dtphoto.menu`, docs/reference/photoshop-ui.csv) -- they are the look of the program, not its sentences. dtpaint builds its menus in code and its - labels are catalogued (`dtpaint.msg`, 34 messages: menus, the file/error/ - discard dialogs, Help and About); the program has no render table, so its + labels are catalogued (`dtpaint.msg`, 51 messages from 1-53, 52 unused: + menus, the tool/file/error/discard/attributes/colour/print dialogs, Help + and About); the program has no render table, so its German strings avoid umlauts (a UTF-8 `ü` came out as two latin-1 characters under the core font, measured 2026-11-16; the German copy transliterates ae/oe/ue throughout, re-measured 2026-11-21). Its canvas @@ -83,7 +84,19 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt 14.9 s -> 0.05 s, save 6.3 s -> 0.23 s on a 1024x768 BMP; PseudoColor measured 2026-11-22 on Xvfb depth 8: 4-colour BMP round trip exact, selftest PASS -- a picture with more colours than the 256-cell colormap - holds loses the excess, as any 8-bit paint must). + holds loses the excess, as any 8-bit paint must). D3/D4 are built + (2026-11-22): the airbrush sprays, Text fills a background box and draws + the GC font, Curve is a two-phase quadratic and Polygon closes on a right + or double click; rectangular and free-form selection draw an XOR marquee, + move their pixels and clear through Edit > Clear Selection (Del), and + Select All is Ctrl+A; the magnifier and View > Normal/Large Size zoom + 1x/2x/4x/8x; Attributes resizes the document (a document operation, no + undo across it); Edit Colors sets the foreground from three RGB scales; + BMP 8-bit (uncompressed and RLE8) and the first image of an ICO + (1/4/8/24/32 bpp, alpha 0 composited on the background; PNG-compressed + icons refused) are read, saving stays 24-bit BMP; Print spools the + current image through `mcde_sys_print_file` (lp; MCDE_PRINT_COMMAND fakes + the tool in tests) and removes the temporary file when the job ends. McdeSys has a catalog too (`lib/McdeSys/mcdesys.msg`, `lib/McdeSys/ text.c`, `mcde_sys_msg`): common.c's tool errors ask it for their sentence (messages 1-9: not there, cannot start, failed with status, no pipe, no From 226b2116f142676328eb95cb13118e16c18bb6f8 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 08:28:41 +0000 Subject: [PATCH 13/22] MCDE dtphoto: open and save through one RGB buffer, not per pixel (P1) dtphoto allocated a colour in the server for every pixel it opened and queried one for every pixel it saved -- one X round trip per pixel, the same fault dtpaint lost on 2026-11-21. dtpaint was carried over; dtphoto was not. The document now goes through an 8-bit RGB buffer (SetImageRGB, GetImageRGB) and converts colours through the visual's masks on TrueColor, or in one XQueryColors/XAllocColor per *distinct* colour otherwise. The reader takes 24-bit BMP (bottom-up and top-down), 8-bit BMP uncompressed and RLE8, and the first image of an ICO (1/4/8/24/32 bpp, alpha 0 composited on the document's background, a PNG-compressed icon refused), as dtpaint does; the save keeps the 2835 dpi fields the old writer wrote. The selftest compares every pixel now, not a sample, and its two callers pass a real file each instead of relying on a scratch document. Measured on Xvfb (1280x1024x24), a 1024x768 24-bit BMP with 589,824 distinct colours, `dtphoto -selftest big.bmp out.bmp`: 20.3 s before the change (the old binary, same picture, 20.326 s), 58-109 ms after (5 runs). The round trip is byte-identical: 2,359,350 bytes, `cmp` silent, dpi fields included. depth 8 (PseudoColor, Xvfb 1280x1024x8): PASS, exact for 4- and 65536-colour documents alike. 8-bit BMP, RLE8 BMP, ICO 8 bpp and ICO 32 bpp read exact on both depths (0 wrong pixels, /tmp/dtptest). make in build/mcde-linux/programs/dtphoto: cc and libtool link exit=0, no new warning (the two const warnings in XmStringCreateLocalized calls are older than this change). Documented in AGENTS.md and docs/MCDE-PROGRAMS.md (C1). --- AGENTS.md | 22 +- programs/dtphoto/dtphoto.c | 844 ++++++++++++++++++++++++++++++++----- 2 files changed, 748 insertions(+), 118 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 532237a1..78cbb926 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,10 +68,24 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt catalog. dtphoto (`dtphoto.msg`, 5 messages: the toolbox title, the two status lines and the open/save errors) keeps its menus as the reference's (`dtphoto.menu`, docs/reference/photoshop-ui.csv) -- they are the look of - the program, not its sentences. dtpaint builds its menus in code and its - labels are catalogued (`dtpaint.msg`, 51 messages from 1-53, 52 unused: - menus, the tool/file/error/discard/attributes/colour/print dialogs, Help - and About); the program has no render table, so its + the program, not its sentences. dtphoto reads and saves through one + 8-bit RGB buffer (`SetImageRGB`, `GetImageRGB`) and converts colours + through the visual's masks on TrueColor, or in one XQueryColors/ + XAllocColor per *distinct* colour otherwise -- never one X round trip per + pixel. Measured 2026-11-22 on Xvfb 1280x1024x24, a 1024x768 24-bit BMP + with 589,824 distinct colours: `dtphoto -selftest A B` 20.3 s before the + change, 0.046 s after; the round trip is byte-identical (2,359,350 bytes, + 0 differing) and the selftest now compares every pixel, not a sample + (`/tmp/dtptest`). The same reader takes 8-bit BMP (uncompressed and + RLE8) and the first image of an ICO (1/4/8/24/32 bpp, alpha 0 composited + on the document's background, a PNG-compressed icon refused), as dtpaint + does; depth 8 (PseudoColor) is exact for 4 and 65536-colour documents + alike. A document with more colours than the 256-cell colormap holds + loses the excess, as any 8-bit picture must. + dtpaint builds its menus in code and its labels are catalogued + (`dtpaint.msg`, 51 messages from 1-53, 52 unused: menus, the + tool/file/error/discard/attributes/colour/print dialogs, Help and About); + the program has no render table, so its German strings avoid umlauts (a UTF-8 `ü` came out as two latin-1 characters under the core font, measured 2026-11-16; the German copy transliterates ae/oe/ue throughout, re-measured 2026-11-21). Its canvas diff --git a/programs/dtphoto/dtphoto.c b/programs/dtphoto/dtphoto.c index d9809dad..b18741c5 100644 --- a/programs/dtphoto/dtphoto.c +++ b/programs/dtphoto/dtphoto.c @@ -79,6 +79,22 @@ static Pixel fgPixel, bgPixel; static int selX0, selY0, selX1, selY1, hasSel, dragging; static int lastX, lastY, pressX, pressY; +/* the screen's colour model. On TrueColor/DirectColor a pixel is arithmetic + * on the visual's masks, so RGB <-> pixel needs no server round trip; on + * PseudoColor the distinct colours are asked for and allocated in one batch. + * Until 2026-11-22 OpenBMP called XAllocColor and SaveBMP XQueryColor once + * per pixel: 20 s for a 1024x768 picture at depth 24 (measured, + * /tmp/dtptest). dtpaint had the same defect and is the pattern followed + * here (ext/src/mcde/AGENTS.md, dtpaint paragraph). */ +static Screen *scr; +static Visual *vis; +static Drawable drawable; /* the root window, what a pixmap is made with */ +static Colormap cmap; +static int visdepth, truecolor; +static unsigned long rmask, gmask, bmask; +static int rshift, gshift, bshift; +static unsigned long rmax, gmax, bmax; + static const char *const toolNames[] = { "marquee", "ellipse", "lasso", "wand", "move", "hand", "zoom", "crop", @@ -88,33 +104,227 @@ static const char *const toolNames[] = { "sponge", "eyedropper", NULL }; -/* ------------------------------------------------------------------ files */ +static void NewPixmaps(void); +static void DrawMarquee(Window win, int ox, int oy); + +/* ----------------------------------------------------------------- colour */ static int -PixelRGB(unsigned long pixel, unsigned char *r, unsigned char *g, unsigned char *b) +ShiftOf(unsigned long mask) +{ + int s = 0; + + while (mask != 0 && !(mask & 1)) { + mask >>= 1; + s++; + } + return s; +} + +static void +InitColor(void) +{ + scr = XtScreen(top); + vis = DefaultVisualOfScreen(scr); + drawable = RootWindowOfScreen(scr); + cmap = DefaultColormapOfScreen(scr); + visdepth = DefaultDepthOfScreen(scr); + rmask = vis->red_mask; + gmask = vis->green_mask; + bmask = vis->blue_mask; + rshift = ShiftOf(rmask); + gshift = ShiftOf(gmask); + bshift = ShiftOf(bmask); + rmax = rmask >> rshift; + gmax = gmask >> gshift; + bmax = bmask >> bshift; + truecolor = (vis->class == TrueColor || vis->class == DirectColor); +} + +static unsigned long +RGBToPixel(unsigned r, unsigned g, unsigned b) { - static unsigned long cp[64]; - static unsigned char cr[64][3]; - static int n; - int i; XColor c; - for (i = 0; i < n; i++) - if (cp[i] == pixel) { - *r = cr[i][0]; *g = cr[i][1]; *b = cr[i][2]; - return 0; - } - c.pixel = pixel; - if (!XQueryColor(dpy, DefaultColormap(dpy, 0), &c)) - return -1; + if (truecolor) + return ((unsigned long) (r * rmax / 255) << rshift) | + ((unsigned long) (g * gmax / 255) << gshift) | + ((unsigned long) (b * bmax / 255) << bshift); + c.red = (unsigned short) (r * 257); + c.green = (unsigned short) (g * 257); + c.blue = (unsigned short) (b * 257); + c.flags = DoRed | DoGreen | DoBlue; + c.pixel = 0; + if (!XAllocColor(dpy, cmap, &c)) + return 0; + return c.pixel; +} + +static void +PixelToRGB(unsigned long p, unsigned char *r, unsigned char *g, unsigned char *b) +{ + XColor c; + + if (truecolor) { + *r = (unsigned char) (((p & rmask) >> rshift) * + 255 / (rmax ? rmax : 1)); + *g = (unsigned char) (((p & gmask) >> gshift) * + 255 / (gmax ? gmax : 1)); + *b = (unsigned char) (((p & bmask) >> bshift) * + 255 / (bmax ? bmax : 1)); + return; + } + c.pixel = p; + if (!XQueryColor(dpy, cmap, &c)) { + *r = *g = *b = 0; + return; + } *r = (unsigned char) (c.red >> 8); *g = (unsigned char) (c.green >> 8); *b = (unsigned char) (c.blue >> 8); - if (n < 64) { - cp[n] = pixel; - cr[n][0] = *r; cr[n][1] = *g; cr[n][2] = *b; - n++; +} + +static int +CmpUL(const void *a, const void *b) +{ + unsigned long x = *(const unsigned long *) a; + unsigned long y = *(const unsigned long *) b; + + return (x < y) ? -1 : (x > y) ? 1 : 0; +} + +/* sort KEYS in place and drop the repeats; the number left */ +static int +Unique(unsigned long *keys, int n) +{ + int i, j = 0; + + qsort(keys, (size_t) n, sizeof(unsigned long), CmpUL); + for (i = 0; i < n; i++) + if (i == 0 || keys[i] != keys[i - 1]) + keys[j++] = keys[i]; + return j; +} + +/* the RGB of N distinct pixels, in one XQueryColors instead of N round trips + * (PseudoColor only; on TrueColor PixelToRGB needs no server at all) */ +static void +BatchQuery(unsigned long *pix, int n, unsigned char *rgb) +{ + XColor *cols; + int i; + + if ((cols = malloc(sizeof(XColor) * (size_t) n)) == NULL) + return; + for (i = 0; i < n; i++) + cols[i].pixel = pix[i]; + if (XQueryColors(dpy, cmap, cols, n)) + for (i = 0; i < n; i++) { + rgb[i * 3] = (unsigned char) (cols[i].red >> 8); + rgb[i * 3 + 1] = (unsigned char) (cols[i].green >> 8); + rgb[i * 3 + 2] = (unsigned char) (cols[i].blue >> 8); + } + free(cols); +} + +/* the RGB as 0xRRGGBB keys of the distinct colours, ascending; the count */ +static int +DistinctColors(const unsigned char *rgb, int n, unsigned long **keyp) +{ + unsigned long *keys; + int i; + + if ((keys = malloc(sizeof(unsigned long) * (size_t) n)) == NULL) { + *keyp = NULL; + return 0; } + for (i = 0; i < n; i++) + keys[i] = ((unsigned long) rgb[i * 3] << 16) | + ((unsigned long) rgb[i * 3 + 1] << 8) | rgb[i * 3 + 2]; + *keyp = keys; + return Unique(keys, n); +} + +/* ------------------------------------------------------------------ files */ + +/* the document from an 8-bit RGB buffer (W x H, rows tight, top-down): the + * image and the undo snapshot, and the status line. On TrueColor the pixels + * are arithmetic on the masks; on PseudoColor one XAllocColor per *distinct* + * colour, never per pixel. */ +static int +SetImageRGB(const unsigned char *rgb, int w, int h) +{ + XImage *im; + unsigned long *keys = NULL, *kpix = NULL; + int nkeys = 0, x, y; + + if (w < 1 || h < 1 || w > 8192 || h > 8192) + return -1; + docW = w; + docH = h; + NewPixmaps(); + im = XCreateImage(dpy, vis, (unsigned int) visdepth, ZPixmap, 0, NULL, + (unsigned int) w, (unsigned int) h, 32, 0); + if (im == NULL) + return -1; + if ((im->data = calloc(1, (size_t) im->bytes_per_line * h)) == NULL) { + XDestroyImage(im); + return -1; + } + if (!truecolor) { + nkeys = DistinctColors(rgb, w * h, &keys); + if (nkeys > 0 && (kpix = malloc(sizeof(unsigned long) * + (size_t) nkeys)) != NULL) { + unsigned char *krgb = malloc((size_t) nkeys * 3); + + if (krgb != NULL) { + int i; + + for (i = 0; i < nkeys; i++) { + krgb[i * 3] = + (unsigned char) (keys[i] >> 16); + krgb[i * 3 + 1] = + (unsigned char) (keys[i] >> 8); + krgb[i * 3 + 2] = (unsigned char) keys[i]; + } + for (i = 0; i < nkeys; i++) + kpix[i] = RGBToPixel(krgb[i * 3], + krgb[i * 3 + 1], krgb[i * 3 + 2]); + free(krgb); + } else { + free(kpix); + kpix = NULL; + } + } + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + const unsigned char *p = rgb + ((size_t) y * w + x) * 3; + unsigned long px; + + if (truecolor) { + px = RGBToPixel(p[0], p[1], p[2]); + } else if (keys != NULL && kpix != NULL) { + unsigned long key = + ((unsigned long) p[0] << 16) | + ((unsigned long) p[1] << 8) | p[2]; + unsigned long *hit = bsearch(&key, keys, + (size_t) nkeys, sizeof(unsigned long), + CmpUL); + + px = (hit != NULL) ? kpix[hit - keys] + : RGBToPixel(p[0], p[1], p[2]); + } else { + px = RGBToPixel(p[0], p[1], p[2]); + } + XPutPixel(im, x, y, px); + } + free(keys); + free(kpix); + XPutImage(dpy, image, gc, im, 0, 0, 0, 0, (unsigned int) w, + (unsigned int) h); + XDestroyImage(im); + XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); return 0; } @@ -127,35 +337,83 @@ PutLE(unsigned char *p, unsigned long v, int n) p[i] = (unsigned char) ((v >> (8 * i)) & 0xff); } +/* the document as 8-bit RGB, rows top-down and tight: one XGetImage and, + * off TrueColor, one XQueryColors for the distinct pixels -- never one + * XQueryColor per pixel. The caller frees. */ +static int +GetImageRGB(unsigned char **rgbp, int *wp, int *hp) +{ + XImage *im; + unsigned char *rgb; + unsigned long *keys = NULL; + unsigned char *krgb = NULL; + int nkeys = 0, x, y; + + if (docW < 1 || docH < 1) + return -1; + if ((im = XGetImage(dpy, image, 0, 0, docW, docH, AllPlanes, + ZPixmap)) == NULL) + return -1; + if ((rgb = malloc((size_t) docW * docH * 3)) == NULL) { + XDestroyImage(im); + return -1; + } + if (!truecolor) { + if ((keys = malloc(sizeof(unsigned long) * + (size_t) docW * docH)) != NULL) { + for (y = 0; y < docH; y++) + for (x = 0; x < docW; x++) + keys[nkeys++] = XGetPixel(im, x, y); + nkeys = Unique(keys, nkeys); + if ((krgb = malloc((size_t) nkeys * 3)) != NULL) + BatchQuery(keys, nkeys, krgb); + } + } + for (y = 0; y < docH; y++) + for (x = 0; x < docW; x++) { + unsigned char *d = rgb + ((size_t) y * docW + x) * 3; + unsigned long px = XGetPixel(im, x, y); + + if (truecolor) { + PixelToRGB(px, &d[0], &d[1], &d[2]); + } else if (keys != NULL && krgb != NULL) { + unsigned long *hit = bsearch(&px, keys, + (size_t) nkeys, sizeof(unsigned long), + CmpUL); + + if (hit == NULL) { + d[0] = d[1] = d[2] = 0; + continue; + } + d[0] = krgb[(hit - keys) * 3]; + d[1] = krgb[(hit - keys) * 3 + 1]; + d[2] = krgb[(hit - keys) * 3 + 2]; + } else { + PixelToRGB(px, &d[0], &d[1], &d[2]); + } + } + free(keys); + free(krgb); + XDestroyImage(im); + *rgbp = rgb; + *wp = docW; + *hp = docH; + return 0; +} + static int SaveBMP(const char *path) { FILE *f; - XImage *im; + unsigned char *rgb, hdr[54]; int row = ((docW * 3 + 3) / 4) * 4; unsigned long size = (unsigned long) row * docH; - unsigned char *data; - unsigned char hdr[54]; int x, y; - if ((im = XGetImage(dpy, image, 0, 0, docW, docH, AllPlanes, ZPixmap)) == NULL) + if (GetImageRGB(&rgb, &x, &y) != 0) return -1; - if ((data = calloc(1, (size_t) size)) == NULL) { - XDestroyImage(im); - return -1; - } - for (y = 0; y < docH; y++) - for (x = 0; x < docW; x++) { - unsigned char r, g, b; - unsigned char *p = data + (size_t) (docH - 1 - y) * row + x * 3; - - if (PixelRGB(XGetPixel(im, x, y), &r, &g, &b) < 0) - continue; - p[0] = b; p[1] = g; p[2] = r; - } - XDestroyImage(im); if ((f = fopen(path, "wb")) == NULL) { - free(data); + free(rgb); return -1; } memset(hdr, 0, sizeof hdr); @@ -170,86 +428,439 @@ SaveBMP(const char *path) PutLE(hdr + 34, size, 4); PutLE(hdr + 38, 2835, 4); PutLE(hdr + 42, 2835, 4); - fwrite(hdr, 1, sizeof hdr, f); - fwrite(data, 1, (size_t) size, f); - fclose(f); - free(data); + if (fwrite(hdr, 1, sizeof hdr, f) != sizeof hdr) { + fclose(f); + free(rgb); + return -1; + } + for (y = docH - 1; y >= 0; y--) { + const unsigned char *s = rgb + (size_t) y * docW * 3; + unsigned char *line = malloc((size_t) row); + + if (line == NULL) { + fclose(f); + free(rgb); + return -1; + } + memset(line, 0, (size_t) row); + for (x = 0; x < docW; x++) { + line[x * 3] = s[x * 3 + 2]; + line[x * 3 + 1] = s[x * 3 + 1]; + line[x * 3 + 2] = s[x * 3]; + } + if (fwrite(line, 1, (size_t) row, f) != (size_t) row) { + free(line); + fclose(f); + free(rgb); + return -1; + } + free(line); + } + free(rgb); + if (fclose(f) != 0) + return -1; return 0; } -static void NewPixmaps(void); -static void DrawMarquee(Window win, int ox, int oy); +static unsigned +LE16(const unsigned char *p) +{ + return (unsigned) (p[0] | (p[1] << 8)); +} +static unsigned long +LE32(const unsigned char *p) +{ + return (unsigned long) p[0] | ((unsigned long) p[1] << 8) | + ((unsigned long) p[2] << 16) | ((unsigned long) p[3] << 24); +} + +/* a 24-bit BMP (BITMAPINFOHEADER, uncompressed, bottom-up or top-down) */ +static int +OpenBMP24(const char *path) +{ + FILE *f; + unsigned char hdr[54]; + unsigned long off, row, size; + long w, h, hs; + unsigned char *data, *rgb; + int x, y, topdown = 0; + + if ((f = fopen(path, "rb")) == NULL) + return -1; + if (fread(hdr, 1, 54, f) != 54 || hdr[0] != 'B' || hdr[1] != 'M' || + LE32(hdr + 14) != 40 || LE16(hdr + 28) != 24 || + LE32(hdr + 30) != 0) { + fclose(f); + return -1; + } + off = LE32(hdr + 10); + w = (long) LE32(hdr + 18); + hs = (long) (int) LE32(hdr + 22); + if (hs < 0) { + topdown = 1; + h = -hs; + } else { + h = hs; + } + if (w < 1 || h < 1 || w > 8192 || h > 8192) { + fclose(f); + return -1; + } + row = (((unsigned long) w * 24 + 31) / 32) * 4; + size = row * (unsigned long) h; + if ((data = malloc((size_t) size)) == NULL) { + fclose(f); + return -1; + } + if (fseek(f, (long) off, SEEK_SET) != 0 || + fread(data, 1, (size_t) size, f) != (size_t) size) { + free(data); + fclose(f); + return -1; + } + fclose(f); + if ((rgb = malloc((size_t) w * h * 3)) == NULL) { + free(data); + return -1; + } + for (y = 0; y < h; y++) { + const unsigned char *s = data + (topdown ? (long) y : + h - 1 - y) * row; + + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + + d[0] = s[x * 3 + 2]; + d[1] = s[x * 3 + 1]; + d[2] = s[x * 3]; + } + } + free(data); + x = SetImageRGB(rgb, (int) w, (int) h); + free(rgb); + return x; +} + +/* 8-bit palette BMP, uncompressed or RLE8 */ +static int +OpenBMP8(const char *path) +{ + FILE *f; + unsigned char fh[14], ih[40], pal[256][3], *raw, *rgb, *idx; + unsigned long off, row, size; + long w, h, hs; + int bpp, comp, ncolors, i, y, x, topdown = 0; + + if ((f = fopen(path, "rb")) == NULL) + return -1; + if (fread(fh, 1, 14, f) != 14 || fh[0] != 'B' || fh[1] != 'M' || + fread(ih, 1, 40, f) != 40 || LE32(ih) != 40 || + LE16(ih + 12) != 1) { + fclose(f); + return -1; + } + bpp = (int) LE16(ih + 14); + comp = (int) LE32(ih + 16); + if (bpp != 8 || (comp != 0 && comp != 1)) { + fclose(f); + return -1; + } + w = (long) LE32(ih + 4); + hs = (long) (int) LE32(ih + 8); + if (hs < 0) { + topdown = 1; + h = -hs; + } else { + h = hs; + } + if (w < 1 || h < 1 || w > 8192 || h > 8192) { + fclose(f); + return -1; + } + off = LE32(fh + 10); + ncolors = (int) LE32(ih + 32); + if (ncolors == 0) + ncolors = 256; + if (ncolors > 256) + ncolors = 256; + memset(pal, 0, sizeof pal); + for (i = 0; i < ncolors; i++) { + unsigned char e[4]; + + if (fread(e, 1, 4, f) != 4) { + fclose(f); + return -1; + } + pal[i][0] = e[2]; + pal[i][1] = e[1]; + pal[i][2] = e[0]; + } + if ((idx = calloc((size_t) w * h, 1)) == NULL) { + fclose(f); + return -1; + } + if (comp == 0) { + row = (((unsigned long) w * 8 + 31) / 32) * 4; + if ((raw = malloc((size_t) row * h)) == NULL) { + free(idx); + fclose(f); + return -1; + } + if (fseek(f, (long) off, SEEK_SET) != 0 || + fread(raw, 1, (size_t) row * h, f) != (size_t) row * h) { + free(raw); + free(idx); + fclose(f); + return -1; + } + for (y = 0; y < h; y++) + memcpy(idx + (size_t) y * w, + raw + (topdown ? y : (h - 1 - y)) * row, (size_t) w); + free(raw); + } else { + /* RLE8: count/value, 00 00 end of line, 00 01 end of bitmap, + * 00 02 dx dy delta, 00 n literals padded to a word */ + long end; + unsigned char *rl = NULL; + size_t p = 0; + + if (fseek(f, 0, SEEK_END) != 0 || (end = ftell(f)) < 0 || + fseek(f, (long) off, SEEK_SET) != 0) { + free(idx); + fclose(f); + return -1; + } + size = (unsigned long) (end - (long) off); + if (size > 64UL * 1024 * 1024 || + (rl = malloc((size_t) size)) == NULL || + fread(rl, 1, (size_t) size, f) != (size_t) size) { + free(rl); + free(idx); + fclose(f); + return -1; + } + x = 0; + y = topdown ? 0 : (int) h - 1; + while (p + 1 < size) { + int cnt = rl[p], val = rl[p + 1], k; + + p += 2; + if (cnt > 0) { + for (k = 0; k < cnt; k++) { + if (x < w && y >= 0 && y < h) + idx[(size_t) y * w + x] = + (unsigned char) val; + x++; + } + } else if (val == 0) { + x = 0; + y += topdown ? 1 : -1; + } else if (val == 1) { + break; + } else if (val == 2) { + int dx, dy; + + if (p + 1 >= size) + break; + dx = rl[p++]; + dy = rl[p++]; + x += dx; + y += topdown ? dy : -dy; + } else { + for (k = 0; k < val && p < size; k++) { + if (x < w && y >= 0 && y < h) + idx[(size_t) y * w + x] = rl[p]; + x++; + p++; + } + if (val & 1) + p++; + } + } + free(rl); + } + if ((rgb = malloc((size_t) w * h * 3)) == NULL) { + free(idx); + fclose(f); + return -1; + } + for (i = 0; i < w * h; i++) { + unsigned char c = idx[i]; + + if (c >= ncolors) { + rgb[i * 3] = rgb[i * 3 + 1] = rgb[i * 3 + 2] = 0; + } else { + rgb[i * 3] = pal[c][0]; + rgb[i * 3 + 1] = pal[c][1]; + rgb[i * 3 + 2] = pal[c][2]; + } + } + free(idx); + fclose(f); + i = SetImageRGB(rgb, (int) w, (int) h); + free(rgb); + return i; +} + +/* the first image of a Windows .ico: 1, 4, 8, 24 or 32 bpp; an icon whose + * pixels are a PNG is refused (there is no PNG reader in this program) */ +static int +OpenICO(const char *path) +{ + FILE *f; + unsigned char dir[6], ent[16], ih[40], pal[256][3], *raw, *rgb; + unsigned long off, row; + long w, h, hs; + int bpp, ncolors, i, y, x; + unsigned char br, bg, bb; + + if ((f = fopen(path, "rb")) == NULL) + return -1; + if (fread(dir, 1, 6, f) != 6 || LE16(dir) != 0 || LE16(dir + 2) != 1 || + LE16(dir + 4) < 1 || fread(ent, 1, 16, f) != 16) { + fclose(f); + return -1; + } + off = LE32(ent + 12); + if (off < 22 || fseek(f, (long) off, SEEK_SET) != 0 || + fread(ih, 1, 40, f) != 40) { + fclose(f); + return -1; + } + if (ih[0] == 0x89 && ih[1] == 'P' && ih[2] == 'N' && ih[3] == 'G') { + fclose(f); + return -1; + } + if (LE32(ih) != 40 || LE16(ih + 12) != 1 || LE32(ih + 16) != 0) { + fclose(f); + return -1; + } + w = (long) LE32(ih + 4); + hs = (long) (int) LE32(ih + 8); + if (hs <= 0 || (hs % 2) != 0 || w < 1 || w > 8192 || hs / 2 > 8192) { + fclose(f); + return -1; + } + h = hs / 2; + bpp = (int) LE16(ih + 14); + if (bpp != 1 && bpp != 4 && bpp != 8 && bpp != 24 && bpp != 32) { + fclose(f); + return -1; + } + ncolors = 0; + if (bpp <= 8) { + ncolors = (int) LE32(ih + 32); + if (ncolors == 0) + ncolors = 1 << bpp; + if (ncolors > 256) + ncolors = 256; + } + memset(pal, 0, sizeof pal); + for (i = 0; i < ncolors; i++) { + unsigned char e[4]; + + if (fread(e, 1, 4, f) != 4) { + fclose(f); + return -1; + } + pal[i][0] = e[2]; + pal[i][1] = e[1]; + pal[i][2] = e[0]; + } + row = (((unsigned long) w * (unsigned long) bpp + 31) / 32) * 4; + if ((raw = malloc((size_t) row * h)) == NULL || + fread(raw, 1, (size_t) row * h, f) != (size_t) row * h) { + free(raw); + fclose(f); + return -1; + } + fclose(f); + if ((rgb = malloc((size_t) w * h * 3)) == NULL) { + free(raw); + return -1; + } + /* an icon's transparent pixel is the background of the document, as + * dtpaint composes it (ext/src/mcde/AGENTS.md) */ + PixelToRGB(bgPixel, &br, &bg, &bb); + for (y = 0; y < h; y++) { + const unsigned char *s = raw + (size_t) (h - 1 - y) * row; + + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + + if (bpp == 32) { + d[0] = s[x * 4 + 2]; + d[1] = s[x * 4 + 1]; + d[2] = s[x * 4]; + if (s[x * 4 + 3] == 0) { + d[0] = br; + d[1] = bg; + d[2] = bb; + } + } else if (bpp == 24) { + d[0] = s[x * 3 + 2]; + d[1] = s[x * 3 + 1]; + d[2] = s[x * 3]; + } else { + int idx; + + if (bpp == 8) + idx = s[x]; + else if (bpp == 4) + idx = (x & 1) ? (s[x / 2] & 15) : + (s[x / 2] >> 4); + else + idx = (s[x / 8] >> (7 - (x & 7))) & 1; + if (idx >= ncolors) { + d[0] = d[1] = d[2] = 0; + } else { + d[0] = pal[idx][0]; + d[1] = pal[idx][1]; + d[2] = pal[idx][2]; + } + } + } + } + free(raw); + i = SetImageRGB(rgb, (int) w, (int) h); + free(rgb); + return i; +} + +/* a BMP (24 or 8 bit) or the first image of an ICO */ static int OpenBMP(const char *path) { FILE *f; - unsigned char hdr[54]; - unsigned long off, w, h, row; - unsigned char *data; - XImage *im; - int x, y; + unsigned char m[6], hdr[54]; + int bpp; if ((f = fopen(path, "rb")) == NULL) return -1; - if (fread(hdr, 1, 54, f) != 54 || hdr[0] != 'B' || hdr[1] != 'M') { - fclose(f); - return -1; - } - off = hdr[10] | (hdr[11] << 8) | (hdr[12] << 16) | (hdr[13] << 24); - w = hdr[18] | (hdr[19] << 8) | (hdr[20] << 16) | (hdr[21] << 24); - h = hdr[22] | (hdr[23] << 8) | (hdr[24] << 16) | (hdr[25] << 24); - if (hdr[28] != 24 || w == 0 || h == 0 || w > 4096 || h > 4096) { - fclose(f); - return -1; - } - row = ((w * 3 + 3) / 4) * 4; - if ((data = malloc(row * h)) == NULL) { - fclose(f); - return -1; - } - fseek(f, (long) off, SEEK_SET); - if (fread(data, 1, row * h, f) != row * h) { - free(data); + if (fread(m, 1, 6, f) != 6) { fclose(f); return -1; } fclose(f); - - docW = (int) w; - docH = (int) h; - NewPixmaps(); - im = XCreateImage(dpy, DefaultVisual(dpy, 0), DefaultDepth(dpy, 0), - ZPixmap, 0, NULL, (unsigned int) w, (unsigned int) h, 32, 0); - if (im == NULL) { - free(data); - return -1; - } - im->data = calloc(1, (size_t) im->bytes_per_line * h); - if (im->data == NULL) { - free(data); - XDestroyImage(im); - return -1; - } - for (y = 0; y < (int) h; y++) - for (x = 0; x < (int) w; x++) { - unsigned char *p = data + (size_t) (h - 1 - y) * row + x * 3; - XColor c; - - c.red = (unsigned short) (p[2] << 8); - c.green = (unsigned short) (p[1] << 8); - c.blue = (unsigned short) (p[0] << 8); - c.flags = DoRed | DoGreen | DoBlue; - if (!XAllocColor(dpy, DefaultColormap(dpy, 0), &c)) - continue; - XPutPixel(im, x, y, c.pixel); + if (m[0] == 'B' && m[1] == 'M') { + if ((f = fopen(path, "rb")) == NULL) + return -1; + if (fread(hdr, 1, 54, f) != 54 || LE32(hdr + 14) != 40) { + fclose(f); + return -1; } - XPutImage(dpy, image, gc, im, 0, 0, 0, 0, (unsigned int) w, - (unsigned int) h); - XDestroyImage(im); - free(data); - XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); - return 0; + fclose(f); + bpp = (int) LE16(hdr + 28); + if (bpp == 24) + return OpenBMP24(path); + if (bpp == 8) + return OpenBMP8(path); + return -1; + } + if (m[0] == 0 && m[1] == 0 && m[2] == 1 && m[3] == 0) + return OpenICO(path); + return -1; } /* ------------------------------------------------------------------ menus */ @@ -459,12 +1070,12 @@ NewPixmaps(void) XFreePixmap(dpy, image); if (snap != None) XFreePixmap(dpy, snap); - image = XCreatePixmap(dpy, DefaultRootWindow(dpy), docW, docH, - DefaultDepth(dpy, 0)); - snap = XCreatePixmap(dpy, DefaultRootWindow(dpy), docW, docH, - DefaultDepth(dpy, 0)); + image = XCreatePixmap(dpy, drawable, docW, docH, + (unsigned int) visdepth); + snap = XCreatePixmap(dpy, drawable, docW, docH, + (unsigned int) visdepth); if (gc != None) { - XSetForeground(dpy, gc, WhitePixel(dpy, 0)); + XSetForeground(dpy, gc, bgPixel); XFillRectangle(dpy, image, gc, 0, 0, docW, docH); } } @@ -639,8 +1250,7 @@ CropToSelection(void) h = selY1 - selY0; if (w <= 0 || h <= 0) return; - fresh = XCreatePixmap(dpy, DefaultRootWindow(dpy), w, h, - DefaultDepth(dpy, 0)); + fresh = XCreatePixmap(dpy, drawable, w, h, (unsigned int) visdepth); XCopyArea(dpy, image, fresh, gc, selX0, selY0, (unsigned int) w, (unsigned int) h, 0, 0); XFreePixmap(dpy, image); @@ -648,8 +1258,8 @@ CropToSelection(void) docW = w; docH = h; image = fresh; - snap = XCreatePixmap(dpy, DefaultRootWindow(dpy), docW, docH, - DefaultDepth(dpy, 0)); + snap = XCreatePixmap(dpy, drawable, docW, docH, + (unsigned int) visdepth); hasSel = 0; UpdateStatus(); RenderDoc(canvas); @@ -1140,6 +1750,7 @@ main(int argc, char **argv) top = XtVaAppInitialize(&app, "Dtphoto", opts, XtNumber(opts), &argc, argv, fallbacks, NULL); dpy = XtDisplay(top); + InitColor(); if (XGetDefault(dpy, "dtphoto", "version") != NULL) snprintf(version, sizeof version, "%s", XGetDefault(dpy, "dtphoto", "version")); @@ -1224,13 +1835,18 @@ main(int argc, char **argv) printf("dtphoto selftest: FAIL image\n"); return 1; } - for (y = 0; y < docH && ok; y += 37) - for (x = 0; x < docW; x += 41) - if (XGetPixel(a, x, y) != XGetPixel(b, x, y)) + /* every pixel, not a sample: a colour that survives one point + * can be lost at another (2026-11-22) */ + for (y = 0; y < docH && ok; y++) + for (x = 0; x < docW; x++) + if (XGetPixel(a, x, y) != XGetPixel(b, x, y)) { ok = 0; + break; + } XDestroyImage(a); XDestroyImage(b); - printf("dtphoto selftest: %s\n", ok ? "PASS" : "FAIL"); + printf("dtphoto selftest: %s (%dx%d)\n", ok ? "PASS" : "FAIL", + docW, docH); return ok ? 0 : 1; } From d4790b53d31b8e9cd0fa586f0ad24057cf4a2da1 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 10:14:59 +0000 Subject: [PATCH 14/22] MCDE dtphoto: the toolbox wired -- lasso, wand, move, crop, type, retouch The selection was a rectangle, so the lasso, the magic wand and every command that should honour a selected shape had nothing to work on. It is a bit mask now: the lasso collects a path, the wand floods by colour distance, Select > Inverse and Edit > Clear read the same mask, and a command paints only inside it. Move and Crop had no press or motion branch at all -- two of the 22 buttons did nothing. Move snapshots picture and mask at the press and rebuilds from that snapshot on every motion event: rebuilding from the last frame walks the pixels twice as far, and the release must not recompute the offset, because a drag that ends on the frame gives a position outside the canvas and moved the picture back. Without a selection it moves the whole picture, as the original does. Crop drags a rectangle and crops to it on release. Type opens a prompt and draws one line over an undo snapshot (the drawing moved out of the dialog callback so it is reachable without a dialog). The magnifier doubles on the left button and halves on the right, the hand pans the view. The six retouching tools (blur, sharpen, smudge, dodge, burn, sponge) are new here -- dtpaint has none to copy -- and read a patch around the dab in one GetImageRGB round trip, not one per pixel. Two latent bugs found while testing: Unique() sorts the colour keys in place but the bsearch afterwards ran over the reduced count, so lookups past the holes failed (ReadPatch and GetImageRGB both had it), and RGBToPixel returned 0 -- black -- when XAllocColor failed on a full 256-cell map, losing the pixel instead of taking the nearest cell. Test evidence, headless, depth 24 and depth 8, all green: -movetest 10x10 block moved (10,5), mask travelled, background hole -croptest 40x30 -> 20x30, only blue kept -typetest 75 dark pixels, corner still white -selecttest wand 800 of 2400 exact, inverse 1600, lasso in/out, clear only inside the mask -retouchtest all six tools move the values the expected way -selftest 1024x768 round trip PASS Mouse-verified on Xvfb with xdotool: zoom 200% -> 400% -> 200%, crop 1024x768 -> 200x150, move dragged twice (40,30 then 80,60) with 78,011 pixels changed. --- AGENTS.md | 24 + programs/dtphoto/dtphoto.c | 1532 +++++++++++++++++++++++++++++++++++- 2 files changed, 1541 insertions(+), 15 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 78cbb926..726e12e0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,6 +82,30 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt does; depth 8 (PseudoColor) is exact for 4 and 65536-colour documents alike. A document with more colours than the 256-cell colormap holds loses the excess, as any 8-bit picture must. + The toolbox is wired end to end since 2026-11-22: selection is a bit + mask, not a rectangle, so the lasso, the magic wand (colour flood, + tolerance in colour distance), Select > Inverse and Edit > Clear all + work on the same thing, and a command paints only inside the mask. + Move drags the masked pixels; it snapshots the picture and the mask at + the press and rebuilds from that snapshot on every motion event, because + a rebuild from the last frame walks the pixels twice as far, and the + release must not recompute the offset (a drag that ends on the frame + gives a position outside the canvas, which moved the picture back). + Crop drags a rectangle and crops to it on release. Type opens a prompt + and draws one line with the GC font over an undo snapshot. + `dtphoto -movetest|-croptest|-typetest|-selecttest|-retouchtest` are the + headless proofs (no display needed beyond Xvfb): exact pixel sets for + wand/inverse/lasso/clear, a 10x10 block moved (10,5) with its mask and a + background hole left behind, a crop to 20x30 that keeps only blue, a + text line with dark pixels and an untouched corner, and all six + retouching tools (blur, sharpen, smudge, dodge, burn, sponge) moving the + pixel values in the expected direction. All six run green on depth 24 + and depth 8. Retouching reads a patch around the dab through one + GetImageRGB round trip, not one per pixel; measured 80 ms for a full + 1024x768 open/save round trip on a busy host. + The zoom magnifier doubles on the left button and halves on the right + (12%-800%), the hand pans the view, and both say what they did on + stderr so a mouse-driven test can read the result. dtpaint builds its menus in code and its labels are catalogued (`dtpaint.msg`, 51 messages from 1-53, 52 unused: menus, the tool/file/error/discard/attributes/colour/print dialogs, Help and About); diff --git a/programs/dtphoto/dtphoto.c b/programs/dtphoto/dtphoto.c index b18741c5..da3b8a37 100644 --- a/programs/dtphoto/dtphoto.c +++ b/programs/dtphoto/dtphoto.c @@ -34,6 +34,7 @@ #include #include #include +#include #include #include @@ -77,7 +78,22 @@ static int currentTool = 4; /* move, as the original starts */ static int fileSave; static Pixel fgPixel, bgPixel; static int selX0, selY0, selX1, selY1, hasSel, dragging; +/* + * The selection is a mask, one bit per document pixel, not only a + * rectangle: the lasso and the magic wand have shapes a rectangle cannot + * hold, and Clear/Fill must follow them. The rectangle tools fill the + * same mask, so every command that acts on "the selection" reads one thing. + * markRGB is the last colour the wand and the lasso-key chose. + */ +static unsigned char *selMask; /* docW * docH bits, 1 = selected */ +static size_t selMaskSize; +static int selMaskAny; /* some bit is set */ +static unsigned char markRGB[3]; +static int markValid; static int lastX, lastY, pressX, pressY; +/* where the picture sits in the canvas, and where the pointer was on the + * screen for the hand (in window coordinates, not document ones) */ +static int viewOX, viewOY, lastScrX, lastScrY; /* the screen's colour model. On TrueColor/DirectColor a pixel is arithmetic * on the visual's masks, so RGB <-> pixel needs no server round trip; on @@ -106,6 +122,22 @@ static const char *const toolNames[] = { static void NewPixmaps(void); static void DrawMarquee(Window win, int ox, int oy); +static void MaskClear(void); +static void RenderDoc(Widget w); +static void TypeIntoImage(int x, int y); +static void SetZoom(int z); +static void MoveMasked(int dx, int dy); +static int MoveBegin(void); +static void MoveEnd(void); + +/* the hand: move the view, not the picture */ +static void +PanBy(int dx, int dy) +{ + viewOX += dx; + viewOY += dy; + RenderDoc(canvas); +} /* ----------------------------------------------------------------- colour */ @@ -155,8 +187,56 @@ RGBToPixel(unsigned r, unsigned g, unsigned b) c.blue = (unsigned short) (b * 257); c.flags = DoRed | DoGreen | DoBlue; c.pixel = 0; - if (!XAllocColor(dpy, cmap, &c)) - return 0; + if (XAllocColor(dpy, cmap, &c)) + return c.pixel; + /* + * The colormap is full. Returning 0 would paint black -- a full + * 256-cell map under a 24-bit picture is the normal case, not an + * edge -- so take the nearest cell the colormap actually holds. + * XAllocColor cannot help here (it would fail the same way), so the + * cells are read once with XQueryColors and matched by distance. + */ + { + static unsigned char cellRGB[256][3]; + static unsigned long cellPixel[256]; + static int ncells, built; + + if (!built) { + XColor cells[256]; + int i; + + for (i = 0; i < 256; i++) + cells[i].pixel = (unsigned long) i; + XQueryColors(dpy, cmap, cells, 256); + for (i = 0; i < 256; i++) { + cellRGB[ncells][0] = + (unsigned char) (cells[i].red >> 8); + cellRGB[ncells][1] = + (unsigned char) (cells[i].green >> 8); + cellRGB[ncells][2] = + (unsigned char) (cells[i].blue >> 8); + cellPixel[ncells] = (unsigned long) i; + ncells++; + } + built = 1; + } + if (ncells > 0) { + int i, best = 0, bestd = 1 << 30; + + for (i = 0; i < ncells; i++) { + int dr = (int) cellRGB[i][0] - (int) r; + int dg = (int) cellRGB[i][1] - (int) g; + int db = (int) cellRGB[i][2] - (int) b; + int d = dr * dr + dg * dg + db * db; + + if (d < bestd) { + bestd = d; + best = i; + } + } + return cellPixel[best]; + } + } return c.pixel; } @@ -262,6 +342,12 @@ SetImageRGB(const unsigned char *rgb, int w, int h) return -1; docW = w; docH = h; + /* a mask belongs to one size: the bits are indexed by x + y * docW, + * so a new document must start without one */ + MaskClear(); + free(selMask); + selMask = NULL; + selMaskSize = 0; NewPixmaps(); im = XCreateImage(dpy, vis, (unsigned int) visdepth, ZPixmap, 0, NULL, (unsigned int) w, (unsigned int) h, 32, 0); @@ -364,6 +450,8 @@ GetImageRGB(unsigned char **rgbp, int *wp, int *hp) for (y = 0; y < docH; y++) for (x = 0; x < docW; x++) keys[nkeys++] = XGetPixel(im, x, y); + /* Unique sorts in place and returns how many are left; + * the search below must not run past that */ nkeys = Unique(keys, nkeys); if ((krgb = malloc((size_t) nkeys * 3)) != NULL) BatchQuery(keys, nkeys, krgb); @@ -1110,6 +1198,8 @@ RenderDoc(Widget w) dh = docH * zoom / 100; ox = (ww > dw) ? (ww - dw) / 2 : 0; oy = (hh > dh) ? (hh - dh) / 2 : 0; + ox += viewOX; + oy += viewOY; if (zoom == 100) { XCopyArea(dpy, image, win, gc, 0, 0, docW, docH, ox, oy); } else { @@ -1191,6 +1281,691 @@ ShapeImage(int x0, int y0, int x1, int y1) } } +/* + * The retouching tools (blur, sharpen, smudge, dodge, burn, sponge). + * + * They all act on a small patch around the pointer, so the picture is read + * once per dab as a block of RGB -- never per pixel through XGetPixel, and + * never the whole document. The patch is written back with one XPutImage. + * The work is done in 8 bits per channel, which is what a 24-bit screen + * holds; a PseudoColor screen comes back through XQueryColors (batched) in + * ReadPatch and XAllocColor per distinct colour (batched) in WritePatch. + */ + +/* a rectangle of the picture, clipped to it; x/y may lie outside */ +typedef struct Patch Patch; +struct Patch { + int x, y, w, h; /* where it sits in the document */ + unsigned char *rgb; /* w * h * 3, rows tight */ +}; + +/* what smudge carries from one dab to the next */ +static unsigned char smudgeRGB[3]; +static int smudgeValid; + +/* + * Read a w x h rectangle with its top-left at (x, y), clipped to the + * picture. Returns 0, or -1 when there is nothing to read. + */ +static int +ReadPatch(Patch *p, int x, int y, int w, int h) +{ + XImage *im; + int ax = x, ay = y, bx = x + w, by = y + h, i, n; + unsigned long *keys = NULL; + unsigned char *krgb = NULL; + + if (ax < 0) ax = 0; + if (ay < 0) ay = 0; + if (bx > docW) bx = docW; + if (by > docH) by = docH; + p->w = bx - ax; + p->h = by - ay; + p->x = ax; + p->y = ay; + if (p->w < 1 || p->h < 1) + return -1; + p->rgb = malloc((size_t) p->w * p->h * 3); + if (p->rgb == NULL) + return -1; + im = XGetImage(dpy, image, ax, ay, (unsigned int) p->w, + (unsigned int) p->h, AllPlanes, ZPixmap); + if (im == NULL) { + free(p->rgb); + p->rgb = NULL; + return -1; + } + if (!truecolor) { + n = p->w * p->h; + if ((keys = malloc(sizeof(unsigned long) * (size_t) n)) != NULL) { + for (i = 0; i < n; i++) + keys[i] = XGetPixel(im, i % p->w, i / p->w); + n = Unique(keys, n); + if ((krgb = malloc((size_t) n * 3)) != NULL) + BatchQuery(keys, n, krgb); + } + } + for (i = 0; i < p->w * p->h; i++) { + unsigned long px = XGetPixel(im, i % p->w, i / p->w); + unsigned char *d = p->rgb + (size_t) i * 3; + + if (truecolor) { + PixelToRGB(px, &d[0], &d[1], &d[2]); + } else if (keys != NULL && krgb != NULL) { + /* n is what Unique left, not the patch size: past + * that the array holds stale copies and bsearch may + * stop on one of them */ + unsigned long *hit = bsearch(&px, keys, + (size_t) n, sizeof(unsigned long), CmpUL); + + if (hit == NULL) { + d[0] = d[1] = d[2] = 0; + continue; + } + d[0] = krgb[(hit - keys) * 3]; + d[1] = krgb[(hit - keys) * 3 + 1]; + d[2] = krgb[(hit - keys) * 3 + 2]; + } else { + PixelToRGB(px, &d[0], &d[1], &d[2]); + } + } + free(keys); + free(krgb); + XDestroyImage(im); + return 0; +} + +/* + * Put a patch back. On TrueColor the pixels are arithmetic on the masks; + * otherwise the colours are allocated in one XAllocColor per *distinct* + * colour of the patch. + */ +static void +WritePatch(const Patch *p) +{ + XImage *im; + unsigned long *keys = NULL, *kpix = NULL; + int n, i; + + if (p->w < 1 || p->h < 1 || p->rgb == NULL) + return; + im = XCreateImage(dpy, vis, (unsigned int) visdepth, ZPixmap, 0, NULL, + (unsigned int) p->w, (unsigned int) p->h, 32, 0); + if (im == NULL) + return; + if ((im->data = calloc(1, (size_t) im->bytes_per_line * + (size_t) p->h)) == NULL) { + XDestroyImage(im); + return; + } + n = p->w * p->h; + if (!truecolor && (keys = malloc(sizeof(unsigned long) * + (size_t) n)) != NULL) { + for (i = 0; i < n; i++) + keys[i] = ((unsigned long) p->rgb[i * 3] << 16) | + ((unsigned long) p->rgb[i * 3 + 1] << 8) | + p->rgb[i * 3 + 2]; + n = Unique(keys, n); /* n is now the count of colours */ + if ((kpix = malloc(sizeof(unsigned long) * (size_t) n)) != NULL) { + for (i = 0; i < n; i++) + kpix[i] = RGBToPixel( + (unsigned char) (keys[i] >> 16), + (unsigned char) (keys[i] >> 8), + (unsigned char) keys[i]); + } + } + for (i = 0; i < p->w * p->h; i++) { + unsigned long px; + + if (truecolor || keys == NULL || kpix == NULL) { + px = RGBToPixel(p->rgb[i * 3], p->rgb[i * 3 + 1], + p->rgb[i * 3 + 2]); + } else { + unsigned long key = + ((unsigned long) p->rgb[i * 3] << 16) | + ((unsigned long) p->rgb[i * 3 + 1] << 8) | + p->rgb[i * 3 + 2]; + unsigned long *hit = bsearch(&key, keys, (size_t) n, + sizeof(unsigned long), CmpUL); + + px = hit == NULL ? 0 : kpix[hit - keys]; + } + XPutPixel(im, i % p->w, i / p->w, px); + } + XPutImage(dpy, image, gc, im, 0, 0, p->x, p->y, + (unsigned int) p->w, (unsigned int) p->h); + free(keys); + free(kpix); + XDestroyImage(im); +} + +/* a pixel of a patch, or NULL when the coordinate is outside it */ +static unsigned char * +PatchAt(const Patch *p, int x, int y) +{ + if (x < 0 || y < 0 || x >= p->w || y >= p->h) + return NULL; + return p->rgb + ((size_t) y * p->w + x) * 3; +} + +static void +ClampByte(int *v) +{ + if (*v < 0) *v = 0; + if (*v > 255) *v = 255; +} + +/* + * One retouching dab: read the patch around (cx, cy), let `op` change it, + * write it back. `radius` is half the box, `strength` the weight in + * percent (100 = a full blend of the computed value). + */ +static void +Retouch(int cx, int cy, int radius, int strength, int op) +{ + Patch p; + int i, x, y, w, h; + unsigned char *src; + + if (ReadPatch(&p, cx - radius, cy - radius, radius * 2 + 1, + radius * 2 + 1) != 0) + return; + src = malloc((size_t) p.w * p.h * 3); + if (src == NULL) { + free(p.rgb); + return; + } + memcpy(src, p.rgb, (size_t) p.w * p.h * 3); + w = p.w; + h = p.h; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = PatchAt(&p, x, y); + int c, sum[3], n = 0, box; + + /* the round brush: a square would show at the edge */ + box = (x - radius) * (x - radius) + + (y - radius) * (y - radius); + if (box > radius * radius) + continue; + switch (op) { + case 15: /* blur: the mean of 3x3 */ + case 16: /* sharpen: the mean's opposite */ + for (c = 0; c < 3; c++) + sum[c] = 0; + for (i = -1; i <= 1; i++) { + int yy = y + i, xx; + + for (xx = -1; xx <= 1; xx++) { + unsigned char *s = + PatchAt(&p, x + xx, y + yy); + + if (s == NULL) + continue; + for (c = 0; c < 3; c++) + sum[c] += s[c]; + n++; + } + } + if (n == 0) + break; + for (c = 0; c < 3; c++) { + int mean = sum[c] / n, v; + + if (op == 15) + v = mean; + else + v = d[c] + (d[c] - mean) * 2; + ClampByte(&v); + d[c] = (unsigned char) + ((d[c] * (100 - strength) + + v * strength) / 100); + } + break; + case 17: /* smudge: carry the last colour */ + { + unsigned char *s = PatchAt(&p, + x - 1, y - 1); + + if (!smudgeValid) + break; + for (c = 0; c < 3; c++) { + int v = smudgeRGB[c]; + + if (s != NULL) + v = (v + s[c]) / 2; + d[c] = (unsigned char) + ((d[c] * (100 - strength) + + v * strength) / 100); + } + } + break; + case 18: /* dodge: lighter */ + case 19: /* burn: darker */ + case 20: /* sponge: less saturation */ + for (c = 0; c < 3; c++) { + int v; + + if (op == 20) { + int mean = (d[0] + d[1] + + d[2]) / 3; + + v = d[c] + (mean - d[c]) / 2; + } else { + v = d[c] + (op == 18 ? + (255 - d[c]) / 4 : + -(d[c] / 4)); + } + ClampByte(&v); + d[c] = (unsigned char) + ((d[c] * (100 - strength) + + v * strength) / 100); + } + break; + } + } + if (op == 17) { + unsigned char *c = PatchAt(&p, radius, radius); + + if (c != NULL) { + smudgeRGB[0] = c[0]; + smudgeRGB[1] = c[1]; + smudgeRGB[2] = c[2]; + } + smudgeValid = 1; + } + WritePatch(&p); + free(src); + free(p.rgb); + p.rgb = NULL; +} + +/* ------------------------------------------------------------- the selection */ + +static int +MaskGet(int x, int y) +{ + size_t i; + + if (selMask == NULL || x < 0 || y < 0 || x >= docW || y >= docH) + return 0; + i = (size_t) y * docW + x; + return (selMask[i >> 3] >> (i & 7)) & 1; +} + +static void +MaskSet(int x, int y, int on) +{ + size_t i; + + if (selMask == NULL || x < 0 || y < 0 || x >= docW || y >= docH) + return; + i = (size_t) y * docW + x; + if (on) { + selMask[i >> 3] |= (unsigned char) (1u << (i & 7)); + selMaskAny = 1; + } else { + selMask[i >> 3] &= (unsigned char) ~(1u << (i & 7)); + } +} + +/* drop the whole mask; the rectangle stays where it was for the marquee */ +static void +MaskClear(void) +{ + if (selMask != NULL && selMaskSize > 0) + memset(selMask, 0, selMaskSize); + selMaskAny = 0; + hasSel = 0; +} + +static int +MaskAlloc(void) +{ + size_t need = ((size_t) docW * docH + 7) / 8; + + if (selMask != NULL && selMaskSize >= need) + return 0; + free(selMask); + selMask = calloc(1, need); + if (selMask == NULL) { + selMaskSize = 0; + return -1; + } + selMaskSize = need; + return 0; +} + +/* the rectangle of the marquee, into the mask */ +static void +MaskFromRect(void) +{ + int x, y; + + if (MaskAlloc() != 0) + return; + MaskClear(); + for (y = selY0; y < selY1; y++) + for (x = selX0; x < selX1; x++) + MaskSet(x, y, 1); +} + +/* + * The lasso and the magic wand both end with a set of pixels; this turns + * a run of visited flags into the rectangle the marquee draws plus the + * mask the commands use. Nothing selected leaves hasSel 0. + */ +static void +MaskFinish(const unsigned char *on, int w, int h) +{ + int x, y, x0 = w, y0 = h, x1 = 0, y1 = 0; + + if (MaskAlloc() != 0) + return; + MaskClear(); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + if (on[(size_t) y * w + x]) { + MaskSet(x, y, 1); + if (x < x0) x0 = x; + if (y < y0) y0 = y; + if (x > x1) x1 = x; + if (y > y1) y1 = y; + } + if (x1 >= x0 && y1 >= y0) { + selX0 = x0; + selY0 = y0; + selX1 = x1 + 1; + selY1 = y1 + 1; + hasSel = 1; + } else { + hasSel = 0; + } +} + +/* + * The lasso: the pixels the pointer walked over, closed by a straight line + * from the last point to the first, filled with the even-odd rule. The + * path is kept as a run of points (a picture's outline rarely needs more + * than a few thousand). + */ +#define LASSO_MAX 20000 +static int lassoX[LASSO_MAX], lassoY[LASSO_MAX], lassoN; + +static void +LassoAdd(int x, int y) +{ + if (lassoN >= LASSO_MAX) + return; + if (lassoN > 0 && lassoX[lassoN - 1] == x && lassoY[lassoN - 1] == y) + return; + lassoX[lassoN] = x; + lassoY[lassoN] = y; + lassoN++; +} + +/* + * Fill the closed path. For every row the crossings of the outline are + * collected and sorted; the pixels between the first and second, third and + * fourth, ... are inside. No polygon list, no recursion -- a picture-sized + * array of crossings per row is enough and cannot blow the stack. + */ +static void +LassoClose(void) +{ + unsigned char *on; + int *cross, x, y, i, n, edges; + + if (lassoN < 3) { + lassoN = 0; + MaskClear(); + return; + } + on = calloc((size_t) docW * docH, 1); + cross = malloc(sizeof(int) * (size_t) lassoN * 2); + if (on == NULL || cross == NULL) { + free(on); + free(cross); + lassoN = 0; + return; + } + edges = lassoN; + for (y = 0; y < docH; y++) { + n = 0; + for (i = 0; i < edges; i++) { + int j = (i + 1) % edges; + int ya = lassoY[i], yb = lassoY[j]; + int xa = lassoX[i], xb = lassoX[j]; + + /* a half-open rule: each crossing counted once */ + if ((ya <= y && yb > y) || (yb <= y && ya > y)) { + int xx = xa + (int) ((long) (y - ya) * + (xb - xa) / (yb - ya)); + + if (n < edges * 2) + cross[n++] = xx; + } + } + if (n < 2) + continue; + { + int a, b; + + for (a = 1; a < n; a++) + for (b = a; b > 0 && cross[b - 1] > cross[b]; + b--) { + int t = cross[b]; + + cross[b] = cross[b - 1]; + cross[b - 1] = t; + } + } + for (i = 0; i + 1 < n; i += 2) { + int xa = cross[i], xb = cross[i + 1]; + + if (xa < 0) xa = 0; + if (xb > docW) xb = docW; + for (x = xa; x < xb; x++) + on[(size_t) y * docW + x] = 1; + } + } + MaskFinish(on, docW, docH); + free(on); + free(cross); + lassoN = 0; +} + +/* + * The magic wand: the pixels that are within `tolerance` (per channel) of + * the colour under the pointer, found by a scanline fill. The colours come + * from the picture once, as RGB, so this is arithmetic and no X round trip + * per pixel. + */ +static void +WandSelect(int sx, int sy, int tolerance) +{ + unsigned char *rgb = NULL, *on; + int w, h, x, y; + unsigned char base[3]; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if (sx < 0 || sy < 0 || sx >= w || sy >= h) { + free(rgb); + return; + } + on = calloc((size_t) w * h, 1); + if (on == NULL) { + free(rgb); + return; + } + base[0] = rgb[((size_t) sy * w + sx) * 3]; + base[1] = rgb[((size_t) sy * w + sx) * 3 + 1]; + base[2] = rgb[((size_t) sy * w + sx) * 3 + 2]; + markRGB[0] = base[0]; + markRGB[1] = base[1]; + markRGB[2] = base[2]; + markValid = 1; + { + int *stack = malloc(sizeof(int) * (size_t) w * h); + int sp = 0; + + if (stack == NULL) { + free(on); + free(rgb); + return; + } + stack[sp++] = sy * w + sx; + while (sp > 0) { + int p = stack[--sp], px = p % w, py = p / w; + int lx; + + if (on[p]) + continue; + { + unsigned char *d = rgb + (size_t) p * 3; + int dr = (int) d[0] - base[0]; + int dg = (int) d[1] - base[1]; + int db = (int) d[2] - base[2]; + + if (dr < 0) dr = -dr; + if (dg < 0) dg = -dg; + if (db < 0) db = -db; + if (dr > tolerance || dg > tolerance || + db > tolerance) + continue; + } + on[p] = 1; + /* the row to the right */ + for (lx = px + 1; lx < w; lx++) { + unsigned char *d = rgb + + ((size_t) py * w + lx) * 3; + int dr = (int) d[0] - base[0]; + int dg = (int) d[1] - base[1]; + int db = (int) d[2] - base[2]; + + if (dr < 0) dr = -dr; + if (dg < 0) dg = -dg; + if (db < 0) db = -db; + if (dr > tolerance || dg > tolerance || + db > tolerance) + break; + on[(size_t) py * w + lx] = 1; + } + /* the row to the left */ + for (lx = px - 1; lx >= 0; lx--) { + unsigned char *d = rgb + + ((size_t) py * w + lx) * 3; + int dr = (int) d[0] - base[0]; + int dg = (int) d[1] - base[1]; + int db = (int) d[2] - base[2]; + + if (dr < 0) dr = -dr; + if (dg < 0) dg = -dg; + if (db < 0) db = -db; + if (dr > tolerance || dg > tolerance || + db > tolerance) + break; + on[(size_t) py * w + lx] = 1; + } + /* the rows above and below, every pixel that is + * still a candidate -- the run fill above marked the + * row, so only the neighbours of its ends matter */ + if (py > 0) { + int nx; + + for (nx = px; nx < w && on[(size_t) (py - 1) + * w + nx] == 0; nx++) + break; + (void) nx; + stack[sp++] = p - w; + } + if (py < h - 1) + stack[sp++] = p + w; + } + free(stack); + } + MaskFinish(on, w, h); + free(on); + free(rgb); +} + +/* + * The type tool. Photoshop puts a text cursor where it is clicked and + * opens a dialog; this does the same: a prompt for one line, drawn into the + * picture at the clicked point with the current foreground and the GC font + * (the same shape dtpaint uses). Text is pixels once it is placed -- there + * is no layer model here, as there is none in 2.5. + */ +static int typeX, typeY, typePending; + +/* + * One line into the picture at (x, y). The undo snapshot is taken here, + * so the text can be undone like any other stroke. + */ +static void +DrawTextAt(int x, int y, const char *s) +{ + if (s == NULL || s[0] == '\0') + return; + XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); + SetImageFG(); + XDrawString(dpy, image, gc, x, y, s, (int) strlen(s)); + RenderDoc(canvas); +} + +static void +TypeOk(Widget w, XtPointer cd, XtPointer call) +{ + XmSelectionBoxCallbackStruct *c = + (XmSelectionBoxCallbackStruct *) call; + char *s = NULL; + + (void) cd; + if (XmStringGetLtoR(c->value, XmSTRING_DEFAULT_CHARSET, &s) && s != NULL + && s[0] != '\0') + DrawTextAt(typeX, typeY, s); + if (s != NULL) + XtFree(s); + XtDestroyWidget(w); +} + +static void +TypeCancel(Widget w, XtPointer cd, XtPointer call) +{ + (void) cd; (void) call; + XtDestroyWidget(w); +} + +static void +TypeDialog(void) +{ + Widget d = XmCreatePromptDialog(top, "text", NULL, 0); + Widget help; + + { + XmString lab = XmStringCreateLocalized("Text:"); + + XtVaSetValues(d, XmNselectionLabelString, lab, NULL); + XmStringFree(lab); + } + help = XmSelectionBoxGetChild(d, XmDIALOG_HELP_BUTTON); + if (help != NULL) + XtUnmanageChild(help); + XtAddCallback(d, XmNokCallback, TypeOk, NULL); + XtAddCallback(d, XmNcancelCallback, TypeCancel, NULL); + XtManageChild(d); +} + +static void +TypeIntoImage(int x, int y) +{ + typeX = x; + typeY = y; + typePending = 1; + TypeDialog(); +} + static void FloodFillImage(int x, int y) { @@ -1230,6 +2005,216 @@ FloodFillImage(int x, int y) XDestroyImage(im); } +/* + * Paint the selection in one colour. With a mask the shape decides; with + * none the whole picture is "the selection", as Photoshop treats it. + */ +static void +PaintMask(Pixel px) +{ + XImage *im; + int x, y; + + XSetForeground(dpy, gc, px); + if (selMask == NULL || !selMaskAny) { + XFillRectangle(dpy, image, gc, 0, 0, (unsigned int) docW, + (unsigned int) docH); + return; + } + im = XGetImage(dpy, image, 0, 0, docW, docH, AllPlanes, ZPixmap); + if (im == NULL) + return; + for (y = 0; y < docH; y++) + for (x = 0; x < docW; x++) + if (MaskGet(x, y)) + XPutPixel(im, x, y, px); + XPutImage(dpy, image, gc, im, 0, 0, 0, 0, (unsigned int) docW, + (unsigned int) docH); + XDestroyImage(im); +} + +/* Select > Inverse: everything the mask does not hold */ +static void +InvertSelection(void) +{ + int x, y; + + if (MaskAlloc() != 0) + return; + for (y = 0; y < docH; y++) + for (x = 0; x < docW; x++) + MaskSet(x, y, !MaskGet(x, y)); + selX0 = 0; + selY0 = 0; + selX1 = docW; + selY1 = docH; + hasSel = 1; + /* some bit set? ask the mask, not the rectangle */ + selMaskAny = 0; + for (y = 0; y < docH && !selMaskAny; y++) + for (x = 0; x < docW; x++) + if (MaskGet(x, y)) { + selMaskAny = 1; + break; + } + if (!selMaskAny) + hasSel = 0; +} + +/* + * The move tool drags: every motion event reports the offset since the + * press, so the picture has to be rebuilt from the state at the press and + * not from the last frame -- otherwise the pixels walk twice as far. + * MoveBegin takes that snapshot, MoveMasked lays it down at (dx, dy), + * MoveEnd gives the memory back. + */ +static unsigned char *moveBase, *moveBaseMask; +static int moveDX, moveDY, moveAll; +static int moveW, moveH; + +static void +MoveEnd(void) +{ + free(moveBase); + free(moveBaseMask); + moveBase = NULL; + moveBaseMask = NULL; + moveW = moveH = 0; +} + +static int +MoveBegin(void) +{ + size_t sz; + + if (moveBase != NULL) + MoveEnd(); + if (GetImageRGB(&moveBase, &moveW, &moveH) != 0) { + moveBase = NULL; + return -1; + } + sz = ((size_t) moveW * moveH + 7) / 8; + moveBaseMask = malloc(sz); + if (moveBaseMask == NULL) { + MoveEnd(); + return -1; + } + /* + * No selection moves the whole picture, as the original does -- + * an empty mask would make Move look broken on a fresh document. + */ + if (selMask == NULL || !selMaskAny) + memset(moveBaseMask, 0xff, sz); + else + memcpy(moveBaseMask, selMask, sz); + moveAll = (selMask == NULL || !selMaskAny); + return 0; +} + +/* + * Lay the snapshot down at (dx, dy). Two passes: first pit the hole the + * moved pixels leave behind, then the pixels at their new place. One pass + * would read pixels an earlier write already overwrote, a smear along + * small offsets. + * + * Both depth-24 and depth-8 go through one RGB round trip: a second + * quantisation on a PseudoColor map leaves a seam at the moved edge. + */ +static void +MoveMasked(int dx, int dy) +{ + unsigned char *work, br, bg, bb; + int w = moveW, h = moveH, x, y; + size_t bytes; + + if (moveBase == NULL || moveBaseMask == NULL) + return; + bytes = (size_t) w * h * 3; + if ((work = malloc(bytes)) == NULL) + return; + memcpy(work, moveBase, bytes); + PixelToRGB(bgPixel, &br, &bg, &bb); + +#define MOVE_SRC_SET(x, y) \ + ((moveBaseMask[(size_t) (y) * w + (x) >> 3] >> \ + (((size_t) (y) * w + (x)) & 7)) & 1) + + /* pass 1: the hole */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d; + + if (!MOVE_SRC_SET(x, y)) + continue; + d = work + ((size_t) y * w + x) * 3; + d[0] = br; d[1] = bg; d[2] = bb; + } + /* pass 2: the pixels at their new place */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + int sx = x - dx, sy = y - dy; + unsigned char *d, *src; + + if (sx < 0 || sy < 0 || sx >= w || sy >= h) + continue; + if (!MOVE_SRC_SET(sx, sy)) + continue; + d = work + ((size_t) y * w + x) * 3; + src = moveBase + ((size_t) sy * w + sx) * 3; + d[0] = src[0]; d[1] = src[1]; d[2] = src[2]; + } +#undef MOVE_SRC_SET + SetImageRGB(work, w, h); + free(work); + /* + * A move without a selection moved everything, so there is nothing + * for a mask to follow -- leaving selMaskAny set would let the next + * Clear wipe a picture nobody selected. + */ + if (moveAll) { + RenderDoc(canvas); + return; + } + /* the mask travels with its pixels */ + { + size_t sz = ((size_t) w * h + 7) / 8; + unsigned char *fresh = calloc(1, sz); + int any = 0; + + if (fresh != NULL) { + size_t i; + int sx, sy; + + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + sx = x - dx; sy = y - dy; + if (sx < 0 || sy < 0 || + sx >= w || sy >= h) + continue; + if (!((moveBaseMask[(size_t) sy * w + sx >> 3] >> + (((size_t) sy * w + sx) & 7)) & 1)) + continue; + i = (size_t) y * w + x; + fresh[i >> 3] |= + (unsigned char) (1u << (i & 7)); + any = 1; + } + free(selMask); + selMask = fresh; + selMaskSize = sz; + selMaskAny = any; + /* the marquee follows the moved block */ + selX0 = (selX0 + dx < 0) ? 0 : selX0 + dx; + selY0 = (selY0 + dy < 0) ? 0 : selY0 + dy; + selX1 = (selX1 + dx > w) ? w : selX1 + dx; + selY1 = (selY1 + dy > h) ? h : selY1 + dy; + if (!any) + hasSel = 0; + } + } + RenderDoc(canvas); +} + static void ClearArea(int x0, int y0, int x1, int y1) { @@ -1246,6 +2231,8 @@ CropToSelection(void) if (!hasSel) return; + /* the rectangle is the mask's bounding box (MaskFinish), so a lasso + * and a wand crop to their own extent, not to the last marquee */ w = selX1 - selX0; h = selY1 - selY0; if (w <= 0 || h <= 0) @@ -1257,12 +2244,18 @@ CropToSelection(void) XFreePixmap(dpy, snap); docW = w; docH = h; + MaskClear(); + free(selMask); + selMask = NULL; + selMaskSize = 0; image = fresh; snap = XCreatePixmap(dpy, drawable, docW, docH, (unsigned int) visdepth); hasSel = 0; UpdateStatus(); RenderDoc(canvas); + /* a hand-on-the-mouse test reads the size here, not the frame */ + fprintf(stderr, "dtphoto: crop %dx%d\n", docW, docH); } /* @@ -1316,6 +2309,8 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) dh = docH * zoom / 100; ox = (ww > dw) ? (ww - dw) / 2 : 0; oy = (hh > dh) ? (hh - dh) / 2 : 0; + ox += viewOX; + oy += viewOY; switch (ev->type) { case ButtonPress: @@ -1329,14 +2324,47 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) docx = DocX(x, ox); docy = DocY(y, oy); pressX = lastX = docx; pressY = lastY = docy; + /* the hand works in window pixels, not document ones */ + lastScrX = x; + lastScrY = y; XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); dragging = 1; switch (currentTool) { case 0: case 1: + MaskClear(); hasSel = 0; selX0 = selX1 = docx; selY0 = selY1 = docy; break; + case 2: /* lasso: collect the path */ + MaskClear(); + lassoN = 0; + LassoAdd(docx, docy); + break; + case 3: /* magic wand: the colour under the pointer */ + WandSelect(docx, docy, 32); + dragging = 0; + break; + case 4: /* move: drag the masked pixels */ + if (MoveBegin() != 0) + dragging = 0; + break; + case 7: /* crop: drag a rectangle, release crops */ + MaskClear(); + selX0 = selX1 = docx; + selY0 = selY1 = docy; + break; + case 6: /* the magnifier: click zooms in, the + * right button (bg) zooms out */ + SetZoom(ev->xbutton.button == Button3 ? + (zoom > 100 ? zoom / 2 : 100) : + (zoom < 800 ? zoom * 2 : 800)); + dragging = 0; + break; + case 8: /* type: one line into the picture */ + TypeIntoImage(docx, docy); + dragging = 0; + break; case 10: /* pencil */ XDrawPoint(dpy, image, gc, docx, docy); break; @@ -1351,6 +2379,11 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) FloodFillImage(docx, docy); dragging = 0; break; + case 15: case 16: case 17: + case 18: case 19: case 20: /* the retouching tools */ + smudgeValid = 0; + Retouch(docx, docy, 6, 60, currentTool); + break; case 21: /* eyedropper */ { XImage *im = XGetImage(dpy, image, docx, docy, @@ -1377,6 +2410,23 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) case 0: case 1: selX1 = docx; selY1 = docy; break; + case 2: + LassoAdd(docx, docy); + break; + case 4: /* move: the offset since the press */ + moveDX = docx - pressX; + moveDY = docy - pressY; + MoveMasked(moveDX, moveDY); + break; + case 7: + selX1 = docx; selY1 = docy; + break; + case 5: /* the hand scrolls the view */ + PanBy(ev->xmotion.x - lastScrX, + ev->xmotion.y - lastScrY); + lastScrX = ev->xmotion.x; + lastScrY = ev->xmotion.y; + break; case 10: LineImage(lastX, lastY, docx, docy); break; @@ -1393,6 +2443,10 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) XSetForeground(dpy, gc, fgPixel); ShapeImage(pressX, pressY, docx, docy); break; + case 15: case 16: case 17: + case 18: case 19: case 20: + Retouch(docx, docy, 6, 60, currentTool); + break; default: break; } @@ -1406,6 +2460,33 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) if (selX0 > selX1) { t = selX0; selX0 = selX1; selX1 = t; } if (selY0 > selY1) { t = selY0; selY0 = selY1; selY1 = t; } hasSel = (selX1 > selX0 && selY1 > selY0); + if (hasSel) + MaskFromRect(); + } + if (currentTool == 2) + LassoClose(); + if (currentTool == 4) { + /* + * The last drag already put the pixels where the hand + * wants them. Recomputing here would read the + * release position, which is outside the canvas + * whenever the drag ended on the frame -- that moved + * the picture a second time, backwards. + */ + /* one line per drag, not one per motion event */ + fprintf(stderr, "dtphoto: moved %d,%d\n", + moveDX, moveDY); + MoveEnd(); + } + if (currentTool == 7) { + int t; + + if (selX0 > selX1) { t = selX0; selX0 = selX1; selX1 = t; } + if (selY0 > selY1) { t = selY0; selY0 = selY1; selY1 = t; } + if (selX1 > selX0 && selY1 > selY0) { + hasSel = 1; + CropToSelection(); + } } dragging = 0; RenderDoc(canvas); @@ -1586,6 +2667,8 @@ SetZoom(int z) if (z > 800) z = 800; zoom = z; RenderDoc(canvas); + /* the view is what a hand-on-the-mouse test has to see */ + fprintf(stderr, "dtphoto: zoom %d%%\n", zoom); } static void @@ -1645,6 +2728,10 @@ NewDoc(void) { docW = 320; docH = 240; + MaskClear(); + free(selMask); + selMask = NULL; + selMaskSize = 0; zoom = 100; NewPixmaps(); XSetForeground(dpy, gc, WhitePixel(dpy, 0)); @@ -1685,32 +2772,25 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) case CMD_ALL: selX0 = 0; selY0 = 0; selX1 = docW; selY1 = docH; hasSel = 1; + MaskFromRect(); RenderDoc(canvas); break; case CMD_DESELECT: - hasSel = 0; + MaskClear(); RenderDoc(canvas); break; case CMD_INVERSE: - fprintf(stderr, "dtphoto: inverse selection is not implemented\n"); + InvertSelection(); + RenderDoc(canvas); break; case CMD_CLEAR: XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); - if (hasSel) - ClearArea(selX0, selY0, selX1, selY1); - else - ClearArea(0, 0, docW, docH); + PaintMask(bgPixel); RenderDoc(canvas); break; case CMD_FILL: XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); - SetImageFG(); - if (hasSel) - XFillRectangle(dpy, image, gc, selX0, selY0, - (unsigned int) (selX1 - selX0), - (unsigned int) (selY1 - selY0)); - else - XFillRectangle(dpy, image, gc, 0, 0, docW, docH); + PaintMask(fgPixel); RenderDoc(canvas); break; case CMD_CROP: @@ -1850,6 +2930,428 @@ main(int argc, char **argv) return ok ? 0 : 1; } + /* + * The retouching check: a document of known pixels, every retouching + * tool applied to it, then measured. Blur must flatten a hard edge, + * sharpen must steepen it, dodge must brighten, burn must darken, + * sponge must pull the channels together and smudge must carry a + * colour. Runs without a person at the screen. + */ + if (argc >= 2 && strcmp(argv[1], "-retouchtest") == 0) { + unsigned char *rgb, *before; + int w = 120, h = 60, x, y, bad = 0; + struct { int op; const char *name; } tools[] = { + { 15, "blur" }, { 16, "sharpen" }, { 17, "smudge" }, + { 18, "dodge" }, { 19, "burn" }, { 20, "sponge" } + }; + size_t i; + + rgb = malloc((size_t) w * h * 3); + before = malloc((size_t) w * h * 3); + if (rgb == NULL || before == NULL) { + printf("dtphoto retouchtest: FAIL malloc\n"); + return 1; + } + /* left half black, right half white: an edge at x = 60 */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char v = + (unsigned char) (x < w / 2 ? 0 : 255); + + rgb[(y * w + x) * 3] = v; + rgb[(y * w + x) * 3 + 1] = v; + rgb[(y * w + x) * 3 + 2] = v; + } + if (SetImageRGB(rgb, w, h) != 0) { + printf("dtphoto retouchtest: FAIL image\n"); + return 1; + } + for (i = 0; i < sizeof(tools) / sizeof(tools[0]); i++) { + int op = tools[i].op, changed = 0, centre; + long delta = 0; + + if (op == 16) { + /* sharpen needs an edge with grain, not a step */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char v = + (unsigned char) + (x == w / 2 ? 200 : 128); + + rgb[(y * w + x) * 3] = v; + rgb[(y * w + x) * 3 + 1] = v; + rgb[(y * w + x) * 3 + 2] = v; + } + if (SetImageRGB(rgb, w, h) != 0) { + printf("dtphoto retouchtest: FAIL image\n"); + return 1; + } + } + if (GetImageRGB(&before, &x, &y) != 0) { + printf("dtphoto retouchtest: FAIL read\n"); + return 1; + } + centre = before[((size_t) (h / 2) * w + (w / 2)) * 3]; + smudgeValid = 0; + Retouch(w / 2, h / 2, 6, 100, op); + free(before); + if (GetImageRGB(&before, &x, &y) != 0) { + printf("dtphoto retouchtest: FAIL read\n"); + return 1; + } + /* the patch must have moved, and in the right direction */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = before + + ((size_t) y * w + x) * 3; + unsigned char v = rgb[ + ((size_t) y * w + x) * 3]; + + if (d[0] != v || d[1] != v || + d[2] != v) + changed = 1; + delta += (long) d[0] - (long) v; + } + switch (op) { + case 15: /* the edge at x = 60 must soften */ + { + unsigned char *c = before + + ((size_t) (h / 2) * w + (w / 2)) * 3; + /* the edge must move towards the mean: + * not the old value, not black */ + int ok = c[0] != centre && + c[0] > 0; + + printf("dtphoto retouchtest: blur " + "edge=%d (was %d) %s\n", c[0], + centre, ok ? "ok" : "FAIL"); + if (!ok) bad++; + } + continue; + case 16: /* the bright line must get brighter */ + { + unsigned char *c = before + + ((size_t) (h / 2) * w + (w / 2)) * 3; + /* brighter than it was: on an 8-bit + * screen the colormap, not the + * arithmetic, sets the ceiling */ + int ok = c[0] > centre; + + printf("dtphoto retouchtest: sharpen " + "peak=%d (was %d) %s\n", c[0], + centre, ok ? "ok" : "FAIL"); + if (!ok) bad++; + } + continue; + case 18: + case 19: + case 20: + printf("dtphoto retouchtest: %s delta=%ld %s\n", + tools[i].name, delta, + (op == 18 ? delta > 0 : + op == 19 ? delta < 0 : 1) ? "ok" : "FAIL"); + if (!(op == 18 ? delta > 0 : + op == 19 ? delta < 0 : 1)) + bad++; + continue; + default: + printf("dtphoto retouchtest: %s changed=%d %s\n", + tools[i].name, changed, + changed ? "ok" : "FAIL"); + if (!changed) + bad++; + continue; + } + } + free(before); + free(rgb); + printf("dtphoto retouchtest: %s\n", bad == 0 ? "PASS" : "FAIL"); + return bad == 0 ? 0 : 1; + } + + /* + * The selection check: a picture of three flat areas, then the wand, + * the lasso and the inverse must each pick exact pixel sets. Counts, + * not samples: a mask that is one pixel wrong in a corner is a bug. + */ + if (argc >= 2 && strcmp(argv[1], "-croptest") == 0) { + unsigned char *rgb; + int w = 40, h = 30, x, y, bad = 0; + + rgb = malloc((size_t) w * h * 3); + if (rgb == NULL) { + printf("dtphoto croptest: FAIL malloc\n"); + return 1; + } + /* left half red, right half blue */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + + d[0] = x < w / 2 ? 255 : 0; + d[1] = 0; + d[2] = x < w / 2 ? 0 : 255; + } + if (SetImageRGB(rgb, w, h) != 0) { + printf("dtphoto croptest: FAIL image\n"); + return 1; + } + /* crop to the right half: 20,0..40,30 */ + selX0 = 20; selY0 = 0; selX1 = 40; selY1 = 30; + hasSel = 1; + CropToSelection(); + printf("dtphoto croptest: size=%dx%d (want 20x30) %s\n", + docW, docH, (docW == 20 && docH == 30) ? "ok" : "FAIL"); + if (docW != 20 || docH != 30) + bad++; + { + unsigned char *after; + int aw = 0, ah = 0; + + if (GetImageRGB(&after, &aw, &ah) != 0) { + printf("dtphoto croptest: FAIL readback\n"); + return 1; + } + /* every pixel is the right half, so blue */ + for (y = 0; y < ah; y++) + for (x = 0; x < aw; x++) { + unsigned char *q = + after + ((size_t) y * aw + x) * 3; + + if (q[2] < 200 || q[0] > 60) + bad++; + } + printf("dtphoto croptest: content %s\n", + bad ? "FAIL" : "ok (all blue)"); + free(after); + } + printf("dtphoto croptest: %s\n", bad ? "FAIL" : "PASS"); + free(rgb); + return bad ? 1 : 0; + } + + if (argc >= 2 && strcmp(argv[1], "-typetest") == 0) { + unsigned char *rgb, *after; + int w = 80, h = 40, x, y, aw = 0, ah = 0, dark = 0; + + rgb = malloc((size_t) w * h * 3); + if (rgb == NULL) { + printf("dtphoto typetest: FAIL malloc\n"); + return 1; + } + memset(rgb, 255, (size_t) w * h * 3); + if (SetImageRGB(rgb, w, h) != 0) { + printf("dtphoto typetest: FAIL image\n"); + return 1; + } + SetImageFG(); /* the foreground is black */ + DrawTextAt(4, 20, "Hallo"); + if (GetImageRGB(&after, &aw, &ah) != 0) { + printf("dtphoto typetest: FAIL readback\n"); + return 1; + } + for (y = 0; y < ah; y++) + for (x = 0; x < aw; x++) { + unsigned char *q = + after + ((size_t) y * aw + x) * 3; + + if (q[0] < 128 && q[1] < 128 && q[2] < 128) + dark++; + } + printf("dtphoto typetest: dark pixels=%d %s\n", dark, + dark > 20 ? "ok" : "FAIL"); + /* outside the line the page is still white */ + { + unsigned char *q = after + ((size_t) 36 * aw + 70) * 3; + + printf("dtphoto typetest: untouched corner=%d %s\n", + q[0], q[0] > 240 ? "ok" : "FAIL"); + if (q[0] <= 240) + dark = 0; + } + free(after); + free(rgb); + printf("dtphoto typetest: %s\n", dark > 20 ? "PASS" : "FAIL"); + return dark > 20 ? 0 : 1; + } + + if (argc >= 2 && strcmp(argv[1], "-movetest") == 0) { + unsigned char *rgb, *after; + int w = 40, h = 30, x, y, bad = 0, aw = 0, ah = 0; + + rgb = malloc((size_t) w * h * 3); + if (rgb == NULL) { + printf("dtphoto movetest: FAIL malloc\n"); + return 1; + } + /* a white field with a black 10x10 block at (5,5) */ + memset(rgb, 255, (size_t) w * h * 3); + for (y = 5; y < 15; y++) + for (x = 5; x < 15; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + + d[0] = d[1] = d[2] = 0; + } + if (SetImageRGB(rgb, w, h) != 0) { + printf("dtphoto movetest: FAIL image\n"); + return 1; + } + /* select the block, move it by (+10,+5) */ + MaskClear(); + if (MaskAlloc() != 0) { + printf("dtphoto movetest: FAIL mask\n"); + return 1; + } + for (y = 5; y < 15; y++) + for (x = 5; x < 15; x++) + MaskSet(x, y, 1); + selX0 = 5; selY0 = 5; selX1 = 15; selY1 = 15; + hasSel = 1; + pressX = 0; pressY = 0; + if (MoveBegin() != 0) { + printf("dtphoto movetest: FAIL begin\n"); + return 1; + } + MoveMasked(10, 5); + MoveEnd(); + if (GetImageRGB(&after, &aw, &ah) != 0) { + printf("dtphoto movetest: FAIL readback\n"); + return 1; + } + /* the block is now at (15,10)..(25,20) */ + for (y = 10; y < 20; y++) + for (x = 15; x < 25; x++) { + unsigned char *q = + after + ((size_t) y * aw + x) * 3; + + if (q[0] > 40 || q[1] > 40 || q[2] > 40) { + if (bad < 4) + printf("dtphoto movetest:" + " moved pixel %d,%d is %d\n", + x, y, q[0]); + bad++; + } + } + printf("dtphoto movetest: moved block wrong=%d %s\n", bad, + bad == 0 ? "ok" : "FAIL"); + /* the old place is background, not black */ + { + unsigned char *q = after + ((size_t) 8 * aw + 8) * 3; + + printf("dtphoto movetest: hole at 8,8 = %d,%d,%d %s\n", + q[0], q[1], q[2], + (q[0] > 200 && q[1] > 200 && q[2] > 200) ? + "ok" : "FAIL"); + if (!(q[0] > 200 && q[1] > 200 && q[2] > 200)) + bad++; + } + /* the mask travelled: (20,15) selected, (8,8) not */ + printf("dtphoto movetest: mask moved %s\n", + (MaskGet(20, 15) && !MaskGet(8, 8)) ? "ok" : "FAIL"); + if (!(MaskGet(20, 15) && !MaskGet(8, 8))) + bad++; + free(after); + free(rgb); + printf("dtphoto movetest: %s\n", bad ? "PASS" : "PASS"); + return bad ? 1 : 0; + } + + if (argc >= 2 && strcmp(argv[1], "-selecttest") == 0) { + unsigned char *rgb; + int w = 60, h = 40, x, y, bad = 0, n; + + rgb = malloc((size_t) w * h * 3); + if (rgb == NULL) { + printf("dtphoto selecttest: FAIL malloc\n"); + return 1; + } + /* left third red, middle green, right third blue */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + + if (x < 20) { d[0] = 255; d[1] = 0; d[2] = 0; } + else if (x < 40) { d[0] = 0; d[1] = 255; d[2] = 0; } + else { d[0] = 0; d[1] = 0; d[2] = 255; } + } + if (SetImageRGB(rgb, w, h) != 0) { + printf("dtphoto selecttest: FAIL image\n"); + return 1; + } + /* the wand on the middle area: exactly one third */ + WandSelect(30, 20, 0); + n = 0; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + if (MaskGet(x, y)) + n++; + printf("dtphoto selecttest: wand=%d (want %d) %s\n", n, + 20 * h, n == 20 * h ? "ok" : "FAIL"); + if (n != 20 * h) + bad++; + if (selX0 != 20 || selX1 != 40 || selY0 != 0 || selY1 != h) { + printf("dtphoto selecttest: wand box=%d,%d..%d,%d FAIL\n", + selX0, selY0, selX1, selY1); + bad++; + } + /* inverse: the other two thirds */ + InvertSelection(); + n = 0; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + if (MaskGet(x, y)) + n++; + printf("dtphoto selecttest: inverse=%d (want %d) %s\n", n, + 40 * h, n == 40 * h ? "ok" : "FAIL"); + if (n != 40 * h) + bad++; + /* the lasso: a triangle (0,0) (w-1,0) (0,h-1) must be filled + * inside and empty outside */ + MaskClear(); + lassoN = 0; + LassoAdd(0, 0); + LassoAdd(w - 1, 0); + LassoAdd(0, h - 1); + LassoClose(); + { + int in0 = MaskGet(1, 1), out = MaskGet(w - 2, h - 2); + + printf("dtphoto selecttest: lasso in=%d out=%d %s\n", + in0, out, (in0 && !out) ? "ok" : "FAIL"); + if (!(in0 && !out)) + bad++; + } + /* Clear inside the wand's set must not touch a pixel outside */ + WandSelect(30, 20, 0); + PaintMask(bgPixel); + { + /* GetImageRGB hands out a new buffer; the one this test + * built was already set into the document */ + unsigned char *now = NULL; + int nw = 0, nh = 0; + + if (GetImageRGB(&now, &nw, &nh) == 0) { + unsigned char *d = now + + ((size_t) 20 * nw + 30) * 3; + unsigned char *e = now + + ((size_t) 20 * nw + 10) * 3; + int ok = d[0] == 255 && d[1] == 255 && + d[2] == 255 && e[0] == 255 && e[1] == 0 && + e[2] == 0; + + printf("dtphoto selecttest: clear in=%d,%d,%d " + "out=%d,%d,%d %s\n", d[0], d[1], d[2], + e[0], e[1], e[2], ok ? "ok" : "FAIL"); + if (!ok) + bad++; + free(now); + } + } + free(rgb); + printf("dtphoto selecttest: %s\n", bad == 0 ? "PASS" : "FAIL"); + return bad == 0 ? 0 : 1; + } + /* * The drawing check: a document with a line, a rectangle and a fill, * saved, then read back and compared at known pixels. From e0f4867ded6312ead1a59598639c87d548668749 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 11:05:24 +0000 Subject: [PATCH 15/22] MCDE dtphoto: the Image and Filter menus carry real operations Image: Invert, Desaturate, Brightness/Contrast, Flip horizontal/vertical, Rotate 180/90 CW/90 CCW, Image Size and Canvas Size. Filter: Blur, Blur More, Sharpen, Sharpen More, Find Edges, Emboss, Solarize, Add Noise, Median/Despeckle, Mosaic. All of them read and write through the same RGB buffer, so no operation costs an X round trip per pixel. Two bugs found while wiring them: - A per-pixel correction ignored the selection. Invert, Desaturate, Brightness and Solarize changed the whole picture even with a mask. They now share OpPerPixel, so a new operation cannot forget the mask. - A menu entry was bound by its label, but the reference has "Horizontal" in Image > Flip and in Layer > Type. CommandOf takes the full path now ("Image/Flip/Horizontal"), the reader stores it in Item.path. Verified, depth 24 and depth 8, 16 runs, 0 red: - -menutest: 31 paths each resolve to the command the callback switches on; an unknown path stays CMD_NONE. - -optest against the arithmetic, not "the picture changed": a hard edge blurred to 170 (six of nine window pixels white), the same edge sharpened clamped to 255 and 0, mosaic cells to their mean (100,30,128), noise deterministic and inside the range, mask inside changed and outside untouched. - -selftest on a 1024x768 24-bit BMP: byte-identical (2,359,350 bytes, 0 differing). - -retouchtest -selecttest -movetest -croptest -typetest still green. - DTPHOTO_CMDS=1 reports 37 bound entries, the 11 Filter paths among them. --- AGENTS.md | 26 + programs/dtphoto/dtphoto.c | 1262 +++++++++++++++++++++++++++++++++++- 2 files changed, 1257 insertions(+), 31 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 726e12e0..7cd1a792 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -103,6 +103,32 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt and depth 8. Retouching reads a patch around the dab through one GetImageRGB round trip, not one per pixel; measured 80 ms for a full 1024x768 open/save round trip on a busy host. + The Image and Filter menus carry real operations since 2026-11-22, all + through the same RGB buffer: Image > Adjust (Invert, Desaturate, + Brightness/Contrast), Flip (horizontal, vertical), Rotate (180, 90 CW, + 90 CCW, which swaps the document size), Image Size (nearest neighbour, + the aspect kept from the width) and Canvas Size (the picture centred in + the larger canvas, the border in the background colour). Filter > + Blur/Sharpen are 3x3 convolutions (Blur More a gaussian-ish kernel, + Sharpen More the strong laplacian), Stylize has Find Edges, Emboss and + Solarize, Noise has Add Noise (a xorshift seed, so the same run gives + the same bytes) and Median/Despeckle, Pixelate has Mosaic. The border + pixels keep what they had -- a 3x3 window at the edge would fold + outside the picture -- and every per-pixel operation honours the + selection: the first four (invert, desaturate, brightness, solarize) + did not, which is why they now share `OpPerPixel` and a new operation + cannot forget the mask. + A menu entry is bound by its full path, not its label: the reference + has "Horizontal" in Image > Flip and in Layer > Type, and the label + alone cannot tell them apart. `CommandOf` takes "menu/sub/item", the + reader stores it in `Item.path`, and `-menutest` proves every path + resolves to the command the callback switches on (31 paths, measured + 2026-11-22). `DTPHOTO_CMDS=1` prints what the loaded menu file bound. + `dtphoto -optest|-menutest` are headless too: the operations are checked + against the arithmetic (a hard edge blurred to 170, the same edge + sharpened clamped to 255 and 0, a mosaic cell to its mean) and not + against "the picture changed". All eight run green on depth 24 and + depth 8. The zoom magnifier doubles on the left button and halves on the right (12%-800%), the hand pans the view, and both say what they did on stderr so a mouse-driven test can read the result. diff --git a/programs/dtphoto/dtphoto.c b/programs/dtphoto/dtphoto.c index da3b8a37..25857c6e 100644 --- a/programs/dtphoto/dtphoto.c +++ b/programs/dtphoto/dtphoto.c @@ -46,6 +46,7 @@ typedef struct Menu Menu; typedef struct { char label[64]; + char path[128]; /* "Image/Flip/Horizontal" */ char key[16]; int separator; Menu *sub; @@ -61,7 +62,15 @@ struct Menu { enum { CMD_NONE, CMD_NEW, CMD_OPEN, CMD_SAVE, CMD_SAVEAS, CMD_QUIT, CMD_UNDO, CMD_ZOOMIN, CMD_ZOOMOUT, CMD_FIT, CMD_ACTUAL, - CMD_ALL, CMD_DESELECT, CMD_CLEAR, CMD_FILL, CMD_CROP, CMD_INVERSE + CMD_ALL, CMD_DESELECT, CMD_CLEAR, CMD_FILL, CMD_CROP, CMD_INVERSE, + /* Image: the whole picture, through the RGB buffer */ + CMD_INVERT, CMD_DESATURATE, CMD_FLIPH, CMD_FLIPV, + CMD_ROT180, CMD_ROT90CW, CMD_ROT90CCW, + CMD_BRIGHTCONTRAST, CMD_IMAGESIZE, CMD_CANVASSIZE, + /* Filter: convolution, noise, pixelate, tone */ + CMD_BLUR, CMD_BLURMORE, CMD_SHARPEN, CMD_SHARPENMORE, + CMD_FINDEDGES, CMD_EMBOSS, CMD_SOLARIZE, + CMD_ADDNOISE, CMD_MEDIAN, CMD_MOSAIC }; static Menu menus[MAXMENUS]; @@ -336,19 +345,41 @@ SetImageRGB(const unsigned char *rgb, int w, int h) { XImage *im; unsigned long *keys = NULL, *kpix = NULL; - int nkeys = 0, x, y; + int nkeys = 0, x, y, same, oldW = docW, oldH = docH; if (w < 1 || h < 1 || w > 8192 || h > 8192) return -1; + same = (w == docW && h == docH); + /* + * Same size: this is a change *to* the picture, so the picture as it + * was is the undo state. Different size: a new document, nothing to + * undo. Without this an Image > Invert could not be undone -- + * SetImageRGB used to copy the *new* pixels into snap. + * + * Not while a tool drags: the canvas copies the picture into snap at + * the press, and that pre-press state is what Undo must bring back. + * Copying here mid-drag would leave the last intermediate frame in + * snap instead (a moved picture could not be undone). + */ + if (same && !dragging && image != None && snap != None) + XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); docW = w; docH = h; - /* a mask belongs to one size: the bits are indexed by x + y * docW, - * so a new document must start without one */ - MaskClear(); - free(selMask); - selMask = NULL; - selMaskSize = 0; - NewPixmaps(); + /* + * The mask is indexed by x + y * docW, so a new size must start + * without one. A same-size change keeps it: Invert and Desaturate + * leave everything where it was, and the selection stays valid. + */ + if (!same) { + MaskClear(); + free(selMask); + selMask = NULL; + selMaskSize = 0; + } + /* the pixmaps are already the right size when nothing changed */ + if (!same || image == None) + NewPixmaps(); + (void) oldW; (void) oldH; im = XCreateImage(dpy, vis, (unsigned int) visdepth, ZPixmap, 0, NULL, (unsigned int) w, (unsigned int) h, 32, 0); if (im == NULL) @@ -963,12 +994,15 @@ Trim(char *p) p[--n] = '\0'; } +static int CommandOf(const char *path); + static void ReadMenus(const char *path) { FILE *f; char line[256]; Menu *stack[MAXDEPTH]; + char prefix[MAXDEPTH][64]; /* the path down to each level */ int depth = 0; if ((f = fopen(path, "r")) == NULL) @@ -996,6 +1030,8 @@ ReadMenus(const char *path) "%s", p + 5); menus[nmenus].count = 0; stack[0] = &menus[nmenus]; + /* "menu Layer @3.0" was already stripped of the tag */ + snprintf(prefix[0], sizeof prefix[0], "%s", p + 5); depth = 1; nmenus++; } else if (strncmp(p, "sub ", 4) == 0 && depth > 0 && @@ -1009,11 +1045,15 @@ ReadMenus(const char *path) it = &m->items[m->count++]; memset(it, 0, sizeof *it); snprintf(it->label, sizeof it->label, "%s", p + 4); + snprintf(it->path, sizeof it->path, "%s/%s", + prefix[depth - 1], p + 4); sub = calloc(1, sizeof *sub); if (sub == NULL) continue; snprintf(sub->name, sizeof sub->name, "%s", p + 4); it->sub = sub; + snprintf(prefix[depth], sizeof prefix[depth], "%s", + it->path); stack[depth++] = sub; } else if (strcmp(p, "endsub") == 0 && depth > 1) { depth--; @@ -1033,6 +1073,9 @@ ReadMenus(const char *path) } snprintf(it->label, sizeof it->label, "%s", p + 5); Trim(it->label); + snprintf(it->path, sizeof it->path, "%s/%s", + prefix[depth - 1], it->label); + it->cmd = CommandOf(it->path); } else if (strcmp(p, "sep") == 0 && depth > 0) { Menu *m = stack[depth - 1]; @@ -1044,24 +1087,58 @@ ReadMenus(const char *path) } static int -CommandOf(const char *label) +CommandOf(const char *path) { - if (strcmp(label, "New...") == 0) return CMD_NEW; - if (strcmp(label, "Open...") == 0) return CMD_OPEN; - if (strcmp(label, "Save") == 0) return CMD_SAVE; - if (strcmp(label, "Save As...") == 0) return CMD_SAVEAS; - if (strcmp(label, "Quit") == 0) return CMD_QUIT; - if (strcmp(label, "Undo") == 0) return CMD_UNDO; - if (strcmp(label, "Zoom In") == 0) return CMD_ZOOMIN; - if (strcmp(label, "Zoom Out") == 0) return CMD_ZOOMOUT; - if (strcmp(label, "Fit on Screen") == 0) return CMD_FIT; - if (strcmp(label, "Actual Pixels") == 0) return CMD_ACTUAL; - if (strcmp(label, "All") == 0) return CMD_ALL; - if (strcmp(label, "None") == 0) return CMD_DESELECT; - if (strcmp(label, "Clear") == 0) return CMD_CLEAR; - if (strcmp(label, "Fill...") == 0) return CMD_FILL; - if (strcmp(label, "Crop") == 0) return CMD_CROP; - if (strcmp(label, "Inverse") == 0) return CMD_INVERSE; + /* the label alone is ambiguous ("Horizontal" is in Image > Flip and + * in Layer > Type), so the caller passes "menu/sub/item" */ + const char *leaf = strrchr(path, '/'); + + if (leaf != NULL) + leaf++; + else + leaf = path; + if (strcmp(path, "File/New...") == 0) return CMD_NEW; + if (strcmp(path, "File/Open...") == 0) return CMD_OPEN; + if (strcmp(path, "File/Save") == 0) return CMD_SAVE; + if (strcmp(path, "File/Save As...") == 0) return CMD_SAVEAS; + if (strcmp(path, "File/Quit") == 0) return CMD_QUIT; + if (strcmp(path, "Edit/Undo") == 0) return CMD_UNDO; + if (strcmp(path, "View/Zoom In") == 0) return CMD_ZOOMIN; + if (strcmp(path, "View/Zoom Out") == 0) return CMD_ZOOMOUT; + if (strcmp(path, "View/Fit on Screen") == 0) return CMD_FIT; + if (strcmp(path, "View/Actual Pixels") == 0) return CMD_ACTUAL; + if (strcmp(path, "Select/All") == 0) return CMD_ALL; + if (strcmp(path, "Select/None") == 0) return CMD_DESELECT; + if (strcmp(path, "Select/Inverse") == 0) return CMD_INVERSE; + if (strcmp(path, "Edit/Clear") == 0) return CMD_CLEAR; + if (strcmp(path, "Edit/Fill...") == 0) return CMD_FILL; + if (strcmp(path, "Edit/Crop") == 0) return CMD_CROP; + /* Image: the operations that act on the whole picture */ + if (strcmp(path, "Image/Adjust/Invert") == 0) return CMD_INVERT; + if (strcmp(path, "Image/Adjust/Desaturate") == 0) return CMD_DESATURATE; + if (strcmp(path, "Image/Adjust/Brightness/Contrast...") == 0) + return CMD_BRIGHTCONTRAST; + if (strcmp(path, "Image/Flip/Horizontal") == 0) return CMD_FLIPH; + if (strcmp(path, "Image/Flip/Vertical") == 0) return CMD_FLIPV; + if (strcmp(path, "Image/Rotate/180") == 0) return CMD_ROT180; + if (strcmp(path, "Image/Rotate/90 CW") == 0) return CMD_ROT90CW; + if (strcmp(path, "Image/Rotate/90 CCW") == 0) return CMD_ROT90CCW; + /* Filter: the convolution family and the pixel filters */ + if (strcmp(path, "Filter/Blur/Blur") == 0) return CMD_BLUR; + if (strcmp(path, "Filter/Blur/Blur More") == 0) return CMD_BLURMORE; + if (strcmp(path, "Filter/Sharpen/Sharpen") == 0) return CMD_SHARPEN; + if (strcmp(path, "Filter/Sharpen/Sharpen More") == 0) + return CMD_SHARPENMORE; + if (strcmp(path, "Filter/Stylize/Find Edges") == 0) return CMD_FINDEDGES; + if (strcmp(path, "Filter/Stylize/Emboss...") == 0) return CMD_EMBOSS; + if (strcmp(path, "Filter/Stylize/Solarize") == 0) return CMD_SOLARIZE; + if (strcmp(path, "Filter/Noise/Add Noise...") == 0) return CMD_ADDNOISE; + if (strcmp(path, "Filter/Noise/Despeckle") == 0) return CMD_MEDIAN; + if (strcmp(path, "Filter/Noise/Median...") == 0) return CMD_MEDIAN; + if (strcmp(path, "Filter/Pixelate/Mosaic...") == 0) return CMD_MOSAIC; + if (strcmp(path, "Image/Image Size...") == 0) return CMD_IMAGESIZE; + if (strcmp(path, "Image/Canvas Size...") == 0) return CMD_CANVASSIZE; + (void) leaf; return CMD_NONE; } @@ -1085,6 +1162,8 @@ MakeAccel(const char *key, char *out, size_t size) snprintf(out, size, "%s%s", mod, name); } +static void DumpBound(const Menu *menus, int n); + static void MenuCallback(Widget w, XtPointer data, XtPointer call); /* dtphoto's message catalog (programs/dtphoto/dtphoto.msg, the locale's @@ -1140,7 +1219,7 @@ BuildMenu(Widget parent, Menu *m) } entry = XtVaCreateManagedWidget(it->label, xmPushButtonWidgetClass, shell, NULL); - XtAddCallback(entry, XmNactivateCallback, MenuCallback, it->label); + XtAddCallback(entry, XmNactivateCallback, MenuCallback, it); if (it->key[0] != '\0') { MakeAccel(it->key, accel, sizeof accel); XtVaSetValues(entry, XmNaccelerator, accel, NULL); @@ -1277,7 +1356,8 @@ ShapeImage(int x0, int y0, int x1, int y1) switch (currentTool) { case 9: XDrawLine(dpy, image, gc, x0, y0, x1, y1); break; case 12: XDrawRectangle(dpy, image, gc, x, y, w, h); break; - case 14: XDrawArc(dpy, image, gc, x, y, w, h, 0, 360 * 64); break; + /* case 14 is the gradient and is painted in GradientImage, not here: + * a ramp is not a shape, it fills the drag's box with a colour ramp */ } } @@ -2258,6 +2338,670 @@ CropToSelection(void) fprintf(stderr, "dtphoto: crop %dx%d\n", docW, docH); } +/* ---------------------------------------------------------- image operations */ + +/* + * Everything in the Image menu works on the whole picture and goes through + * one RGB buffer: read once, transform in memory, write once. Per pixel + * XGetPixel/XPutPixel would be a round trip each -- the defect that cost + * open and save 20 s before 2026-11-22. + * + * A transform keeps the undo snapshot: the caller passes the buffer it + * read, the new size comes back, and SetImageRGB stores image and snap. + * Where the transform has to keep the old picture (a rotation changes the + * document size), SetImageRGB takes the new one; the caller copies the old + * image into snap afterwards when the size stayed the same. + */ + +/* + * The selection clips a correction: a picture with a mask is changed only + * inside it, as in the original. Every operation goes through this, so no + * one of them can forget the mask the way the first four did. + */ +typedef void (*ChanFn)(unsigned char *p, void *cd); + +static void +OpPerPixel(ChanFn fn, void *cd) +{ + unsigned char *rgb; + int w, h, x, y; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + if (selMaskAny && !MaskGet(x, y)) + continue; + fn(rgb + ((size_t) y * w + x) * 3, cd); + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Invert: 255 - v on all three channels */ +static void +InvertPx(unsigned char *p, void *cd) +{ + (void) cd; + p[0] = (unsigned char) (255 - p[0]); + p[1] = (unsigned char) (255 - p[1]); + p[2] = (unsigned char) (255 - p[2]); +} + +static void +OpInvert(void) +{ + OpPerPixel(InvertPx, NULL); +} + +/* Desaturate: the luminance of the original (Photoshop uses 0.299/0.587/0.114) */ +static void +DesatPx(unsigned char *p, void *cd) +{ + (void) cd; + p[0] = p[1] = p[2] = (unsigned char) + ((299L * p[0] + 587L * p[1] + 114L * p[2]) / 1000); +} + +static void +OpDesaturate(void) +{ + OpPerPixel(DesatPx, NULL); +} + +/* Flip and rotate: the pixels move, the document keeps its size (or swaps it) */ +static int +OpFlip(int horizontal) +{ + unsigned char *rgb, *out; + int w, h, x, y; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return -1; + if ((out = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return -1; + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + int sx = horizontal ? w - 1 - x : x; + int sy = horizontal ? y : h - 1 - y; + + memcpy(out + ((size_t) y * w + x) * 3, + rgb + ((size_t) sy * w + sx) * 3, 3); + } + SetImageRGB(out, w, h); + free(out); + free(rgb); + return 0; +} + +/* turn: 0 = 180, 1 = 90 clockwise, -1 = 90 counter-clockwise */ +static int +OpRotate(int turn) +{ + unsigned char *rgb, *out; + int w, h, nw, nh, x, y; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return -1; + if (turn == 0) { + nw = w; + nh = h; + } else { + nw = h; + nh = w; + } + if ((out = malloc((size_t) nw * nh * 3)) == NULL) { + free(rgb); + return -1; + } + for (y = 0; y < nh; y++) + for (x = 0; x < nw; x++) { + int sx, sy; + + if (turn == 0) { + sx = w - 1 - x; + sy = h - 1 - y; + } else if (turn > 0) { + /* clockwise: the left column becomes the top row */ + sx = y; + sy = h - 1 - x; + } else { + sx = w - 1 - y; + sy = x; + } + memcpy(out + ((size_t) y * nw + x) * 3, + rgb + ((size_t) sy * w + sx) * 3, 3); + } + SetImageRGB(out, nw, nh); + free(out); + free(rgb); + return 0; +} + +/* Brightness and contrast as Photoshop's own: -100..100 each */ +typedef struct { double k; double add; } BrightCD; + +static void +BrightPx(unsigned char *p, void *cd) +{ + BrightCD *bc = (BrightCD *) cd; + int i; + + for (i = 0; i < 3; i++) { + double v = (p[i] - 128.0) * bc->k + 128.0 + bc->add; + + if (v < 0.0) v = 0.0; + if (v > 255.0) v = 255.0; + p[i] = (unsigned char) (v + 0.5); + } +} + +static int +OpBrightContrast(int brightness, int contrast) +{ + BrightCD bc; + double c = (100.0 + contrast) / 100.0; + + if (c <= 0.0) + c = 0.01; + /* contrast 100 doubles, -100 flattens to nothing */ + if (contrast >= 0) + bc.k = 1.0 / (1.0 - contrast / 200.0); + else + bc.k = 1.0 + contrast / 100.0; + bc.add = brightness * 255.0 / 100.0; + OpPerPixel(BrightPx, &bc); + return 0; +} + +/* Scale the picture to (nw, nh), nearest neighbour as the original does for + * an integer zoom; enough for Image Size, which is what this is for. */ +static int +OpResize(int nw, int nh) +{ + unsigned char *rgb, *out; + int w, h, x, y; + + if (nw < 1 || nh < 1 || nw > 8192 || nh > 8192) + return -1; + if (GetImageRGB(&rgb, &w, &h) != 0) + return -1; + if ((out = malloc((size_t) nw * nh * 3)) == NULL) { + free(rgb); + return -1; + } + for (y = 0; y < nh; y++) + for (x = 0; x < nw; x++) { + int sx = x * w / nw; + int sy = y * h / nh; + + if (sx >= w) sx = w - 1; + if (sy >= h) sy = h - 1; + memcpy(out + ((size_t) y * nw + x) * 3, + rgb + ((size_t) sy * w + sx) * 3, 3); + } + SetImageRGB(out, nw, nh); + free(out); + free(rgb); + return 0; +} + +/* Canvas Size: keep the pixels, move them by (dx, dy) inside the new size; + * what the new canvas does not cover is background. */ +static int +OpCanvasSize(int nw, int nh, int dx, int dy) +{ + unsigned char *rgb, *out; + unsigned char br, bg, bb; + int w, h, x, y; + + if (nw < 1 || nh < 1 || nw > 8192 || nh > 8192) + return -1; + if (GetImageRGB(&rgb, &w, &h) != 0) + return -1; + if ((out = malloc((size_t) nw * nh * 3)) == NULL) { + free(rgb); + return -1; + } + PixelToRGB(bgPixel, &br, &bg, &bb); + for (y = 0; y < nh; y++) + for (x = 0; x < nw; x++) { + unsigned char *d = out + ((size_t) y * nw + x) * 3; + int sx = x - dx, sy = y - dy; + + if (sx < 0 || sy < 0 || sx >= w || sy >= h) { + d[0] = br; d[1] = bg; d[2] = bb; + } else { + memcpy(d, rgb + ((size_t) sy * w + sx) * 3, 3); + } + } + SetImageRGB(out, nw, nh); + free(out); + free(rgb); + return 0; +} + +/* + * The Filter menu: a convolution over the RGB buffer, the picture read and + * written once. A 3x3 kernel is enough for blur, sharpen, find edges and + * emboss; the border pixels keep what they had, which is what the original + * does too (it clamps instead of wrapping). + */ +static void +Convolve3x3(const double k[9], double bias) +{ + unsigned char *rgb, *src; + int w, h, x, y, c; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + int ix, iy; + + /* the border has no neighbours to fold with */ + if (x == 0 || y == 0 || x == w - 1 || y == h - 1) { + if (selMaskAny && !MaskGet(x, y)) { + memcpy(d, src + ((size_t) y * w + x) * 3, 3); + } + continue; + } + if (selMaskAny && !MaskGet(x, y)) { + memcpy(d, src + ((size_t) y * w + x) * 3, 3); + continue; + } + for (c = 0; c < 3; c++) { + double sum = bias; + + for (iy = 0; iy < 3; iy++) + for (ix = 0; ix < 3; ix++) + sum += k[iy * 3 + ix] * + src[((size_t) (y + iy - 1) * w + + (x + ix - 1)) * 3 + c]; + if (sum < 0.0) sum = 0.0; + if (sum > 255.0) sum = 255.0; + d[c] = (unsigned char) (sum + 0.5); + } + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +static void +OpBlur(int more) +{ + /* the 3x3 box blur, the divisor 9 */ + static const double box[9] = { + 1.0 / 9, 1.0 / 9, 1.0 / 9, + 1.0 / 9, 1.0 / 9, 1.0 / 9, + 1.0 / 9, 1.0 / 9, 1.0 / 9 + }; + /* "Blur More" is a stronger, gaussian-ish kernel */ + static const double more_k[9] = { + 1.0 / 16, 2.0 / 16, 1.0 / 16, + 2.0 / 16, 4.0 / 16, 2.0 / 16, + 1.0 / 16, 2.0 / 16, 1.0 / 16 + }; + + Convolve3x3(more ? more_k : box, 0.0); +} + +static void +OpSharpen(int more) +{ + static const double sharp[9] = { + 0.0, -1.0, 0.0, + -1.0, 5.0, -1.0, + 0.0, -1.0, 0.0 + }; + static const double edge[9] = { + -1.0, -1.0, -1.0, + -1.0, 9.0, -1.0, + -1.0, -1.0, -1.0 + }; + + Convolve3x3(more ? edge : sharp, 0.0); +} + +static void +OpFindEdges(void) +{ + static const double lap[9] = { + 0.0, -1.0, 0.0, + -1.0, 4.0, -1.0, + 0.0, -1.0, 0.0 + }; + unsigned char *rgb; + int w, h, i; + + /* the edges first, then the original turns them into grey lines */ + Convolve3x3(lap, 0.0); + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + for (i = 0; i < w * h * 3; i++) + rgb[i] = (unsigned char) (255 - rgb[i]); + SetImageRGB(rgb, w, h); + free(rgb); +} + +static void +OpEmboss(void) +{ + static const double emb[9] = { + -2.0, -1.0, 0.0, + -1.0, 1.0, 1.0, + 0.0, 1.0, 2.0 + }; + + Convolve3x3(emb, 128.0); +} + +/* Noise: a deterministic scatter, so a test can predict it exactly */ +static void +OpAddNoise(int amount) +{ + unsigned char *rgb; + int w, h, x, y; + unsigned long seed = 12345UL; + + if (amount < 0) amount = 0; + if (amount > 100) amount = 100; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *p = rgb + ((size_t) y * w + x) * 3; + int n, c; + + if (selMaskAny && !MaskGet(x, y)) + continue; + /* xorshift: no libc rand, the same value everywhere */ + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + n = (int) (seed % 201UL) - 100; + n = n * amount / 100; + for (c = 0; c < 3; c++) { + int v = p[c] + n; + + if (v < 0) v = 0; + if (v > 255) v = 255; + p[c] = (unsigned char) v; + } + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Median: the 3x3 median per channel, the classic despeckle */ +static void +OpMedian(void) +{ + unsigned char *rgb, *src; + int w, h, x, y, c; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + + if (x == 0 || y == 0 || x == w - 1 || y == h - 1) { + memcpy(d, src + ((size_t) y * w + x) * 3, 3); + continue; + } + if (selMaskAny && !MaskGet(x, y)) { + memcpy(d, src + ((size_t) y * w + x) * 3, 3); + continue; + } + for (c = 0; c < 3; c++) { + unsigned char v[9]; + int i, j; + + for (i = 0; i < 9; i++) + v[i] = src[((size_t) (y + i / 3 - 1) * w + + (x + i % 3 - 1)) * 3 + c]; + /* nine values: an insertion sort is fastest */ + for (i = 1; i < 9; i++) { + unsigned char t = v[i]; + + for (j = i; j > 0 && v[j - 1] > t; j--) + v[j] = v[j - 1]; + v[j] = t; + } + d[c] = v[4]; + } + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Pixelate: one block, one colour -- the mean of the block */ +static void +OpMosaic(int cell) +{ + unsigned char *rgb; + int w, h, x, y, bx, by, c; + + if (cell < 1) cell = 1; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + for (by = 0; by < h; by += cell) + for (bx = 0; bx < w; bx += cell) { + int bw = bx + cell > w ? w - bx : cell; + int bh = by + cell > h ? h - by : cell; + unsigned char mean[3]; + + for (c = 0; c < 3; c++) { + unsigned long sum = 0; + int n = 0; + + for (y = by; y < by + bh; y++) + for (x = bx; x < bx + bw; x++) { + if (selMaskAny && !MaskGet(x, y)) + continue; + sum += rgb[((size_t) y * w + x) * 3 + c]; + n++; + } + mean[c] = (unsigned char) + (n > 0 ? sum / (unsigned long) n : 0); + } + for (y = by; y < by + bh; y++) + for (x = bx; x < bx + bw; x++) { + unsigned char *d; + + if (selMaskAny && !MaskGet(x, y)) + continue; + d = rgb + ((size_t) y * w + x) * 3; + memcpy(d, mean, 3); + } + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Solarize: the tone curve of the original, invert above mid grey */ +static void +SolarizePx(unsigned char *p, void *cd) +{ + (void) cd; + if (p[0] > 127) p[0] = (unsigned char) (255 - p[0]); + if (p[1] > 127) p[1] = (unsigned char) (255 - p[1]); + if (p[2] > 127) p[2] = (unsigned char) (255 - p[2]); +} + +static void +OpSolarize(void) +{ + OpPerPixel(SolarizePx, NULL); +} + +/* + * The gradient tool. Photoshop draws a linear ramp from the foreground to + * the background colour along the drag; the mask, when there is one, clips + * it. The picture is read once and written once, like every other op. + */ +static void +GradientImage(int x0, int y0, int x1, int y1) +{ + unsigned char *rgb, fr, fg, fb, tr, tg, tb; + int w, h, x, y; + long dx = x1 - x0, dy = y1 - y0; + long len2 = dx * dx + dy * dy; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if (len2 == 0) { + free(rgb); + return; + } + PixelToRGB(fgPixel, &fr, &fg, &fb); + PixelToRGB(bgPixel, &tr, &tg, &tb); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + long t; + unsigned char *d; + + if (selMaskAny && !MaskGet(x, y)) + continue; + /* how far along the drag, clamped to the ends */ + t = ((long) (x - x0) * dx + (long) (y - y0) * dy) * + 1000 / len2; + if (t < 0) t = 0; + if (t > 1000) t = 1000; + d = rgb + ((size_t) y * w + x) * 3; + d[0] = (unsigned char) (fr + (tr - fr) * t / 1000); + d[1] = (unsigned char) (fg + (tg - fg) * t / 1000); + d[2] = (unsigned char) (fb + (tb - fb) * t / 1000); + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* + * A one-field number dialog, the pattern the type dialog already uses. + * XmSelectionBox keeps what a person types; the callback gets the string. + */ +typedef void (*NumberFn)(int a, int b); + +static void +NumberOk(Widget w, XtPointer cd, XtPointer call) +{ + XmSelectionBoxCallbackStruct *c = + (XmSelectionBoxCallbackStruct *) call; + NumberFn fn = (NumberFn) cd; + char *s = NULL; + int a = 0, b = 0; + + if (XmStringGetLtoR(c->value, XmSTRING_DEFAULT_CHARSET, &s) && s != NULL) { + if (sscanf(s, "%d %d", &a, &b) < 1) + a = b = 0; + if (fn != NULL) + fn(a, b); + XtFree(s); + } + XtDestroyWidget(w); +} + +static void +NumberCancel(Widget w, XtPointer cd, XtPointer call) +{ + (void) cd; (void) call; + XtDestroyWidget(w); +} + +static void +NumberDialog(const char *prompt, const char *initial, NumberFn fn) +{ + Widget d = XmCreatePromptDialog(top, "number", NULL, 0); + Widget help; + XmString lab; + + lab = XmStringCreateLocalized(prompt); + XtVaSetValues(d, XmNselectionLabelString, lab, XmNtextString, + XmStringCreateLocalized(initial), NULL); + XmStringFree(lab); + help = XmSelectionBoxGetChild(d, XmDIALOG_HELP_BUTTON); + if (help != NULL) + XtUnmanageChild(help); + XtAddCallback(d, XmNokCallback, NumberOk, (XtPointer) fn); + XtAddCallback(d, XmNcancelCallback, NumberCancel, NULL); + XtManageChild(d); +} + +static void +BrightContrastOk(int brightness, int contrast) +{ + OpBrightContrast(brightness, contrast); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: brightness %d contrast %d\n", brightness, + contrast); +} + +static void +ImageSizeOk(int w, int h) +{ + (void) h; + if (w < 1) + return; + /* one field is the width; the height keeps the aspect */ + OpResize(w, docH * w / (docW > 0 ? docW : 1)); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: image size %dx%d\n", docW, docH); +} + +static void +CanvasSizeOk(int w, int h) +{ + if (w < 1 || h < 1) + return; + /* the extra canvas grows around the picture, as the original centres it */ + OpCanvasSize(w, h, (w - docW) / 2, (h - docH) / 2); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: canvas size %dx%d\n", docW, docH); +} + +static void +AddNoiseOk(int amount, int unused) +{ + (void) unused; + OpAddNoise(amount); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: add noise %d\n", amount); +} + +static void +MosaicOk(int cell, int unused) +{ + (void) unused; + OpMosaic(cell); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: mosaic %d\n", cell); +} + +/* one line for a tool or a menu action, so a mouse test can read it */ +static void +OpDone(const char *what) +{ + RenderDoc(canvas); + fprintf(stderr, "dtphoto: %s\n", what); +} + /* * A dashed rectangle over the document: the marquee of the original. * Drawn on the window, not into the picture; the document keeps its pixels. @@ -2379,6 +3123,9 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) FloodFillImage(docx, docy); dragging = 0; break; + case 14: /* gradient: drag sets the direction */ + GradientImage(docx, docy, docx, docy); + break; case 15: case 16: case 17: case 18: case 19: case 20: /* the retouching tools */ smudgeValid = 0; @@ -2437,12 +3184,16 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) XSetForeground(dpy, gc, bgPixel); Dab(docx, docy, 6); break; - case 9: case 13: case 14: + case 9: case 13: XCopyArea(dpy, snap, image, gc, 0, 0, docW, docH, 0, 0); if (currentTool == 9) XSetForeground(dpy, gc, fgPixel); ShapeImage(pressX, pressY, docx, docy); break; + case 14: /* gradient: a ramp along the drag */ + XCopyArea(dpy, snap, image, gc, 0, 0, docW, docH, 0, 0); + GradientImage(pressX, pressY, docx, docy); + break; case 15: case 16: case 17: case 18: case 19: case 20: Retouch(docx, docy, 6, 60, currentTool); @@ -2741,11 +3492,43 @@ NewDoc(void) RenderDoc(canvas); } +static void +DumpBoundMenu(const Menu *m) +{ + int j; + + for (j = 0; j < m->count; j++) { + const Item *it = &m->items[j]; + + if (it->separator) + continue; + if (it->sub != NULL) { + DumpBoundMenu(it->sub); + continue; + } + if (it->cmd == CMD_NONE) + continue; + fprintf(stderr, "dtphoto: bound %s (%d)\n", it->path, it->cmd); + } +} + +/* the list of menu entries the program can actually carry out: the reader + * fills Item.cmd, so this is what is bound, not what a document claims */ +static void +DumpBound(const Menu *menus, int n) +{ + int i; + + for (i = 0; i < n; i++) + DumpBoundMenu(&menus[i]); +} + static void MenuCallback(Widget w, XtPointer data, XtPointer call) { - const char *label = (const char *) data; - int cmd = CommandOf(label); + const Item *it = (const Item *) data; + const char *label = it != NULL ? it->label : ""; + int cmd = it != NULL ? it->cmd : CMD_NONE; (void) w; (void) call; switch (cmd) { @@ -2797,6 +3580,73 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); CropToSelection(); break; + /* Image: whole-picture operations, all through one RGB buffer */ + case CMD_INVERT: + OpInvert(); + UpdateStatus(); + OpDone("invert"); + break; + case CMD_DESATURATE: + OpDesaturate(); + UpdateStatus(); + OpDone("desaturate"); + break; + case CMD_FLIPH: + OpFlip(1); + OpDone("flip horizontal"); + break; + case CMD_FLIPV: + OpFlip(0); + OpDone("flip vertical"); + break; + case CMD_ROT180: + OpRotate(0); + UpdateStatus(); + OpDone("rotate 180"); + break; + case CMD_ROT90CW: + OpRotate(1); + UpdateStatus(); + OpDone("rotate 90 cw"); + break; + case CMD_ROT90CCW: + OpRotate(-1); + UpdateStatus(); + OpDone("rotate 90 ccw"); + break; + case CMD_BRIGHTCONTRAST: + NumberDialog("Brightness Contrast (-100..100):", "0 0", + BrightContrastOk); + break; + case CMD_IMAGESIZE: { + char buf[32]; + + snprintf(buf, sizeof buf, "%d", docW); + NumberDialog("Image Size (width):", buf, ImageSizeOk); + break; + } + case CMD_CANVASSIZE: { + char buf[32]; + + snprintf(buf, sizeof buf, "%d %d", docW, docH); + NumberDialog("Canvas Size (width height):", buf, CanvasSizeOk); + break; + } + /* Filter */ + case CMD_BLUR: OpBlur(0); OpDone("blur"); break; + case CMD_BLURMORE: OpBlur(1); OpDone("blur more"); break; + case CMD_SHARPEN: OpSharpen(0); OpDone("sharpen"); break; + case CMD_SHARPENMORE: OpSharpen(1); OpDone("sharpen more"); break; + case CMD_FINDEDGES: OpFindEdges(); OpDone("find edges"); break; + case CMD_EMBOSS: OpEmboss(); OpDone("emboss"); break; + case CMD_SOLARIZE: OpSolarize(); OpDone("solarize"); break; + case CMD_ADDNOISE: + NumberDialog("Add Noise (0..100):", "20", AddNoiseOk); + break; + case CMD_MEDIAN: OpMedian(); OpDone("median"); break; + case CMD_MOSAIC: + NumberDialog("Mosaic (cell size):", "8", MosaicOk); + break; default: fprintf(stderr, "dtphoto: %s\n", label); break; @@ -2854,6 +3704,8 @@ main(int argc, char **argv) fprintf(stderr, "dtphoto: menu[%d] \"%s\" (%d)\n", i, menus[i].name, menus[i].count); } + if (getenv("DTPHOTO_CMDS") != NULL) + DumpBound(menus, nmenus); form = XtVaCreateManagedWidget("form", xmFormWidgetClass, mainw, XmNfractionBase, 100, XmNwidth, 900, XmNheight, 600, NULL); @@ -3352,6 +4204,354 @@ main(int argc, char **argv) return bad == 0 ? 0 : 1; } + /* The menu bindings, without a mouse: every path the program claims + * to carry out must resolve to the command the callback switches + * on. A path that resolves to CMD_NONE is an entry that does + * nothing but print its own label. */ + if (argc >= 2 && strcmp(argv[1], "-menutest") == 0) { + static const struct { const char *path; int cmd; } want[] = { + { "File/New...", CMD_NEW }, + { "File/Open...", CMD_OPEN }, + { "File/Save", CMD_SAVE }, + { "File/Save As...", CMD_SAVEAS }, + { "Edit/Undo", CMD_UNDO }, + { "Edit/Clear", CMD_CLEAR }, + { "Edit/Crop", CMD_CROP }, + { "Select/All", CMD_ALL }, + { "Select/None", CMD_DESELECT }, + { "Select/Inverse", CMD_INVERSE }, + { "Image/Adjust/Invert", CMD_INVERT }, + { "Image/Adjust/Desaturate", CMD_DESATURATE }, + { "Image/Adjust/Brightness/Contrast...", CMD_BRIGHTCONTRAST }, + { "Image/Flip/Horizontal", CMD_FLIPH }, + { "Image/Flip/Vertical", CMD_FLIPV }, + { "Image/Rotate/180", CMD_ROT180 }, + { "Image/Rotate/90 CW", CMD_ROT90CW }, + { "Image/Rotate/90 CCW", CMD_ROT90CCW }, + { "Image/Image Size...", CMD_IMAGESIZE }, + { "Image/Canvas Size...", CMD_CANVASSIZE }, + { "Filter/Blur/Blur", CMD_BLUR }, + { "Filter/Blur/Blur More", CMD_BLURMORE }, + { "Filter/Sharpen/Sharpen", CMD_SHARPEN }, + { "Filter/Sharpen/Sharpen More", CMD_SHARPENMORE }, + { "Filter/Stylize/Find Edges", CMD_FINDEDGES }, + { "Filter/Stylize/Emboss...", CMD_EMBOSS }, + { "Filter/Stylize/Solarize", CMD_SOLARIZE }, + { "Filter/Noise/Add Noise...", CMD_ADDNOISE }, + { "Filter/Noise/Despeckle", CMD_MEDIAN }, + { "Filter/Noise/Median...", CMD_MEDIAN }, + { "Filter/Pixelate/Mosaic...", CMD_MOSAIC } + }; + size_t i; + int bad = 0; + + for (i = 0; i < sizeof want / sizeof want[0]; i++) { + int got = CommandOf(want[i].path); + + if (got != want[i].cmd) { + printf("dtphoto menutest: %s -> %d want %d FAIL\n", + want[i].path, got, want[i].cmd); + bad++; + } + } + /* an unknown path must not grab a command */ + if (CommandOf("Filter/Blur/No Such Thing") != CMD_NONE) { + printf("dtphoto menutest: unknown path bound FAIL\n"); + bad++; + } + printf("dtphoto menutest: %d paths, %d bad\n", + (int) (sizeof want / sizeof want[0]), bad); + printf("dtphoto menutest: %s\n", bad == 0 ? "PASS" : "FAIL"); + return bad == 0 ? 0 : 1; + } + + /* + * The image operations, checked against the arithmetic and not against + * "the picture changed": invert is 255-v, desaturate is the luminance, + * a flip is an exact permutation, a rotation moves a known corner to a + * known corner. A wrong one of these is a wrong picture, not a bug + * that shows later. + */ + if (argc >= 2 && strcmp(argv[1], "-optest") == 0) { + unsigned char *rgb; + int w = 6, h = 4, x, y, bad = 0; + + rgb = malloc((size_t) w * h * 3); + if (rgb == NULL) { + printf("dtphoto optest: FAIL malloc\n"); + return 1; + } + /* a picture where every pixel is distinct: + * r = x*40, g = y*60, b = 128 */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *p = rgb + ((size_t) y * w + x) * 3; + + p[0] = (unsigned char) (x * 40); + p[1] = (unsigned char) (y * 60); + p[2] = 128; + } + +#define OPT_LOAD() do { \ + if (SetImageRGB(rgb, w, h) != 0) { \ + printf("dtphoto optest: FAIL image\n"); \ + free(rgb); return 1; \ + } \ +} while (0) + /* fetch the document and check one pixel against (r,g,b) */ +#define OPT_PIX(tag, px, py, er, eg, eb) do { \ + unsigned char *now = NULL; int nw = 0, nh = 0; \ + if (GetImageRGB(&now, &nw, &nh) != 0) { \ + printf("dtphoto optest: FAIL readback\n"); \ + free(rgb); return 1; \ + } \ + if (px < nw && py < nh) { \ + unsigned char *q = now + ((size_t) (py) * nw + (px)) * 3; \ + int ok = q[0] == (er) && q[1] == (eg) && q[2] == (eb); \ + printf("dtphoto optest: %s (%d,%d)=%d,%d,%d want %d,%d,%d %s\n", \ + tag, px, py, q[0], q[1], q[2], er, eg, eb, ok ? "ok" : "FAIL"); \ + if (!ok) bad++; \ + } else { \ + printf("dtphoto optest: %s (%d,%d) outside %dx%d FAIL\n", \ + tag, px, py, nw, nh); \ + bad++; \ + } \ + free(now); \ +} while (0) + + /* invert: the corner (0,0) = 0,0,128 becomes 255,255,127 */ + OPT_LOAD(); + OpInvert(); + OPT_PIX("invert", 0, 0, 255, 255, 127); + OPT_PIX("invert", 5, 3, 55, 75, 127); + + /* desaturate: (0,0,128) -> 14; (5,3)=(200,180,128) -> + * (299*200 + 587*180 + 114*128)/1000 = 180 */ + OPT_LOAD(); + OpDesaturate(); + OPT_PIX("desat", 0, 0, 14, 14, 14); + OPT_PIX("desat", 5, 3, 180, 180, 180); + + /* flip horizontal: the left column ends up on the right */ + OPT_LOAD(); + OpFlip(1); + OPT_PIX("fliph", 5, 0, 0, 0, 128); + OPT_PIX("fliph", 0, 0, 200, 0, 128); + + /* flip vertical: the top row ends up at the bottom */ + OPT_LOAD(); + OpFlip(0); + OPT_PIX("flipv", 0, 3, 0, 0, 128); + OPT_PIX("flipv", 0, 0, 0, 180, 128); + + /* rotate 180: the corner (0,0) lands on (w-1,h-1) */ + OPT_LOAD(); + OpRotate(0); + OPT_PIX("rot180", 5, 3, 0, 0, 128); + OPT_PIX("rot180", 0, 0, 200, 180, 128); + + /* rotate 90 clockwise: the document is now h wide, w high; + * the top-left pixel of the result is the bottom-left of the + * original */ + OPT_LOAD(); + OpRotate(1); + OPT_PIX("rot90cw", 0, 0, 0, 180, 128); + OPT_PIX("rot90cw", 3, 5, 200, 0, 128); + + /* rotate 90 counter-clockwise: the top-left is the top-right */ + OPT_LOAD(); + OpRotate(-1); + OPT_PIX("rot90ccw", 0, 0, 200, 0, 128); + OPT_PIX("rot90ccw", 3, 5, 0, 180, 128); + + /* brightness +100 lifts everything to white, -100 to black */ + OPT_LOAD(); + OpBrightContrast(100, 0); + OPT_PIX("bright+100", 0, 0, 255, 255, 255); + OPT_LOAD(); + OpBrightContrast(-100, 0); + OPT_PIX("bright-100", 0, 0, 0, 0, 0); + /* contrast 0 leaves the picture alone */ + OPT_LOAD(); + OpBrightContrast(0, 0); + OPT_PIX("contrast0", 3, 1, 120, 60, 128); + + /* resize to double: (2,2) is what (1,1) held -- sx=1, sy=1 */ + OPT_LOAD(); + OpResize(12, 8); + OPT_PIX("resize", 2, 2, 40, 60, 128); + OPT_PIX("resize", 11, 7, 200, 180, 128); + + /* canvas size 10x8 keeps the picture in the middle: the old + * (0,0) is now at (2,2) */ + OPT_LOAD(); + OpCanvasSize(10, 8, 2, 2); + OPT_PIX("canvas", 2, 2, 0, 0, 128); + OPT_PIX("canvas", 0, 0, 255, 255, 255); + + /* the gradient: a ramp from black to white along x */ + OPT_LOAD(); + fgPixel = BlackPixel(dpy, 0); + bgPixel = WhitePixel(dpy, 0); + GradientImage(0, 0, w - 1, 0); + OPT_PIX("gradient", 0, 0, 0, 0, 0); + OPT_PIX("gradient", 5, 0, 255, 255, 255); + OPT_PIX("gradient", 5, 3, 255, 255, 255); + + /* + * The filters. The test picture has r = 40x, g = 60y, b = 128, + * so a 3x3 box blur of the interior keeps the b channel at 128 + * and leaves r/g at their own value (a ramp blur is the value + * in the middle of the window). + */ + OPT_LOAD(); + OpBlur(0); + OPT_PIX("blur", 2, 1, 80, 60, 128); + /* the border keeps what it had: no neighbours to fold with */ + OPT_PIX("blur", 0, 0, 0, 0, 128); + + /* + * A ramp blur keeps the ramp, so that alone proves nothing. + * A hard edge does: a picture white on the left half, black on + * the right, blurred, must have grey where the edge was and + * white/black at the untouched border. + */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *p = rgb + ((size_t) y * w + x) * 3; + + p[0] = p[1] = p[2] = x < 3 ? 255 : 0; + } + OPT_LOAD(); + OpBlur(0); + /* (2,1): the window is x=1..3, three rows -- six white of nine: + * 1530/9 = 170 */ + OPT_PIX("blur-edge", 2, 1, 170, 170, 170); + /* the corner has no neighbours, so it stays white */ + OPT_PIX("blur-edge", 0, 0, 255, 255, 255); + /* the far side stays black */ + OPT_PIX("blur-edge", 5, 3, 0, 0, 0); + + /* and sharpen pushes the edge further apart than blur does: + * 5*200 - (200+200+200+56) = 344, clamped to 255 */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *p = rgb + ((size_t) y * w + x) * 3; + + p[0] = p[1] = p[2] = x < 3 ? 200 : 56; + } + OPT_LOAD(); + OpSharpen(0); + OPT_PIX("sharpen-edge", 2, 1, 255, 255, 255); + /* on the dark side: 5*56 - (200+56+56+56) = -88, so black */ + OPT_PIX("sharpen-edge", 3, 1, 0, 0, 0); + + /* the edge picture replaced the ramp; put the ramp back */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *p = rgb + ((size_t) y * w + x) * 3; + + p[0] = (unsigned char) (x * 40); + p[1] = (unsigned char) (y * 60); + p[2] = 128; + } + + /* median on a linear ramp is the value itself */ + OPT_LOAD(); + OpMedian(); + OPT_PIX("median", 2, 1, 80, 60, 128); + OPT_PIX("median", 0, 0, 0, 0, 128); + + /* solarize: every channel above mid grey is inverted; + * (0,0,128) -> (0,0,127) and (200,180,128) -> (55,75,127) */ + OPT_LOAD(); + OpSolarize(); + OPT_PIX("solarize", 0, 0, 0, 0, 127); + OPT_PIX("solarize", 5, 3, 55, 75, 127); + + /* mosaic 2: the block (2..3, 0..1) gets the mean of its four + * pixels: r = (80+120+80+120)/4 = 100, g = (0+0+60+60)/4 = 30 */ + OPT_LOAD(); + OpMosaic(2); + OPT_PIX("mosaic", 2, 0, 100, 30, 128); + OPT_PIX("mosaic", 3, 1, 100, 30, 128); + + /* + * Noise: deterministic (one seed), so the same call twice gives + * the same bytes; and it never leaves the 0..255 range. + */ + { + unsigned char *a = NULL, *b = NULL; + int aw = 0, ah = 0, bw = 0, bh = 0, i, same = 1; + int spread = 0; + + OPT_LOAD(); + OpAddNoise(50); + GetImageRGB(&a, &aw, &ah); + OPT_LOAD(); + OpAddNoise(50); + GetImageRGB(&b, &bw, &bh); + if (a != NULL && b != NULL && aw == bw && ah == bh) { + for (i = 0; i < aw * ah * 3; i++) + if (a[i] != b[i]) + same = 0; + } else { + same = 0; + } + /* the noise must actually have moved something */ + for (i = 0; a != NULL && i < aw * ah; i += 3) { + if (a[i] != (int) (40 * ((i / 3) % aw))) + spread = 1; + } + printf("dtphoto optest: noise deterministic %s, moved %s\n", + same ? "ok" : "FAIL", spread ? "ok" : "FAIL"); + if (!same || !spread) + bad++; + free(a); + free(b); + } + + /* + * The selection clips a correction. A mask over the left half + * means Invert must leave the right half alone. + */ + { + unsigned char *now = NULL; + int nw = 0, nh = 0, inside = 0, outside = 0; + + OPT_LOAD(); + if (MaskAlloc() != 0) { + printf("dtphoto optest: FAIL mask alloc\n"); + free(rgb); + return 1; + } + selMaskAny = 1; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + MaskSet(x, y, x < w / 2); + OpInvert(); + GetImageRGB(&now, &nw, &nh); + if (now != NULL) { + unsigned char *in = now + 0; + unsigned char *out = now + ((size_t) 1 * nw + + (nw - 1)) * 3; + + inside = in[0] == 255 && in[2] == 127; + outside = out[0] == 200 && out[2] == 128; + } + printf("dtphoto optest: mask inside %s, outside %s\n", + inside ? "ok" : "FAIL", outside ? "ok" : "FAIL"); + if (!inside || !outside) + bad++; + free(now); + MaskClear(); + } + + free(rgb); + printf("dtphoto optest: %s\n", bad == 0 ? "PASS" : "FAIL"); + return bad == 0 ? 0 : 1; + } + /* * The drawing check: a document with a line, a rectangle and a fill, * saved, then read back and compared at known pixels. From 0d0a144d6674b3e4b9c698b4a4d080694782e17d Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 12:06:04 +0000 Subject: [PATCH 16/22] MCDE: PNG, JPEG and GIF in dtphoto, one picture writer in libDtSvc dtphoto read only BMP and ICO and wrote only BMP; PNG, JPEG and GIF were listed as open in docs/MCDE-PROGRAMS.md since 2026-11-12. The reader was already there: McdeThumbRead in libDtSvc has all five formats, is X-free and is what dtfile uses for its miniatures. dtphoto calls it for everything its own reader does not know, so the program carries no second decoder. There was no picture writer anywhere in the tree, so McdeThumbWrite now sits next to the reader: PNG through libpng's simplified API, BMP in C99, the ending decides, an unknown ending is refused instead of silently becoming a BMP. Measured on Xvfb depth 24 (2026-11-22): - 40x30 PNG -> PNG, 1200 of 1200 pixels identical, CRC checked. - 40x30 GIF -> PNG, 0 of 1200 pixels different. - 40x30 JPEG q100 -> PNG, at most 3 steps per channel (compression, not the reader); the same picture written from libpng is 0 steps. - Depth 8: a 32-colour picture comes back 0 of 256 pixels different; a 1200-colour ramp differs by mean 28.6/255, which is the colormap -- the same ramp is 0 on depth 24. test_thumb writes a 13x7 ramp (every pixel unique) as PNG and BMP and reads it back pixel for pixel. Proved the test bites: writing the BMP rows top-down turns it red at 78 of 91 pixels, PNG_FORMAT_BGR at 91 of 91. The unknown-ending and zero-size cases are checked too. dtphoto: the file dialog filters on every format it reads, not on *.bmp. All 18 dtphoto test modes stay green on depth 24 and depth 8, test_thumb ok. --- AGENTS.md | 47 +- include/Mcde/Thumb.h | 8 + lib/DtSvc/DtUtil2/McdeThumb.c | 121 ++ lib/DtSvc/DtUtil2/test_thumb.c | 99 ++ programs/dtphoto/dtphoto.c | 1536 ++++++++++++++++- programs/dtphoto/dtphoto.msg | 1 + .../localized/de_DE.UTF-8/msg/dtphoto.msg | 1 + 7 files changed, 1774 insertions(+), 39 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7cd1a792..a3d4ddee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -132,6 +132,36 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt The zoom magnifier doubles on the left button and halves on the right (12%-800%), the hand pans the view, and both say what they did on stderr so a mouse-driven test can read the result. + The Select menu's morphology works on an exact euclidean distance field + (two passes, then the distance to the nearest selected and the nearest + unselected pixel), so Expand, Contract, Border, Smooth, Grow, Similar + and Feather are arithmetic, not guesses. Feather needed a second + layer: one bit per pixel cannot carry a soft edge, so `selCover` holds + 0-255 beside the bit mask and every consumer -- `OpPerPixel`, the + gradient, `PaintMask` -- mixes by that coverage instead of cutting at + the bit. `-selmodtest` checks the numbers (a 5x5 block contracted by 1 + loses its four corners and nothing else, a 2 px band from Border, Grow + taking the neighbouring colour and Similar the whole picture). + `Window > Show Options` opens the Options box, which is where the + tool parameters live: pencil and eraser radius, the wand's tolerance + (which Grow/Similar read too), the retouch radius and strength, and the + gradient as linear or radial. Every field writes straight into the + variable the event handler reads, so there is no second copy, and each + edit says `dtphoto: options =` on stderr. The box is built + by a fixed row list, and a row returns the FIELD, not its label: a text + field is taller than its label, so attaching the next row to the label + stacked the fields on top of each other and the tolerance field was + unreachable (measured 2026-11-22, the click landed in the eraser field). + `DTPHOTO_OPTIONS=1` opens the box at startup, which is how the test + reaches it without a mouse. + Painting is clipped to the selection, as in the original: the pencil + (a hard square tip of 2r+1), the brush (a round one) and the eraser all + go through `PaintTip`, which reads the box around the dab once, mixes by + the coverage and writes it back. Before that the pencil drew its tip + over the whole picture whatever the mask said, and the pencil ignored + its radius entirely (one XDrawPoint). `-optest` proves both: a tip laid + across the edge of a 2 px selection changes only those two columns, and + the wand at tolerance 0 takes one pixel where tolerance 100 takes six. dtpaint builds its menus in code and its labels are catalogued (`dtpaint.msg`, 51 messages from 1-53, 52 unused: menus, the tool/file/error/discard/attributes/colour/print dialogs, Help and About); @@ -158,7 +188,17 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt undo across it); Edit Colors sets the foreground from three RGB scales; BMP 8-bit (uncompressed and RLE8) and the first image of an ICO (1/4/8/24/32 bpp, alpha 0 composited on the background; PNG-compressed - icons refused) are read, saving stays 24-bit BMP; Print spools the + icons refused) go through the program's own reader; PNG, JPEG, GIF and + XPM come from `McdeThumbRead` (libDtSvc), so the program carries no + second decoder. Saving writes the format the name ends in, `.png` and + `.bmp` through `McdeThumbWrite`, anything else as 24-bit BMP. Measured + 2026-11-22 on Xvfb depth 24: a 40x30 PNG written back is 1200 of 1200 + pixels identical, a GIF 0 of 1200 different, JPEG q100 at most 3 steps + per channel; on depth 8 a 32-colour picture comes back exact and the + 1200-colour ramp is off by the colormap (mean 28.6 of 255), which is the + visual, not the reader. `test_thumb` writes a 13x7 ramp and reads it + back pixel for pixel, and turns red when the writer's rows are flipped or + its channels swapped. Print spools the current image through `mcde_sys_print_file` (lp; MCDE_PRINT_COMMAND fakes the tool in tests) and removes the temporary file when the job ends. McdeSys has a catalog too (`lib/McdeSys/mcdesys.msg`, `lib/McdeSys/ @@ -192,7 +232,10 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt test `test_thumb`) is the miniature: PNG, JPEG, GIF, BMP and XPM read with libpng, libjpeg and C99, scaled with a box filter and cached in `~/.dt/thumbs/<64|128|256>/` -- the one picture reader for dtfile and the - programs that show pictures, no gdk-pixbuf, no program per picture. + programs that show pictures, no gdk-pixbuf, no program per picture. Since + 2026-11-22 it writes too: `McdeThumbWrite` (PNG through libpng's simplified + API, BMP in C99, the ending decides), so an editor saves without a second + encoder. - Programs of its own: `dtbar` (top bar and global menu, protocol `include/Mcde/GlobalMenu.h`), `dtkeys`, `dtthemesync`, `dtappscan`, `dtsystemsettings` (panes by category, McdeSys only), `dtdiskutility`, diff --git a/include/Mcde/Thumb.h b/include/Mcde/Thumb.h index 8d68ba92..9ff13e20 100644 --- a/include/Mcde/Thumb.h +++ b/include/Mcde/Thumb.h @@ -51,6 +51,14 @@ void McdeThumbFree(McdeThumbImage *image); int McdeThumbScale(const unsigned char *src, int sw, int sh, int maxw, int maxh, unsigned char **dst, int *w, int *h); +/* IMAGE (8-bit RGB) written to PATH. The format comes from the name's + * ending: .png and .bmp are written, anything else is refused. A picture + * written here is read back by McdeThumbRead() pixel for pixel, which is + * what the test checks. 0 on success, -1 on a bad argument, an unknown + * ending or a write error. */ +int McdeThumbWrite(const char *path, const unsigned char *rgb, int w, + int h); + /* IMAGE on SCREEN as a pixmap of the screen's depth; the size is the * picture's, in pixels. 0 on success, -1 when the picture cannot be read or * the visual is not one this module writes (PseudoColor is not). */ diff --git a/lib/DtSvc/DtUtil2/McdeThumb.c b/lib/DtSvc/DtUtil2/McdeThumb.c index 88b99ed3..21264081 100644 --- a/lib/DtSvc/DtUtil2/McdeThumb.c +++ b/lib/DtSvc/DtUtil2/McdeThumb.c @@ -29,6 +29,7 @@ #include #include +#include #include #include #include @@ -908,6 +909,15 @@ bad: /* ------------------------------------------------------------------ */ /* BMP: BI_RGB, 8 and 24 and 32 bits */ +static void +Le32Put(unsigned char *p, unsigned long v) +{ + p[0] = (unsigned char) (v & 0xff); + p[1] = (unsigned char) ((v >> 8) & 0xff); + p[2] = (unsigned char) ((v >> 16) & 0xff); + p[3] = (unsigned char) ((v >> 24) & 0xff); +} + static unsigned long Le32(const unsigned char *p) { @@ -1551,3 +1561,114 @@ McdeThumbScale(const unsigned char *src, int sw, int sh, int maxw, int maxh, return -1; return ScaleTo(src, sw, sh, maxw, maxh, dst, w, h); } + +/* ------------------------------------------------------------------ */ +/* writing a picture, the reverse of the readers above */ + +/* the ending of PATH, lower case, without the dot; NULL when there is none */ +static const char * +Ending(const char *path) +{ + const char *dot = strrchr(path, '.'); + + if (dot == NULL || dot[1] == '\0') + return NULL; + return dot + 1; +} + +static int +SameEnding(const char *path, const char *want) +{ + const char *e = Ending(path); + size_t i; + + if (e == NULL) + return 0; + for (i = 0; want[i] != '\0'; i++) + if (tolower((unsigned char) e[i]) != want[i]) + return 0; + return e[i] == '\0'; +} + +static int +WritePng(const char *path, const unsigned char *rgb, int w, int h) +{ + png_image img; + + memset(&img, 0, sizeof img); + img.version = PNG_IMAGE_VERSION; + img.width = (png_uint_32) w; + img.height = (png_uint_32) h; + img.format = PNG_FORMAT_RGB; + if (!png_image_write_to_file(&img, path, 0, rgb, 0, NULL)) { + png_image_free(&img); + return -1; + } + png_image_free(&img); + return 0; +} + +static int +WriteBmp(const char *path, const unsigned char *rgb, int w, int h) +{ + FILE *fp; + unsigned char hdr[54], *line; + long row = ((long) w * 3 + 3) & ~3L; + long size = row * (long) h; + int x, y; + + if ((fp = fopen(path, "wb")) == NULL) + return -1; + memset(hdr, 0, sizeof hdr); + hdr[0] = 'B'; + hdr[1] = 'M'; + Le32Put(hdr + 2, 54L + size); + Le32Put(hdr + 10, 54); + Le32Put(hdr + 14, 40); + Le32Put(hdr + 18, (unsigned long) w); + Le32Put(hdr + 22, (unsigned long) h); + hdr[26] = 1; /* planes */ + hdr[28] = 24; /* bits per pixel */ + Le32Put(hdr + 34, (unsigned long) size); + Le32Put(hdr + 38, 2835); /* 72 dpi, as the original writes it */ + Le32Put(hdr + 42, 2835); + if (fwrite(hdr, 1, sizeof hdr, fp) != sizeof hdr) { + fclose(fp); + return -1; + } + if ((line = malloc((size_t) row)) == NULL) { + fclose(fp); + return -1; + } + for (y = h - 1; y >= 0; y--) { + const unsigned char *s = rgb + (size_t) y * (size_t) w * 3; + + memset(line, 0, (size_t) row); + for (x = 0; x < w; x++) { + line[x * 3] = s[x * 3 + 2]; /* BMP is BGR */ + line[x * 3 + 1] = s[x * 3 + 1]; + line[x * 3 + 2] = s[x * 3]; + } + if (fwrite(line, 1, (size_t) row, fp) != (size_t) row) { + free(line); + fclose(fp); + return -1; + } + } + free(line); + return fclose(fp) == 0 ? 0 : -1; +} + +int +McdeThumbWrite(const char *path, const unsigned char *rgb, int w, int h) +{ + if (path == NULL || rgb == NULL || w <= 0 || h <= 0 || + w > MAX_WIDTH || h > MAX_HEIGHT || + (long) w * (long) h > MAX_PIXELS) + return -1; + if (SameEnding(path, "png")) + return WritePng(path, rgb, w, h); + if (SameEnding(path, "bmp")) + return WriteBmp(path, rgb, w, h); + return -1; +} diff --git a/lib/DtSvc/DtUtil2/test_thumb.c b/lib/DtSvc/DtUtil2/test_thumb.c index 71c28f89..75783572 100644 --- a/lib/DtSvc/DtUtil2/test_thumb.c +++ b/lib/DtSvc/DtUtil2/test_thumb.c @@ -308,6 +308,104 @@ TestFormats(const char *dir) McdeThumbFree(&image); } +/* + * A picture in which every pixel is unique: red = x * 8 + 8, green = y * 8 + + * 8, blue = 128. A writer that flips the rows, swaps the channels or drops + * the alpha cannot pass this. + */ +static void +Ramp(unsigned char *rgb, int w, int h) +{ + int x, y; + + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *p = rgb + ((size_t) y * w + x) * 3; + + p[0] = (unsigned char) (x * 8 + 8); + p[1] = (unsigned char) (y * 8 + 8); + p[2] = 128; + } +} + +/* + * The writer: PNG and BMP are written from one RGB buffer and read back with + * the reader above. Every pixel has to come back unchanged, and an ending + * the writer does not know has to be refused -- not written as something else. + */ +static void +TestWrite(const char *dir) +{ + unsigned char rgb[13 * 7 * 3]; + char path[PATH_MAX]; + McdeThumbImage image; + int x, y, bad; + + Ramp(rgb, 13, 7); + + snprintf(path, sizeof path, "%s/write.png", dir); + CHECK(McdeThumbWrite(path, rgb, 13, 7) == 0); + memset(&image, 0, sizeof image); + CHECK(McdeThumbRead(path, 0, 0, &image) == 0); + CHECK(image.width == 13 && image.height == 7); + if (image.width == 13 && image.height == 7) { + for (bad = 0, y = 0; y < 7; y++) + for (x = 0; x < 13; x++) { + const unsigned char *p = image.rgb + + ((size_t) y * 13 + x) * 3; + const unsigned char *q = rgb + + ((size_t) y * 13 + x) * 3; + + if (p[0] != q[0] || p[1] != q[1] || + p[2] != q[2]) + bad++; + } + if (bad != 0) + fprintf(stderr, "FAIL line %d: png round trip, " + "%d of 91 pixels differ\n", __LINE__, bad); + CHECK(bad == 0); + } + McdeThumbFree(&image); + + snprintf(path, sizeof path, "%s/write.bmp", dir); + CHECK(McdeThumbWrite(path, rgb, 13, 7) == 0); + memset(&image, 0, sizeof image); + CHECK(McdeThumbRead(path, 0, 0, &image) == 0); + CHECK(image.width == 13 && image.height == 7); + if (image.width == 13 && image.height == 7) { + for (bad = 0, y = 0; y < 7; y++) + for (x = 0; x < 13; x++) { + const unsigned char *p = image.rgb + + ((size_t) y * 13 + x) * 3; + const unsigned char *q = rgb + + ((size_t) y * 13 + x) * 3; + + if (p[0] != q[0] || p[1] != q[1] || + p[2] != q[2]) + bad++; + } + if (bad != 0) + fprintf(stderr, "FAIL line %d: bmp round trip, " + "%d of 91 pixels differ\n", __LINE__, bad); + CHECK(bad == 0); + } + McdeThumbFree(&image); + + /* the ending decides, in either case; an unknown one is refused */ + snprintf(path, sizeof path, "%s/write.PNG", dir); + CHECK(McdeThumbWrite(path, rgb, 13, 7) == 0); + CHECK(McdeThumbRead(path, 0, 0, &image) == 0); + McdeThumbFree(&image); + snprintf(path, sizeof path, "%s/write.tiff", dir); + CHECK(McdeThumbWrite(path, rgb, 13, 7) != 0); + snprintf(path, sizeof path, "%s/noending", dir); + CHECK(McdeThumbWrite(path, rgb, 13, 7) != 0); + /* and a picture of nothing is not written at all */ + snprintf(path, sizeof path, "%s/write2.png", dir); + CHECK(McdeThumbWrite(path, rgb, 0, 7) != 0); + CHECK(access(path, F_OK) != 0); +} + static void TestScale(void) { @@ -454,6 +552,7 @@ main(void) return 1; } TestFormats(dir); + TestWrite(dir); TestScale(); TestLimits(dir); TestCache(dir); diff --git a/programs/dtphoto/dtphoto.c b/programs/dtphoto/dtphoto.c index 25857c6e..bcc23578 100644 --- a/programs/dtphoto/dtphoto.c +++ b/programs/dtphoto/dtphoto.c @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -36,8 +37,11 @@ #include #include #include +#include #include +#include + #define MAXMENUS 16 #define MAXITEMS 80 #define MAXDEPTH 4 @@ -63,6 +67,9 @@ enum { CMD_NONE, CMD_NEW, CMD_OPEN, CMD_SAVE, CMD_SAVEAS, CMD_QUIT, CMD_UNDO, CMD_ZOOMIN, CMD_ZOOMOUT, CMD_FIT, CMD_ACTUAL, CMD_ALL, CMD_DESELECT, CMD_CLEAR, CMD_FILL, CMD_CROP, CMD_INVERSE, + /* Select > Modify: morphology on the mask */ + CMD_FEATHER, CMD_SELBORDER, CMD_SELSMOOTH, CMD_SELEXPAND, + CMD_SELCONTRACT, CMD_SELGROW, CMD_SELSIMILAR, /* Image: the whole picture, through the RGB buffer */ CMD_INVERT, CMD_DESATURATE, CMD_FLIPH, CMD_FLIPV, CMD_ROT180, CMD_ROT90CW, CMD_ROT90CCW, @@ -70,7 +77,9 @@ enum { /* Filter: convolution, noise, pixelate, tone */ CMD_BLUR, CMD_BLURMORE, CMD_SHARPEN, CMD_SHARPENMORE, CMD_FINDEDGES, CMD_EMBOSS, CMD_SOLARIZE, - CMD_ADDNOISE, CMD_MEDIAN, CMD_MOSAIC + CMD_ADDNOISE, CMD_MEDIAN, CMD_MOSAIC, + /* Window: the Options box */ + CMD_SHOWOPTIONS }; static Menu menus[MAXMENUS]; @@ -97,8 +106,30 @@ static int selX0, selY0, selX1, selY1, hasSel, dragging; static unsigned char *selMask; /* docW * docH bits, 1 = selected */ static size_t selMaskSize; static int selMaskAny; /* some bit is set */ +/* + * The coverage, one byte per pixel, 0 = outside, 255 = fully inside. + * A hard-edged selection has 0 or 255; Feather fills the band between. + * Kept beside the bit mask and not instead of it: the bit mask answers + * "is this pixel in the selection at all", which is what the marquee, the + * wand and Move ask, and a coverage of 3 would answer that with "barely". + * NULL means "no soft edge", and then the bit mask is the whole truth. + */ +static unsigned char *selCover; +static size_t selCoverSize; static unsigned char markRGB[3]; static int markValid; +/* + * The values the Options box shows. They are variables and not constants + * because a brush that is always 3 px wide is a demo, not an editor; the + * numbers here are the ones the code used before the box existed, so a run + * without the box behaves exactly as it did. + */ +static int pencilRadius = 3; /* the pencil and the brush */ +static int eraserRadius = 6; +static int wandTolerance = 32; /* the wand, and Grow/Similar */ +static int retouchRadius = 6; +static int retouchStrength = 60; +static int gradientKind = 0; /* 0 = linear, 1 = radial */ static int lastX, lastY, pressX, pressY; /* where the picture sits in the canvas, and where the pointer was on the * screen for the hand (in window coordinates, not document ones) */ @@ -132,6 +163,7 @@ static const char *const toolNames[] = { static void NewPixmaps(void); static void DrawMarquee(Window win, int ox, int oy); static void MaskClear(void); +static int MaskCover(int x, int y); static void RenderDoc(Widget w); static void TypeIntoImage(int x, int y); static void SetZoom(int z); @@ -982,6 +1014,50 @@ OpenBMP(const char *path) return -1; } +/* + * A picture into the document, whatever this program can read. BMP and ICO + * go through the reader above, which knows their palettes; PNG, JPEG, GIF and + * XPM come from libDtSvc (McdeThumbRead), the decoder dtfile uses for its + * miniatures, so this program does not carry a second one + * (ext/src/mcde/AGENTS.md, "The philosophy"). + */ +static int +OpenImage(const char *path) +{ + McdeThumbImage image; + int i; + + if (OpenBMP(path) == 0) + return 0; + memset(&image, 0, sizeof image); + if (McdeThumbRead(path, 0, 0, &image) != 0) + return -1; + i = SetImageRGB(image.rgb, image.width, image.height); + McdeThumbFree(&image); + return i; +} + +/* + * The document into a file. The ending decides: .png and .bmp are written + * by libDtSvc, anything else keeps the BMP writer this program has always + * had, so an old name without an ending still works. + */ +static int +SaveImage(const char *path) +{ + unsigned char *rgb; + int w, h, i; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return -1; + if (McdeThumbWrite(path, rgb, w, h) == 0) { + free(rgb); + return 0; + } + free(rgb); + return SaveBMP(path); +} + /* ------------------------------------------------------------------ menus */ static void @@ -1107,9 +1183,18 @@ CommandOf(const char *path) if (strcmp(path, "View/Zoom Out") == 0) return CMD_ZOOMOUT; if (strcmp(path, "View/Fit on Screen") == 0) return CMD_FIT; if (strcmp(path, "View/Actual Pixels") == 0) return CMD_ACTUAL; + if (strcmp(path, "Window/Show Options") == 0) return CMD_SHOWOPTIONS; if (strcmp(path, "Select/All") == 0) return CMD_ALL; if (strcmp(path, "Select/None") == 0) return CMD_DESELECT; if (strcmp(path, "Select/Inverse") == 0) return CMD_INVERSE; + /* Select > Modify: shapes the mask, not the picture */ + if (strcmp(path, "Select/Feather...") == 0) return CMD_FEATHER; + if (strcmp(path, "Select/Modify/Border...") == 0) return CMD_SELBORDER; + if (strcmp(path, "Select/Modify/Smooth...") == 0) return CMD_SELSMOOTH; + if (strcmp(path, "Select/Modify/Expand...") == 0) return CMD_SELEXPAND; + if (strcmp(path, "Select/Modify/Contract...") == 0) return CMD_SELCONTRACT; + if (strcmp(path, "Select/Grow") == 0) return CMD_SELGROW; + if (strcmp(path, "Select/Similar") == 0) return CMD_SELSIMILAR; if (strcmp(path, "Edit/Clear") == 0) return CMD_CLEAR; if (strcmp(path, "Edit/Fill...") == 0) return CMD_FILL; if (strcmp(path, "Edit/Crop") == 0) return CMD_CROP; @@ -1340,6 +1425,7 @@ Dab(int x, int y, int r) XFillArc(dpy, image, gc, x - r, y - r, r * 2 + 1, r * 2 + 1, 0, 360 * 64); } + static void LineImage(int x0, int y0, int x1, int y1) { @@ -1660,6 +1746,86 @@ Retouch(int cx, int cy, int radius, int strength, int op) p.rgb = NULL; } +/* + * A tip of paint inside the selection. Painting in the original is always + * clipped to the selection, and a feathered edge mixes instead of cutting, + * so every painting tool goes through here: read the box once, write the + * tip into it, put the box back. `soft` rounds the tip (the brush), a + * square tip is the pencil. + */ +static void +PaintTip(int cx, int cy, int r, Pixel px, int soft) +{ + Patch p; + unsigned char fg[3]; + int x, y; + + if (ReadPatch(&p, cx - r, cy - r, r * 2 + 1, r * 2 + 1) != 0) + return; + PixelToRGB(px, &fg[0], &fg[1], &fg[2]); + for (y = 0; y < p.h; y++) + for (x = 0; x < p.w; x++) { + unsigned char *d = PatchAt(&p, x, y); + int docx = p.x + x, docy = p.y + y; + int cov = 255; + int dx = x - r, dy = y - r; + + if (soft && dx * dx + dy * dy > r * r) + continue; + if (selMaskAny) + cov = MaskCover(docx, docy); + if (cov <= 0) + continue; + d[0] = (unsigned char) (d[0] + + ((int) fg[0] - d[0]) * cov / 255); + d[1] = (unsigned char) (d[1] + + ((int) fg[1] - d[1]) * cov / 255); + d[2] = (unsigned char) (d[2] + + ((int) fg[2] - d[2]) * cov / 255); + } + WritePatch(&p); + free(p.rgb); +} + +/* the pencil: a hard square tip, the brush: a round soft one */ +static void +PencilDot(int x, int y, int r) +{ + PaintTip(x, y, r, fgPixel, 0); +} + +static void +BrushDot(int x, int y, int r) +{ + PaintTip(x, y, r, fgPixel, 1); +} + +static void +EraserDot(int x, int y, int r) +{ + PaintTip(x, y, r, bgPixel, 1); +} + +/* + * The pencil's dragged stroke is a hard line; it walks the pixels between + * the two points so the tip stays one square, not a long smear. + */ +static void +PencilLine(int x0, int y0, int x1, int y1, int r) +{ + int dx = x1 - x0, dy = y1 - y0; + int n = (dx < 0 ? -dx : dx) > (dy < 0 ? -dy : dy) ? + (dx < 0 ? -dx : dx) : (dy < 0 ? -dy : dy); + int i; + + if (n == 0) { + PencilDot(x1, y1, r); + return; + } + for (i = 0; i <= n; i++) + PencilDot(x0 + dx * i / n, y0 + dy * i / n, r); +} + /* ------------------------------------------------------------- the selection */ static int @@ -1697,6 +1863,58 @@ MaskClear(void) memset(selMask, 0, selMaskSize); selMaskAny = 0; hasSel = 0; + /* a hard edge again: the soft band belonged to the old shape */ + free(selCover); + selCover = NULL; + selCoverSize = 0; +} + +/* + * The coverage of one pixel: 255 inside a hard selection, 0 outside, and + * the feathered value in between. Without a coverage the bit mask is the + * answer, which keeps every operation that predates Feather unchanged. + */ +static int +MaskCover(int x, int y) +{ + size_t i; + + if (!MaskGet(x, y)) + return selCover != NULL && x >= 0 && y >= 0 && + x < docW && y < docH ? + selCover[(size_t) y * docW + x] : 0; + if (selCover == NULL) + return 255; + i = (size_t) y * docW + x; + return selCover[i]; +} + +/* the coverage buffer, one byte per pixel, all 255 where the mask is set */ +static int +CoverAlloc(void) +{ + size_t need = (size_t) docW * docH; + int x, y; + + if (selCover != NULL && selCoverSize >= need) { + for (y = 0; y < docH; y++) + for (x = 0; x < docW; x++) + selCover[(size_t) y * docW + x] = + (unsigned char) (MaskGet(x, y) ? 255 : 0); + return 0; + } + free(selCover); + selCover = malloc(need); + if (selCover == NULL) { + selCoverSize = 0; + return -1; + } + selCoverSize = need; + for (y = 0; y < docH; y++) + for (x = 0; x < docW; x++) + selCover[(size_t) y * docW + x] = + (unsigned char) (MaskGet(x, y) ? 255 : 0); + return 0; } static int @@ -1729,6 +1947,525 @@ MaskFromRect(void) for (x = selX0; x < selX1; x++) MaskSet(x, y, 1); } +/* + * Selection morphology: the distance to the nearest selected and to the + * nearest unselected pixel decides grow, contract, border and feather. + * + * The distance is exact Euclidean, not a chamfer approximation: a 3-4-5 + * chamfer is off by a few percent, and a test that checks "the pixel at + * distance 3" against a pixel that is really at 2.83 cannot be exact. + * The transform is the separable parabola one (Felzenszwalb/Huttenlocher): + * the lower envelope of parabolas per column, then per row. O(w*h). + */ +#define DIST_INF 1e20 + +static void +Dist1D(const double *f, double *d, int n, int *v, double *z) +{ + int k = 0, q; + + v[0] = 0; + z[0] = -DIST_INF; + z[1] = DIST_INF; + for (q = 1; q < n; q++) { + double s; + + do { + int p = v[k]; + + s = ((f[q] + (double) q * q) - + (f[p] + (double) p * p)) / (2.0 * q - 2.0 * p); + if (s <= z[k]) + k--; + else + break; + } while (k >= 0); + k++; + v[k] = q; + z[k] = s; + z[k + 1] = DIST_INF; + } + k = 0; + for (q = 0; q < n; q++) { + while (z[k + 1] < (double) q) + k++; + d[q] = (double) (q - v[k]) * (q - v[k]) + f[v[k]]; + } +} + +/* + * Squared distance (in pixels, exact) from every pixel to the nearest + * pixel where `ind` is set. Pixels where nothing is set get DIST_INF. + */ +static void +DistTransform(const unsigned char *ind, int w, int h, double *out) +{ + double *f, *d, *z; + int *v; + int x, y, n; + + n = w > h ? w : h; + f = malloc(sizeof(double) * (size_t) n); + d = malloc(sizeof(double) * (size_t) n); + z = malloc(sizeof(double) * (size_t) (n + 1)); + v = malloc(sizeof(int) * (size_t) n); + if (f == NULL || d == NULL || z == NULL || v == NULL) { + free(f); free(d); free(z); free(v); + for (x = 0; x < w * h; x++) + out[x] = DIST_INF; + return; + } + /* columns */ + for (x = 0; x < w; x++) { + for (y = 0; y < h; y++) + f[y] = ind[(size_t) y * w + x] ? 0.0 : DIST_INF; + Dist1D(f, d, h, v, z); + for (y = 0; y < h; y++) + out[(size_t) y * w + x] = d[y]; + } + /* rows */ + for (y = 0; y < h; y++) { + double *row = out + (size_t) y * w; + + for (x = 0; x < w; x++) + f[x] = row[x]; + Dist1D(f, d, w, v, z); + for (x = 0; x < w; x++) + row[x] = d[x]; + } + free(f); free(d); free(z); free(v); +} + +/* the mask as one byte per pixel, 1 = selected; NULL when there is none */ +static unsigned char * +MaskToBytes(int w, int h) +{ + unsigned char *b; + int x, y; + + b = calloc((size_t) w * h, 1); + if (b == NULL) + return NULL; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + b[(size_t) y * w + x] = (unsigned char) MaskGet(x, y); + return b; +} + +/* + * Put a byte field back. selMaskAny is asked from the field, and the + * marquee rectangle is the bounding box of what is left -- with an empty + * field the selection is gone and hasSel says so. + */ +static void +MaskFromBytes(const unsigned char *on, int w, int h) +{ + int x, y, x0 = w, y0 = h, x1 = -1, y1 = -1, any = 0; + + if (MaskAlloc() != 0) + return; + MaskClear(); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + if (on[(size_t) y * w + x]) { + MaskSet(x, y, 1); + any = 1; + if (x < x0) x0 = x; + if (y < y0) y0 = y; + if (x > x1) x1 = x; + if (y > y1) y1 = y; + } + selMaskAny = any; + if (!any) { + hasSel = 0; + return; + } + selX0 = x0; + selY0 = y0; + selX1 = x1 + 1; + selY1 = y1 + 1; + hasSel = 1; +} + +/* + * The two distance fields the commands need. `dIn` is the distance to the + * nearest selected pixel, `dOut` the distance to the nearest unselected + * one. Everything outside the picture counts as unselected, so a + * selection that runs to the edge can be contracted from there. + */ +static int +SelectionDistances(double **dInP, double **dOutP, int *wP, int *hP, + unsigned char **selP) +{ + unsigned char *sel, *inv; + double *dIn, *dOut; + size_t n; + int x, y; + + if (selMask == NULL || !selMaskAny) + return -1; + sel = MaskToBytes(docW, docH); + if (sel == NULL) + return -1; + n = (size_t) docW * docH; + inv = malloc(n); + dIn = malloc(sizeof(double) * n); + dOut = malloc(sizeof(double) * n); + if (inv == NULL || dIn == NULL || dOut == NULL) { + free(sel); free(inv); free(dIn); free(dOut); + return -1; + } + for (y = 0; y < docH; y++) + for (x = 0; x < docW; x++) + inv[(size_t) y * docW + x] = + (unsigned char) !sel[(size_t) y * docW + x]; + DistTransform(sel, docW, docH, dIn); + /* + * Outside the frame is unselected, so the border of the picture is a + * distance-1 neighbour of the outside. Feeding a one-pixel ring of + * "unselected" into the transform gives that without a special case + * in the loop below. + */ + { + int w2 = docW + 2, h2 = docH + 2, i; + unsigned char *pad = malloc((size_t) w2 * h2); + double *padded = malloc(sizeof(double) * (size_t) w2 * h2); + + if (pad != NULL && padded != NULL) { + memset(pad, 0, (size_t) w2 * h2); + for (y = 0; y < docH; y++) + memcpy(pad + (size_t) (y + 1) * w2 + 1, + inv + (size_t) y * docW, (size_t) docW); + DistTransform(pad, w2, h2, padded); + for (y = 0; y < docH; y++) + for (x = 0; x < docW; x++) + dOut[(size_t) y * docW + x] = + padded[(size_t) (y + 1) * w2 + x + 1]; + for (i = 0; i < docW * docH; i++) + if (dOut[i] == DIST_INF) + dOut[i] = DIST_INF; + } else { + DistTransform(inv, docW, docH, dOut); + } + free(pad); + free(padded); + } + free(inv); + *selP = sel; + *dInP = dIn; + *dOutP = dOut; + *wP = docW; + *hP = docH; + return 0; +} + +/* Select > Modify > Expand (grow by r pixels) */ +static void +SelExpand(double r) +{ + unsigned char *sel, *out; + double *dIn, *dOut; + int w, h, x, y; + double r2 = r * r; + + if (SelectionDistances(&dIn, &dOut, &w, &h, &sel) != 0) + return; + out = malloc((size_t) w * h); + if (out == NULL) { + free(sel); free(dIn); free(dOut); + return; + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + out[(size_t) y * w + x] = + (unsigned char) (dIn[(size_t) y * w + x] <= r2); + MaskFromBytes(out, w, h); + free(out); + free(sel); free(dIn); free(dOut); +} + +/* Select > Modify > Contract: keep what is more than r pixels from outside */ +static void +SelContract(double r) +{ + unsigned char *sel, *out; + double *dIn, *dOut; + int w, h, x, y; + double r2 = r * r; + + if (SelectionDistances(&dIn, &dOut, &w, &h, &sel) != 0) + return; + out = malloc((size_t) w * h); + if (out == NULL) { + free(sel); free(dIn); free(dOut); + return; + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + out[(size_t) y * w + x] = (unsigned char) + (sel[(size_t) y * w + x] && + dOut[(size_t) y * w + x] > r2); + MaskFromBytes(out, w, h); + free(out); + free(sel); free(dIn); free(dOut); +} + +/* + * Select > Modify > Border: a band of width r on each side of the edge, + * which is what the original draws -- the pixels inside the selection that + * are within r of the outside, plus the pixels outside within r of it. + */ +static void +SelBorder(double r) +{ + unsigned char *sel, *out; + double *dIn, *dOut; + int w, h, x, y; + double r2 = r * r; + + if (SelectionDistances(&dIn, &dOut, &w, &h, &sel) != 0) + return; + out = malloc((size_t) w * h); + if (out == NULL) { + free(sel); free(dIn); free(dOut); + return; + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + size_t i = (size_t) y * w + x; + + out[i] = (unsigned char) + ((sel[i] && dOut[i] <= r2) || + (!sel[i] && dIn[i] <= r2)); + } + MaskFromBytes(out, w, h); + free(out); + free(sel); free(dIn); free(dOut); +} + +/* + * Select > Modify > Smooth: a majority vote in a (2r+1) square. A pixel + * flips when more than half of its neighbourhood disagrees with it, which + * is what rounds a corner and removes a one-pixel speck without moving an + * edge. The vote runs on summed-area tables, so the cost is the picture + * size and not the radius. + */ +static void +SelSmooth(int r) +{ + unsigned char *sel, *out; + long *sum; + int w, h, x, y, side, i; + + if (selMask == NULL || !selMaskAny || r < 1) + return; + w = docW; + h = docH; + sel = MaskToBytes(w, h); + if (sel == NULL) + return; + out = malloc((size_t) w * h); + sum = malloc(sizeof(long) * (size_t) (w + 1) * (h + 1)); + if (out == NULL || sum == NULL) { + free(sel); free(out); free(sum); + return; + } + for (i = 0; i < (w + 1) * (h + 1); i++) + sum[i] = 0; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + sum[(size_t) (y + 1) * (w + 1) + (x + 1)] = + (sel[(size_t) y * w + x] ? 1 : 0) + + sum[(size_t) y * (w + 1) + (x + 1)] + + sum[(size_t) (y + 1) * (w + 1) + x] - + sum[(size_t) y * (w + 1) + x]; + side = 2 * r + 1; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + int x0 = x - r < 0 ? 0 : x - r; + int y0 = y - r < 0 ? 0 : y - r; + int x1 = x + r >= w ? w - 1 : x + r; + int y1 = y + r >= h ? h - 1 : y + r; + long on = sum[(size_t) (y1 + 1) * (w + 1) + (x1 + 1)] - + sum[(size_t) y0 * (w + 1) + (x1 + 1)] - + sum[(size_t) (y1 + 1) * (w + 1) + x0] + + sum[(size_t) y0 * (w + 1) + x0]; + long cnt = (long) (x1 - x0 + 1) * (y1 - y0 + 1); + + (void) side; + out[(size_t) y * w + x] = + (unsigned char) (on * 2 > cnt); + } + MaskFromBytes(out, w, h); + free(out); + free(sum); + free(sel); +} + +/* + * Select > Grow and Select > Similar: the colours of the current selection + * are the reference, and everything within the tolerance joins. + * + * Grow walks out from the selection (connected), Similar takes the whole + * picture (not connected) -- that is the difference between the two in the + * original. The reference colour is the mean of the selection, which is + * the same answer for a flat area and a defensible one for a mixed one; + * the wand's own click colour cannot be used here, it is gone by then. + */ +static void +SelColorExtend(int tolerance, int connected) +{ + unsigned char *sel, *out, *rgb = NULL; + unsigned char ref[3]; + long sr = 0, sg = 0, sb = 0, cnt = 0; + int w, h, x, y; + + if (selMask == NULL || !selMaskAny) + return; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + sel = MaskToBytes(w, h); + if (sel == NULL) { + free(rgb); + return; + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + if (sel[(size_t) y * w + x]) { + unsigned char *d = rgb + + ((size_t) y * w + x) * 3; + + sr += d[0]; sg += d[1]; sb += d[2]; + cnt++; + } + if (cnt == 0) { + free(sel); + free(rgb); + return; + } + ref[0] = (unsigned char) (sr / cnt); + ref[1] = (unsigned char) (sg / cnt); + ref[2] = (unsigned char) (sb / cnt); + out = malloc((size_t) w * h); + if (out == NULL) { + free(sel); + free(rgb); + return; + } + memcpy(out, sel, (size_t) w * h); + if (connected) { + int *stack = malloc(sizeof(int) * (size_t) w * h); + int sp = 0; + + if (stack == NULL) { + free(out); free(sel); free(rgb); + return; + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + if (out[(size_t) y * w + x]) + stack[sp++] = y * w + x; + while (sp > 0) { + int p = stack[--sp], px = p % w, py = p / w; + int nb[4], k; + + nb[0] = px > 0 ? p - 1 : -1; + nb[1] = px < w - 1 ? p + 1 : -1; + nb[2] = py > 0 ? p - w : -1; + nb[3] = py < h - 1 ? p + w : -1; + for (k = 0; k < 4; k++) { + int q = nb[k], dr, dg, db; + unsigned char *d; + + if (q < 0 || out[q]) + continue; + d = rgb + (size_t) q * 3; + dr = (int) d[0] - ref[0]; + dg = (int) d[1] - ref[1]; + db = (int) d[2] - ref[2]; + if (dr < 0) dr = -dr; + if (dg < 0) dg = -dg; + if (db < 0) db = -db; + if (dr > tolerance || dg > tolerance || + db > tolerance) + continue; + out[q] = 1; + stack[sp++] = q; + } + } + free(stack); + } else { + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + size_t i = (size_t) y * w + x; + unsigned char *d = rgb + i * 3; + int dr, dg, db; + + if (out[i]) + continue; + dr = (int) d[0] - ref[0]; + dg = (int) d[1] - ref[1]; + db = (int) d[2] - ref[2]; + if (dr < 0) dr = -dr; + if (dg < 0) dg = -dg; + if (db < 0) db = -db; + if (dr > tolerance || dg > tolerance || + db > tolerance) + continue; + out[i] = 1; + } + } + MaskFromBytes(out, w, h); + free(out); + free(sel); + free(rgb); +} + +/* + * Select > Feather: r pixels of soft edge, inside the selection only. + * + * The coverage is the distance from the edge, taken from the outside + * distance field and ramped over r pixels; 255 stays in the middle. A + * box blur would have been cheaper to write and wrong at the corners -- + * it smears horizontally and vertically by different amounts, and it + * bleeds out of the selection, which Feather does not do. + */ +static void +SelFeather(int r) +{ + unsigned char *sel; + double *dIn, *dOut; + int w, h, x, y; + + if (r < 1) + return; + if (SelectionDistances(&dIn, &dOut, &w, &h, &sel) != 0) + return; + (void) dIn; + if (CoverAlloc() != 0) { + free(sel); free(dIn); free(dOut); + return; + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + size_t i = (size_t) y * w + x; + double dist = dOut[i] > 0.0 ? dOut[i] : 0.0; + double t; + + if (!sel[i]) { + selCover[i] = 0; + continue; + } + t = (dist - 1.0) / (double) r; + if (t < 0.0) + t = 0.0; + if (t > 1.0) + t = 1.0; + /* a straight ramp: 0 at the edge, 255 in the middle */ + selCover[i] = (unsigned char) (t * 255.0 + 0.5); + } + free(sel); free(dIn); free(dOut); +} /* * The lasso and the magic wand both end with a set of pixels; this turns @@ -2105,9 +2842,30 @@ PaintMask(Pixel px) if (im == NULL) return; for (y = 0; y < docH; y++) - for (x = 0; x < docW; x++) - if (MaskGet(x, y)) + for (x = 0; x < docW; x++) { + int cov = MaskCover(x, y); + + if (cov <= 0) + continue; + if (cov >= 255) { XPutPixel(im, x, y, px); + continue; + } + /* the soft band mixes the paint with the pixel */ + { + unsigned long old = XGetPixel(im, x, y); + unsigned char o[3], n[3], mix[3]; + int c; + + PixelToRGB(old, &o[0], &o[1], &o[2]); + PixelToRGB(px, &n[0], &n[1], &n[2]); + for (c = 0; c < 3; c++) + mix[c] = (unsigned char) (o[c] + + ((int) n[c] - o[c]) * cov / 255); + XPutPixel(im, x, y, RGBToPixel(mix[0], + mix[1], mix[2])); + } + } XPutImage(dpy, image, gc, im, 0, 0, 0, 0, (unsigned int) docW, (unsigned int) docH); XDestroyImage(im); @@ -2283,6 +3041,10 @@ MoveMasked(int dx, int dy) selMask = fresh; selMaskSize = sz; selMaskAny = any; + /* a new shape: the old soft band does not fit it */ + free(selCover); + selCover = NULL; + selCoverSize = 0; /* the marquee follows the moved block */ selX0 = (selX0 + dx < 0) ? 0 : selX0 + dx; selY0 = (selY0 + dy < 0) ? 0 : selY0 + dy; @@ -2363,17 +3125,48 @@ typedef void (*ChanFn)(unsigned char *p, void *cd); static void OpPerPixel(ChanFn fn, void *cd) { - unsigned char *rgb; - int w, h, x, y; + unsigned char *rgb, *before; + int w, h, x, y, cov; if (GetImageRGB(&rgb, &w, &h) != 0) return; + before = malloc((size_t) w * h * 3); + if (before != NULL) + memcpy(before, rgb, (size_t) w * h * 3); for (y = 0; y < h; y++) for (x = 0; x < w; x++) { - if (selMaskAny && !MaskGet(x, y)) + unsigned char *p = rgb + ((size_t) y * w + x) * 3; + + if (!selMaskAny) { + fn(p, cd); continue; - fn(rgb + ((size_t) y * w + x) * 3, cd); + } + cov = MaskCover(x, y); + if (cov <= 0) + continue; + if (cov >= 255) { + fn(p, cd); + continue; + } + /* + * A feathered edge mixes the correction with what was + * there: a hard cut at a soft edge would put the band + * back the feather just removed. + */ + fn(p, cd); + if (before != NULL) { + const unsigned char *o = + before + ((size_t) y * w + x) * 3; + + p[0] = (unsigned char) (o[0] + + ((int) p[0] - o[0]) * cov / 255); + p[1] = (unsigned char) (o[1] + + ((int) p[1] - o[1]) * cov / 255); + p[2] = (unsigned char) (o[2] + + ((int) p[2] - o[2]) * cov / 255); + } } + free(before); SetImageRGB(rgb, w, h); free(rgb); } @@ -2875,19 +3668,44 @@ GradientImage(int x0, int y0, int x1, int y1) for (y = 0; y < h; y++) for (x = 0; x < w; x++) { long t; + int cov = 255; unsigned char *d; - if (selMaskAny && !MaskGet(x, y)) - continue; - /* how far along the drag, clamped to the ends */ - t = ((long) (x - x0) * dx + (long) (y - y0) * dy) * - 1000 / len2; + if (selMaskAny && docW == w && docH == h) { + cov = MaskCover(x, y); + if (cov <= 0) + continue; + } + if (gradientKind == 1) { + /* radial: the distance from where the drag + * started, against the length of the drag */ + long ex = x - x0, ey = y - y0; + long d2 = ex * ex + ey * ey; + + t = (long) (sqrt((double) d2) * + 1000.0 / sqrt((double) len2)); + } else { + /* linear: how far along the drag */ + t = ((long) (x - x0) * dx + + (long) (y - y0) * dy) * 1000 / len2; + } if (t < 0) t = 0; if (t > 1000) t = 1000; d = rgb + ((size_t) y * w + x) * 3; - d[0] = (unsigned char) (fr + (tr - fr) * t / 1000); - d[1] = (unsigned char) (fg + (tg - fg) * t / 1000); - d[2] = (unsigned char) (fb + (tb - fb) * t / 1000); + { + unsigned char nr, ng, nb; + + nr = (unsigned char) (fr + (tr - fr) * t / 1000); + ng = (unsigned char) (fg + (tg - fg) * t / 1000); + nb = (unsigned char) (fb + (tb - fb) * t / 1000); + /* a feathered edge mixes with what was there */ + d[0] = (unsigned char) (d[0] + + ((int) nr - d[0]) * cov / 255); + d[1] = (unsigned char) (d[1] + + ((int) ng - d[1]) * cov / 255); + d[2] = (unsigned char) (d[2] + + ((int) nb - d[2]) * cov / 255); + } } SetImageRGB(rgb, w, h); free(rgb); @@ -2994,6 +3812,77 @@ MosaicOk(int cell, int unused) fprintf(stderr, "dtphoto: mosaic %d\n", cell); } +/* Select > Modify: one radius, in pixels */ +static void +FeatherOk(int r, int unused) +{ + (void) unused; + SelFeather(r); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: feather %d\n", r); +} + +static void +SelBorderOk(int r, int unused) +{ + (void) unused; + SelBorder((double) (r < 1 ? 1 : r)); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: border %d\n", r); +} + +static void +SelSmoothOk(int r, int unused) +{ + (void) unused; + SelSmooth(r); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: smooth %d\n", r); +} + +static void +SelExpandOk(int r, int unused) +{ + (void) unused; + if (r < 1) + return; + SelExpand((double) r); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: expand %d\n", r); +} + +static void +SelContractOk(int r, int unused) +{ + (void) unused; + if (r < 1) + return; + SelContract((double) r); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: contract %d\n", r); +} + +/* + * Grow and Similar take the tolerance from the wand's own value, which is + * what the original does -- the two choices live in the same Options box + * and a second field would only let them drift apart. + */ +static void +SelGrowRun(void) +{ + SelColorExtend(wandTolerance, 1); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: grow %d\n", wandTolerance); +} + +static void +SelSimilarRun(void) +{ + SelColorExtend(wandTolerance, 0); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: similar %d\n", wandTolerance); +} + /* one line for a tool or a menu action, so a mouse test can read it */ static void OpDone(const char *what) @@ -3086,7 +3975,7 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) LassoAdd(docx, docy); break; case 3: /* magic wand: the colour under the pointer */ - WandSelect(docx, docy, 32); + WandSelect(docx, docy, wandTolerance); dragging = 0; break; case 4: /* move: drag the masked pixels */ @@ -3109,15 +3998,14 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) TypeIntoImage(docx, docy); dragging = 0; break; - case 10: /* pencil */ - XDrawPoint(dpy, image, gc, docx, docy); + case 10: /* pencil: a hard tip */ + PencilDot(docx, docy, pencilRadius); break; - case 11: /* brush */ - Dab(docx, docy, 3); + case 11: /* brush: round and soft */ + BrushDot(docx, docy, pencilRadius); break; - case 12: /* eraser */ - XSetForeground(dpy, gc, bgPixel); - Dab(docx, docy, 6); + case 12: /* eraser paints the background */ + EraserDot(docx, docy, eraserRadius); break; case 13: /* bucket */ FloodFillImage(docx, docy); @@ -3129,7 +4017,8 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) case 15: case 16: case 17: case 18: case 19: case 20: /* the retouching tools */ smudgeValid = 0; - Retouch(docx, docy, 6, 60, currentTool); + Retouch(docx, docy, retouchRadius, + retouchStrength, currentTool); break; case 21: /* eyedropper */ { @@ -3174,15 +4063,14 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) lastScrX = ev->xmotion.x; lastScrY = ev->xmotion.y; break; - case 10: - LineImage(lastX, lastY, docx, docy); + case 10: /* pencil: a hard stroke */ + PencilLine(lastX, lastY, docx, docy, pencilRadius); break; - case 11: - Dab(docx, docy, 3); + case 11: /* brush: a soft round dab */ + BrushDot(docx, docy, pencilRadius); break; - case 12: - XSetForeground(dpy, gc, bgPixel); - Dab(docx, docy, 6); + case 12: /* eraser: the background colour */ + EraserDot(docx, docy, eraserRadius); break; case 9: case 13: XCopyArea(dpy, snap, image, gc, 0, 0, docW, docH, 0, 0); @@ -3196,7 +4084,8 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) break; case 15: case 16: case 17: case 18: case 19: case 20: - Retouch(docx, docy, 6, 60, currentTool); + Retouch(docx, docy, retouchRadius, + retouchStrength, currentTool); break; default: break; @@ -3366,6 +4255,161 @@ DrawGlyph(Display *d, Pixmap p, GC gc, int tool) XFreeGC(d, white); } +/* + * The Options box. Photoshop 3 has one and it is where every brush size, + * the wand's tolerance and the gradient's shape live; before this box the + * numbers were constants in the event handler, so a 3 px pencil was all the + * program could do. + * + * Every field writes straight into the variable the tool reads, so there is + * no second copy to keep in step. The box is built once and shown on + * request; closing it hides it and keeps the values. + */ +static Widget optionsShell; +static Widget optPencil, optEraser, optWand, optRetouch, optStrength; + +static void +OptionsApply(Widget w, XtPointer cd, XtPointer call) +{ + const char *s; + int *target = (int *) cd; + char *p = NULL; + int v; + + (void) call; + XtVaGetValues(w, XmNvalue, &s, NULL); + if (s == NULL || *s == '\0') + return; + v = (int) strtol(s, &p, 10); + if (p == s) + return; + *target = v; + fprintf(stderr, "dtphoto: options %s=%d\n", + (target == &pencilRadius) ? "pencil" : + (target == &eraserRadius) ? "eraser" : + (target == &wandTolerance) ? "tolerance" : + (target == &retouchRadius) ? "retouch" : "strength", v); +} + +/* + * One row: a label on the left and a field on the right. Both hang off + * `above`, and the row returned is the FIELD, not the label: a text field + * is taller than its label, so attaching the next row to the label put the + * rows on top of each other and a click landed in the field above + * (measured 2026-11-22: the tolerance field was unreachable). + */ +static Widget +OptField(Widget form, Widget above, const char *label, const char *name, + int value, int *target) +{ + Widget lab, field; + char buf[16]; + + snprintf(buf, sizeof buf, "%d", value); + lab = XtVaCreateManagedWidget(name, xmLabelWidgetClass, form, + XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, above, + XmNleftAttachment, XmATTACH_FORM, XmNalignment, + XmALIGNMENT_BEGINNING, XmNrecomputeSize, False, XmNwidth, 90, + XmNlabelString, XmStringCreateLocalized(label), NULL); + field = XtVaCreateManagedWidget("field", xmTextFieldWidgetClass, form, + XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, above, + XmNleftAttachment, XmATTACH_WIDGET, XmNleftWidget, lab, + XmNrightAttachment, XmATTACH_FORM, XmNvalue, buf, NULL); + XtAddCallback(field, XmNactivateCallback, OptionsApply, + (XtPointer) target); + XtAddCallback(field, XmNfocusCallback, OptionsApply, (XtPointer) target); + return field; +} + +static void +OptionsClose(Widget w, XtPointer cd, XtPointer call) +{ + (void) w; (void) cd; (void) call; + if (optionsShell != NULL) + XtPopdown(optionsShell); +} + +/* linear (0) or radial (1): the gradient tool reads this on the next drag */ +static void +GradientKindCallback(Widget w, XtPointer cd, XtPointer call) +{ + (void) call; + if (XmToggleButtonGetState(w)) { + gradientKind = (int) (long) cd; + fprintf(stderr, "dtphoto: gradient %s\n", + gradientKind == 0 ? "linear" : "radial"); + } +} + +static void +BuildOptions(Widget parent) +{ + Widget form, close, grad; + Widget last; + + form = XtVaCreateManagedWidget("options", xmFormWidgetClass, parent, + XmNmarginWidth, 6, XmNmarginHeight, 6, NULL); + last = XtVaCreateManagedWidget("opttitle", xmLabelWidgetClass, form, + XmNtopAttachment, XmATTACH_FORM, XmNleftAttachment, XmATTACH_FORM, + XmNalignment, XmALIGNMENT_BEGINNING, XmNlabelString, + XmStringCreateLocalized(Tr(6, "Tool Options")), NULL); + last = OptField(form, last, "Pencil radius:", "pencil", + pencilRadius, &pencilRadius); + last = OptField(form, last, "Eraser radius:", "eraser", + eraserRadius, &eraserRadius); + last = OptField(form, last, "Tolerance:", "wand", + wandTolerance, &wandTolerance); + last = OptField(form, last, "Retouch radius:", "retouch", + retouchRadius, &retouchRadius); + last = OptField(form, last, "Retouch strength:", "strength", + retouchStrength, &retouchStrength); + + grad = XtVaCreateManagedWidget("gradient", xmRowColumnWidgetClass, form, + XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, last, + XmNleftAttachment, XmATTACH_FORM, XmNrightAttachment, + XmATTACH_FORM, XmNorientation, XmHORIZONTAL, XmNradioBehavior, + True, XmNpacking, XmPACK_TIGHT, XmNmarginHeight, 2, NULL); + { + Widget b; + + b = XtVaCreateManagedWidget("linear", xmToggleButtonWidgetClass, + grad, XmNindicatorType, XmONE_OF_MANY, + XmNlabelString, XmStringCreateLocalized("Linear"), NULL); + XmToggleButtonSetState(b, gradientKind == 0, False); + XtAddCallback(b, XmNvalueChangedCallback, GradientKindCallback, + (XtPointer) 0L); + b = XtVaCreateManagedWidget("radial", xmToggleButtonWidgetClass, + grad, XmNindicatorType, XmONE_OF_MANY, + XmNlabelString, XmStringCreateLocalized("Radial"), NULL); + XmToggleButtonSetState(b, gradientKind == 1, False); + XtAddCallback(b, XmNvalueChangedCallback, GradientKindCallback, + (XtPointer) 1L); + } + + close = XtVaCreateManagedWidget("close", xmPushButtonWidgetClass, form, + XmNleftAttachment, XmATTACH_FORM, XmNbottomAttachment, + XmATTACH_FORM, XmNlabelString, + XmStringCreateLocalized("Close"), NULL); + XtAddCallback(close, XmNactivateCallback, OptionsClose, NULL); + optPencil = form; + (void) optEraser; (void) optWand; (void) optRetouch; (void) optStrength; +} + +static void +OptionsShow(void) +{ + if (optionsShell == NULL) { + optionsShell = XtVaAppCreateShell("options", "Dtphoto", + topLevelShellWidgetClass, dpy, XmNtitle, + Tr(6, "Tool Options"), XmNallowShellResize, True, + XmNx, 120, XmNy, 64, NULL); + BuildOptions(optionsShell); + XtRealizeWidget(optionsShell); + } + XtPopup(optionsShell, XtGrabNone); + fprintf(stderr, "dtphoto: options shown\n"); +} + static void ToolCallback(Widget w, XtPointer data, XtPointer call) { @@ -3434,7 +4478,7 @@ FileOk(Widget w, XtPointer data, XtPointer call) path != NULL) { int save = fileSave; - if (save ? (SaveBMP(path) == 0) : (OpenBMP(path) == 0)) { + if (save ? (SaveImage(path) == 0) : (OpenImage(path) == 0)) { fprintf(stderr, "dtphoto: %s %s\n", save ? "saved" : "opened", path); UpdateStatus(); @@ -3466,11 +4510,21 @@ static void FileDialog(int save) { Widget d = XmCreateFileSelectionDialog(top, "file", NULL, 0); + XmString pat; fileSave = save; XtAddCallback(d, XmNokCallback, FileOk, NULL); XtAddCallback(d, XmNcancelCallback, FileCancel, NULL); XtVaSetValues(d, XmNfileTypeMask, XmFILE_REGULAR, NULL); + /* + * The filter has to name every format this program reads, or opening + * a PNG means typing its name: the reader knows more than the writer + * did in 1993 (2026-11-22). + */ + pat = XmStringCreateLocalized("*.png *.jpg *.jpeg *.gif *.bmp *.ico " + "*.xpm *"); + XtVaSetValues(d, XmNpattern, pat, NULL); + XmStringFree(pat); XtManageChild(d); } @@ -3541,6 +4595,9 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) XCopyArea(dpy, snap, image, gc, 0, 0, docW, docH, 0, 0); RenderDoc(canvas); break; + case CMD_SHOWOPTIONS: + OptionsShow(); + break; case CMD_ZOOMIN: SetZoom(zoom * 2); break; case CMD_ZOOMOUT: SetZoom(zoom / 2); break; case CMD_FIT: { @@ -3566,6 +4623,31 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) InvertSelection(); RenderDoc(canvas); break; + case CMD_FEATHER: { + char buf[32]; + + snprintf(buf, sizeof buf, "%d", retouchRadius); + NumberDialog("Feather radius (pixels):", buf, FeatherOk); + break; + } + case CMD_SELBORDER: + NumberDialog("Border width (pixels):", "4", SelBorderOk); + break; + case CMD_SELSMOOTH: + NumberDialog("Smooth radius (pixels):", "2", SelSmoothOk); + break; + case CMD_SELEXPAND: + NumberDialog("Expand by (pixels):", "4", SelExpandOk); + break; + case CMD_SELCONTRACT: + NumberDialog("Contract by (pixels):", "4", SelContractOk); + break; + case CMD_SELGROW: + SelGrowRun(); + break; + case CMD_SELSIMILAR: + SelSimilarRun(); + break; case CMD_CLEAR: XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); PaintMask(bgPixel); @@ -3743,6 +4825,11 @@ main(int argc, char **argv) XtRealizeWidget(toolShell); XtPopup(toolShell, XtGrabNone); + /* the Options box is a request, normally from Window/Show Options; + * this makes it reachable without a mouse, for the tests */ + if (getenv("DTPHOTO_OPTIONS") != NULL) + OptionsShow(); + NewDoc(); /* @@ -3753,12 +4840,12 @@ main(int argc, char **argv) XImage *a, *b; int x, y, ok = 1; - if (OpenBMP(argv[2]) != 0 || SaveBMP(argv[3]) != 0) { + if (OpenImage(argv[2]) != 0 || SaveImage(argv[3]) != 0) { printf("dtphoto selftest: FAIL open/save\n"); return 1; } a = XGetImage(dpy, snap, 0, 0, docW, docH, AllPlanes, ZPixmap); - if (OpenBMP(argv[3]) != 0) { + if (OpenImage(argv[3]) != 0) { printf("dtphoto selftest: FAIL reopen\n"); return 1; } @@ -4220,6 +5307,13 @@ main(int argc, char **argv) { "Select/All", CMD_ALL }, { "Select/None", CMD_DESELECT }, { "Select/Inverse", CMD_INVERSE }, + { "Select/Feather...", CMD_FEATHER }, + { "Select/Modify/Border...", CMD_SELBORDER }, + { "Select/Modify/Smooth...", CMD_SELSMOOTH }, + { "Select/Modify/Expand...", CMD_SELEXPAND }, + { "Select/Modify/Contract...", CMD_SELCONTRACT }, + { "Select/Grow", CMD_SELGROW }, + { "Select/Similar", CMD_SELSIMILAR }, { "Image/Adjust/Invert", CMD_INVERT }, { "Image/Adjust/Desaturate", CMD_DESATURATE }, { "Image/Adjust/Brightness/Contrast...", CMD_BRIGHTCONTRAST }, @@ -4272,6 +5366,289 @@ main(int argc, char **argv) * known corner. A wrong one of these is a wrong picture, not a bug * that shows later. */ + if (argc >= 2 && strcmp(argv[1], "-selmodtest") == 0) { + /* + * Selection morphology, against numbers worked out by hand. + * + * The document is 21x11 with a 5x5 block at (8,3)..(12,7), + * so every distance below is a small integer and the exact + * Euclidean transform has to land on it -- a chamfer would + * not, and the test would say so. + */ + int w = 21, h = 11, bad = 0, x, y; + unsigned char *rgb; + int n; + + rgb = malloc((size_t) w * h * 3); + if (rgb == NULL) { + printf("dtphoto selmodtest: FAIL malloc\n"); + return 1; + } + for (n = 0; n < w * h; n++) { + rgb[n * 3] = 10; + rgb[n * 3 + 1] = 20; + rgb[n * 3 + 2] = 30; + } + SetImageRGB(rgb, w, h); + free(rgb); + +#define SELMOD_BLOCK() \ + do { \ + int bx, by; \ + MaskClear(); \ + if (MaskAlloc() != 0) { \ + printf("dtphoto selmodtest: FAIL alloc\n"); \ + return 1; \ + } \ + selMaskAny = 1; \ + for (by = 3; by <= 7; by++) \ + for (bx = 8; bx <= 12; bx++) \ + MaskSet(bx, by, 1); \ + hasSel = 1; \ + selX0 = 8; selY0 = 3; selX1 = 13; selY1 = 8; \ + } while (0) + +#define SELMOD_WANT(name, px, py, want) \ + do { \ + int got = MaskGet(px, py); \ + if (got != (want)) { \ + printf("dtphoto selmodtest: %s (%d,%d)=%d want %d " \ + "FAIL\n", name, px, py, got, (want)); \ + bad++; \ + } \ + } while (0) + + /* --- Expand by 2: the block plus a 2 px ring --- */ + SELMOD_BLOCK(); + SelExpand(2.0); + SELMOD_WANT("expand", 6, 5, 1); /* 2 left of the block */ + SELMOD_WANT("expand", 8, 5, 1); + SELMOD_WANT("expand", 5, 5, 0); /* 3 left: outside */ + SELMOD_WANT("expand", 10, 1, 1); /* 2 above */ + SELMOD_WANT("expand", 10, 0, 0); /* 3 above: outside */ + SELMOD_WANT("expand", 8, 3, 1); /* a corner stays in */ + /* the ring is round, not square: (6,1) is 5.66 away */ + SELMOD_WANT("expand-corner", 6, 1, 0); + SELMOD_WANT("expand-corner", 7, 2, 1); /* 2.83 away, in */ + + /* --- Contract by 1: the block loses its rim --- */ + SELMOD_BLOCK(); + SelContract(1.0); + SELMOD_WANT("contract", 8, 3, 0); /* rim: 1 away */ + SELMOD_WANT("contract", 9, 4, 1); /* 2 away: stays */ + SELMOD_WANT("contract", 10, 5, 1); /* centre stays */ + SELMOD_WANT("contract", 9, 5, 1); /* 2 away */ + + /* --- Contract by 2: a 5x5 block leaves one pixel --- */ + SELMOD_BLOCK(); + SelContract(2.0); + SELMOD_WANT("contract2", 10, 5, 1); + SELMOD_WANT("contract2", 9, 4, 0); + + /* --- Border 1: the rim only, inside and outside --- */ + SELMOD_BLOCK(); + SelBorder(1.0); + SELMOD_WANT("border", 7, 5, 1); /* one outside */ + SELMOD_WANT("border", 8, 5, 1); /* one inside */ + SELMOD_WANT("border", 9, 5, 0); /* two inside: centre */ + SELMOD_WANT("border", 10, 5, 0); + SELMOD_WANT("border", 6, 5, 0); /* two outside */ + + /* --- Smooth 1: a lone pixel disappears, a block stays --- */ + MaskClear(); + if (MaskAlloc() != 0) + return 1; + selMaskAny = 1; + MaskSet(2, 2, 1); + SelSmooth(1); + SELMOD_WANT("smooth-speck", 2, 2, 0); + SELMOD_BLOCK(); + { + int before = 0, after = 0; + + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + before += MaskGet(x, y); + SelSmooth(1); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + after += MaskGet(x, y); + /* + * A 5x5 block: the four corners see 3 of 9 set + * pixels, so they leave; the rim between them sees + * 6 and stays. 25 -> 21, worked out on paper. + */ + if (before != 25 || after != 21) { + printf("dtphoto selmodtest: smooth-block " \ + "%d->%d want 25->21 FAIL\n", before, after); + bad++; + } + SELMOD_WANT("smooth-corner", 8, 3, 0); + SELMOD_WANT("smooth-rim", 9, 3, 1); + } + + /* + * --- Grow vs Similar --- + * + * Two 3x3 squares of the same colour at (2,2) and (14,2), + * nothing between. Grow, started from the left one, must + * reach only the pixels of that square: the right one is not + * connected. Similar takes both. + */ + { + unsigned char *pic = malloc((size_t) w * h * 3); + + if (pic == NULL) + return 1; + for (n = 0; n < w * h; n++) { + pic[n * 3] = 200; + pic[n * 3 + 1] = 200; + pic[n * 3 + 2] = 200; + } + for (y = 2; y <= 4; y++) + for (x = 2; x <= 4; x++) { + pic[((size_t) y * w + x) * 3] = 0; + pic[((size_t) y * w + x) * 3 + 1] = 0; + pic[((size_t) y * w + x) * 3 + 2] = 0; + } + for (y = 2; y <= 4; y++) + for (x = 14; x <= 16; x++) { + pic[((size_t) y * w + x) * 3] = 0; + pic[((size_t) y * w + x) * 3 + 1] = 0; + pic[((size_t) y * w + x) * 3 + 2] = 0; + } + SetImageRGB(pic, w, h); + free(pic); + + MaskClear(); + if (MaskAlloc() != 0) + return 1; + selMaskAny = 1; + MaskSet(3, 3, 1); + wandTolerance = 32; + SelColorExtend(wandTolerance, 1); + SELMOD_WANT("grow-left", 2, 2, 1); + SELMOD_WANT("grow-left", 4, 4, 1); + SELMOD_WANT("grow-right", 15, 3, 0); + + MaskClear(); + if (MaskAlloc() != 0) + return 1; + selMaskAny = 1; + MaskSet(3, 3, 1); + SelColorExtend(wandTolerance, 0); + SELMOD_WANT("similar-left", 2, 2, 1); + SELMOD_WANT("similar-right", 15, 3, 1); + SELMOD_WANT("similar-white", 10, 8, 0); + } + + /* + * --- Feather --- + * + * A 9x9 block feathered by 4 has to ramp: the rim pixel gets + * a small coverage, the centre 255, and nothing outside is + * touched. The exact numbers come from the ramp + * (dist-1)/r, so they are arithmetic, not taste. + */ + { + int c0, c1, c2, out; + + MaskClear(); + if (MaskAlloc() != 0) + return 1; + selMaskAny = 1; + for (y = 1; y <= 9; y++) + for (x = 1; x <= 9; x++) + MaskSet(x, y, 1); + hasSel = 1; + SelFeather(4); + c0 = MaskCover(5, 5); /* centre: 255 */ + c1 = MaskCover(1, 5); /* rim: dist 1 -> 0 */ + c2 = MaskCover(5, 1); /* dist 1 -> 0 */ + out = MaskCover(0, 5); /* outside the block */ + if (c0 != 255) { + printf("dtphoto selmodtest: feather-centre=%d " \ + "want 255 FAIL\n", c0); + bad++; + } + if (c1 != 0 || c2 != 0) { + printf("dtphoto selmodtest: feather-rim=%d,%d " \ + "want 0,0 FAIL\n", c1, c2); + bad++; + } + if (out != 0) { + printf("dtphoto selmodtest: feather-out=%d " \ + "want 0 FAIL\n", out); + bad++; + } + /* the ramp must be monotone and reach the middle */ + if (!(MaskCover(2, 5) <= MaskCover(3, 5) && + MaskCover(3, 5) <= MaskCover(4, 5) && + MaskCover(4, 5) <= MaskCover(5, 5))) { + printf("dtphoto selmodtest: feather ramp not " \ + "monotone FAIL\n"); + bad++; + } + /* + * And it must reach the pixel operation: Invert with + * a feathered edge has to leave the rim nearly alone + * and turn the centre completely. + */ + { + unsigned char *now = NULL; + int nw = 0, nh = 0, k; + + /* the Similar block above replaced the picture */ + rgb = malloc((size_t) w * h * 3); + if (rgb != NULL) { + for (k = 0; k < w * h; k++) { + rgb[k * 3] = 10; + rgb[k * 3 + 1] = 20; + rgb[k * 3 + 2] = 30; + } + SetImageRGB(rgb, w, h); + free(rgb); + } + OpInvert(); + GetImageRGB(&now, &nw, &nh); + if (now != NULL) { + unsigned char *mid = now + + ((size_t) 5 * nw + 5) * 3; + unsigned char *rim = now + + ((size_t) 5 * nw + 1) * 3; + + /* centre: 10,20,30 -> 245,235,225 */ + if (mid[0] != 245 || mid[1] != 235 || + mid[2] != 225) { + printf("dtphoto selmodtest: " \ + "feather-invert mid=%d,%d," \ + "%d want 245,235,225 " \ + "FAIL\n", mid[0], mid[1], + mid[2]); + bad++; + } + /* rim: coverage 0, so untouched */ + if (rim[0] != 10 || rim[1] != 20 || + rim[2] != 30) { + printf("dtphoto selmodtest: " \ + "feather-invert rim=%d,%d," \ + "%d want 10,20,30 " \ + "FAIL\n", rim[0], rim[1], + rim[2]); + bad++; + } + free(now); + } + } + } + +#undef SELMOD_BLOCK +#undef SELMOD_WANT + MaskClear(); + printf("dtphoto selmodtest: %s\n", bad == 0 ? "PASS" : "FAIL"); + return bad == 0 ? 0 : 1; + } + if (argc >= 2 && strcmp(argv[1], "-optest") == 0) { unsigned char *rgb; int w = 6, h = 4, x, y, bad = 0; @@ -4398,6 +5775,91 @@ main(int argc, char **argv) OPT_PIX("gradient", 5, 0, 255, 255, 255); OPT_PIX("gradient", 5, 3, 255, 255, 255); + /* + * The radial gradient: the drag is 5 px to the right, so + * (0,0) is the foreground, (5,3) is past the end and takes + * the background, and (3,0) is 3/5 of the way there: + * 0 + 255*600/1000 = 153. + */ + OPT_LOAD(); + gradientKind = 1; + GradientImage(0, 0, 5, 0); + OPT_PIX("radial", 0, 0, 0, 0, 0); + OPT_PIX("radial", 3, 0, 153, 153, 153); + OPT_PIX("radial", 5, 3, 255, 255, 255); + gradientKind = 0; + + /* the gradient must stay inside a selection */ + OPT_LOAD(); + MaskAlloc(); + MaskClear(); + MaskSet(0, 0, 1); + MaskSet(1, 0, 1); + selMaskAny = 1; + GradientImage(0, 0, w - 1, 0); + OPT_PIX("gradient-sel", 0, 0, 0, 0, 0); + OPT_PIX("gradient-sel", 5, 3, 200, 180, 128); + /* + * The wand reads wandTolerance, the number the Options box + * writes: at 0 it takes only the exact colour, at 100 the + * neighbouring step as well. + */ + OPT_LOAD(); + wandTolerance = 0; + WandSelect(0, 0, wandTolerance); + int optInside = 0; + { + int xx, yy; + + for (yy = 0; yy < 4; yy++) + for (xx = 0; xx < 6; xx++) + optInside += MaskGet(xx, yy) ? 1 : 0; + } + printf("dtphoto optest: wand tol 0 -> %d px\n", optInside); + MaskClear(); + selMaskAny = 0; + wandTolerance = 100; + WandSelect(0, 0, wandTolerance); + { + int xx, yy, wide = 0; + + for (yy = 0; yy < 4; yy++) + for (xx = 0; xx < 6; xx++) + wide += MaskGet(xx, yy) ? 1 : 0; + printf("dtphoto optest: wand tol 100 -> %d px %s\n", + wide, wide > optInside ? "ok" : "FAIL"); + if (wide <= optInside) + bad++; + } + MaskClear(); + selMaskAny = 0; + wandTolerance = 32; + + /* the mask outlives the call: every test after this one + * would silently run inside two pixels */ + MaskClear(); + selMaskAny = 0; + + /* + * Painting is clipped to the selection, as in the original: + * a pencil tip laid across the edge of a 2 px selection + * may only change those two columns. + */ + OPT_LOAD(); + MaskAlloc(); + MaskClear(); + MaskSet(0, 0, 1); + MaskSet(1, 0, 1); + selMaskAny = 1; + fgPixel = BlackPixel(dpy, 0); + PencilDot(2, 0, 2); + OPT_PIX("paint-sel", 0, 0, 0, 0, 0); + OPT_PIX("paint-sel", 1, 0, 0, 0, 0); + OPT_PIX("paint-sel", 3, 0, 120, 0, 128); + MaskClear(); + selMaskAny = 0; + fgPixel = BlackPixel(dpy, 0); + /* * The filters. The test picture has r = 40x, g = 60y, b = 128, * so a 3x3 box blur of the interior keeps the b channel at 128 @@ -4571,7 +6033,7 @@ main(int argc, char **argv) currentTool = saved; } FloodFillImage(30, 30); - if (SaveBMP(argv[2]) != 0) { + if (SaveImage(argv[2]) != 0) { printf("dtphoto demo: FAIL save\n"); return 1; } @@ -4588,7 +6050,7 @@ main(int argc, char **argv) /* a picture on the command line, as the original opens one */ if (argc > 1 && argv[1][0] != '-') { snprintf(path, sizeof path, "%s", argv[1]); - if (OpenBMP(path) == 0) { + if (OpenImage(path) == 0) { UpdateStatus(); RenderDoc(canvas); } diff --git a/programs/dtphoto/dtphoto.msg b/programs/dtphoto/dtphoto.msg index 63e8a458..ed8ed082 100644 --- a/programs/dtphoto/dtphoto.msg +++ b/programs/dtphoto/dtphoto.msg @@ -7,3 +7,4 @@ $set 1 3 Doc: %dK/%dK 4 The picture could not be opened. 5 The picture could not be saved. +6 Tool Options diff --git a/programs/localized/de_DE.UTF-8/msg/dtphoto.msg b/programs/localized/de_DE.UTF-8/msg/dtphoto.msg index 4e6342b0..929cfcbb 100644 --- a/programs/localized/de_DE.UTF-8/msg/dtphoto.msg +++ b/programs/localized/de_DE.UTF-8/msg/dtphoto.msg @@ -7,3 +7,4 @@ $set 1 3 Dok: %dK/%dK 4 Das Bild konnte nicht geöffnet werden. 5 Das Bild konnte nicht gespeichert werden. +6 Werkzeugoptionen From 4cfd730565fcbb64b0271c976405fa15de63eda3 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 13:09:53 +0000 Subject: [PATCH 17/22] MCDE dtphoto: every menu path bound, the View switches drawn and read All 206 paths of dtphoto.menu resolve to a command the callback switches on. The table had 43 doubled entries and 11 paths that named a menu entry the menu does not have ("Image/Adjust/Image Size..." instead of "Image/Image Size...", "@3.0" tags the reader already strips); both are gone, CommandOf walks the table to its NULL entry, and -menutest now proves the table against itself: 206 paths, 0 doubled, 0 bad, and an unknown path stays CMD_NONE. DTPHOTO_CMDS=1 used to bind 38, now 206, none on CMD_NONE. The View switches were flags nobody read. SnapX/SnapY pull a marquee or crop drag onto the grid or a guide a guide in reach wins over the grid, Lock Guides refuses new and keeps existing ones), DrawGuides paints the grid, the guides and the rulers on the canvas and not into the picture. Two new headless tests, both green on depth 24 and depth 8: -viewtest snapping arithmetic: 37 -> 32 on a 16 grid, 40 -> 48, a guide at 35 catches 37, a vertical guide leaves y alone, locked guides neither grow nor clear. -drawtest counts the pixels on a real pixmap: grid 12509, one guide 280 (= the canvas height), rulers 558 and none of them inside the canvas. Measured: drawtest, viewtest, menutest, optest, selmodtest, retouchtest, selecttest, movetest, croptest, typetest -> 20 green, 0 red (10 tests x depth 24/depth 8); -selftest PASS on both, byte-identical output. --- AGENTS.md | 15 +- programs/dtphoto/dtphoto.c | 6221 +++++++++++++++++++++++++++++++++++- 2 files changed, 6114 insertions(+), 122 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a3d4ddee..cbea83bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -122,8 +122,19 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt has "Horizontal" in Image > Flip and in Layer > Type, and the label alone cannot tell them apart. `CommandOf` takes "menu/sub/item", the reader stores it in `Item.path`, and `-menutest` proves every path - resolves to the command the callback switches on (31 paths, measured - 2026-11-22). `DTPHOTO_CMDS=1` prints what the loaded menu file bound. + resolves to the command the callback switches on, that no path is + claimed twice and that a path nobody knows stays CMD_NONE (206 paths, + 0 doubled, measured 2026-11-22). The table ends at its NULL entry so + the test walks it without knowing the length. `DTPHOTO_CMDS=1` prints + what the loaded menu file bound: 206 of 206, none on CMD_NONE. Every + menu path in `dtphoto.menu` resolves, so a bound entry is a wired one. + The View switches are read, not just flipped: `SnapX`/`SnapY` pull a + marquee or crop drag onto the grid or a guide, `DrawGuides` paints the + grid, the guides and the rulers on the canvas (not into the picture), + and `-viewtest` checks the snapping arithmetic while `-drawtest` + counts the pixels the decorations add on a real pixmap. A flag that + only toggles itself is a menu entry that does nothing, which is why + both tests exist. `dtphoto -optest|-menutest` are headless too: the operations are checked against the arithmetic (a hard edge blurred to 170, the same edge sharpened clamped to 255 and 0, a mosaic cell to its mean) and not diff --git a/programs/dtphoto/dtphoto.c b/programs/dtphoto/dtphoto.c index bcc23578..ff4c9bfd 100644 --- a/programs/dtphoto/dtphoto.c +++ b/programs/dtphoto/dtphoto.c @@ -20,6 +20,9 @@ #include #include #include +#include +#include +#include #include #include @@ -31,12 +34,15 @@ #include #include #include +#include #include #include #include #include +#include #include #include +#include #include #include @@ -79,7 +85,59 @@ enum { CMD_FINDEDGES, CMD_EMBOSS, CMD_SOLARIZE, CMD_ADDNOISE, CMD_MEDIAN, CMD_MOSAIC, /* Window: the Options box */ - CMD_SHOWOPTIONS + CMD_SHOWOPTIONS, + /* Image > Adjust: the curve family and the two colour-range ones */ + CMD_LEVELS, CMD_CURVES, CMD_COLORBALANCE, CMD_HUESAT, CMD_THRESHOLD, + CMD_POSTERIZE, CMD_EQUALIZE, CMD_REPLACECOLOR, CMD_SELECTIVECOLOR, + /* File: the entries that work on the document as a whole */ + CMD_CLOSE, CMD_REVERT, CMD_FILEINFO, CMD_PAGESETUP, CMD_PRINT, + CMD_PREFS, + /* Edit: the clipboard and the pattern */ + CMD_CUT, CMD_COPY, CMD_PASTE, CMD_STROKE, CMD_DEFPATTERN, + /* Select: the colour range and the matting */ + CMD_COLORRANGE, CMD_DEFRINGE, CMD_REMOVEBLACK, CMD_REMOVEWHITE, + /* Image > Mode */ + CMD_MODEBITMAP, CMD_MODEGRAY, CMD_MODEINDEXED, CMD_MODERGB, + CMD_MODELAB, CMD_ROTARB, CMD_DUPLICATE, CMD_APPLYIMAGE, + CMD_CALCULATIONS, CMD_HISTOGRAM, CMD_TRAP, + /* Filter: the rest of the reference's list */ + CMD_GAUSSIAN, CMD_MOTIONBLUR, CMD_RADIALBLUR, CMD_SMARTBLUR, + CMD_DISPLACE, CMD_PINCH, CMD_POLAR, CMD_RIPPLE, CMD_SHEAR, + CMD_SPHERIZE, CMD_TWIRL, CMD_WAVE, CMD_ZIGZAG, CMD_DUST, + CMD_HALFTONE, CMD_CRYSTALLIZE, CMD_FACET, CMD_FRAGMENT, + CMD_MEZZOTINT, CMD_POINTILLIZE, CMD_CLOUDS, CMD_DIFFCLOUDS, + CMD_LENSFLARE, CMD_LIGHTING, CMD_TEXTUREFILL, CMD_SHARPENEDGES, + CMD_UNSHARP, CMD_DIFFUSE, CMD_EXTRUDE, CMD_TILES, + CMD_TRACECONTOUR, CMD_WIND, CMD_DEINTERLACE, CMD_NTSC, + CMD_CUSTOM, CMD_HIGHPASS, CMD_MAXIMUM, CMD_MINIMUM, CMD_OFFSET, + /* View, Window, Help */ + CMD_RULERS, CMD_GRID, CMD_SHOWTOOLS, CMD_SHOWBRUSHES, + CMD_SHOWPICKER, CMD_SHOWSWATCHES, CMD_SHOWSCRATCH, CMD_SHOWINFO, + CMD_CASCADE, CMD_CLOSEALL, CMD_ABOUT, + /* the last of the reference's list: every menu entry gets a verb */ + CMD_OPENAS, CMD_PLACE, CMD_SAVECOPY, CMD_ACQUIRE, CMD_EXPORT, + CMD_PASTEINTO, CMD_PASTELAYER, CMD_CREATEPUB, CMD_PUBOPTS, + CMD_SNAPSHOT, + CMD_MODEDUOTONE, CMD_MODECMYK, CMD_MODEMULTI, CMD_COLORTABLE, + CMD_CMYKPREVIEW, CMD_GAMUT, CMD_IMAGEDUP, + CMD_EFFECTSCALE, CMD_EFFECTROTATE, CMD_EFFECTSKEW, CMD_EFFECTDISTORT, + CMD_EFFECTPERSP, + CMD_LAYERNEW, CMD_LAYERADJ, CMD_LAYERDUP, CMD_LAYERDELETE, + CMD_LAYEROPTS, CMD_ADJOPTS, + CMD_DROPSHADOW, CMD_INNERSHADOW, CMD_OUTERGLOW, CMD_INNERGLOW, + CMD_BEVEL, CMD_RENDERLAYER, CMD_TYPEH, CMD_TYPEV, + CMD_LAYERSCALE, CMD_LAYERROTATE, CMD_LAYERSKEW, CMD_LAYERDISTORT, + CMD_LAYERPERSP, CMD_LAYERNUMERIC, + CMD_BRINGFRONT, CMD_BRINGFWD, CMD_SENDBWD, CMD_SENDBACK, + CMD_MERGEDOWN, CMD_MERGEVISIBLE, CMD_FLATTEN, + CMD_LAYERDEFRINGE, CMD_LAYERBLACK, CMD_LAYERWHITE, + CMD_FLOAT, CMD_DEFLOAT, CMD_HIDEEDGES, CMD_LOADSEL, CMD_SAVESEL, + CMD_LASTFILTER, CMD_EMBEDWM, CMD_READWM, + CMD_NEWVIEW, CMD_PREVIEWCMYK, CMD_PREVIEWRGB, CMD_VIEWGAMUT, + CMD_SHOWEDGES, CMD_SHOWPATH, CMD_SHOWGUIDES, CMD_SNAPGUIDES, + CMD_LOCKGUIDES, CMD_CLEARGUIDES, CMD_SNAPGRID, + CMD_TILE, CMD_ARRANGEICONS, CMD_SHOWLAYERS, CMD_SHOWCHANNELS, + CMD_SHOWPATHS, CMD_SHOWCOMMANDS }; static Menu menus[MAXMENUS]; @@ -93,6 +151,11 @@ static GC gc; static int docW = 320, docH = 240; static int zoom = 100; static int currentTool = 4; /* move, as the original starts */ +/* the View menu: what is drawn over the picture and what a drag snaps + * to. These are read by DrawGuides and SnapX/SnapY, so a menu entry + * that flips one of them has a visible effect. */ +static int showRulers = 1, showGrid, showGuides; +static int snapGuides, lockGuides, snapGrid, snapLayers; static int fileSave; static Pixel fgPixel, bgPixel; static int selX0, selY0, selX1, selY1, hasSel, dragging; @@ -129,6 +192,8 @@ static int eraserRadius = 6; static int wandTolerance = 32; /* the wand, and Grow/Similar */ static int retouchRadius = 6; static int retouchStrength = 60; +static int undoDepth = 1; /* how many steps Undo keeps */ +static char *docPath; /* the file the document came from, or NULL */ static int gradientKind = 0; /* 0 = linear, 1 = radial */ static int lastX, lastY, pressX, pressY; /* where the picture sits in the canvas, and where the pointer was on the @@ -144,6 +209,9 @@ static int viewOX, viewOY, lastScrX, lastScrY; * here (ext/src/mcde/AGENTS.md, dtpaint paragraph). */ static Screen *scr; static Visual *vis; +/* the luminance Photoshop uses, the numbers of Desaturate */ +#define LUMA(r, g, b) ((299L * (r) + 587L * (g) + 114L * (b)) / 1000L) + static Drawable drawable; /* the root window, what a pixmap is made with */ static Colormap cmap; static int visdepth, truecolor; @@ -170,6 +238,9 @@ static void SetZoom(int z); static void MoveMasked(int dx, int dy); static int MoveBegin(void); static void MoveEnd(void); +static void OpDone(const char *what); +static void FieldDialog(const char *title, const char *labels, + const char *initial, void (*fn)(const int *v)); /* the hand: move the view, not the picture */ static void @@ -1027,13 +1098,20 @@ OpenImage(const char *path) McdeThumbImage image; int i; - if (OpenBMP(path) == 0) + if (OpenBMP(path) == 0) { + free(docPath); + docPath = strdup(path); return 0; + } memset(&image, 0, sizeof image); if (McdeThumbRead(path, 0, 0, &image) != 0) return -1; i = SetImageRGB(image.rgb, image.width, image.height); McdeThumbFree(&image); + if (i == 0) { + free(docPath); + docPath = strdup(path); + } return i; } @@ -1050,15 +1128,244 @@ SaveImage(const char *path) if (GetImageRGB(&rgb, &w, &h) != 0) return -1; - if (McdeThumbWrite(path, rgb, w, h) == 0) { + if (McdeThumbWrite(path, rgb, w, h) == 0 || + SaveBMP(path) == 0) { free(rgb); + free(docPath); + docPath = strdup(path); return 0; } free(rgb); - return SaveBMP(path); + return -1; } -/* ------------------------------------------------------------------ menus */ +/* + * The menu entries dtphoto can carry out, by full path. A table, not a + * chain of strcmp: the list is what -menutest reads, and a path that is + * listed here but has no case in MenuCallback is a bug the test can find. + * The label alone is ambiguous ("Horizontal" is in Image > Flip and in + * Layer > Type), so the reader passes "menu/sub/item". + */ +static const struct { + const char *path; + int cmd; +} CmdTable[] = { + /* File */ + { "File/New...", CMD_NEW }, + { "File/Open...", CMD_OPEN }, + { "File/Close", CMD_CLOSE }, + { "File/Save", CMD_SAVE }, + { "File/Save As...", CMD_SAVEAS }, + { "File/Revert", CMD_REVERT }, + { "File/File Info...", CMD_FILEINFO }, + { "File/Page Setup...", CMD_PAGESETUP }, + { "File/Print...", CMD_PRINT }, + { "File/Preferences", CMD_PREFS }, + { "File/Quit", CMD_QUIT }, + /* Edit */ + { "Edit/Undo", CMD_UNDO }, + { "Edit/Cut", CMD_CUT }, + { "Edit/Copy", CMD_COPY }, + { "Edit/Paste", CMD_PASTE }, + { "Edit/Stroke...", CMD_STROKE }, + { "Edit/Define Pattern", CMD_DEFPATTERN }, + { "Edit/Fill...", CMD_FILL }, + { "Edit/Clear", CMD_CLEAR }, + { "Edit/Crop", CMD_CROP }, + /* Select */ + { "Select/All", CMD_ALL }, + { "Select/None", CMD_DESELECT }, + { "Select/Inverse", CMD_INVERSE }, + { "Select/Feather...", CMD_FEATHER }, + { "Select/Modify/Border...", CMD_SELBORDER }, + { "Select/Modify/Smooth...", CMD_SELSMOOTH }, + { "Select/Modify/Expand...", CMD_SELEXPAND }, + { "Select/Modify/Contract...", CMD_SELCONTRACT }, + { "Select/Grow", CMD_SELGROW }, + { "Select/Similar", CMD_SELSIMILAR }, + { "Select/Color Range...", CMD_COLORRANGE }, + { "Select/Matting/Defringe...", CMD_DEFRINGE }, + { "Select/Matting/Remove Black Matte", CMD_REMOVEBLACK }, + { "Select/Matting/Remove White Matte", CMD_REMOVEWHITE }, + /* Image: the whole picture, through the RGB buffer */ + { "Image/Mode/Bitmap", CMD_MODEBITMAP }, + { "Image/Mode/Grayscale", CMD_MODEGRAY }, + { "Image/Mode/Indexed Color...", CMD_MODEINDEXED }, + { "Image/Mode/RGB Color", CMD_MODERGB }, + { "Image/Mode/Lab Color", CMD_MODELAB }, + { "Image/Adjust/Invert", CMD_INVERT }, + { "Image/Adjust/Desaturate", CMD_DESATURATE }, + { "Image/Adjust/Brightness/Contrast...", CMD_BRIGHTCONTRAST }, + { "Image/Adjust/Levels...", CMD_LEVELS }, + { "Image/Adjust/Curves...", CMD_CURVES }, + { "Image/Adjust/Color Balance...", CMD_COLORBALANCE }, + { "Image/Adjust/Hue/Saturation...", CMD_HUESAT }, + { "Image/Adjust/Threshold...", CMD_THRESHOLD }, + { "Image/Adjust/Posterize...", CMD_POSTERIZE }, + { "Image/Adjust/Equalize", CMD_EQUALIZE }, + { "Image/Adjust/Replace Color...", CMD_REPLACECOLOR }, + { "Image/Adjust/Selective Color...", CMD_SELECTIVECOLOR }, + { "Image/Duplicate...", CMD_DUPLICATE }, + { "Image/Apply Image...", CMD_APPLYIMAGE }, + { "Image/Calculations...", CMD_CALCULATIONS }, + { "Image/Flip/Horizontal", CMD_FLIPH }, + { "Image/Flip/Vertical", CMD_FLIPV }, + { "Image/Rotate/180", CMD_ROT180 }, + { "Image/Rotate/90 CW", CMD_ROT90CW }, + { "Image/Rotate/90 CCW", CMD_ROT90CCW }, + { "Image/Rotate/Arbitrary...", CMD_ROTARB }, + { "Image/Image Size...", CMD_IMAGESIZE }, + { "Image/Canvas Size...", CMD_CANVASSIZE }, + { "Image/Histogram...", CMD_HISTOGRAM }, + { "Image/Trap...", CMD_TRAP }, + /* Filter: convolution, distortion, noise, pixelate, render, tone */ + { "Filter/Blur/Blur", CMD_BLUR }, + { "Filter/Blur/Blur More", CMD_BLURMORE }, + { "Filter/Blur/Gaussian Blur...", CMD_GAUSSIAN }, + { "Filter/Blur/Motion Blur...", CMD_MOTIONBLUR }, + { "Filter/Blur/Radial Blur...", CMD_RADIALBLUR }, + { "Filter/Blur/Smart Blur...", CMD_SMARTBLUR }, + { "Filter/Distort/Displace...", CMD_DISPLACE }, + { "Filter/Distort/Pinch...", CMD_PINCH }, + { "Filter/Distort/Polar Coordinates...", CMD_POLAR }, + { "Filter/Distort/Ripple...", CMD_RIPPLE }, + { "Filter/Distort/Shear...", CMD_SHEAR }, + { "Filter/Distort/Spherize...", CMD_SPHERIZE }, + { "Filter/Distort/Twirl...", CMD_TWIRL }, + { "Filter/Distort/Wave...", CMD_WAVE }, + { "Filter/Distort/ZigZag...", CMD_ZIGZAG }, + { "Filter/Noise/Add Noise...", CMD_ADDNOISE }, + { "Filter/Noise/Despeckle", CMD_MEDIAN }, + { "Filter/Noise/Dust & Scratches...", CMD_DUST }, + { "Filter/Noise/Median...", CMD_MEDIAN }, + { "Filter/Pixelate/Color Halftone...", CMD_HALFTONE }, + { "Filter/Pixelate/Crystallize...", CMD_CRYSTALLIZE }, + { "Filter/Pixelate/Facet", CMD_FACET }, + { "Filter/Pixelate/Fragment", CMD_FRAGMENT }, + { "Filter/Pixelate/Mezzotint...", CMD_MEZZOTINT }, + { "Filter/Pixelate/Mosaic...", CMD_MOSAIC }, + { "Filter/Pixelate/Pointillize...", CMD_POINTILLIZE }, + { "Filter/Render/Clouds", CMD_CLOUDS }, + { "Filter/Render/Difference Clouds", CMD_DIFFCLOUDS }, + { "Filter/Render/Lens Flare...", CMD_LENSFLARE }, + { "Filter/Render/Lighting Effects...", CMD_LIGHTING }, + { "Filter/Render/Texture Fill...", CMD_TEXTUREFILL }, + { "Filter/Sharpen/Sharpen", CMD_SHARPEN }, + { "Filter/Sharpen/Sharpen More", CMD_SHARPENMORE }, + { "Filter/Sharpen/Sharpen Edges", CMD_SHARPENEDGES }, + { "Filter/Sharpen/Unsharp Mask...", CMD_UNSHARP }, + { "Filter/Stylize/Diffuse...", CMD_DIFFUSE }, + { "Filter/Stylize/Emboss...", CMD_EMBOSS }, + { "Filter/Stylize/Extrude...", CMD_EXTRUDE }, + { "Filter/Stylize/Find Edges", CMD_FINDEDGES }, + { "Filter/Stylize/Solarize", CMD_SOLARIZE }, + { "Filter/Stylize/Tiles...", CMD_TILES }, + { "Filter/Stylize/Trace Contour...", CMD_TRACECONTOUR }, + { "Filter/Stylize/Wind...", CMD_WIND }, + { "Filter/Video/De-Interlace...", CMD_DEINTERLACE }, + { "Filter/Video/NTSC Colors", CMD_NTSC }, + { "Filter/Other/Custom...", CMD_CUSTOM }, + { "Filter/Other/High Pass...", CMD_HIGHPASS }, + { "Filter/Other/Maximum...", CMD_MAXIMUM }, + { "Filter/Other/Minimum...", CMD_MINIMUM }, + { "Filter/Other/Offset...", CMD_OFFSET }, + /* View */ + { "View/Zoom In", CMD_ZOOMIN }, + { "View/Zoom Out", CMD_ZOOMOUT }, + { "View/Fit on Screen", CMD_FIT }, + { "View/Actual Pixels", CMD_ACTUAL }, + { "View/Rulers", CMD_RULERS }, + { "View/Show Grid", CMD_GRID }, + /* Window */ + { "Window/Show Options", CMD_SHOWOPTIONS }, + { "Window/Show Tools", CMD_SHOWTOOLS }, + { "Window/Show Brushes", CMD_SHOWBRUSHES }, + { "Window/Show Picker", CMD_SHOWPICKER }, + { "Window/Show Swatches", CMD_SHOWSWATCHES }, + { "Window/Show Scratch", CMD_SHOWSCRATCH }, + { "Window/Show Info", CMD_SHOWINFO }, + { "Window/Cascade", CMD_CASCADE }, + { "Window/Close All", CMD_CLOSEALL }, + /* Help */ + { "File/Open As...", CMD_OPENAS }, + { "File/Place...", CMD_PLACE }, + { "File/Save a Copy...", CMD_SAVECOPY }, + { "File/Acquire", CMD_ACQUIRE }, + { "File/Export", CMD_EXPORT }, + { "Edit/Paste Into", CMD_PASTEINTO }, + { "Edit/Paste Layer...", CMD_PASTELAYER }, + { "Edit/Create Publisher...", CMD_CREATEPUB }, + { "Edit/Publisher Options...", CMD_PUBOPTS }, + { "Edit/Take Snapshot", CMD_SNAPSHOT }, + { "Image/Mode/Duotone", CMD_MODEDUOTONE }, + { "Image/Mode/CMYK Color", CMD_MODECMYK }, + { "Image/Mode/Multichannel", CMD_MODEMULTI }, + { "Image/Mode/Color Table...", CMD_COLORTABLE }, + { "Image/Mode/CMYK Preview", CMD_CMYKPREVIEW }, + { "Image/Mode/Gamut Warning", CMD_GAMUT }, + { "Image/Effects/Scale", CMD_EFFECTSCALE }, + { "Image/Effects/Rotate", CMD_EFFECTROTATE }, + { "Image/Effects/Skew", CMD_EFFECTSKEW }, + { "Image/Effects/Distort", CMD_EFFECTDISTORT }, + { "Image/Effects/Perspective", CMD_EFFECTPERSP }, + { "Layer/New/Layer", CMD_LAYERNEW }, + { "Layer/New/Adjustment Layer", CMD_LAYERADJ }, + { "Layer/Duplicate Layer...", CMD_LAYERDUP }, + { "Layer/Delete Layer", CMD_LAYERDELETE }, + { "Layer/Layer Options...", CMD_LAYEROPTS }, + { "Layer/Adjustment Options...", CMD_ADJOPTS }, + { "Layer/Effects/Drop Shadow", CMD_DROPSHADOW }, + { "Layer/Effects/Inner Shadow", CMD_INNERSHADOW }, + { "Layer/Effects/Outer Glow", CMD_OUTERGLOW }, + { "Layer/Effects/Inner Glow", CMD_INNERGLOW }, + { "Layer/Effects/Bevel and Emboss", CMD_BEVEL }, + { "Layer/Type/Render Layer", CMD_RENDERLAYER }, + { "Layer/Type/Horizontal", CMD_TYPEH }, + { "Layer/Type/Vertical", CMD_TYPEV }, + { "Layer/Transform/Scale", CMD_LAYERSCALE }, + { "Layer/Transform/Rotate", CMD_LAYERROTATE }, + { "Layer/Transform/Skew", CMD_LAYERSKEW }, + { "Layer/Transform/Distort", CMD_LAYERDISTORT }, + { "Layer/Transform/Perspective", CMD_LAYERPERSP }, + { "Layer/Transform/Numeric...", CMD_LAYERNUMERIC }, + { "Layer/Arrange/Bring to Front", CMD_BRINGFRONT }, + { "Layer/Arrange/Bring Forward", CMD_BRINGFWD }, + { "Layer/Arrange/Send Backward", CMD_SENDBWD }, + { "Layer/Arrange/Send to Back", CMD_SENDBACK }, + { "Layer/Merge Down", CMD_MERGEDOWN }, + { "Layer/Merge Visible", CMD_MERGEVISIBLE }, + { "Layer/Flatten Image", CMD_FLATTEN }, + { "Layer/Matting/Defringe...", CMD_LAYERDEFRINGE }, + { "Layer/Matting/Remove Black Matte", CMD_LAYERBLACK }, + { "Layer/Matting/Remove White Matte", CMD_LAYERWHITE }, + { "Select/Float", CMD_FLOAT }, + { "Select/Defloat", CMD_DEFLOAT }, + { "Select/Hide Edges", CMD_HIDEEDGES }, + { "Select/Load Selection...", CMD_LOADSEL }, + { "Select/Save Selection...", CMD_SAVESEL }, + { "Filter/Last Filter", CMD_LASTFILTER }, + { "Filter/Digimarc/Embed Watermark...", CMD_EMBEDWM }, + { "Filter/Digimarc/Read Watermark", CMD_READWM }, + { "View/New View", CMD_NEWVIEW }, + { "View/Preview/CMYK", CMD_PREVIEWCMYK }, + { "View/Preview/RGB", CMD_PREVIEWRGB }, + { "View/Gamut Warning", CMD_VIEWGAMUT }, + { "View/Show Edges", CMD_SHOWEDGES }, + { "View/Show Path", CMD_SHOWPATH }, + { "View/Show Guides", CMD_SHOWGUIDES }, + { "View/Snap to Guides", CMD_SNAPGUIDES }, + { "View/Lock Guides", CMD_LOCKGUIDES }, + { "View/Clear Guides", CMD_CLEARGUIDES }, + { "View/Snap to Grid", CMD_SNAPGRID }, + { "Window/Tile", CMD_TILE }, + { "Window/Arrange Icons", CMD_ARRANGEICONS }, + { "Window/Show Layers", CMD_SHOWLAYERS }, + { "Window/Show Channels", CMD_SHOWCHANNELS }, + { "Window/Show Paths", CMD_SHOWPATHS }, + { "Window/Show Commands", CMD_SHOWCOMMANDS }, + { "Help/About dtphoto...", CMD_ABOUT }, + { NULL, CMD_NONE } /* the end of the table, for the menutest */ +}; static void Trim(char *p) @@ -1070,7 +1377,18 @@ Trim(char *p) p[--n] = '\0'; } -static int CommandOf(const char *path); +static int +CommandOf(const char *path) +{ + size_t i; + + /* the table ends at its NULL entry, so the menutest can walk it + * without knowing its length */ + for (i = 0; CmdTable[i].path != NULL; i++) + if (strcmp(path, CmdTable[i].path) == 0) + return CmdTable[i].cmd; + return CMD_NONE; +} static void ReadMenus(const char *path) @@ -1162,71 +1480,6 @@ ReadMenus(const char *path) fclose(f); } -static int -CommandOf(const char *path) -{ - /* the label alone is ambiguous ("Horizontal" is in Image > Flip and - * in Layer > Type), so the caller passes "menu/sub/item" */ - const char *leaf = strrchr(path, '/'); - - if (leaf != NULL) - leaf++; - else - leaf = path; - if (strcmp(path, "File/New...") == 0) return CMD_NEW; - if (strcmp(path, "File/Open...") == 0) return CMD_OPEN; - if (strcmp(path, "File/Save") == 0) return CMD_SAVE; - if (strcmp(path, "File/Save As...") == 0) return CMD_SAVEAS; - if (strcmp(path, "File/Quit") == 0) return CMD_QUIT; - if (strcmp(path, "Edit/Undo") == 0) return CMD_UNDO; - if (strcmp(path, "View/Zoom In") == 0) return CMD_ZOOMIN; - if (strcmp(path, "View/Zoom Out") == 0) return CMD_ZOOMOUT; - if (strcmp(path, "View/Fit on Screen") == 0) return CMD_FIT; - if (strcmp(path, "View/Actual Pixels") == 0) return CMD_ACTUAL; - if (strcmp(path, "Window/Show Options") == 0) return CMD_SHOWOPTIONS; - if (strcmp(path, "Select/All") == 0) return CMD_ALL; - if (strcmp(path, "Select/None") == 0) return CMD_DESELECT; - if (strcmp(path, "Select/Inverse") == 0) return CMD_INVERSE; - /* Select > Modify: shapes the mask, not the picture */ - if (strcmp(path, "Select/Feather...") == 0) return CMD_FEATHER; - if (strcmp(path, "Select/Modify/Border...") == 0) return CMD_SELBORDER; - if (strcmp(path, "Select/Modify/Smooth...") == 0) return CMD_SELSMOOTH; - if (strcmp(path, "Select/Modify/Expand...") == 0) return CMD_SELEXPAND; - if (strcmp(path, "Select/Modify/Contract...") == 0) return CMD_SELCONTRACT; - if (strcmp(path, "Select/Grow") == 0) return CMD_SELGROW; - if (strcmp(path, "Select/Similar") == 0) return CMD_SELSIMILAR; - if (strcmp(path, "Edit/Clear") == 0) return CMD_CLEAR; - if (strcmp(path, "Edit/Fill...") == 0) return CMD_FILL; - if (strcmp(path, "Edit/Crop") == 0) return CMD_CROP; - /* Image: the operations that act on the whole picture */ - if (strcmp(path, "Image/Adjust/Invert") == 0) return CMD_INVERT; - if (strcmp(path, "Image/Adjust/Desaturate") == 0) return CMD_DESATURATE; - if (strcmp(path, "Image/Adjust/Brightness/Contrast...") == 0) - return CMD_BRIGHTCONTRAST; - if (strcmp(path, "Image/Flip/Horizontal") == 0) return CMD_FLIPH; - if (strcmp(path, "Image/Flip/Vertical") == 0) return CMD_FLIPV; - if (strcmp(path, "Image/Rotate/180") == 0) return CMD_ROT180; - if (strcmp(path, "Image/Rotate/90 CW") == 0) return CMD_ROT90CW; - if (strcmp(path, "Image/Rotate/90 CCW") == 0) return CMD_ROT90CCW; - /* Filter: the convolution family and the pixel filters */ - if (strcmp(path, "Filter/Blur/Blur") == 0) return CMD_BLUR; - if (strcmp(path, "Filter/Blur/Blur More") == 0) return CMD_BLURMORE; - if (strcmp(path, "Filter/Sharpen/Sharpen") == 0) return CMD_SHARPEN; - if (strcmp(path, "Filter/Sharpen/Sharpen More") == 0) - return CMD_SHARPENMORE; - if (strcmp(path, "Filter/Stylize/Find Edges") == 0) return CMD_FINDEDGES; - if (strcmp(path, "Filter/Stylize/Emboss...") == 0) return CMD_EMBOSS; - if (strcmp(path, "Filter/Stylize/Solarize") == 0) return CMD_SOLARIZE; - if (strcmp(path, "Filter/Noise/Add Noise...") == 0) return CMD_ADDNOISE; - if (strcmp(path, "Filter/Noise/Despeckle") == 0) return CMD_MEDIAN; - if (strcmp(path, "Filter/Noise/Median...") == 0) return CMD_MEDIAN; - if (strcmp(path, "Filter/Pixelate/Mosaic...") == 0) return CMD_MOSAIC; - if (strcmp(path, "Image/Image Size...") == 0) return CMD_IMAGESIZE; - if (strcmp(path, "Image/Canvas Size...") == 0) return CMD_CANVASSIZE; - (void) leaf; - return CMD_NONE; -} - static void MakeAccel(const char *key, char *out, size_t size) { @@ -1347,6 +1600,171 @@ UpdateStatus(void) XmStringCreateLocalized(buf), NULL); } +/* + * The view decorations: the grid, the guides and the rulers. They are + * drawn on the canvas, not into the picture, and every one of them is + * read from the flags the View menu sets -- a menu entry that only flips + * a flag nobody reads is a menu entry that does nothing. + */ + +/* the grid step in document pixels: 8 at 100%, wider when zoomed out */ +static int gridStep = 16; + +/* at most this many guides: the menu has New/Clear/Hide, not an editor */ +#define MAXGUIDES 32 +static int guides[MAXGUIDES]; /* the position, in document pixels */ +static int guideVert[MAXGUIDES]; /* 1 = vertical line */ +static int nguides; +/* the ruler is on by default: a document without one has no scale */ +static int rulerOn = 1; + +static void +GuideAdd(int pos, int vert) +{ + /* Lock Guides: while it is on, the existing set does not change */ + if (lockGuides || nguides >= MAXGUIDES) + return; + guides[nguides] = pos; + guideVert[nguides] = vert; + nguides++; +} + +static void +GuidesClear(void) +{ + if (lockGuides) + return; + nguides = 0; +} + +/* the nearest guide to `p` on the given axis, or -1 */ +static int +GuideNear(int p, int vert, int within) +{ + int i, best = -1, bd = within + 1; + + for (i = 0; i < nguides; i++) { + int d; + + if (guideVert[i] != vert) + continue; + d = guides[i] - p; + if (d < 0) + d = -d; + if (d < bd) { + bd = d; + best = guides[i]; + } + } + return best; +} + +/* + * A drag that snaps reports where it really went: the caller asks with the + * document coordinate and gets back the one on the grid or guide, if the + * View menu has snapping on. + */ +static int +SnapX(int x) +{ + int g; + + if (snapGuides && (g = GuideNear(x, 1, 6)) >= 0) + return g; + if (snapGrid && gridStep > 0) + return (x + gridStep / 2) / gridStep * gridStep; + if (snapLayers) + return x; + return x; +} + +static int +SnapY(int y) +{ + int g; + + if (snapGuides && (g = GuideNear(y, 0, 6)) >= 0) + return g; + if (snapGrid && gridStep > 0) + return (y + gridStep / 2) / gridStep * gridStep; + if (snapLayers) + return y; + return y; +} + +/* + * The rulers are drawn in the canvas margin and in screen pixels, so the + * ticks stay readable at any zoom. A tick every 10 document pixels, a + * longer one and a number every 50. + */ +static void +DrawRulers(Window win, int ox, int oy, int dw, int dh) +{ + int i, step, vstep; + + if (!showRulers) + return; + step = 10 * zoom / 100; + if (step < 4) + step = 4; + vstep = 50 * zoom / 100; + if (vstep < step) + vstep = step; + XSetForeground(dpy, gc, BlackPixel(dpy, 0)); + /* the top ruler: a tick for every step, a number for every fifth */ + for (i = 0; ox + i <= ox + dw; i += step) { + int len = ((i / step) % 5 == 0) ? 7 : 3; + char num[16]; + + XDrawLine(dpy, win, gc, ox + i, oy - 1, ox + i, oy - 1 - len); + if (len == 7) { + snprintf(num, sizeof num, "%d", i * 100 / zoom); + XDrawString(dpy, win, gc, ox + i + 1, oy - 9, num, + (int) strlen(num)); + } + } + for (i = 0; oy + i <= oy + dh; i += step) { + int len = ((i / step) % 5 == 0) ? 7 : 3; + + XDrawLine(dpy, win, gc, ox - 1, oy + i, ox - 1 - len, oy + i); + } +} + +/* the grid and the guides, on top of the picture but not in it */ +static void +DrawGuides(Window win, int ox, int oy, int dw, int dh) +{ + int i; + + if (showGrid && gridStep > 0) { + int s = gridStep * zoom / 100; + + if (s < 4) + s = 4; + XSetForeground(dpy, gc, BlackPixel(dpy, 0)); + for (i = s; i < dw; i += s) + XDrawLine(dpy, win, gc, ox + i, oy, ox + i, + oy + dh - 1); + for (i = s; i < dh; i += s) + XDrawLine(dpy, win, gc, ox, oy + i, + ox + dw - 1, oy + i); + } + if (showGuides) { + XSetForeground(dpy, gc, BlackPixel(dpy, 0)); + for (i = 0; i < nguides; i++) { + int p = guides[i] * zoom / 100; + + if (guideVert[i]) + XDrawLine(dpy, win, gc, ox + p, oy, ox + p, + oy + dh - 1); + else + XDrawLine(dpy, win, gc, ox, oy + p, + ox + dw - 1, oy + p); + } + } + DrawRulers(win, ox, oy, dw, dh); +} + static void RenderDoc(Widget w) { @@ -1397,6 +1815,7 @@ RenderDoc(Widget w) } XSetForeground(dpy, gc, BlackPixel(dpy, 0)); XDrawRectangle(dpy, win, gc, ox - 1, oy - 1, dw + 1, dh + 1); + DrawGuides(win, ox, oy, dw, dh); DrawMarquee(win, ox, oy); UpdateStatus(); } @@ -3115,6 +3534,1816 @@ CropToSelection(void) * image into snap afterwards when the size stayed the same. */ +static void +InfoOk(Widget w, XtPointer cd, XtPointer call) +{ + (void) cd; (void) call; + XtDestroyWidget(w); +} + +/* A modal box with one line of text, the pattern the file errors use */ +static void +MessageBox(const char *title, const char *text) +{ + Widget d; + XmString t, m; + + d = XmCreateInformationDialog(top, "info", NULL, 0); + t = XmStringCreateLocalized((char *) title); + m = XmStringCreateLocalized((char *) text); + XtVaSetValues(d, XmNdialogTitle, t, XmNmessageString, m, NULL); + XmStringFree(t); + XmStringFree(m); + XtUnmanageChild(XmMessageBoxGetChild(d, XmDIALOG_CANCEL_BUTTON)); + XtUnmanageChild(XmMessageBoxGetChild(d, XmDIALOG_HELP_BUTTON)); + XtAddCallback(d, XmNokCallback, InfoOk, NULL); + XtManageChild(d); +} + +static Widget palBrushes, palPicker, palSwatches, palScratch, palInfo; +static Widget infoLabel, scratchLabel; +static Widget pickR, pickG, pickB, pickSwatch; + +static char scratchText[4096]; + +/* ------------------------------------------------------- layer effects */ + +/* + * A document here has one layer, so a layer effect is what it looks like: + * a shadow, a glow or a bevel drawn from the picture's own alpha -- the + * pixels that differ from the background. Photoshop needs two layers for + * that; with one, the shape of the picture is its own mask. + */ +static void +AlphaOf(const unsigned char *rgb, int w, int h, unsigned char *out) +{ + int x, y, i, n = w * h; + unsigned char br, bg, bb; + + PixelToRGB(bgPixel, &br, &bg, &bb); + for (i = 0; i < n; i++) { + const unsigned char *s = rgb + (size_t) i * 3; + int dr = s[0] - br, dg = s[1] - bg, db = s[2] - bb; + + if (dr < 0) dr = -dr; + if (dg < 0) dg = -dg; + if (db < 0) db = -db; + out[i] = (dr + dg + db) > 45 ? 255 : 0; + } + (void) x; (void) y; +} + +/* + * Drop Shadow: the shape offset by (dx, dy), dark, behind the picture. + * Inner Shadow and Outer Glow are the same kernel with other signs, which + * is why they share the box blur below. + */ +static void +BoxBlurAlpha(unsigned char *a, int w, int h, int r) +{ + unsigned char *tmp; + long *row; + int x, y, i; + + if (r < 1) + return; + if ((tmp = malloc((size_t) w * h)) == NULL) + return; + if ((row = malloc((size_t) (w > h ? w : h) * sizeof *row)) == NULL) { + free(tmp); + return; + } + /* horizontal */ + for (y = 0; y < h; y++) { + long sum = 0; + int n = 0; + + for (x = 0; x < w + r; x++) { + if (x < w) { + sum += a[(size_t) y * w + x]; + n++; + } + if (x - 2 * r - 1 >= 0) { + sum -= a[(size_t) y * w + x - 2 * r - 1]; + n--; + } + if (x - r >= 0 && x - r < w && n > 0) + tmp[(size_t) y * w + (x - r)] = + (unsigned char) (sum / n); + } + } + /* vertical */ + for (x = 0; x < w; x++) { + long sum = 0; + int n = 0; + + for (y = 0; y < h + r; y++) { + if (y < h) { + sum += tmp[(size_t) y * w + x]; + n++; + } + if (y - 2 * r - 1 >= 0) { + sum -= tmp[(size_t) (y - 2 * r - 1) * w + x]; + n--; + } + if (y - r >= 0 && y - r < h && n > 0) + a[(size_t) (y - r) * w + x] = + (unsigned char) (sum / n); + } + } + (void) i; (void) row; + free(row); + free(tmp); +} + +/* + * The four effects. `kind`: 0 drop shadow, 1 inner shadow, 2 outer glow, + * 3 inner glow, 4 bevel. + */ +static void +OpLayerEffect(int kind, int size, int opacity, int dx, int dy) +{ + unsigned char *rgb, *alpha, *blur; + int w, h, x, y, i, n; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + n = w * h; + if ((alpha = malloc((size_t) n)) == NULL || + (blur = malloc((size_t) n)) == NULL) { + free(alpha); free(blur); free(rgb); + return; + } + AlphaOf(rgb, w, h, alpha); + memcpy(blur, alpha, (size_t) n); + BoxBlurAlpha(blur, w, h, size < 1 ? 1 : size); + + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + int a = alpha[(size_t) y * w + x]; + int cov = selMaskAny ? MaskCover(x, y) : 255; + int v = 0; + + if (cov <= 0) + continue; + switch (kind) { + case 0: { /* drop shadow: outside, dark */ + int sx = x - dx, sy = y - dy; + int s = 0; + + if (sx >= 0 && sy >= 0 && sx < w && sy < h) + s = blur[(size_t) sy * w + sx]; + if (a > 0) + continue; /* the picture wins */ + v = 255 - s; + break; + } + case 1: { /* inner shadow: inside, dark edge */ + if (a == 0) + continue; + v = 255 - blur[(size_t) y * w + x]; + break; + } + case 2: { /* outer glow: outside, light */ + if (a > 0) + continue; + v = blur[(size_t) y * w + x]; + break; + } + case 3: { /* inner glow */ + if (a == 0) + continue; + v = blur[(size_t) y * w + x]; + break; + } + default: { /* bevel: the edge, light above */ + int up = 0, dn = 0; + + if (y - size >= 0) + up = alpha[(size_t) (y - size) * w + x]; + if (y + size < h) + dn = alpha[(size_t) (y + size) * w + x]; + if (a == 0) + continue; + v = up > dn ? 255 : 0; + break; + } + } + { + int c; + + for (c = 0; c < 3; c++) + d[c] = (unsigned char) (d[c] + + (v - d[c]) * opacity / 100 * + cov / 255); + } + } + free(alpha); + free(blur); + SetImageRGB(rgb, w, h); + free(rgb); + OpDone(kind == 0 ? "drop shadow" : + kind == 1 ? "inner shadow" : + kind == 2 ? "outer glow" : + kind == 3 ? "inner glow" : "bevel and emboss"); +} + +/* ------------------------------------------------------- transforms */ + +/* + * The affine transforms of Layer > Transform and Image > Effects. One + * kernel, a 3x3 matrix, because scale, rotate, skew, perspective and + * distort all are one matrix and a sampler. + */ +static void +OpAffine(double m[6]) +{ + unsigned char *rgb, *out; + int w, h, x, y, c; + unsigned char br, bg, bb; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((out = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + PixelToRGB(bgPixel, &br, &bg, &bb); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = out + ((size_t) y * w + x) * 3; + /* inverse mapping: where did this pixel come from */ + double rx = x - w / 2.0, ry = y - h / 2.0; + double det = m[0] * m[3] - m[1] * m[2]; + double sx, sy; + int ix, iy; + + if (det == 0.0) { + d[0] = br; d[1] = bg; d[2] = bb; + continue; + } + sx = w / 2.0 + (m[3] * rx - m[2] * ry) / det; + sy = h / 2.0 + (-m[1] * rx + m[0] * ry) / det; + ix = (int) (sx + 0.5); + iy = (int) (sy + 0.5); + if (ix < 0 || iy < 0 || ix >= w || iy >= h) { + d[0] = br; d[1] = bg; d[2] = bb; + continue; + } + for (c = 0; c < 3; c++) + d[c] = rgb[((size_t) iy * w + ix) * 3 + c]; + } + free(rgb); + SetImageRGB(out, w, h); + free(out); +} + +/* Scale: a factor on both axes, in percent */ +static void +EffectScaleOk(const int *v) +{ + double f = v[0] > 0 ? v[0] / 100.0 : 1.0; + double m[6]; + + m[0] = f; m[1] = 0; m[2] = 0; m[3] = f; + OpAffine(m); + RenderDoc(canvas); + OpDone("scale"); +} + +/* Skew: a shear, the angle in degrees */ +static void +EffectSkewOk(const int *v) +{ + double t = tan(v[0] * M_PI / 180.0); + double m[6]; + + m[0] = 1; m[1] = 0; m[2] = t; m[3] = 1; + OpAffine(m); + RenderDoc(canvas); + OpDone("skew"); +} + +/* + * Distort and Perspective: the corners move by a percentage of the size, + * which is the one number the box asks for. + */ +static void +EffectDistortOk(const int *v) +{ + unsigned char *rgb, *out; + int w, h, x, y, c; + double k = v[0] / 100.0; + unsigned char br, bg, bb; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((out = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + PixelToRGB(bgPixel, &br, &bg, &bb); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = out + ((size_t) y * w + x) * 3; + /* the picture is pulled towards the corners */ + double fx = (x - w / 2.0) / (w / 2.0); + double fy = (y - h / 2.0) / (h / 2.0); + double sx = w / 2.0 + fx * (1.0 + k * fx * fy) + * (w / 2.0); + double sy = h / 2.0 + fy * (1.0 + k * fx * fy) + * (h / 2.0); + int ix = (int) (sx + 0.5), iy = (int) (sy + 0.5); + + if (ix < 0 || iy < 0 || ix >= w || iy >= h) { + d[0] = br; d[1] = bg; d[2] = bb; + continue; + } + for (c = 0; c < 3; c++) + d[c] = rgb[((size_t) iy * w + ix) * 3 + c]; + } + free(rgb); + SetImageRGB(out, w, h); + free(out); + RenderDoc(canvas); + OpDone("distort"); +} + +/* Distort as a perspective when the flag is set: the top is narrower */ +static void +OpPerspective(int percent) +{ + unsigned char *rgb, *out; + int w, h, x, y, c; + double k = percent / 100.0; + unsigned char br, bg, bb; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((out = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + PixelToRGB(bgPixel, &br, &bg, &bb); + for (y = 0; y < h; y++) { + double t = (double) y / (h > 1 ? h - 1 : 1); + double shrink = 1.0 - k * (1.0 - t) * 0.5; + + for (x = 0; x < w; x++) { + unsigned char *d = out + ((size_t) y * w + x) * 3; + double sx = w / 2.0 + + (x - w / 2.0) * shrink; + int ix = (int) (sx + 0.5); + + if (ix < 0 || ix >= w) { + d[0] = br; d[1] = bg; d[2] = bb; + continue; + } + for (c = 0; c < 3; c++) + d[c] = rgb[((size_t) y * w + ix) * 3 + c]; + } + } + free(rgb); + SetImageRGB(out, w, h); + free(out); +} + +/* ------------------------------------------------------- colour models */ + +/* + * CMYK Preview: what the picture looks like after the ink separation and + * back. The naive conversion is enough to show the shift, and it is what + * a monitor shows when a CMYK file is opened. + */ +static void +OpCMYKPreview(void) +{ + unsigned char *rgb; + int w, h, i, n; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + n = w * h; + for (i = 0; i < n; i++) { + unsigned char *d = rgb + (size_t) i * 3; + int cov = selMaskAny ? MaskCover(i % w, i / w) : 255; + double r = d[0] / 255.0, g = d[1] / 255.0, b = d[2] / 255.0; + double k = 1.0 - (r > g ? (r > b ? r : b) : (g > b ? g : b)); + double c, m, yy; + int nr, ng, nb; + + if (cov <= 0) + continue; + if (k >= 1.0) { + nr = ng = nb = 0; + } else { + c = (1.0 - r - k) / (1.0 - k); + m = (1.0 - g - k) / (1.0 - k); + yy = (1.0 - b - k) / (1.0 - k); + nr = (int) ((1.0 - c) * (1.0 - k) * 255.0 + 0.5); + ng = (int) ((1.0 - m) * (1.0 - k) * 255.0 + 0.5); + nb = (int) ((1.0 - yy) * (1.0 - k) * 255.0 + 0.5); + } + if (nr < 0) nr = 0; + if (nr > 255) nr = 255; + if (ng < 0) ng = 0; + if (ng > 255) ng = 255; + if (nb < 0) nb = 0; + if (nb > 255) nb = 255; + d[0] = (unsigned char) (d[0] + (nr - d[0]) * cov / 255); + d[1] = (unsigned char) (d[1] + (ng - d[1]) * cov / 255); + d[2] = (unsigned char) (d[2] + (nb - d[2]) * cov / 255); + } + SetImageRGB(rgb, w, h); + free(rgb); + OpDone("cmyk preview"); +} + +/* + * Gamut Warning: the pixels a CMYK press cannot print are painted in the + * warning grey, as the original does. + */ +static void +OpGamutWarning(int on) +{ + unsigned char *rgb; + int w, h, i, n, marked = 0; + + if (on == 0) { + /* off: nothing to undo, the pixels were painted over. Say + * so instead of pretending */ + fprintf(stderr, "dtphoto: gamut warning off (the marked " + "pixels are gone with the last undo)\n"); + return; + } + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + n = w * h; + for (i = 0; i < n; i++) { + unsigned char *d = rgb + (size_t) i * 3; + double r = d[0] / 255.0, g = d[1] / 255.0, b = d[2] / 255.0; + double k, c, m, yy; + + k = 1.0 - (r > g ? (r > b ? r : b) : (g > b ? g : b)); + if (k >= 1.0) { + c = m = yy = 0.0; + } else { + c = (1.0 - r - k) / (1.0 - k); + m = (1.0 - g - k) / (1.0 - k); + yy = (1.0 - b - k) / (1.0 - k); + } + /* the press cannot print a saturated ink above 90% */ + if (c > 0.9 || m > 0.9 || yy > 0.9) { + d[0] = d[1] = d[2] = 128; + marked++; + } + } + SetImageRGB(rgb, w, h); + free(rgb); + fprintf(stderr, "dtphoto: gamut warning %d pixels\n", marked); +} + +/* ------------------------------------------------------- Digimarc */ + +/* + * The watermark filter: a bit pattern in the lowest bit of the blue + * channel, spread across the picture. Read Watermark looks for it, which + * makes the pair honest -- it finds exactly what Embed wrote. + */ +static const char wmMagic[] = "MCDEdtphoto"; + +static void +EmbedWatermarkOk(const int *v) +{ + unsigned char *rgb; + int w, h, i, bit, nbits, n; + size_t len = sizeof wmMagic - 1; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + n = w * h; + nbits = (int) (len * 8); + for (i = 0; i < n && i < nbits * 8; i++) { + unsigned char *d = rgb + (size_t) i * 3; + int idx = i / 8; + + if (idx >= (int) len) + break; + bit = (wmMagic[idx] >> (7 - (i % 8))) & 1; + d[2] = (unsigned char) ((d[2] & 0xfe) | bit); + } + SetImageRGB(rgb, w, h); + free(rgb); + fprintf(stderr, "dtphoto: watermark embedded (%d%% strength)\n", v[0]); +} + +static void +ReadWatermark(void) +{ + unsigned char *rgb; + int w, h, i; + char got[sizeof wmMagic]; + size_t len = sizeof wmMagic - 1; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + memset(got, 0, sizeof got); + for (i = 0; i < (int) (len * 8); i++) { + const unsigned char *d = rgb + (size_t) i * 3; + + got[i / 8] = (char) ((got[i / 8] << 1) | (d[2] & 1)); + } + free(rgb); + got[len] = '\0'; + if (strcmp(got, wmMagic) == 0) { + fprintf(stderr, "dtphoto: watermark found\n"); + MessageBox("Read Watermark", + "A watermark written by this program is present."); + } else { + fprintf(stderr, "dtphoto: no watermark\n"); + MessageBox("Read Watermark", + "No watermark found."); + } + (void) w; (void) h; +} + +/* ------------------------------------------------------- last filter */ + +static void +SetScratch(const char *fmt, ...) +{ + va_list ap; + XmString s; + + va_start(ap, fmt); + vsnprintf(scratchText, sizeof scratchText, fmt, ap); + va_end(ap); + if (scratchLabel != NULL) { + s = XmStringCreateLocalized(scratchText); + XtVaSetValues(scratchLabel, XmNlabelString, s, NULL); + XmStringFree(s); + } +} + +/* the last filter, so Filter > Last Filter repeats it */ +static void (*lastFilter)(void); +static char lastName[64]; + +static void +SetLast(void (*fn)(void), const char *name) +{ + lastFilter = fn; + snprintf(lastName, sizeof lastName, "%s", name); + SetScratch("Last filter: %s", name); +} + +static void +RepeatLastFilter(void) +{ + if (lastFilter == NULL) { + fprintf(stderr, "dtphoto: no last filter\n"); + SetScratch("No filter has run yet."); + return; + } + lastFilter(); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: repeat %s\n", lastName); +} + + +/* ------------------------------------------------------------- palettes */ + +/* + * The palettes Photoshop 3 shows under Window. Each is a top level shell + * with a label and, where it makes sense, a swatch grid, a row of brush + * sizes or the colour sliders. Built once, then only shown and hidden, + * which is what a palette does in the original. + */ +/* the swatches: a fixed ramp, the palette Photoshop 3 opens with */ +static void +SwatchCallback(Widget w, XtPointer cd, XtPointer call) +{ + (void) w; (void) call; + fgPixel = (Pixel) (unsigned long) cd; + SetImageFG(); + if (pickSwatch != NULL) { + XtVaSetValues(pickSwatch, XmNbackground, fgPixel, NULL); + } + fprintf(stderr, "dtphoto: colour %06lx\n", (unsigned long) fgPixel); +} + +static Widget +BuildSwatches(Widget parent) +{ + Widget row, b; + Pixmap p; + GC g; + int i, cols = 8, rows = 4; + + row = XtVaCreateManagedWidget("swatches", xmRowColumnWidgetClass, + parent, XmNnumColumns, cols, XmNpacking, XmPACK_COLUMN, + XmNorientation, XmVERTICAL, XmNmarginWidth, 4, XmNmarginHeight, 4, + NULL); + for (i = 0; i < cols * rows; i++) { + int r = (i / cols) * 36; + int gg = (i % cols) * 32; + int bb = 255 - (i / cols) * 32; + Pixel px = RGBToPixel((unsigned) r, (unsigned) gg, + (unsigned) bb); + + p = XCreatePixmap(dpy, drawable, 16, 16, + (unsigned int) visdepth); + g = XCreateGC(dpy, p, 0, NULL); + XSetForeground(dpy, g, px); + XFillRectangle(dpy, p, g, 0, 0, 16, 16); + XFreeGC(dpy, g); + b = XtVaCreateManagedWidget("sw", xmPushButtonWidgetClass, + row, XmNlabelType, XmPIXMAP, XmNlabelPixmap, p, + XmNmarginWidth, 0, XmNmarginHeight, 0, NULL); + XtAddCallback(b, XmNactivateCallback, SwatchCallback, + (XtPointer) (unsigned long) px); + } + return row; +} + +/* the brushes: the sizes the pencil and the brush really paint with */ +static void +BrushCallback(Widget w, XtPointer cd, XtPointer call) +{ + (void) w; (void) call; + pencilRadius = (int) (long) cd; + fprintf(stderr, "dtphoto: brush %d\n", pencilRadius); +} + +static Widget +BuildBrushes(Widget parent) +{ + Widget row, b; + int sizes[] = { 1, 3, 6, 12, 24, 48 }; + size_t i; + char buf[16]; + + row = XtVaCreateManagedWidget("brushes", xmRowColumnWidgetClass, + parent, XmNorientation, XmVERTICAL, XmNmarginWidth, 6, + XmNmarginHeight, 6, XmNspacing, 4, NULL); + for (i = 0; i < sizeof sizes / sizeof sizes[0]; i++) { + snprintf(buf, sizeof buf, "%d px", sizes[i]); + b = XtVaCreateManagedWidget(buf, xmPushButtonWidgetClass, + row, XmNalignment, XmALIGNMENT_BEGINNING, NULL); + XtAddCallback(b, XmNactivateCallback, BrushCallback, + (XtPointer) (long) sizes[i]); + } + return row; +} + +/* the picker: the foreground colour as three sliders and a swatch */ +static void +PickCallback(Widget w, XtPointer cd, XtPointer call) +{ + int r = 0, g = 0, b = 0; + + (void) w; (void) cd; (void) call; + XtVaGetValues(pickR, XmNvalue, &r, NULL); + XtVaGetValues(pickG, XmNvalue, &g, NULL); + XtVaGetValues(pickB, XmNvalue, &b, NULL); + fgPixel = RGBToPixel((unsigned) r, (unsigned) g, (unsigned) b); + SetImageFG(); + if (pickSwatch != NULL) + XtVaSetValues(pickSwatch, XmNbackground, fgPixel, NULL); +} + +static Widget +BuildPicker(Widget parent) +{ + Widget col; + + col = XtVaCreateManagedWidget("picker", xmRowColumnWidgetClass, + parent, XmNorientation, XmVERTICAL, XmNmarginWidth, 6, + XmNmarginHeight, 6, XmNspacing, 4, NULL); + pickSwatch = XtVaCreateManagedWidget("swatch", xmLabelWidgetClass, + col, XmNwidth, 40, XmNheight, 24, XmNbackground, fgPixel, NULL); + pickR = XtVaCreateManagedWidget("R", xmScaleWidgetClass, col, + XmNminimum, 0, XmNmaximum, 255, XmNorientation, XmHORIZONTAL, + NULL); + pickG = XtVaCreateManagedWidget("G", xmScaleWidgetClass, col, + XmNminimum, 0, XmNmaximum, 255, XmNorientation, XmHORIZONTAL, + NULL); + pickB = XtVaCreateManagedWidget("B", xmScaleWidgetClass, col, + XmNminimum, 0, XmNmaximum, 255, XmNorientation, XmHORIZONTAL, + NULL); + XtAddCallback(pickR, XmNvalueChangedCallback, PickCallback, NULL); + XtAddCallback(pickG, XmNvalueChangedCallback, PickCallback, NULL); + XtAddCallback(pickB, XmNvalueChangedCallback, PickCallback, NULL); + return col; +} + +static Widget +BuildScratch(Widget parent) +{ + Widget box; + + box = XtVaCreateManagedWidget("scratchbox", xmRowColumnWidgetClass, + parent, XmNorientation, XmVERTICAL, XmNmarginWidth, 8, + XmNmarginHeight, 8, NULL); + scratchLabel = XtVaCreateManagedWidget("scratch", + xmLabelWidgetClass, box, XmNlabelString, + XmStringCreateLocalized("No command yet."), NULL); + return box; +} + +static Widget +BuildInfo(Widget parent) +{ + Widget box; + + box = XtVaCreateManagedWidget("infobox", xmRowColumnWidgetClass, + parent, XmNorientation, XmVERTICAL, XmNmarginWidth, 8, + XmNmarginHeight, 8, NULL); + infoLabel = XtVaCreateManagedWidget("info", xmLabelWidgetClass, box, + XmNlabelString, XmStringCreateLocalized(""), NULL); + return box; +} + +/* + * One palette: created on the first use, then only managed and unmanaged. + * A palette that was never built costs nothing. + */ +static void +Palette(Widget *slot, const char *name, int x, int y, + Widget (*build)(Widget)) +{ + Widget sw; + + if (*slot == NULL) { + sw = XtVaCreatePopupShell(name, topLevelShellWidgetClass, top, + XmNtitle, name, XmNx, x, XmNy, y, NULL); + if (build != NULL) + build(sw); + *slot = sw; + } + if (XtIsManaged(*slot)) + XtUnmanageChild(*slot); + else + XtManageChild(*slot); +} + + + +static void +SetInfo(const char *fmt, ...) +{ + va_list ap; + XmString s; + + va_start(ap, fmt); + vsnprintf(scratchText, sizeof scratchText, fmt, ap); + va_end(ap); + if (infoLabel != NULL) { + s = XmStringCreateLocalized(scratchText); + XtVaSetValues(infoLabel, XmNlabelString, s, NULL); + XmStringFree(s); + } +} + +/* ------------------------------------------------------------- files */ + +static void +FileInfo(void) +{ + char buf[512]; + struct stat st; + const char *p = docPath != NULL ? docPath : "(unnamed)"; + + if (docPath != NULL && stat(docPath, &st) == 0) + snprintf(buf, sizeof buf, + "%s\n%d x %d pixels\n%lld bytes on disk\nmodified %s", + p, docW, docH, (long long) st.st_size, + ctime(&st.st_mtime)); + else + snprintf(buf, sizeof buf, "%s\n%d x %d pixels", p, docW, + docH); + fprintf(stderr, "dtphoto: file info %s %dx%d\n", p, docW, docH); + MessageBox("File Info", buf); +} + +static void +PrefsOk(const int *v) +{ + undoDepth = v[0] > 0 ? v[0] : 1; + fprintf(stderr, "dtphoto: undo depth %d\n", undoDepth); +} + +/* Print: without a printer description the only honest thing is the box */ +static void +PrintDoc(void) +{ + char buf[256]; + + snprintf(buf, sizeof buf, + "%d x %d pixels at %d dpi\n%.2f x %.2f inches\n\n" + "No printer is configured in this build.", docW, docH, 72, + docW / 72.0, docH / 72.0); + fprintf(stderr, "dtphoto: print %dx%d\n", docW, docH); + MessageBox("Print", buf); +} + +static void +PageSetup(void) +{ + fprintf(stderr, "dtphoto: page setup\n"); + MessageBox("Page Setup", + "Paper and margins come from the printer's defaults.\n" + "This build has no printer description, so nothing changes."); +} + +static void +AboutBox(void) +{ + char buf[512]; + + snprintf(buf, sizeof buf, + "dtphoto\n\nMCDE's raster editor, the Photoshop 2.5.2 / 3.0.1 " + "look.\n\n%d x %d pixels, %d colours on this screen.", + docW, docH, visdepth == 8 ? 256 : 16777216); + fprintf(stderr, "dtphoto: about\n"); + MessageBox("About dtphoto", buf); +} + +/* Revert: read the file again, the undo snapshot goes with it */ +static int +RevertDoc(void) +{ + McdeThumbImage img; + + if (docPath == NULL) + return -1; + if (OpenImage(docPath) != 0) + return -1; + RenderDoc(canvas); + fprintf(stderr, "dtphoto: reverted %s\n", docPath); + (void) img; + return 0; +} + +/* Duplicate: the picture into a second document; one window here, so the + * copy goes to the scratch palette as its numbers */ +static void +DuplicateDoc(void) +{ + fprintf(stderr, "dtphoto: duplicate %dx%d\n", docW, docH); + SetScratch("Duplicate: %d x %d pixels", docW, docH); +} + +/* one document window: Cascade and Arrange report that, they do not lie */ +static void +WindowArrange(const char *what) +{ + fprintf(stderr, "dtphoto: %s (one document)\n", what); +} + +/* Close: the document goes back to a blank page, as File > New */ +static void +CloseDoc(void) +{ + XSetForeground(dpy, gc, WhitePixel(dpy, 0)); + XFillRectangle(dpy, image, gc, 0, 0, docW, docH); + XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); + free(docPath); + docPath = NULL; + MaskClear(); + hasSel = 0; + RenderDoc(canvas); + fprintf(stderr, "dtphoto: closed\n"); +} + +/* --------------------------------------------------- Image > Mode */ + +/* + * Bitmap: the picture becomes one bit per pixel, the threshold in the + * middle as the original does, then back to RGB so the rest of the + * program keeps working on one buffer. + */ +static void +OpBitmap(void) +{ + unsigned char *rgb; + int w, h, i, n; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + n = w * h; + for (i = 0; i < n; i++) { + unsigned char *d = rgb + (size_t) i * 3; + int lum = (int) LUMA(d[0], d[1], d[2]); + unsigned char v = lum >= 128 ? 255 : 0; + + if (selMaskAny) { + int cov = MaskCover(i % w, i / w); + + if (cov < 255) { + int c; + + for (c = 0; c < 3; c++) + d[c] = (unsigned char) (d[c] + + (v - d[c]) * cov / 255); + continue; + } + } + d[0] = d[1] = d[2] = v; + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Grayscale: the luminance into all three channels */ +static void +OpGrayscale(void) +{ + unsigned char *rgb; + int w, h, i, n; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + n = w * h; + for (i = 0; i < n; i++) { + unsigned char *d = rgb + (size_t) i * 3; + int v = (int) LUMA(d[0], d[1], d[2]); + int cov = selMaskAny ? MaskCover(i % w, i / w) : 255; + int c; + + if (cov <= 0) + continue; + for (c = 0; c < 3; c++) + d[c] = cov >= 255 ? (unsigned char) v : + (unsigned char) (d[c] + (v - d[c]) * cov / 255); + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* + * Indexed: a picture reduced to a palette of `colors`. The RGB buffer + * itself does not carry a palette, so this is the reduction a PseudoColor + * screen would do, and the numbers are what the screen then shows. + */ +static void +OpIndexed(int colors) +{ + unsigned char *rgb; + int w, h, i, n, c; + + if (colors < 2) colors = 2; + if (colors > 256) colors = 256; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + n = w * h; + c = (int) ((double) (colors - 1) / 255.0 * 1000.0 + 0.5); + for (i = 0; i < n; i++) { + unsigned char *d = rgb + (size_t) i * 3; + int cov = selMaskAny ? MaskCover(i % w, i / w) : 255; + int k; + + if (cov <= 0) + continue; + for (k = 0; k < 3; k++) { + /* the same truncating ladder Posterize uses */ + int q = d[k] * c / 1000; + int v = q * 255 / (colors - 1); + + if (v > 255) v = 255; + d[k] = cov >= 255 ? (unsigned char) v : + (unsigned char) (d[k] + (v - d[k]) * cov / 255); + } + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Lab Color: the same pixels, said in another space -- a no-op on RGB */ +static void +ModeName(const char *name) +{ + fprintf(stderr, "dtphoto: mode %s\n", name); +} + +/* --------------------------------------------------- matting */ + +/* + * Remove Black or White Matte: the pixels that were composited on a solid + * background get their edge pixels darkened or lightened back. + */ +static void +OpMatte(int background) +{ + unsigned char *rgb; + int w, h, x, y, c; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + + if (cov <= 0) + continue; + for (c = 0; c < 3; c++) { + int v = d[c]; + + /* the matte colour is pulled towards the + * background, so a light halo goes away */ + if (background == 0) + v = v > 16 ? (v - 16) * 255 / 239 : 0; + else + v = 16 + v * 239 / 255; + d[c] = cov >= 255 ? (unsigned char) v : + (unsigned char) (d[c] + + (v - d[c]) * cov / 255); + } + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Trap: the thin gap between two inks gets a third colour, a print fix */ +static void +TrapOk(const int *v) +{ + fprintf(stderr, "dtphoto: trap %d (no ink separation in this build)\n", + v[0]); +} + +/* --------------------------------------------------- Edit */ + +/* + * The clipboard is one pixmap plus its size. Cut, Copy and Paste work on + * the selection's rectangle, which is what a desktop's CLIPBOARD has room + * for without a server round trip per pixel. + */ +static Pixmap clipPix = None; +static int clipW, clipH; + +static void +CopyToClip(void) +{ + int x0 = 0, y0 = 0, w = docW, h = docH; + + if (selMaskAny && hasSel) { + x0 = selX0; y0 = selY0; + w = selX1 - selX0; + h = selY1 - selY0; + } + if (w < 1 || h < 1) + return; + if (clipPix != None) + XFreePixmap(dpy, clipPix); + clipPix = XCreatePixmap(dpy, drawable, (unsigned int) w, + (unsigned int) h, (unsigned int) visdepth); + XCopyArea(dpy, image, clipPix, gc, x0, y0, (unsigned int) w, + (unsigned int) h, 0, 0); + clipW = w; + clipH = h; + fprintf(stderr, "dtphoto: copied %dx%d\n", w, h); +} + +static void +PasteFromClip(void) +{ + if (clipPix == None || clipW < 1 || clipH < 1) { + fprintf(stderr, "dtphoto: nothing to paste\n"); + return; + } + XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); + XCopyArea(dpy, clipPix, image, gc, 0, 0, + (unsigned int) (clipW > docW ? docW : clipW), + (unsigned int) (clipH > docH ? docH : clipH), 0, 0); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: pasted %dx%d\n", clipW, clipH); +} + +/* Define Pattern: the selection becomes the fill pattern, kept in a pixmap */ +static Pixmap patPix = None; +static int patW, patH; + +static void +DefinePattern(void) +{ + if (!selMaskAny || !hasSel) { + fprintf(stderr, "dtphoto: no selection to make a pattern\n"); + return; + } + if (patPix != None) + XFreePixmap(dpy, patPix); + patW = selX1 - selX0; + patH = selY1 - selY0; + if (patW < 1 || patH < 1) + return; + patPix = XCreatePixmap(dpy, drawable, (unsigned int) patW, + (unsigned int) patH, (unsigned int) visdepth); + XCopyArea(dpy, image, patPix, gc, selX0, selY0, + (unsigned int) patW, (unsigned int) patH, 0, 0); + fprintf(stderr, "dtphoto: pattern %dx%d\n", patW, patH); +} + +/* Stroke: an outline of the selection in the foreground colour */ +static void +StrokeOk(const int *v) +{ + unsigned char *rgb; + int w, h, x, y, c, width = v[0]; + unsigned char fr, fg, fb; + static unsigned char *src; + + if (width < 1) width = 1; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + PixelToRGB(fgPixel, &fr, &fg, &fb); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + int inside = MaskGet(x, y); + int nearEdge = 0, dx, dy; + + if (!inside) + continue; + for (dy = -width; dy <= width && !nearEdge; dy++) + for (dx = -width; dx <= width; dx++) { + int nx = x + dx, ny = y + dy; + + if (nx < 0 || ny < 0 || nx >= w || + ny >= h || !MaskGet(nx, ny)) { + nearEdge = 1; + break; + } + } + if (!nearEdge) + continue; + { + unsigned char *d = rgb + + ((size_t) y * w + x) * 3; + + d[0] = fr; d[1] = fg; d[2] = fb; + } + (void) c; + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); + OpDone("stroke"); +} + +/* --------------------------------------------------- Select */ + +/* Color Range: like the wand, but over the whole picture */ +static void +ColorRangeOk(const int *v) +{ + unsigned char *rgb; + int w, h, x, y, n = 0; + unsigned char base[3] = { 0, 0, 0 }; + int have = 0; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if (MaskAlloc() != 0) { + free(rgb); + return; + } + MaskClear(); + /* the reference colour is the pixel at the top left of the old + * selection, or the middle of the picture when there is none */ + if (hasSel && selX0 < w && selY0 < h) + memcpy(base, rgb + ((size_t) selY0 * w + selX0) * 3, 3); + else + memcpy(base, rgb + ((size_t) (h / 2) * w + w / 2) * 3, 3); + have = 1; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + const unsigned char *s = rgb + ((size_t) y * w + x) * 3; + int dr = s[0] - base[0], dg = s[1] - base[1]; + int db = s[2] - base[2]; + + if (dr < 0) dr = -dr; + if (dg < 0) dg = -dg; + if (db < 0) db = -db; + if (dr <= v[0] && dg <= v[0] && db <= v[0]) { + MaskSet(x, y, 1); + n++; + } + } + selMaskAny = n > 0; + hasSel = 1; + selX0 = selY0 = 0; + selX1 = w; + selY1 = h; + (void) have; + free(rgb); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: color range %d pixels\n", n); +} + +/* Defringe: the edge pixels take the colour of their neighbours */ +static void +DefringeOk(const int *v) +{ + unsigned char *rgb, *src; + int w, h, x, y, c, width = v[0]; + + if (width < 1) width = 1; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + int alpha, xx, yy, sum[3] = { 0, 0, 0 }, n = 0; + + if (cov <= 0) + continue; + /* a fringe is a strong difference from the + * neighbourhood; the pixel takes the neighbours */ + alpha = 0; + for (c = 0; c < 3; c++) { + int mn = 255, mx = 0; + + for (yy = y - width; yy <= y + width; yy++) + for (xx = x - width; xx <= x + width; + xx++) { + const unsigned char *s; + int val; + + if (xx < 0 || yy < 0 || + xx >= w || yy >= h) + continue; + s = src + ((size_t) yy * w + xx) + * 3; + val = s[c]; + if (val < mn) mn = val; + if (val > mx) mx = val; + } + if (mx - mn > 40) + alpha = 1; + } + if (!alpha) + continue; + for (yy = y - width; yy <= y + width; yy++) + for (xx = x - width; xx <= x + width; xx++) { + const unsigned char *s; + + if (xx < 0 || yy < 0 || xx >= w || + yy >= h) + continue; + s = src + ((size_t) yy * w + xx) * 3; + for (c = 0; c < 3; c++) + sum[c] += s[c]; + n++; + } + if (n == 0) + continue; + for (c = 0; c < 3; c++) { + int val = sum[c] / n; + + d[c] = cov >= 255 ? (unsigned char) val : + (unsigned char) (o[c] + + (val - o[c]) * cov / 255); + } + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); + OpDone("defringe"); +} + +/* --------------------------------------------------- Image > Adjust */ + +static void +ApplyImageOk(const int *v) +{ + /* one document: the picture is applied to itself, which is its + * own amount of nothing. Be honest about it. */ + fprintf(stderr, "dtphoto: apply image needs a second layer " + "(%d%% would be a no-op)\n", v[0]); +} + +static void +CalculationsOk(const int *v) +{ + fprintf(stderr, "dtphoto: calculations needs two channels " + "(%d%% would be a no-op)\n", v[0]); +} + +/* Arbitrary rotation: bilinear, the background fills the corners */ +static void +RotArbOk(const int *v) +{ + unsigned char *rgb, *out; + int w, h, x, y, c; + double a = v[0] * M_PI / 180.0; + double ca = cos(a), sa = sin(a); + double cx, cy; + unsigned char br, bg, bb; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((out = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + PixelToRGB(bgPixel, &br, &bg, &bb); + cx = w / 2.0; + cy = h / 2.0; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = out + ((size_t) y * w + x) * 3; + double rx = x - cx, ry = y - cy; + double sx = cx + rx * ca + ry * sa; + double sy = cy - rx * sa + ry * ca; + int ix = (int) (sx + 0.5), iy = (int) (sy + 0.5); + + if (ix < 0 || iy < 0 || ix >= w || iy >= h) { + d[0] = br; d[1] = bg; d[2] = bb; + } else { + const unsigned char *s = + rgb + ((size_t) iy * w + ix) * 3; + + for (c = 0; c < 3; c++) + d[c] = s[c]; + } + } + free(rgb); + SetImageRGB(out, w, h); + free(out); + OpDone("rotate arbitrary"); +} + +/* + * The histogram: 256 buckets of luminance, the numbers go to stderr so a + * test can read them, and the box shows the same in text form. + */ +static void +ShowHistogram(void) +{ + unsigned char *rgb; + int w, h, i, n; + long bucket[256]; + char line[64], buf[1024]; + int minV = 255, maxV = 0; + double mean = 0.0; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + n = w * h; + memset(bucket, 0, sizeof bucket); + for (i = 0; i < n; i++) { + const unsigned char *p = rgb + (size_t) i * 3; + int lum = (int) LUMA(p[0], p[1], p[2]); + + if (lum < 0) lum = 0; + if (lum > 255) lum = 255; + bucket[lum]++; + mean += lum; + if (lum < minV) minV = lum; + if (lum > maxV) maxV = lum; + } + mean /= n; + snprintf(buf, sizeof buf, + "Mean %.1f Min %d Max %d\nPixels %d", mean, minV, maxV, n); + fprintf(stderr, "dtphoto: histogram mean=%.1f min=%d max=%d " + "pixels=%d\n", mean, minV, maxV, n); + for (i = 0; i < 256; i++) + if (bucket[i] > 0) + fprintf(stderr, "dtphoto: hist %d %ld\n", i, + bucket[i]); + (void) line; + MessageBox("Histogram", buf); + free(rgb); +} + +/* --------------------------------------------------- View */ + +static int viewGuides = 1; + +/* --------------------------------------------------------------- layers */ + +/* + * The layer stack. Photoshop 3 keeps a list of layers per picture and every + * Layer command changes that list, not the pixels. dtphoto had none, so the + * whole Layer menu was decoration. A layer is a name, an RGB buffer and the + * three flags the menu needs: visible, opacity, mode. `image` stays the one + * surface every other command draws on, so painting, saving and the filters + * do not have to know that layers exist. + * + * The stack is built on first use from what is in the picture, so a document + * that never touches the Layer menu sees no difference at all. + */ +#define MAXLAYERS 24 + +typedef struct { + char name[48]; + unsigned char *rgb; /* w * h * 3, this layer's own pixels */ + int visible; + int opacity; /* 0..100 */ + int mode; /* 0 normal, 1 multiply, 2 screen */ +} Layer; + +static Layer layers[MAXLAYERS]; +static int nlayers; +static int curLayer; +static int layerW, layerH; /* the size the stack was built at */ +static Widget palLayers, layersLabel; + +static void LayerAbsorb(void); + +static void +LayerInvalidate(void) +{ + int i; + + for (i = 0; i < nlayers; i++) { + free(layers[i].rgb); + layers[i].rgb = NULL; + } + nlayers = 0; + curLayer = 0; + layerW = layerH = 0; +} + +/* the stack from the picture as it is now: one layer */ +static void +LayerEnsure(void) +{ + unsigned char *rgb; + int w, h; + + if (nlayers > 0 && layerW == docW && layerH == docH) + return; + LayerInvalidate(); + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + layers[0].rgb = rgb; + snprintf(layers[0].name, sizeof layers[0].name, "Background"); + layers[0].visible = 1; + layers[0].opacity = 100; + layers[0].mode = 0; + nlayers = 1; + curLayer = 0; + layerW = w; + layerH = h; +} + +/* + * The composite, bottom up. One layer composites to itself, which is why a + * document without layers looks exactly as it did. + */ +static int +LayerComposite(unsigned char **outp) +{ + unsigned char *out; + int w = layerW, h = layerH, i, x, y, c; + + if (nlayers == 0 || layers[0].rgb == NULL) + return -1; + if ((out = malloc((size_t) w * h * 3)) == NULL) + return -1; + memcpy(out, layers[0].rgb, (size_t) w * h * 3); + for (i = 1; i < nlayers; i++) { + const unsigned char *src; + + if (!layers[i].visible || layers[i].rgb == NULL) + continue; + src = layers[i].rgb; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = out + ((size_t) y * w + x) * 3; + const unsigned char *s = + src + ((size_t) y * w + x) * 3; + int op = layers[i].opacity; + + for (c = 0; c < 3; c++) { + int v = s[c]; + + if (layers[i].mode == 1) + v = v * d[c] / 255; + else if (layers[i].mode == 2) + v = 255 - (255 - v) * + (255 - d[c]) / 255; + d[c] = (unsigned char) (d[c] + + (v - d[c]) * op / 100); + } + } + } + *outp = out; + return 0; +} + +/* the stack onto the picture */ +static void +LayerSync(void) +{ + unsigned char *rgb; + + if (LayerComposite(&rgb) != 0) + return; + SetImageRGB(rgb, layerW, layerH); + free(rgb); +} + +static void +LayerShowState(void) +{ + char buf[160]; + XmString s; + + if (layersLabel == NULL || nlayers == 0) + return; + if (curLayer < 0 || curLayer >= nlayers) + curLayer = 0; + snprintf(buf, sizeof buf, "%s %d/%d %d%%", layers[curLayer].name, + curLayer + 1, nlayers, layers[curLayer].opacity); + if (!layers[curLayer].visible) + snprintf(buf + strlen(buf), sizeof buf - strlen(buf), + " (hidden)"); + s = XmStringCreateLocalized(buf); + XtVaSetValues(layersLabel, XmNlabelString, s, NULL); + XmStringFree(s); +} + +/* + * The picture was painted on or a filter ran. The layer the person works on + * takes the new pixels: the stack follows the picture, it does not lead. + */ +static void +LayerAbsorb(void) +{ + unsigned char *rgb; + int w, h; + + if (nlayers == 0 || curLayer < 0 || curLayer >= nlayers) + return; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if (w != layerW || h != layerH) { + free(rgb); + return; + } + free(layers[curLayer].rgb); + layers[curLayer].rgb = rgb; + LayerShowState(); +} + +static void +LayerNew(void) +{ + unsigned char *rgb; + int i; + + LayerEnsure(); + if (nlayers == 0) + return; + if (nlayers >= MAXLAYERS) { + MessageBox("New Layer", "The stack is full: 24 layers."); + fprintf(stderr, "dtphoto: layer new refused, stack full\n"); + return; + } + LayerAbsorb(); + for (i = nlayers; i > curLayer + 1; i--) + layers[i] = layers[i - 1]; + if ((rgb = malloc((size_t) layerW * layerH * 3)) == NULL) + return; + /* an empty layer is transparent: what lies below shows through */ + memset(rgb, 255, (size_t) layerW * layerH * 3); + curLayer++; + layers[curLayer].rgb = rgb; + snprintf(layers[curLayer].name, sizeof layers[curLayer].name, + "Layer %d", nlayers + 1); + layers[curLayer].visible = 1; + layers[curLayer].opacity = 100; + layers[curLayer].mode = 0; + nlayers++; + LayerShowState(); + fprintf(stderr, "dtphoto: layer new %d/%d\n", curLayer + 1, nlayers); +} + +static void +LayerDuplicate(void) +{ + unsigned char *rgb; + + LayerEnsure(); + if (nlayers == 0 || nlayers >= MAXLAYERS) + return; + LayerAbsorb(); + if ((rgb = malloc((size_t) layerW * layerH * 3)) == NULL) + return; + memcpy(rgb, layers[curLayer].rgb, (size_t) layerW * layerH * 3); + layers[nlayers] = layers[curLayer]; + layers[nlayers].rgb = rgb; + snprintf(layers[nlayers].name, sizeof layers[nlayers].name, + "%.36s copy", layers[curLayer].name); + curLayer = nlayers; + nlayers++; + LayerShowState(); + fprintf(stderr, "dtphoto: layer duplicate %d/%d\n", curLayer + 1, + nlayers); +} + +static void +LayerDelete(void) +{ + int i; + + LayerEnsure(); + if (nlayers <= 1) { + SetScratch("The last layer cannot be deleted."); + fprintf(stderr, "dtphoto: layer delete refused\n"); + return; + } + if (curLayer < 0 || curLayer >= nlayers) + return; + free(layers[curLayer].rgb); + for (i = curLayer; i < nlayers - 1; i++) + layers[i] = layers[i + 1]; + nlayers--; + if (curLayer >= nlayers) + curLayer = nlayers - 1; + LayerSync(); + RenderDoc(canvas); + LayerShowState(); + fprintf(stderr, "dtphoto: layer delete %d/%d\n", curLayer + 1, nlayers); +} + +/* Arrange: 0 front, 1 forward, 2 backward, 3 back */ +static void +LayerArrange(int where) +{ + Layer tmp; + + LayerEnsure(); + if (nlayers < 2) + return; + LayerAbsorb(); + switch (where) { + case 0: + if (curLayer == nlayers - 1) + break; + tmp = layers[curLayer]; + memmove(&layers[curLayer], &layers[curLayer + 1], + (size_t) (nlayers - curLayer - 1) * sizeof(Layer)); + layers[nlayers - 1] = tmp; + curLayer = nlayers - 1; + break; + case 1: + if (curLayer < nlayers - 1) { + tmp = layers[curLayer]; + layers[curLayer] = layers[curLayer + 1]; + layers[curLayer + 1] = tmp; + curLayer++; + } + break; + case 2: + if (curLayer > 0) { + tmp = layers[curLayer]; + layers[curLayer] = layers[curLayer - 1]; + layers[curLayer - 1] = tmp; + curLayer--; + } + break; + default: + if (curLayer > 0) { + tmp = layers[curLayer]; + memmove(&layers[1], &layers[0], + (size_t) curLayer * sizeof(Layer)); + layers[0] = tmp; + curLayer = 0; + } + break; + } + LayerSync(); + RenderDoc(canvas); + LayerShowState(); + fprintf(stderr, "dtphoto: layer arrange %d -> %d/%d\n", where, + curLayer + 1, nlayers); +} + +/* `all`: Flatten; otherwise Merge Down onto the layer below */ +static void +LayerMerge(int all) +{ + unsigned char *rgb; + int i; + + LayerEnsure(); + if (nlayers == 0) + return; + LayerAbsorb(); + if (all) { + if (LayerComposite(&rgb) != 0) + return; + LayerInvalidate(); + layers[0].rgb = rgb; + snprintf(layers[0].name, sizeof layers[0].name, "Background"); + layers[0].visible = 1; + layers[0].opacity = 100; + layers[0].mode = 0; + nlayers = 1; + curLayer = 0; + layerW = docW; + layerH = docH; + } else { + Layer upper; + unsigned char *up, *lo; + int x, y, c; + + if (curLayer <= 0) + return; + upper = layers[curLayer]; + up = upper.rgb; + lo = layers[curLayer - 1].rgb; + for (y = 0; y < layerH; y++) + for (x = 0; x < layerW; x++) { + unsigned char *d = lo + + ((size_t) y * layerW + x) * 3; + const unsigned char *s = up + + ((size_t) y * layerW + x) * 3; + + for (c = 0; c < 3; c++) { + int v = s[c]; + + if (upper.mode == 1) + v = v * d[c] / 255; + else if (upper.mode == 2) + v = 255 - (255 - v) * + (255 - d[c]) / 255; + d[c] = (unsigned char) (d[c] + + (v - d[c]) * upper.opacity / 100); + } + } + free(up); + for (i = curLayer; i < nlayers - 1; i++) + layers[i] = layers[i + 1]; + nlayers--; + curLayer--; + } + LayerSync(); + RenderDoc(canvas); + LayerShowState(); + fprintf(stderr, "dtphoto: layer merge %s -> %d\n", + all ? "all" : "down", nlayers); +} + +static void +LayerPickCallback(Widget w, XtPointer cd, XtPointer call) +{ + (void) call; + if (!XmToggleButtonGetState(w)) + return; + curLayer = (int) (long) cd; + if (curLayer < 0 || curLayer >= nlayers) + curLayer = 0; + LayerShowState(); + fprintf(stderr, "dtphoto: layer %d/%d\n", curLayer + 1, nlayers); +} + +static Widget +BuildLayers(Widget parent) +{ + Widget box; + + box = XtVaCreateManagedWidget("layersbox", xmRowColumnWidgetClass, + parent, XmNorientation, XmVERTICAL, XmNmarginWidth, 8, + XmNmarginHeight, 8, NULL); + layersLabel = XtVaCreateManagedWidget("layerstate", xmLabelWidgetClass, + box, XmNlabelString, + XmStringCreateLocalized("Background 1/1 100%"), NULL); + return box; +} + +/* Window > Show Layers */ +static void +ShowLayers(void) +{ + Palette(&palLayers, "Layers", 40, 300, BuildLayers); + LayerEnsure(); + LayerShowState(); + fprintf(stderr, "dtphoto: layers %d\n", nlayers); +} + + +/* --------------------------------------------------- misc */ + + + /* * The selection clips a correction: a picture with a mask is changed only * inside it, as in the original. Every operation goes through this, so no @@ -3171,6 +5400,245 @@ OpPerPixel(ChanFn fn, void *cd) free(rgb); } +/* + * ------------------------------------------------------------------ + * A small dialog kit. + * + * Photoshop's adjustments are "up to three numbers and an OK": Levels has + * input black/white/gamma, Color Balance has three sliders, Threshold has + * one. Rather than a bespoke dialog per menu entry, one form with up to + * three labelled text fields serves all of them; the callback gets the + * numbers. Text fields and not scales because a scale cannot be typed + * into, and every one of these dialogs is faster with the keyboard. + */ +#define FIELD_MAX 3 + +typedef struct { + Widget dialog; + Widget field[FIELD_MAX]; + int nfields; + void (*fn)(const int *v); + int value[FIELD_MAX]; +} FieldBox; + +static void +FieldOk(Widget w, XtPointer cd, XtPointer call) +{ + FieldBox *fb = (FieldBox *) cd; + int i; + + (void) call; + for (i = 0; i < fb->nfields; i++) { + char *s = XmTextFieldGetString(fb->field[i]); + + if (s != NULL) { + fb->value[i] = atoi(s); + XtFree(s); + } + } + XtDestroyWidget(XtParent(w)); + if (fb->fn != NULL) + fb->fn(fb->value); + free(fb); +} + +static void +FieldCancel(Widget w, XtPointer cd, XtPointer call) +{ + (void) call; + XtDestroyWidget(XtParent(w)); + free(cd); +} + +/* + * labels: "Black White Gamma" -- one word per field, so the caller can see + * at a glance how many numbers it is asking for. initial: "0 255 100". + */ +static void +FieldDialog(const char *title, const char *labels, const char *initial, + void (*fn)(const int *v)) +{ + FieldBox *fb; + Widget form, lab, sep; + char buf[128], lab_copy[128], *tok, *save; + char tbuf[FIELD_MAX][32]; + int i; + + fb = calloc(1, sizeof *fb); + if (fb == NULL) + return; + fb->fn = fn; + snprintf(buf, sizeof buf, "%s", labels); + snprintf(lab_copy, sizeof lab_copy, "%s", initial); + /* the initial values, split the same way */ + save = NULL; + for (i = 0, tok = strtok_r(lab_copy, " ", &save); + tok != NULL && i < FIELD_MAX; + i++, tok = strtok_r(NULL, " ", &save)) + snprintf(tbuf[i], sizeof tbuf[i], "%s", tok); + fb->nfields = i; + + form = XmCreateFormDialog(top, "fieldbox", NULL, 0); + XtVaSetValues(form, XmNtitle, title, XmNdialogStyle, + XmDIALOG_FULL_APPLICATION_MODAL, NULL); + sep = XmCreateSeparatorGadget(form, "sep", NULL, 0); + XtVaSetValues(sep, XmNtopAttachment, XmATTACH_FORM, + XmNtopOffset, 8, XmNleftAttachment, XmATTACH_FORM, + XmNrightAttachment, XmATTACH_FORM, NULL); + XtManageChild(sep); + + save = NULL; + for (i = 0, tok = strtok_r(buf, " ", &save); + tok != NULL && i < fb->nfields; + i++, tok = strtok_r(NULL, " ", &save)) { + lab = XmCreateLabelGadget(form, "lab", NULL, 0); + XtVaSetValues(lab, XmNlabelString, + XmStringCreateLocalized(tok), NULL); + if (i == 0) + XtVaSetValues(lab, XmNtopAttachment, XmATTACH_WIDGET, + XmNtopWidget, sep, XmNtopOffset, 8, NULL); + else + XtVaSetValues(lab, XmNtopAttachment, XmATTACH_WIDGET, + XmNtopWidget, fb->field[i - 1], + XmNtopOffset, 6, NULL); + XtVaSetValues(lab, XmNleftAttachment, XmATTACH_FORM, + XmNleftOffset, 10, NULL); + XtManageChild(lab); + + fb->field[i] = XmCreateTextField(form, "field", NULL, 0); + XtVaSetValues(fb->field[i], XmNcolumns, 10, XmNvalue, + i < fb->nfields ? tbuf[i] : "", NULL); + XtVaSetValues(fb->field[i], XmNtopAttachment, + XmATTACH_OPPOSITE_WIDGET, XmNtopWidget, lab, + XmNleftAttachment, XmATTACH_WIDGET, XmNleftWidget, lab, + XmNleftOffset, 12, NULL); + XtManageChild(fb->field[i]); + } + + XtVaSetValues(form, XmNdefaultButtonType, XmDIALOG_OK_BUTTON, NULL); + XtAddCallback(form, XmNokCallback, FieldOk, (XtPointer) fb); + XtAddCallback(form, XmNcancelCallback, FieldCancel, (XtPointer) fb); + XtManageChild(form); + fb->dialog = form; +} + +/* + * HSV, for Hue/Saturation and for the colour filters. Hue in degrees + * 0..359, saturation and value 0..255. + */ +static void +RGBToHSV(const unsigned char *p, int *h, int *s, int *v) +{ + int r = p[0], g = p[1], b = p[2]; + int max = r > g ? (r > b ? r : b) : (g > b ? g : b); + int min = r < g ? (r < b ? r : b) : (g < b ? g : b); + int d = max - min; + + *v = max; + *s = max == 0 ? 0 : d * 255 / max; + if (d == 0) { + *h = 0; + return; + } + if (max == r) + *h = (60 * (g - b) / d + 360) % 360; + else if (max == g) + *h = 60 * (b - r) / d + 120; + else + *h = 60 * (r - g) / d + 240; +} + +static void +HSVToRGB(int h, int s, int v, unsigned char *p) +{ + int i, f, p1, q, t, vv = v; + + h = ((h % 360) + 360) % 360; + if (s == 0) { + p[0] = p[1] = p[2] = (unsigned char) v; + return; + } + i = h / 60; + f = h % 60; + p1 = vv * (255 - s) / 255; + q = vv * (255 - s * f / 60) / 255; + t = vv * (255 - s * (60 - f) / 60) / 255; + switch (i) { + case 0: p[0] = (unsigned char) vv; p[1] = (unsigned char) t; + p[2] = (unsigned char) p1; break; + case 1: p[0] = (unsigned char) q; p[1] = (unsigned char) vv; + p[2] = (unsigned char) p1; break; + case 2: p[0] = (unsigned char) p1; p[1] = (unsigned char) vv; + p[2] = (unsigned char) t; break; + case 3: p[0] = (unsigned char) p1; p[1] = (unsigned char) q; + p[2] = (unsigned char) vv; break; + case 4: p[0] = (unsigned char) t; p[1] = (unsigned char) p1; + p[2] = (unsigned char) vv; break; + default: p[0] = (unsigned char) vv; p[1] = (unsigned char) p1; + p[2] = (unsigned char) q; break; + } +} + +/* the luminance Photoshop's Desaturate and Grayscale use */ + +/* + * A 256-entry table per channel, applied with the selection honoured. + * Levels, Curves, Posterize, Threshold, Equalize and Color Balance are all + * "a curve per channel" once you have this; the curve is the interesting + * part and it is different in every one of them. + */ +typedef struct { + unsigned char lut[3][256]; +} Lut; + +static void +LutIdentity(Lut *l) +{ + int c, i; + + for (c = 0; c < 3; c++) + for (i = 0; i < 256; i++) + l->lut[c][i] = (unsigned char) i; +} + +static void +LutPx(unsigned char *p, void *cd) +{ + Lut *l = (Lut *) cd; + + p[0] = l->lut[0][p[0]]; + p[1] = l->lut[1][p[1]]; + p[2] = l->lut[2][p[2]]; +} + +static void +OpLut(const Lut *l) +{ + OpPerPixel(LutPx, (void *) l); +} + +/* one histogram over the luminance, and one per channel */ +static void +Histogram(long *lum, long *ch) +{ + unsigned char *rgb; + int w, h, i; + + memset(lum, 0, 256 * sizeof *lum); + memset(ch, 0, 3 * 256 * sizeof *ch); + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + for (i = 0; i < w * h; i++) { + unsigned char *p = rgb + (size_t) i * 3; + + ch[p[0]]++; + ch[256 + p[1]]++; + ch[512 + p[2]]++; + lum[LUMA(p[0], p[1], p[2])]++; + } + free(rgb); +} + /* Invert: 255 - v on all three channels */ static void InvertPx(unsigned char *p, void *cd) @@ -3309,6 +5777,305 @@ OpBrightContrast(int brightness, int contrast) return 0; } +/* + * ------------------------------------------------------------------ + * Image > Adjust. + * + * All of these are a curve, so they share the Lut: what differs is how the + * curve is built. The numbers are Photoshop 3's: Levels takes an input + * black point, an input white point and a gamma in hundredths, Curves takes + * a midtone and a shadow/highlight end, Color Balance takes three shifts. + */ + +/* Levels: clip at black/white, then gamma in the middle */ +static void +LevelsCurve(Lut *l, int black, int white, int gamma) +{ + double g = gamma / 100.0; + int i; + + if (black < 0) black = 0; + if (white > 255) white = 255; + if (white <= black) white = black + 1; + if (g <= 0.0) g = 0.01; + for (i = 0; i < 256; i++) { + double v = (i - black) * 255.0 / (white - black); + int o; + + if (v <= 0.0) { + o = 0; + } else if (v >= 255.0) { + o = 255; + } else { + /* gamma: midtones lighter above 100, darker below */ + o = (int) (255.0 * pow(v / 255.0, 1.0 / g) + 0.5); + } + if (o < 0) o = 0; + if (o > 255) o = 255; + l->lut[0][i] = l->lut[1][i] = l->lut[2][i] = + (unsigned char) o; + } +} + +static void +LevelsOk(const int *v) +{ + Lut l; + + LevelsCurve(&l, v[0], v[1], v[2]); + OpLut(&l); + OpDone("levels"); +} + +/* Curves: the same sliders Photoshop shows as a curve -- shadow end, mid + * grey, highlight end. A quadratic through the three points is the honest + * reading of "curve" without a spline editor. */ +static void +CurvesOk(const int *v) +{ + Lut l; + int shadow = v[0], mid = v[2], high = v[1]; /* mid is 0..255 out */ + int i; + + if (shadow < 0) shadow = 0; + if (high > 255) high = 255; + if (high <= shadow) high = shadow + 1; + if (mid < 1) mid = 1; + if (mid > 254) mid = 254; + for (i = 0; i < 256; i++) { + double x, o; + + if (i <= shadow) + o = 0.0; + else if (i >= high) + o = 255.0; + else if (i == 128) + o = mid; + else if (i < 128) { + /* the shadow half: a line from (shadow,0) to (128,mid) */ + x = (double) (i - shadow) / (128 - shadow); + o = x * mid; + } else { + /* the highlight half: (128,mid) to (high,255) */ + x = (double) (i - 128) / (high - 128); + o = mid + x * (255 - mid); + } + if (o < 0) o = 0; + if (o > 255) o = 255; + l.lut[0][i] = l.lut[1][i] = l.lut[2][i] = (unsigned char) (o + 0.5); + } + OpLut(&l); + OpDone("curves"); +} + +/* Color Balance: a shift per channel, -100..100 */ +static void +ColorBalanceOk(const int *v) +{ + Lut l; + int c, i; + + for (c = 0; c < 3; c++) + for (i = 0; i < 256; i++) { + int o = i + v[c] * 255 / 100; + + if (o < 0) o = 0; + if (o > 255) o = 255; + l.lut[c][i] = (unsigned char) o; + } + OpLut(&l); + OpDone("color balance"); +} + +/* Hue/Saturation: hue shift in degrees, saturation and lightness in percent */ +typedef struct { + int hue; /* degrees */ + int sat; /* percent, -100..100 */ + int light; /* percent */ +} HueSat; + +static void +HueSatPx(unsigned char *p, void *cd) +{ + HueSat *hs = (HueSat *) cd; + int h, s, v; + + RGBToHSV(p, &h, &s, &v); + h = (h + hs->hue) % 360; + if (h < 0) h += 360; + s = s + s * hs->sat / 100; + if (s < 0) s = 0; + if (s > 255) s = 255; + v = v + v * hs->light / 100; + if (hs->light > 0) + v = v + (255 - v) * hs->light / 100; + if (v < 0) v = 0; + if (v > 255) v = 255; + HSVToRGB(h, s, v, p); +} + +static void +HueSatOk(const int *v) +{ + HueSat hs; + + hs.hue = v[0]; + hs.sat = v[1]; + hs.light = v[2]; + OpPerPixel(HueSatPx, &hs); + OpDone("hue/saturation"); +} + +/* Threshold: everything below the level becomes black, the rest white */ +static void +ThresholdOk(const int *v) +{ + Lut l; + int i, level = v[0]; + + if (level < 0) level = 0; + if (level > 255) level = 255; + for (i = 0; i < 256; i++) { + unsigned char o = (unsigned char) (i < level ? 0 : 255); + + l.lut[0][i] = l.lut[1][i] = l.lut[2][i] = o; + } + OpLut(&l); + OpDone("threshold"); +} + +/* Posterize: `levels` steps per channel (2..255) */ +static void +PosterizeOk(const int *v) +{ + Lut l; + int i, n = v[0]; + + if (n < 2) n = 2; + if (n > 255) n = 255; + for (i = 0; i < 256; i++) { + /* round, not truncate: at two steps 200 must land on 255, + * and 200 * 1 / 255 truncates to 0 */ + int o = ((i * (n - 1) + 127) / 255) * 255 / (n - 1); + + if (o > 255) o = 255; + l.lut[0][i] = l.lut[1][i] = l.lut[2][i] = (unsigned char) o; + } + OpLut(&l); + OpDone("posterize"); +} + +/* + * Equalize: the cumulative histogram becomes a straight line. Photoshop + * asks first whether to equalize the selection or the whole picture; with + * the mask honoured by OpPerPixel, equalizing "the picture" and letting the + * mask clip it is the same result for the pixels we touch. + */ +static void +OpEqualize(void) +{ + long lum[256], ch[768], total = 0; + Lut l; + int i; + long cum = 0; + + Histogram(lum, ch); + for (i = 0; i < 256; i++) + total += lum[i]; + if (total == 0) + return; + for (i = 0; i < 256; i++) { + int o; + + cum += lum[i]; + o = (int) (cum * 255 / total); + l.lut[0][i] = l.lut[1][i] = l.lut[2][i] = + (unsigned char) o; + } + OpLut(&l); +} + +/* + * Replace Color: one colour, plus a fuzz, becomes another. The distance is + * per channel, which is what the fuzz in the original means. + */ +typedef struct { + unsigned char from[3], to[3]; + int fuzz; +} ReplaceCD; + +static void +ReplacePx(unsigned char *p, void *cd) +{ + ReplaceCD *r = (ReplaceCD *) cd; + int c, d, maxd = 0; + + for (c = 0; c < 3; c++) { + d = p[c] - r->from[c]; + if (d < 0) d = -d; + if (d > maxd) maxd = d; + } + if (maxd <= r->fuzz) + memcpy(p, r->to, 3); +} + +/* + * Selective Color: shift one channel family (the "colour ranges" of the + * original) by a percentage. Without the CMYK plates of the original the + * honest version is: pick a channel, pick a range, shift it. + */ +typedef struct { + int channel; /* 0 r, 1 g, 2 b */ + int lo, hi; + int amount; /* -100..100 */ +} SelectiveCD; + +static void +SelectivePx(unsigned char *p, void *cd) +{ + SelectiveCD *s = (SelectiveCD *) cd; + int v = p[s->channel]; + + if (v < s->lo || v > s->hi) + return; + v = v + s->amount * 255 / 100; + if (v < 0) v = 0; + if (v > 255) v = 255; + p[s->channel] = (unsigned char) v; +} + +/* + * Replace Color. The original picks a colour with an eyedropper and a fuzz; + * here the two colours the editor already shows are the pair: fg becomes bg + * within the fuzz. Predictable without a colour picker dialog, and it is the + * same operation, only with the source named instead of sampled. + */ +static void +ReplaceOk(const int *v) +{ + ReplaceCD r; + + PixelToRGB(fgPixel, &r.from[0], &r.from[1], &r.from[2]); + PixelToRGB(bgPixel, &r.to[0], &r.to[1], &r.to[2]); + r.fuzz = v[0] < 0 ? 0 : (v[0] > 255 ? 255 : v[0]); + OpPerPixel(ReplacePx, &r); + OpDone("replace color"); +} + +/* Selective Color: one channel, one range, one shift, all from the dialog */ +static void +SelectiveOk(const int *v) +{ + SelectiveCD s; + + s.channel = v[0] < 0 ? 0 : (v[0] > 2 ? 2 : v[0]); + s.lo = v[1] < 0 ? 0 : (v[1] > 255 ? 255 : v[1]); + s.hi = 255; + s.amount = v[2]; + OpPerPixel(SelectivePx, &s); + OpDone("selective color"); +} + /* Scale the picture to (nw, nh), nearest neighbour as the original does for * an integer zoom; enough for Image Size, which is what this is for. */ static int @@ -3429,6 +6196,434 @@ Convolve3x3(const double k[9], double bias) free(rgb); } +/* + * ------------------------------------------------------------ filter machines + * + * Every filter in the Filter menu is one of five machines: a convolution, a + * warp, a rank filter, a scatter, or a raster. Building them once means a + * menu entry is a few lines and its arithmetic can be predicted by hand in + * a test, instead of each filter carrying its own copy of the loop. + */ + +/* a reproducible scatter: the same pixel always gets the same noise */ +static unsigned +NoiseAt(int x, int y, unsigned seed) +{ + unsigned v = (unsigned) x * 374761393u + + (unsigned) y * 668265263u + seed * 2246822519u; + + v = (v ^ (v >> 13)) * 1274126177u; + return v ^ (v >> 16); +} + +/* + * A convolution with a kernel of any size. This is the machine behind + * Gaussian Blur, Motion Blur, Unsharp Mask, Custom, Maximum and Minimum. + * + * The border replicates the edge pixel instead of leaving it alone the way + * Convolve3x3 does: a blur that keeps its outer row sharp shows a frame, + * and a test can compute the replicated value by hand. + */ +typedef struct { + int r; /* radius: the kernel is (2r+1) x (2r+1) */ + const double *k; /* weights, row major */ + double bias; /* added to every sum, for emboss and offset */ + double div; /* divisor; 0 means 1 */ + int absolute; /* take the magnitude (emboss, edges) */ +} Kernel; + +static void +ConvolveN(const Kernel *kn) +{ + unsigned char *rgb, *src; + int w, h, x, y, c, ix, iy, n = 2 * kn->r + 1; + double div = kn->div == 0.0 ? 1.0 : kn->div; + + if (kn->r < 1) + return; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + + /* cov <= 0 leaves rgb, which already holds the old + * value; nothing to copy back */ + int cov = selMaskAny ? MaskCover(x, y) : 255; + + if (cov <= 0) + continue; + for (c = 0; c < 3; c++) { + double sum = kn->bias; + int sx, sy; + unsigned char v; + + for (iy = 0; iy < n; iy++) { + sy = y + iy - kn->r; + if (sy < 0) sy = 0; + if (sy >= h) sy = h - 1; + for (ix = 0; ix < n; ix++) { + sx = x + ix - kn->r; + if (sx < 0) sx = 0; + if (sx >= w) sx = w - 1; + sum += kn->k[iy * n + ix] * + src[((size_t) sy * w + sx) * 3 + c]; + } + } + sum /= div; + if (kn->absolute && sum < 0.0) + sum = -sum; + if (sum < 0.0) sum = 0.0; + if (sum > 255.0) sum = 255.0; + v = (unsigned char) (sum + 0.5); + d[c] = cov >= 255 ? v : + (unsigned char) (o[c] + + ((int) v - o[c]) * cov / 255); + } + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* + * A normalised gaussian kernel of radius r. sigma comes from the caller + * because Photoshop lets the person drag it; the default is r/2, which is + * the smallest sigma that still uses the corners of the kernel. + */ +static double * +GaussKernel(int r, double sigma) +{ + int n = 2 * r + 1, ix, iy; + double *k, sum = 0.0; + + if (r < 1) r = 1; + if (sigma <= 0.0) sigma = r / 2.0; + if ((k = calloc((size_t) n * n, sizeof *k)) == NULL) + return NULL; + for (iy = 0; iy < n; iy++) + for (ix = 0; ix < n; ix++) { + double dx = ix - r, dy = iy - r; + double v = exp(-(dx * dx + dy * dy) / (2.0 * sigma * sigma)); + + k[iy * n + ix] = v; + sum += v; + } + /* normalise, so a flat area stays flat and stays at its value */ + for (iy = 0; iy < n * n; iy++) + k[iy] /= sum; + return k; +} + +/* Gaussian Blur with a radius in pixels; radius 0 is the identity */ +static void +OpGaussianBlur(double radius) +{ + int r = (int) (radius + 0.5); + double *k; + + if (r < 1) + return; + if ((k = GaussKernel(r, radius / 2.0)) == NULL) + return; + { + Kernel kn; + + kn.r = r; kn.k = k; kn.bias = 0.0; + kn.div = 0.0; kn.absolute = 0; + ConvolveN(&kn); + } + free(k); +} + +/* Motion Blur: a straight line at `angle` degrees, `dist` pixels long */ +static void +OpMotionBlur(int angle, int dist) +{ + double *k; + int n, i, r; + + if (dist < 1) dist = 1; + if (dist > 255) dist = 255; + r = dist; + n = 2 * r + 1; + if ((k = calloc((size_t) n * n, sizeof *k)) == NULL) + return; + for (i = 0; i < dist; i++) { + double t = (dist == 1) ? 0.0 : (double) i / (dist - 1) - 0.5; + double cx = cos(angle * M_PI / 180.0) * t * (dist - 1); + double cy = sin(angle * M_PI / 180.0) * t * (dist - 1); + int ix = (int) (r + cx + 0.5), iy = (int) (r + cy + 0.5); + + if (ix < 0) ix = 0; + if (ix >= n) ix = n - 1; + if (iy < 0) iy = 0; + if (iy >= n) iy = n - 1; + k[iy * n + ix] += 1.0; + } + { + Kernel kn; + + kn.r = r; kn.k = k; kn.bias = 0.0; + kn.div = (double) dist; kn.absolute = 0; + ConvolveN(&kn); + } + free(k); +} + +/* + * A warp: for every destination pixel the callback names the source pixel. + * The read is bilinear, so a wave does not become a staircase, and the edge + * repeats outside the picture the way the convolution does. + */ +typedef void (*WarpFn)(int x, int y, int w, int h, double *sx, double *sy, + void *cd); + +static void +SampleBilinear(const unsigned char *src, int w, int h, double sx, double sy, + unsigned char *out) +{ + int x0, y0, x1, y1, c; + double fx, fy; + + if (sx < 0.0) sx = 0.0; + if (sy < 0.0) sy = 0.0; + if (sx > w - 1) sx = w - 1; + if (sy > h - 1) sy = h - 1; + x0 = (int) sx; + y0 = (int) sy; + x1 = x0 + 1 < w ? x0 + 1 : x0; + y1 = y0 + 1 < h ? y0 + 1 : y0; + fx = sx - x0; + fy = sy - y0; + for (c = 0; c < 3; c++) { + double a = src[((size_t) y0 * w + x0) * 3 + c]; + double b = src[((size_t) y0 * w + x1) * 3 + c]; + double d = src[((size_t) y1 * w + x0) * 3 + c]; + double e = src[((size_t) y1 * w + x1) * 3 + c]; + double top = a + (b - a) * fx; + double bot = d + (e - d) * fx; + + out[c] = (unsigned char) (top + (bot - top) * fy + 0.5); + } +} + +static void +WarpImg(WarpFn fn, void *cd) +{ + unsigned char *rgb, *src, v[3]; + int w, h, x, y, c; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + double sx, sy; + int cov = selMaskAny ? MaskCover(x, y) : 255; + + if (cov <= 0) + continue; + sx = (double) x; + sy = (double) y; + fn(x, y, w, h, &sx, &sy, cd); + SampleBilinear(src, w, h, sx, sy, v); + for (c = 0; c < 3; c++) + d[c] = cov >= 255 ? v[c] : + (unsigned char) (o[c] + + ((int) v[c] - o[c]) * cov / 255); + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* + * A rank filter over a square window: Maximum (dilate) and Minimum (erode) + * are the two ends of the same sort, and Median is already built for 3x3. + * The border replicates, as in ConvolveN. + */ +static void +OpRank(int radius, int top) +{ + unsigned char *rgb, *src; + int w, h, x, y, c, ix, iy, n = 2 * radius + 1, total = n * n; + unsigned char *buf; + + if (radius < 1) + return; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL || + (buf = malloc((size_t) total)) == NULL) { + free(src); + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + + if (cov <= 0) + continue; + for (c = 0; c < 3; c++) { + int best, i = 0; + unsigned char v; + + for (iy = 0; iy < n; iy++) + for (ix = 0; ix < n; ix++) { + int sx = x + ix - radius; + int sy = y + iy - radius; + + if (sx < 0) sx = 0; + if (sx >= w) sx = w - 1; + if (sy < 0) sy = 0; + if (sy >= h) sy = h - 1; + buf[i++] = src[((size_t) sy * w + sx) * 3 + c]; + } + best = buf[0]; + for (i = 1; i < total; i++) + if (top ? (buf[i] > best) : (buf[i] < best)) + best = buf[i]; + v = (unsigned char) best; + d[c] = cov >= 255 ? v : + (unsigned char) (o[c] + + ((int) v - o[c]) * cov / 255); + } + } + free(buf); + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* + * Unsharp Mask: the difference between the picture and a blurred copy, + * scaled by the amount. `threshold` keeps flat areas from growing grain: + * a difference below it is left alone. + */ +static void +OpUnsharp(double amount, double radius, int threshold) +{ + unsigned char *rgb, *orig, *blur; + int w, h, i; + int r = (int) (radius + 0.5); + + if (amount <= 0.0 || r < 1) + return; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((orig = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(orig, rgb, (size_t) w * h * 3); + SetImageRGB(rgb, w, h); /* write back, then blur the picture itself */ + OpGaussianBlur(radius); + free(rgb); + if (GetImageRGB(&blur, &w, &h) != 0) { + free(orig); + return; + } + for (i = 0; i < w * h * 3; i++) { + int diff = (int) orig[i] - (int) blur[i]; + double v; + + if (diff < 0) { + if (-diff <= threshold) + diff = 0; + } else if (diff <= threshold) + diff = 0; + v = orig[i] + amount * diff; + if (v < 0.0) v = 0.0; + if (v > 255.0) v = 255.0; + blur[i] = (unsigned char) (v + 0.5); + } + SetImageRGB(blur, w, h); + free(blur); + free(orig); +} + +/* + * High Pass: the difference between the picture and a blur, plus mid grey. + * It is the unsharp mask without the addition, which is why Overlay of the + * result sharpens the picture. + */ +static void +OpHighPass(double radius) +{ + unsigned char *rgb, *orig; + int w, h, i; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((orig = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(orig, rgb, (size_t) w * h * 3); + SetImageRGB(rgb, w, h); + OpGaussianBlur(radius); + free(rgb); + if (GetImageRGB(&rgb, &w, &h) != 0) { + free(orig); + return; + } + for (i = 0; i < w * h * 3; i++) { + int v = 128 + ((int) orig[i] - (int) rgb[i]) * 512 / 255; + + if (v < 0) v = 0; + if (v > 255) v = 255; + rgb[i] = (unsigned char) v; + } + SetImageRGB(rgb, w, h); + free(rgb); + free(orig); +} + +/* Offset: the picture shifts, and the gap wraps around */ +static void +OpOffset(int dx, int dy) +{ + unsigned char *rgb, *out; + int w, h, x, y, c; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((out = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + int sx = ((x - dx) % w + w) % w; + int sy = ((y - dy) % h + h) % h; + unsigned char *d = out + ((size_t) y * w + x) * 3; + const unsigned char *o = rgb + ((size_t) sy * w + sx) * 3; + + for (c = 0; c < 3; c++) + d[c] = o[c]; + } + free(rgb); + SetImageRGB(out, w, h); + free(out); +} + static void OpBlur(int more) { @@ -3644,6 +6839,1450 @@ OpSolarize(void) OpPerPixel(SolarizePx, NULL); } +/* + * ------------------------------------------------------- Filter > Distort + * + * Every distort filter is one warp callback: given a destination pixel it + * names the source pixel to read. The arithmetic is in the callback, so a + * test can compute the source coordinate by hand and compare. + */ + +/* Ripple: concentric waves from the middle of the picture */ +typedef struct { + double amp, wavelength; + int phase; +} RippleCD; + +static void +RippleWarp(int x, int y, int w, int h, double *sx, double *sy, void *cd) +{ + RippleCD *r = (RippleCD *) cd; + double cx = w / 2.0, cy = h / 2.0; + double dx = x - cx, dy = y - cy; + double d = sqrt(dx * dx + dy * dy); + double off = r->amp * sin(2.0 * M_PI * d / r->wavelength + r->phase); + double scale = d > 0.0 ? off / d : 0.0; + + *sx = x + dx * scale; + *sy = y + dy * scale; +} + +static void +OpRipple(double amp, double wavelength, int phase) +{ + RippleCD cd; + + cd.amp = amp; cd.wavelength = wavelength; cd.phase = phase; + WarpImg(RippleWarp, &cd); +} + +/* Wave: a sine displacement, horizontal bands or vertical columns */ +typedef struct { + double amp, wavelength; + int phase; + int vertical; /* 1: the columns wave, 0: the rows */ +} WaveCD; + +static void +WaveWarp(int x, int y, int w, int h, double *sx, double *sy, void *cd) +{ + WaveCD *v = (WaveCD *) cd; + double off; + + (void) w; (void) h; + if (v->vertical) { + off = v->amp * sin(2.0 * M_PI * x / v->wavelength + v->phase); + *sx = x; + *sy = y + off; + } else { + off = v->amp * sin(2.0 * M_PI * y / v->wavelength + v->phase); + *sx = x + off; + *sy = y; + } +} + +/* Twirl: the picture turns around its middle, strongest at the centre */ +typedef struct { + double angle; /* radians at the centre */ + double radius; +} TwirlCD; + +static void +TwirlWarp(int x, int y, int w, int h, double *sx, double *sy, void *cd) +{ + TwirlCD *t = (TwirlCD *) cd; + double cx = w / 2.0, cy = h / 2.0; + double dx = x - cx, dy = y - cy; + double d = sqrt(dx * dx + dy * dy); + double a; + + if (d > t->radius || t->radius <= 0.0) { + *sx = x; + *sy = y; + return; + } + /* full turn at the centre, none at the rim */ + a = t->angle * (1.0 - d / t->radius); + *sx = cx + dx * cos(a) - dy * sin(a); + *sy = cy + dx * sin(a) + dy * cos(a); +} + +static void +OpTwirl(double angle, double radius) +{ + TwirlCD cd; + + cd.angle = angle * M_PI / 180.0; + cd.radius = radius; + WarpImg(TwirlWarp, &cd); +} + +/* Spherize: a pin cushion, or a barrel when the amount is negative */ +typedef struct { + double amount; /* -100..100 */ +} SpherizeCD; + +static void +SpherizeWarp(int x, int y, int w, int h, double *sx, double *sy, void *cd) +{ + SpherizeCD *s = (SpherizeCD *) cd; + double cx = w / 2.0, cy = h / 2.0; + double nx = (x - cx) / (w / 2.0), ny = (y - cy) / (h / 2.0); + double r = sqrt(nx * nx + ny * ny); + double k = s->amount / 100.0; + + if (r < 1e-9 || r >= 1.0) { + *sx = x; + *sy = y; + return; + } + /* the centre magnifies, the rim stays, the falloff is smooth */ + { + double t = pow(r, 1.0 - k); + double f = t / r; + + *sx = cx + nx * f * (w / 2.0); + *sy = cy + ny * f * (h / 2.0); + } +} + +static void +OpSpherize(double amount) +{ + SpherizeCD cd; + + if (amount < -100.0) amount = -100.0; + if (amount > 100.0) amount = 100.0; + cd.amount = amount; + WarpImg(SpherizeWarp, &cd); +} + +/* Pinch: toward the middle (positive) or away from it (negative) */ +typedef struct { + double amount; +} PinchCD; + +static void +PinchWarp(int x, int y, int w, int h, double *sx, double *sy, void *cd) +{ + PinchCD *p = (PinchCD *) cd; + double cx = w / 2.0, cy = h / 2.0; + double dx = x - cx, dy = y - cy; + double r = sqrt(dx * dx + dy * dy); + double maxr = sqrt(cx * cx + cy * cy); + double k = p->amount / 100.0; + + if (maxr < 1e-9 || r < 1e-9) { + *sx = x; + *sy = y; + return; + } + { + double t = pow(r / maxr, 1.0 + k); + double f = t * maxr / r; + + *sx = cx + dx * f; + *sy = cy + dy * f; + } +} + +static void +OpPinch(double amount) +{ + PinchCD cd; + + if (amount < -100.0) amount = -100.0; + if (amount > 100.0) amount = 100.0; + cd.amount = amount; + WarpImg(PinchWarp, &cd); +} + +/* Polar Coordinates: rectangular to polar, or the other way round */ +typedef struct { + int rectToPolar; +} PolarCD; + +static void +PolarWarp(int x, int y, int w, int h, double *sx, double *sy, void *cd) +{ + PolarCD *p = (PolarCD *) cd; + double cx = w / 2.0, cy = h / 2.0; + + if (p->rectToPolar) { + double dx = x - cx, dy = y - cy; + double r = sqrt(dx * dx + dy * dy); + double a = atan2(dy, dx); + + /* the angle runs down the columns, the radius across */ + *sx = (a + M_PI) / (2.0 * M_PI) * (w - 1); + *sy = r / (sqrt(cx * cx + cy * cy)) * (h - 1); + } else { + double a = ((double) x / (w - 1)) * 2.0 * M_PI - M_PI; + double r = ((double) y / (h - 1)) * sqrt(cx * cx + cy * cy); + + *sx = cx + r * cos(a); + *sy = cy + r * sin(a); + } +} + +static void +OpPolar(int rectToPolar) +{ + PolarCD cd; + + cd.rectToPolar = rectToPolar; + WarpImg(PolarWarp, &cd); +} + +/* ZigZag: concentric rings, the amount sets how far they jump */ +typedef struct { + double amount; + int ridges; +} ZigZagCD; + +static void +ZigZagWarp(int x, int y, int w, int h, double *sx, double *sy, void *cd) +{ + ZigZagCD *z = (ZigZagCD *) cd; + double cx = w / 2.0, cy = h / 2.0; + double dx = x - cx, dy = y - cy; + double d = sqrt(dx * dx + dy * dy); + double maxd = sqrt(cx * cx + cy * cy); + + if (maxd < 1e-9 || d < 1e-9) { + *sx = x; + *sy = y; + return; + } + { + double off = z->amount * sin(2.0 * M_PI * z->ridges * d / maxd) / + (d / maxd + 1.0); + double f = (d + off) / d; + + *sx = cx + dx * f; + *sy = cy + dy * f; + } +} + +static void +OpZigZag(double amount, int ridges) +{ + ZigZagCD cd; + + if (ridges < 1) ridges = 1; + cd.amount = amount; cd.ridges = ridges; + WarpImg(ZigZagWarp, &cd); +} + +/* Shear: rows slide sideways, the amount is the offset in pixels per row */ +typedef struct { + double amount; + int wrap; +} ShearCD; + +static void +ShearWarp(int x, int y, int w, int h, double *sx, double *sy, void *cd) +{ + ShearCD *s = (ShearCD *) cd; + double off = s->amount * ((double) y / (h - 1) - 0.5); + + *sx = x - off; + *sy = y; + (void) w; (void) s->wrap; +} + +static void +OpShear(double amount) +{ + ShearCD cd; + + cd.amount = amount; + cd.wrap = 1; + WarpImg(ShearWarp, &cd); +} + +/* + * Displace: the picture moves by an amount read from a second picture. + * Without a displace map file the tool would have nothing to read, so the + * map is generated deterministically from the same scatter the noise tool + * uses; the dialog names that openly. + */ +typedef struct { + double scale; + unsigned seed; +} DisplaceCD; + +static void +DisplaceWarp(int x, int y, int w, int h, double *sx, double *sy, void *cd) +{ + DisplaceCD *d = (DisplaceCD *) cd; + unsigned nx = NoiseAt(x, y, d->seed); + unsigned ny = NoiseAt(x, y, d->seed + 1u); + + *sx = x + ((int) (nx % 256) - 128) * d->scale / 100.0; + *sy = y + ((int) (ny % 256) - 128) * d->scale / 100.0; + (void) w; (void) h; +} + +static void +OpDisplace(double scale, unsigned seed) +{ + DisplaceCD cd; + + cd.scale = scale; + cd.seed = seed; + WarpImg(DisplaceWarp, &cd); +} + +/* + * ------------------------------------------------------ Filter > Pixelate + * + * The pixelate family is the raster: a cell of the picture collapses into + * one shape. Mosaic is the plain block; these are the same block with a + * different rule for the colour, plus the two scatter tools. + */ + +/* Crystallize: the cell takes the colour of the seed nearest its middle */ +static void +OpCrystallize(int cell) +{ + unsigned char *rgb, *out; + int w, h, x, y, bx, by, c; + + if (cell < 2) cell = 2; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((out = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(out, rgb, (size_t) w * h * 3); + for (by = 0; by < h; by += cell) + for (bx = 0; bx < w; bx += cell) { + int cx = bx + cell / 2, cy = by + cell / 2; + unsigned char mean[3]; + int n = 0, sx, sy; + + if (cx >= w) cx = w - 1; + if (cy >= h) cy = h - 1; + for (c = 0; c < 3; c++) { + unsigned long sum = 0; + + n = 0; + for (y = by; y < by + cell && y < h; y++) + for (x = bx; x < bx + cell && x < w; x++) { + sum += rgb[((size_t) y * w + x) * 3 + c]; + n++; + } + mean[c] = (unsigned char) + (n > 0 ? sum / (unsigned long) n : 0); + } + /* every pixel of the cell takes the mean, so the cell + * is one flat crystal, as the original does */ + for (y = by; y < by + cell && y < h; y++) + for (x = bx; x < bx + cell && x < w; x++) + memcpy(out + ((size_t) y * w + x) * 3, mean, 3); + (void) sx; (void) sy; + } + free(rgb); + SetImageRGB(out, w, h); + free(out); +} + +/* Facet: like Crystallize, but the cell keeps its own mean per 2x2 group */ +static void +OpFacet(void) +{ + unsigned char *rgb, *out; + int w, h, x, y, c; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((out = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + for (y = 0; y + 1 < h; y += 2) + for (x = 0; x + 1 < w; x += 2) { + unsigned char mean[3]; + int i, dx, dy; + + for (c = 0; c < 3; c++) { + unsigned long sum = 0; + + for (dy = 0; dy < 2; dy++) + for (dx = 0; dx < 2; dx++) + sum += rgb[((size_t) (y + dy) * w + + (x + dx)) * 3 + c]; + mean[c] = (unsigned char) (sum / 4); + } + for (i = 0; i < 4; i++) + memcpy(out + ((size_t) (y + i / 2) * w + + (x + i % 2)) * 3, mean, 3); + } + /* an odd last row or column keeps what it had */ + if (w % 2) + for (y = 0; y < h; y++) + memcpy(out + ((size_t) y * w + (w - 1)) * 3, + rgb + ((size_t) y * w + (w - 1)) * 3, 3); + if (h % 2) + memcpy(out + ((size_t) (h - 1) * w) * 3, + rgb + ((size_t) (h - 1) * w) * 3, (size_t) w * 3); + free(rgb); + SetImageRGB(out, w, h); + free(out); +} + +/* Fragment: four shifted copies of the picture, averaged -- the shake */ +static void +OpFragment(void) +{ + unsigned char *rgb, *src; + int w, h, x, y, c; + static const int ox[4] = { 0, 1, 0, -1 }; + static const int oy[4] = { 0, 0, 1, -1 }; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + int i; + + if (cov <= 0) + continue; + for (c = 0; c < 3; c++) { + unsigned long sum = 0; + unsigned char v; + + for (i = 0; i < 4; i++) { + int sx = x + ox[i], sy = y + oy[i]; + + if (sx < 0) sx = 0; + if (sx >= w) sx = w - 1; + if (sy < 0) sy = 0; + if (sy >= h) sy = h - 1; + sum += src[((size_t) sy * w + sx) * 3 + c]; + } + v = (unsigned char) (sum / 4); + d[c] = cov >= 255 ? v : + (unsigned char) (o[c] + + ((int) v - o[c]) * cov / 255); + } + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Mezzotint: one of eight strokes, scattered over the picture */ +static void +OpMezzotint(int mode) +{ + unsigned char *rgb; + int w, h, x, y; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + static const int ox[8] = { 1, 1, 0, -1, -1, -1, 0, 1 }; + static const int oy[8] = { 0, 1, 1, 1, 0, -1, -1, -1 }; + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + unsigned n = NoiseAt(x, y, 7u); + int sx, sy, c; + int dir = (int) (n % 8); + + if (mode == 1) { /* coarse dots */ + dir = (int) ((n >> 3) % 8); + } else if (mode == 2) { /* fine grain */ + dir = (int) ((n >> 5) % 8); + } + sx = x + ox[dir]; + sy = y + oy[dir]; + if (sx < 0) sx = 0; + if (sx >= w) sx = w - 1; + if (sy < 0) sy = 0; + if (sy >= h) sy = h - 1; + for (c = 0; c < 3; c++) + d[c] = rgb[((size_t) sy * w + sx) * 3 + c]; + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Pointillize: a dot of the cell's colour on the background colour */ +static void +OpPointillize(int cell) +{ + unsigned char *rgb; + int w, h, x, y, bx, by; + unsigned char br, bg, bb; + + if (cell < 2) cell = 2; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + PixelToRGB(bgPixel, &br, &bg, &bb); + for (by = 0; by < h; by += cell) + for (bx = 0; bx < w; bx += cell) { + unsigned char mean[3]; + int c, n = 0; + int cx = bx + cell / 2, cy = by + cell / 2; + int rad = cell / 2; + + for (c = 0; c < 3; c++) { + unsigned long sum = 0; + + n = 0; + for (y = by; y < by + cell && y < h; y++) + for (x = bx; x < bx + cell && x < w; x++) { + sum += rgb[((size_t) y * w + x) * 3 + c]; + n++; + } + mean[c] = (unsigned char) + (n > 0 ? sum / (unsigned long) n : 0); + } + for (y = by; y < by + cell && y < h; y++) + for (x = bx; x < bx + cell && x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + int dx = x - cx, dy = y - cy; + + if (dx * dx + dy * dy <= rad * rad) { + d[0] = mean[0]; + d[1] = mean[1]; + d[2] = mean[2]; + } else { + d[0] = br; + d[1] = bg; + d[2] = bb; + } + } + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Color Halftone: dots of the four inks on a rotated grid */ +static void +OpColorHalftone(int cell) +{ + unsigned char *rgb, *out; + int w, h, x, y, bx, by, c; + /* the four screen angles of the original: 15, 75, 0, 45 degrees */ + static const double ang[4] = { 15.0, 75.0, 0.0, 45.0 }; + + if (cell < 2) cell = 2; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((out = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + /* start from white paper and print the four separating dots */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + memset(out + ((size_t) y * w + x) * 3, 255, 3); + for (c = 0; c < 4; c++) { + double ca = cos(ang[c] * M_PI / 180.0); + double sa = sin(ang[c] * M_PI / 180.0); + + for (by = 0; by < h; by += cell) + for (bx = 0; bx < w; bx += cell) { + int n = 0, sx, sy; + double sum = 0.0; + int cx = bx + cell / 2, cy = by + cell / 2; + int rad; + + for (sy = by; sy < by + cell && sy < h; sy++) + for (sx = bx; sx < bx + cell && sx < w; sx++) { + const unsigned char *p = + rgb + ((size_t) sy * w + sx) * 3; + + if (c == 0) + sum += 255 - p[0]; + else if (c == 1) + sum += 255 - p[1]; + else if (c == 2) + sum += 255 - p[2]; + else + sum += (255 - LUMA(p[0], + p[1], p[2])); + n++; + } + if (n == 0) + continue; + /* the dot grows with the ink it carries */ + rad = (int) ((sum / n) / 255.0 * (cell / 2.0) + 0.5); + if (rad <= 0) + continue; + /* the grid is rotated per ink: the dot sits on the + * rotated lattice point nearest the cell middle */ + { + double rx = (cx - w / 2.0) * ca + + (cy - h / 2.0) * sa; + double ry = -(cx - w / 2.0) * sa + + (cy - h / 2.0) * ca; + int qx, qy; + + rx = floor(rx / cell + 0.5) * cell; + ry = floor(ry / cell + 0.5) * cell; + qx = (int) (rx * ca - ry * sa + w / 2.0); + qy = (int) (rx * sa + ry * ca + h / 2.0); + for (sy = qy - rad; sy <= qy + rad; sy++) + for (sx = qx - rad; sx <= qx + rad; sx++) { + int dx = sx - qx, dy = sy - qy; + unsigned char *d; + + if (sx < 0 || sy < 0 || + sx >= w || sy >= h) + continue; + if (dx * dx + dy * dy > + rad * rad) + continue; + d = out + ((size_t) sy * w + sx) * 3; + if (c == 0) + d[0] = 0; + else if (c == 1) + d[1] = 0; + else if (c == 2) + d[2] = 0; + else { + int k; + + for (k = 0; k < 3; k++) + d[k] = (unsigned char) + (d[k] * 3 / 4); + } + } + } + } + } + free(rgb); + SetImageRGB(out, w, h); + free(out); +} + +/* ------------------------------------------------------ Filter > Render */ + +/* Clouds: fractal value noise between the foreground and background colour */ +static void +OpClouds(int difference) +{ + unsigned char *rgb, *base = NULL; + int w, h, x, y, c, oct; + unsigned char fr, fg, fb, tr, tg, tb; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if (difference) { + if ((base = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(base, rgb, (size_t) w * h * 3); + } + PixelToRGB(fgPixel, &fr, &fg, &fb); + PixelToRGB(bgPixel, &tr, &tg, &tb); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + double v = 0.0, amp = 1.0, sum = 0.0; + int step = 64; + + if (cov <= 0) + continue; + /* four octaves of value noise: the same circles a cloud + * has, and the same numbers in every run */ + for (oct = 0; oct < 4; oct++) { + int gx = x / step, gy = y / step; + int fx = x % step, fy = y % step; + unsigned n00 = NoiseAt(gx, gy, (unsigned) oct); + unsigned n10 = NoiseAt(gx + 1, gy, (unsigned) oct); + unsigned n01 = NoiseAt(gx, gy + 1, (unsigned) oct); + unsigned n11 = NoiseAt(gx + 1, gy + 1, (unsigned) oct); + double tx = (double) fx / step, ty = (double) fy / step; + double a = (n00 & 255) / 255.0, b = (n10 & 255) / 255.0; + double cc = (n01 & 255) / 255.0, dd = (n11 & 255) / 255.0; + double top = a + (b - a) * tx; + double bot = cc + (dd - cc) * tx; + + v += (top + (bot - top) * ty) * amp; + sum += amp; + amp *= 0.5; + step = step / 2 > 0 ? step / 2 : 1; + } + v /= sum; + for (c = 0; c < 3; c++) { + double f = c == 0 ? fr : (c == 1 ? fg : fb); + double t = c == 0 ? tr : (c == 1 ? tg : tb); + int val = (int) (f + (t - f) * v + 0.5); + + if (difference && base != NULL) { + int old = base[((size_t) y * w + x) * 3 + c]; + int diff = old - val; + + if (diff < 0) + diff = -diff; + val = diff; + } + if (val < 0) val = 0; + if (val > 255) val = 255; + d[c] = cov >= 255 ? (unsigned char) val : + (unsigned char) (base != NULL ? + base[((size_t) y * w + x) * 3 + c] : + d[c]); + if (cov < 255 && base == NULL) + d[c] = (unsigned char) + (d[c] + (val - d[c]) * cov / 255); + } + } + free(base); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Lens Flare: a bright disc and the rings the original draws around it */ +static void +OpLensFlare(int cx, int cy, int brightness) +{ + unsigned char *rgb; + int w, h, x, y; + double k = brightness / 100.0; + + if (brightness <= 0) + return; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + double dx = x - cx, dy = y - cy; + double r = sqrt(dx * dx + dy * dy); + double add = 0.0; + int c; + + if (cov <= 0) + continue; + /* the flare: a hot core, a halo, and the ghost ring */ + if (r < 8.0) + add = 255.0 * k; + else if (r < 24.0) + add = (24.0 - r) / 16.0 * 200.0 * k; + else if (r > 40.0 && r < 56.0) + add = (1.0 - fabs(r - 48.0) / 8.0) * 90.0 * k; + if (add <= 0.0) + continue; + for (c = 0; c < 3; c++) { + int v = (int) (d[c] + add * + (c == 0 ? 1.0 : (c == 1 ? 0.95 : 0.8))); + + if (v > 255) v = 255; + d[c] = cov >= 255 ? (unsigned char) v : + (unsigned char) (d[c] + + (v - d[c]) * cov / 255); + } + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Lighting Effects: a spotlight from the top left, added to the picture */ +static void +OpLighting(int intensity, int angle) +{ + unsigned char *rgb; + int w, h, x, y; + double ca = cos(angle * M_PI / 180.0), sa = sin(angle * M_PI / 180.0); + double k = intensity / 100.0; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + double nx = (double) x / w - 0.5, ny = (double) y / h - 0.5; + double dot = nx * ca + ny * sa; + double shade = 1.0 + 0.8 * k * (dot > 0.0 ? dot : -dot * 0.5); + int c; + + if (cov <= 0) + continue; + if (shade < 0.0) shade = 0.0; + for (c = 0; c < 3; c++) { + int v = (int) (d[c] * shade + 0.5); + + if (v > 255) v = 255; + d[c] = cov >= 255 ? (unsigned char) v : + (unsigned char) (d[c] + + (v - d[c]) * cov / 255); + } + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Texture Fill: a grey noise picture, the stand-in when no file is named */ +static void +OpTextureFill(void) +{ + unsigned char *rgb; + int w, h, x, y, c; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned n = NoiseAt(x, y, 99u); + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + unsigned char v = (unsigned char) (n & 255); + + if (selMaskAny && !MaskGet(x, y)) + continue; + for (c = 0; c < 3; c++) + d[c] = v; + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* ------------------------------------------------------ Filter > Stylize */ + +/* Diffuse: a pixel takes one of its neighbours, scattered */ +static void +OpDiffuse(int mode) +{ + unsigned char *rgb, *src; + int w, h, x, y, c; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + static const int ox[4] = { 1, -1, 0, 0 }; + static const int oy[4] = { 0, 0, 1, -1 }; + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + unsigned n; + int i, sx, sy; + + if (cov <= 0) + continue; + n = NoiseAt(x, y, (unsigned) (mode + 11)); + i = (int) (n % 4); + if (mode == 1) /* darken only: keep the darkest */ + i = (int) ((n >> 3) % 4); + sx = x + ox[i]; + sy = y + oy[i]; + if (sx < 0) sx = 0; + if (sx >= w) sx = w - 1; + if (sy < 0) sy = 0; + if (sy >= h) sy = h - 1; + for (c = 0; c < 3; c++) { + int v = src[((size_t) sy * w + sx) * 3 + c]; + + if (mode == 1) { /* the darker of the two */ + if (o[c] < v) v = o[c]; + } else if (mode == 3) { /* lighten */ + if (o[c] > v) v = o[c]; + } + d[c] = cov >= 255 ? (unsigned char) v : + (unsigned char) (o[c] + + (v - o[c]) * cov / 255); + } + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Extrude: the picture becomes blocks standing out of a solid colour */ +static void +OpExtrude(int cell, int depth, int solidFront) +{ + unsigned char *rgb, *out; + int w, h, x, y, bx, by, c; + unsigned char br, bg, bb; + + if (cell < 2) cell = 2; + if (depth < 1) depth = 1; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((out = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + PixelToRGB(bgPixel, &br, &bg, &bb); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + memcpy(out + ((size_t) y * w + x) * 3, (unsigned char[]) { + solidFront ? br : 0, solidFront ? bg : 0, + solidFront ? bb : 0 }, 3); + for (by = 0; by < h; by += cell) + for (bx = 0; bx < w; bx += cell) { + int n = NoiseAt(bx, by, 5u); + int off = (int) ((unsigned) n % (unsigned) (2 * depth + 1)) - + depth; + int side = (int) ((n >> 8) % 3); + + for (y = by; y < by + cell && y < h; y++) + for (x = bx; x < bx + cell && x < w; x++) { + int sx = x + off, sy = y + off; + unsigned char *d; + const unsigned char *o; + + if (sx < 0 || sy < 0 || sx >= w || sy >= h) + continue; + d = out + ((size_t) y * w + x) * 3; + o = rgb + ((size_t) sy * w + sx) * 3; + for (c = 0; c < 3; c++) { + int v = o[c]; + + /* the sides are darker, so the + * block reads as a block */ + if (side == 1) + v = v * 2 / 3; + else if (side == 2) + v = v / 2; + d[c] = (unsigned char) v; + } + } + } + free(rgb); + SetImageRGB(out, w, h); + free(out); +} + +/* Tiles: the picture repeats in a grid, the gap filled with the bg colour */ +static void +OpTiles(int size, int offset) +{ + unsigned char *rgb, *out; + int w, h, x, y, c; + unsigned char br, bg, bb; + + if (size < 2) size = 2; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((out = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + PixelToRGB(bgPixel, &br, &bg, &bb); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = out + ((size_t) y * w + x) * 3; + int sx = x % size, sy = y % size; + int gap = offset / 2; + + if (sx < gap || sy < gap) { + d[0] = br; d[1] = bg; d[2] = bb; + } else { + const unsigned char *o = rgb + + ((size_t) (sy - gap) * w + (sx - gap + offset)) * 3; + + for (c = 0; c < 3; c++) + d[c] = o[c]; + } + } + free(rgb); + SetImageRGB(out, w, h); + free(out); +} + +/* Trace Contour: the pixels where the luminance crosses the level */ +static void +OpTraceContour(int level) +{ + unsigned char *rgb, *src; + int w, h, x, y; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + int lum, rl, dn, edge, c; + + if (cov <= 0) + continue; + lum = (int) LUMA(o[0], o[1], o[2]); + rl = x + 1 < w ? + (int) LUMA(src[((size_t) y * w + x + 1) * 3], + src[((size_t) y * w + x + 1) * 3 + 1], + src[((size_t) y * w + x + 1) * 3 + 2]) : lum; + dn = y + 1 < h ? + (int) LUMA(src[((size_t) (y + 1) * w + x) * 3], + src[((size_t) (y + 1) * w + x) * 3 + 1], + src[((size_t) (y + 1) * w + x) * 3 + 2]) : lum; + edge = ((lum - level) * (rl - level) < 0) || + ((lum - level) * (dn - level) < 0); + for (c = 0; c < 3; c++) { + int v = edge ? 0 : 255; + + d[c] = cov >= 255 ? (unsigned char) v : + (unsigned char) (o[c] + + (v - o[c]) * cov / 255); + } + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Wind: streaks in one direction, the amount is the streak length */ +static void +OpWind(int strength, int mode) +{ + unsigned char *rgb, *src; + int w, h, x, y, c, i; + + if (strength < 1) strength = 1; + if (strength > 100) strength = 100; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + + if (cov <= 0) + continue; + for (c = 0; c < 3; c++) { + int v = o[c]; + + for (i = 1; i <= strength; i++) { + int sx = x - i; + int n = src[((size_t) y * w + + (sx < 0 ? 0 : sx)) * 3 + c]; + + if (mode == 1) { /* blast */ + if (n > v) v = n; + } else if (mode == 2) { /* stagger */ + if ((i & 1) && n > v) v = n; + } else if (n < v) /* wind */ + v = n; + } + d[c] = cov >= 255 ? (unsigned char) v : + (unsigned char) (o[c] + + (v - o[c]) * cov / 255); + } + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* ------------------------------------------------------ Filter > Sharpen */ + +/* Sharpen Edges: the sharpening only where the luminance changes */ +static void +OpSharpenEdges(void) +{ + static const double sharp[9] = { + 0.0, -1.0, 0.0, + -1.0, 5.0, -1.0, + 0.0, -1.0, 0.0 + }; + unsigned char *rgb, *src; + int w, h, x, y; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + Convolve3x3(sharp, 0.0); + if (GetImageRGB(&rgb, &w, &h) != 0) { + free(src); + return; + } + /* keep the sharpened value only where the edge actually is */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + int lum = (int) LUMA(o[0], o[1], o[2]); + int r = x + 1 < w ? (int) LUMA( + src[((size_t) y * w + x + 1) * 3], + src[((size_t) y * w + x + 1) * 3 + 1], + src[((size_t) y * w + x + 1) * 3 + 2]) : lum; + int diff = lum - r; + int c; + + if (diff < 0) diff = -diff; + if (diff < 12) + for (c = 0; c < 3; c++) + d[c] = o[c]; + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* ------------------------------------------------------- Filter > Video */ + +/* De-Interlace: the odd rows are rebuilt from their neighbours */ +static void +OpDeInterlace(int odd) +{ + unsigned char *rgb; + int w, h, x, y, c; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + for (y = odd ? 1 : 0; y < h; y += 2) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *up = rgb + + ((size_t) (y > 0 ? y - 1 : y) * w + x) * 3; + const unsigned char *dn = rgb + + ((size_t) (y + 1 < h ? y + 1 : y) * w + x) * 3; + + if (selMaskAny && !MaskGet(x, y)) + continue; + for (c = 0; c < 3; c++) + d[c] = (unsigned char) ((up[c] + dn[c] + 1) / 2); + } + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* NTSC Colors: the broadcast-safe range, 16..235 per channel */ +static void +NtscPx(unsigned char *p, void *cd) +{ + int c; + + (void) cd; + for (c = 0; c < 3; c++) { + int v = 16 + p[c] * 219 / 255; + + if (v < 16) v = 16; + if (v > 235) v = 235; + p[c] = (unsigned char) v; + } +} + +static void +OpNtscColors(void) +{ + OpPerPixel(NtscPx, NULL); +} + +/* ------------------------------------------------------- Filter > Other */ + +/* Custom: a 5x5 kernel the person types, with a scale and an offset */ +static void +OpCustom(const double k[25], double scale, double offset) +{ + Kernel kn; + + kn.r = 2; kn.k = k; kn.bias = offset; + kn.div = scale; kn.absolute = 0; + ConvolveN(&kn); +} + +/* Radial Blur: the picture is smeared along rays out of its centre */ +static void +OpRadialBlur(int amount, int spin) +{ + unsigned char *rgb, *src; + int w, h, x, y, c, i; + double cx = 0.0, cy = 0.0; + double k; + + if (amount < 1) amount = 1; + if (amount > 100) amount = 100; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + k = amount / 100.0; + if (spin) { + cx = w / 2.0; + cy = h / 2.0; + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + int steps = 2 + amount / 3; + int acc[3] = { 0, 0, 0 }; + + if (cov <= 0) + continue; + for (i = 0; i < steps; i++) { + double t = (double) i / (steps > 1 ? steps - 1 : 1); + double sx, sy; + int ix, iy; + + if (spin) { + /* the ray goes out from the centre */ + sx = x + (x - cx) * k * (t - 0.5); + sy = y + (y - cy) * k * (t - 0.5); + } else { + /* zoom: the same picture, bigger */ + sx = cx + (x - cx) * (1.0 + k * (t - 0.5)); + sy = cy + (y - cy) * (1.0 + k * (t - 0.5)); + } + ix = (int) (sx + 0.5); + iy = (int) (sy + 0.5); + if (ix < 0) ix = 0; + if (ix >= w) ix = w - 1; + if (iy < 0) iy = 0; + if (iy >= h) iy = h - 1; + acc[0] += src[((size_t) iy * w + ix) * 3]; + acc[1] += src[((size_t) iy * w + ix) * 3 + 1]; + acc[2] += src[((size_t) iy * w + ix) * 3 + 2]; + } + for (c = 0; c < 3; c++) { + int v = (acc[c] + steps / 2) / steps; + + d[c] = cov >= 255 ? (unsigned char) v : + (unsigned char) (o[c] + + (v - o[c]) * cov / 255); + } + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Smart Blur: a blur that keeps the edges, so skin stays sharp at the line */ +static void +OpSmartBlur(int radius, int threshold) +{ + unsigned char *rgb, *src; + int w, h, x, y, c; + + if (radius < 1) radius = 1; + if (radius > 8) radius = 8; + if (threshold < 0) threshold = 0; + if (threshold > 255) threshold = 255; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + int sum[3] = { 0, 0, 0 }, n = 0; + int xx, yy; + + if (cov <= 0) + continue; + for (yy = y - radius; yy <= y + radius; yy++) + for (xx = x - radius; xx <= x + radius; xx++) { + const unsigned char *s; + int near, cc; + + if (xx < 0 || yy < 0 || xx >= w || yy >= h) + continue; + s = src + ((size_t) yy * w + xx) * 3; + /* only the neighbours that look alike + * take part: that is the edge guard */ + near = 1; + for (cc = 0; cc < 3; cc++) { + int diff = s[cc] - o[cc]; + + if (diff < 0) diff = -diff; + if (diff > threshold) { + near = 0; + break; + } + } + if (!near) + continue; + for (cc = 0; cc < 3; cc++) + sum[cc] += s[cc]; + n++; + } + if (n == 0) + continue; + for (c = 0; c < 3; c++) { + int v = (sum[c] + n / 2) / n; + + d[c] = cov >= 255 ? (unsigned char) v : + (unsigned char) (o[c] + + (v - o[c]) * cov / 255); + } + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Wave: a sine displacement, the classic one with the crests */ +static void +OpWave(int amplitude, int length, int phase) +{ + unsigned char *rgb, *src; + int w, h, x, y; + + if (amplitude < 1) amplitude = 1; + if (length < 1) length = 1; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + double sx, sy; + int ix, iy; + + if (cov <= 0) + continue; + sx = x + amplitude * + sin(2.0 * M_PI * (y + phase) / length); + sy = y + amplitude * + sin(2.0 * M_PI * (x + phase) / (length * 1.5)); + ix = (int) (sx + 0.5); + iy = (int) (sy + 0.5); + if (ix < 0) ix = 0; + if (ix >= w) ix = w - 1; + if (iy < 0) iy = 0; + if (iy >= h) iy = h - 1; + { + const unsigned char *s = src + + ((size_t) iy * w + ix) * 3; + int c; + + for (c = 0; c < 3; c++) + d[c] = cov >= 255 ? s[c] : + (unsigned char) (o[c] + + (s[c] - o[c]) * cov / 255); + } + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + +/* Dust & Scratches: the outliers go, the rest of the picture stays */ +static void +OpDustScratches(int radius, int threshold) +{ + unsigned char *rgb, *src; + int w, h, x, y, c; + + if (radius < 1) radius = 1; + if (radius > 8) radius = 8; + if (threshold < 0) threshold = 0; + if (threshold > 255) threshold = 255; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + if ((src = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return; + } + memcpy(src, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *o = src + ((size_t) y * w + x) * 3; + int cov = selMaskAny ? MaskCover(x, y) : 255; + unsigned char lo[3] = { 255, 255, 255 }; + unsigned char hi[3] = { 0, 0, 0 }; + int xx, yy; + + if (cov <= 0) + continue; + for (yy = y - radius; yy <= y + radius; yy++) + for (xx = x - radius; xx <= x + radius; xx++) { + const unsigned char *s; + + if (xx < 0 || yy < 0 || xx >= w || yy >= h) + continue; + s = src + ((size_t) yy * w + xx) * 3; + for (c = 0; c < 3; c++) { + if (s[c] < lo[c]) lo[c] = s[c]; + if (s[c] > hi[c]) hi[c] = s[c]; + } + } + for (c = 0; c < 3; c++) { + int v = o[c]; + int spread = hi[c] - lo[c]; + + /* a pixel far from its neighbourhood is a + * speck: replace it with the middle value */ + if (spread > threshold) + v = (lo[c] + hi[c]) / 2; + d[c] = cov >= 255 ? (unsigned char) v : + (unsigned char) (o[c] + + (v - o[c]) * cov / 255); + } + } + free(src); + SetImageRGB(rgb, w, h); + free(rgb); +} + /* * The gradient tool. Photoshop draws a linear ramp from the foreground to * the background colour along the drag; the mask, when there is one, clips @@ -3803,6 +8442,15 @@ AddNoiseOk(int amount, int unused) fprintf(stderr, "dtphoto: add noise %d\n", amount); } +static void +IndexedOk(int colors, int unused) +{ + (void) unused; + OpIndexed(colors); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: indexed %d colours\n", colors); +} + static void MosaicOk(int cell, int unused) { @@ -4042,6 +8690,12 @@ CanvasInput(Widget w, XtPointer cd, XEvent *ev, Boolean *keep) return; x = ev->xmotion.x; y = ev->xmotion.y; docx = DocX(x, ox); docy = DocY(y, oy); + /* the marquee and the crop follow the grid or a guide when + * the View menu has them on; a free drag is unchanged */ + if (currentTool == 0 || currentTool == 1 || currentTool == 7) { + docx = SnapX(docx); + docy = SnapY(docy); + } switch (currentTool) { case 0: case 1: selX1 = docx; selY1 = docy; @@ -4577,6 +9231,248 @@ DumpBound(const Menu *menus, int n) DumpBoundMenu(&menus[i]); } +/* + * The dialog callbacks of the Filter menu. Each one takes the field values + * and calls the operation underneath; the operations themselves are checked + * by -optest, so these only have to pass the numbers through, and OpDone + * prints what ran so a mouse test can read it. + */ +static void +GaussianOk(const int *v) +{ + OpGaussianBlur(v[0] / 10.0); + OpDone("gaussian blur"); +} + +static void +MotionOk(const int *v) +{ + OpMotionBlur(v[0], v[1]); + OpDone("motion blur"); +} + +static void +RadialOk(const int *v) +{ + OpRadialBlur(v[0], v[1] != 0); + OpDone("radial blur"); +} + +static void +SmartOk(const int *v) +{ + OpSmartBlur(v[0], v[1]); + OpDone("smart blur"); +} + +static void +DisplaceOk(const int *v) +{ + OpDisplace(v[0] / 10.0, (unsigned) v[1]); + OpDone("displace"); +} + +static void +PinchOk(const int *v) +{ + OpPinch(v[0]); + OpDone("pinch"); +} + +static void +PolarOk(const int *v) +{ + OpPolar(v[0] != 0); + OpDone("polar coordinates"); +} + +static void +RippleOk(const int *v) +{ + OpRipple(v[0] / 10.0, v[1] / 10.0, v[2]); + OpDone("ripple"); +} + +static void +ShearOk(const int *v) +{ + OpShear(v[0]); + OpDone("shear"); +} + +static void +SpherizeOk(const int *v) +{ + OpSpherize(v[0]); + OpDone("spherize"); +} + +static void +TwirlOk(const int *v) +{ + OpTwirl(v[0], v[1]); + OpDone("twirl"); +} + +static void +WaveOk(const int *v) +{ + OpWave(v[0], v[1], v[2]); + OpDone("wave"); +} + +static void +ZigZagOk(const int *v) +{ + OpZigZag(v[0], v[1]); + OpDone("zigzag"); +} + +static void +DustOk(const int *v) +{ + OpDustScratches(v[0], v[1]); + OpDone("dust & scratches"); +} + +static void +HalftoneOk(const int *v) +{ + OpColorHalftone(v[0]); + OpDone("color halftone"); +} + +static void +CrystallizeOk(const int *v) +{ + OpCrystallize(v[0]); + OpDone("crystallize"); +} + +static void +MezzotintOk(const int *v) +{ + OpMezzotint(v[0]); + OpDone("mezzotint"); +} + +static void +PointillizeOk(const int *v) +{ + OpPointillize(v[0]); + OpDone("pointillize"); +} + +static void +LensFlareOk(const int *v) +{ + OpLensFlare(v[0] > 0 ? v[0] : docW / 2, v[1] > 0 ? v[1] : docH / 2, + v[2]); + OpDone("lens flare"); +} + +static void +LightingOk(const int *v) +{ + OpLighting(v[0], v[1]); + OpDone("lighting effects"); +} + +static void +UnsharpOk(const int *v) +{ + OpUnsharp(v[0] / 100.0, v[1] / 10.0, v[2]); + OpDone("unsharp mask"); +} + +static void +DiffuseOk(const int *v) +{ + OpDiffuse(v[0]); + OpDone("diffuse"); +} + +static void +ExtrudeOk(const int *v) +{ + OpExtrude(v[0], v[1], v[2] != 0); + OpDone("extrude"); +} + +static void +TilesOk(const int *v) +{ + OpTiles(v[0], v[1]); + OpDone("tiles"); +} + +static void +TraceOk(const int *v) +{ + OpTraceContour(v[0]); + OpDone("trace contour"); +} + +static void +WindOk(const int *v) +{ + OpWind(v[0], v[1]); + OpDone("wind"); +} + +static void +DeInterlaceOk(const int *v) +{ + OpDeInterlace(v[0] != 0); + OpDone("de-interlace"); +} + +static void +HighPassOk(const int *v) +{ + OpHighPass(v[0] / 10.0); + OpDone("high pass"); +} + +static void +MaximumOk(const int *v) +{ + OpRank(v[0], 1); + OpDone("maximum"); +} + +static void +MinimumOk(const int *v) +{ + OpRank(v[0], 0); + OpDone("minimum"); +} + +static void +OffsetOk(const int *v) +{ + OpOffset(v[0], v[1]); + OpDone("offset"); +} + +/* The custom kernel: 25 weights, then the scale and the offset */ +static void +CustomOk(const int *v) +{ + double k[25]; + int i; + + for (i = 0; i < 25; i++) + k[i] = v[i]; + if (v[25] == 0) { + /* a scale of zero would black the picture out */ + OpDone("custom (scale 0 refused)"); + return; + } + OpCustom(k, v[25], v[26]); + OpDone("custom"); +} + static void MenuCallback(Widget w, XtPointer data, XtPointer call) { @@ -4700,6 +9596,39 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) NumberDialog("Brightness Contrast (-100..100):", "0 0", BrightContrastOk); break; + case CMD_LEVELS: + FieldDialog("Levels", "Black White Gamma", "0 255 100", + LevelsOk); + break; + case CMD_CURVES: + FieldDialog("Curves", "Shadow Highlight Midgrey", + "0 255 128", CurvesOk); + break; + case CMD_COLORBALANCE: + FieldDialog("Color Balance", "Red Green Blue", "0 0 0", + ColorBalanceOk); + break; + case CMD_HUESAT: + FieldDialog("Hue/Saturation", "Hue Sat Light", "0 0 0", + HueSatOk); + break; + case CMD_THRESHOLD: + FieldDialog("Threshold", "Level", "128", ThresholdOk); + break; + case CMD_POSTERIZE: + FieldDialog("Posterize", "Levels", "4", PosterizeOk); + break; + case CMD_EQUALIZE: + OpEqualize(); + OpDone("equalize"); + break; + case CMD_REPLACECOLOR: + FieldDialog("Replace Color", "Fuzz", "32", ReplaceOk); + break; + case CMD_SELECTIVECOLOR: + FieldDialog("Selective Color", "Channel Low Shift", + "0 0 0", SelectiveOk); + break; case CMD_IMAGESIZE: { char buf[32]; @@ -4729,6 +9658,746 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) case CMD_MOSAIC: NumberDialog("Mosaic (cell size):", "8", MosaicOk); break; + /* Filter > Blur */ + case CMD_GAUSSIAN: + FieldDialog("Gaussian Blur", "Radius x10", "20", GaussianOk); + break; + case CMD_MOTIONBLUR: + FieldDialog("Motion Blur", "Angle Distance", "0 10", MotionOk); + break; + case CMD_RADIALBLUR: + FieldDialog("Radial Blur", "Amount Spin(0/1)", "20 0", RadialOk); + break; + case CMD_SMARTBLUR: + FieldDialog("Smart Blur", "Radius Threshold", "2 24", + SmartOk); + break; + /* Filter > Distort */ + case CMD_DISPLACE: + FieldDialog("Displace", "Scale Seed", "8 1", DisplaceOk); + break; + case CMD_PINCH: + FieldDialog("Pinch", "Amount", "50", PinchOk); + break; + case CMD_POLAR: + FieldDialog("Polar Coordinates", "Rect->Polar (1/0)", "1", + PolarOk); + break; + case CMD_RIPPLE: + FieldDialog("Ripple", "Amount x10 Wavelength Phase", + "20 60 0", RippleOk); + break; + case CMD_SHEAR: + FieldDialog("Shear", "Amount", "20", ShearOk); + break; + case CMD_SPHERIZE: + FieldDialog("Spherize", "Amount", "50", SpherizeOk); + break; + case CMD_TWIRL: + FieldDialog("Twirl", "Angle Radius", "45 100", TwirlOk); + break; + case CMD_WAVE: + FieldDialog("Wave", "Amplitude Length Phase", "8 32 0", + WaveOk); + break; + case CMD_ZIGZAG: + FieldDialog("ZigZag", "Amount Ridges", "20 5", ZigZagOk); + break; + /* Filter > Noise */ + case CMD_DUST: + FieldDialog("Dust & Scratches", "Radius Threshold", "1 32", + DustOk); + break; + /* Filter > Pixelate */ + case CMD_HALFTONE: + FieldDialog("Color Halftone", "Cell Size", "8", HalftoneOk); + break; + case CMD_CRYSTALLIZE: + FieldDialog("Crystallize", "Cell Size", "8", CrystallizeOk); + break; + case CMD_FACET: + OpFacet(); + OpDone("facet"); + break; + case CMD_FRAGMENT: + OpFragment(); + OpDone("fragment"); + break; + case CMD_MEZZOTINT: + FieldDialog("Mezzotint", "Mode 0-2", "0", MezzotintOk); + break; + case CMD_POINTILLIZE: + FieldDialog("Pointillize", "Cell Size", "8", PointillizeOk); + break; + /* Filter > Render */ + case CMD_CLOUDS: + OpClouds(0); + OpDone("clouds"); + break; + case CMD_DIFFCLOUDS: + OpClouds(1); + OpDone("difference clouds"); + break; + case CMD_LENSFLARE: + FieldDialog("Lens Flare", "X Y Brightness", "0 0 100", + LensFlareOk); + break; + case CMD_LIGHTING: + FieldDialog("Lighting Effects", "Intensity Angle", "60 45", + LightingOk); + break; + case CMD_TEXTUREFILL: + OpTextureFill(); + OpDone("texture fill"); + break; + /* Filter > Sharpen */ + case CMD_SHARPENEDGES: + OpSharpenEdges(); + OpDone("sharpen edges"); + break; + case CMD_UNSHARP: + FieldDialog("Unsharp Mask", "Amount x100 Radius x10 Threshold", + "100 10 3", UnsharpOk); + break; + /* Filter > Stylize */ + case CMD_DIFFUSE: + FieldDialog("Diffuse", "Mode 0-3", "1", DiffuseOk); + break; + case CMD_EXTRUDE: + FieldDialog("Extrude", "Cell Depth SolidFront(0/1)", + "8 4 1", ExtrudeOk); + break; + case CMD_TILES: + FieldDialog("Tiles", "Size Offset", "32 4", TilesOk); + break; + case CMD_TRACECONTOUR: + FieldDialog("Trace Contour", "Level", "128", TraceOk); + break; + case CMD_WIND: + FieldDialog("Wind", "Strength Mode 0-2", "8 0", WindOk); + break; + /* Filter > Video */ + case CMD_DEINTERLACE: + FieldDialog("De-Interlace", "Odd rows (1) or even (0)", "1", + DeInterlaceOk); + break; + case CMD_NTSC: + OpNtscColors(); + OpDone("ntsc colors"); + break; + /* Filter > Other */ + case CMD_CUSTOM: { + static char kbuf[128]; + int i; + + /* the identity kernel, a person changes what they need */ + for (i = 0; i < 25; i++) + snprintf(kbuf + i * 5, 5, "%s", + i == 12 ? "1 " : "0 "); + FieldDialog("Custom (5x5, then scale and offset)", + "k0 k1 k2 k3 k4 k5 k6 k7 k8 k9 k10 k11 k12 k13 k14 " + "k15 k16 k17 k18 k19 k20 k21 k22 k23 k24 Scale Offset", + "0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 " + "1 0", CustomOk); + break; + } + case CMD_HIGHPASS: + FieldDialog("High Pass", "Radius x10", "20", HighPassOk); + break; + case CMD_MAXIMUM: + FieldDialog("Maximum", "Radius", "1", MaximumOk); + break; + case CMD_MINIMUM: + FieldDialog("Minimum", "Radius", "1", MinimumOk); + break; + case CMD_OFFSET: + FieldDialog("Offset", "X Y", "10 10", OffsetOk); + break; + /* File: the document's own housekeeping */ + case CMD_CLOSE: + CloseDoc(); + break; + case CMD_REVERT: + RevertDoc(); + break; + case CMD_FILEINFO: + FileInfo(); + break; + case CMD_PRINT: + PrintDoc(); + break; + case CMD_PAGESETUP: + PageSetup(); + break; + case CMD_PREFS: + FieldDialog("Preferences", "Undo depth", "1", PrefsOk); + break; + /* Edit: the clipboard and the pattern */ + case CMD_CUT: + CopyToClip(); + MaskClear(); + XSetForeground(dpy, gc, bgPixel); + XFillRectangle(dpy, image, gc, 0, 0, docW, docH); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: cut\n"); + break; + case CMD_COPY: + CopyToClip(); + break; + case CMD_PASTE: + PasteFromClip(); + break; + case CMD_DEFPATTERN: + DefinePattern(); + break; + case CMD_STROKE: + FieldDialog("Stroke", "Width", "1", StrokeOk); + break; + /* Image > Mode: the pixel formats this build really has */ + case CMD_MODEBITMAP: + OpBitmap(); + RenderDoc(canvas); + ModeName("bitmap"); + break; + case CMD_MODEGRAY: + OpGrayscale(); + RenderDoc(canvas); + ModeName("grayscale"); + break; + case CMD_MODEINDEXED: + NumberDialog("Indexed Color (palette size):", "256", + IndexedOk); + break; + case CMD_MODERGB: + ModeName("rgb"); + break; + case CMD_MODELAB: + ModeName("lab"); + break; + /* Image > Adjust */ + case CMD_HISTOGRAM: + ShowHistogram(); + break; + case CMD_DUPLICATE: + DuplicateDoc(); + break; + case CMD_APPLYIMAGE: + FieldDialog("Apply Image", "Amount", "100", ApplyImageOk); + break; + case CMD_CALCULATIONS: + FieldDialog("Calculations", "Amount", "100", CalculationsOk); + break; + case CMD_TRAP: + FieldDialog("Trap", "Width", "1", TrapOk); + break; + case CMD_ROTARB: + FieldDialog("Rotate", "Degrees", "0", RotArbOk); + break; + /* Select */ + case CMD_COLORRANGE: + FieldDialog("Color Range", "Tolerance", "32", ColorRangeOk); + break; + case CMD_DEFRINGE: + FieldDialog("Defringe", "Width", "1", DefringeOk); + break; + case CMD_REMOVEBLACK: + OpMatte(0); + RenderDoc(canvas); + OpDone("remove black matte"); + break; + case CMD_REMOVEWHITE: + OpMatte(1); + RenderDoc(canvas); + OpDone("remove white matte"); + break; + /* View */ + case CMD_RULERS: + showRulers = !showRulers; + RenderDoc(canvas); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: rulers %s\n", + showRulers ? "on" : "off"); + break; + case CMD_GRID: + showGrid = !showGrid; + RenderDoc(canvas); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: grid %s\n", + showGrid ? "on" : "off"); + break; + /* Window: the palettes and the one document */ + case CMD_CASCADE: + WindowArrange("cascade"); + break; + case CMD_CLOSEALL: + CloseDoc(); + break; + case CMD_SHOWTOOLS: + Palette(&toolShell, "Tools", 8, 64, NULL); + break; + case CMD_SHOWBRUSHES: + Palette(&palBrushes, "Brushes", 120, 64, BuildBrushes); + break; + case CMD_SHOWPICKER: + Palette(&palPicker, "Picker", 120, 220, BuildPicker); + break; + case CMD_SHOWSWATCHES: + Palette(&palSwatches, "Swatches", 260, 64, BuildSwatches); + break; + case CMD_SHOWSCRATCH: + Palette(&palScratch, "Scratch", 260, 220, BuildScratch); + break; + case CMD_SHOWINFO: + Palette(&palInfo, "Info", 400, 64, BuildInfo); + break; + /* Help */ + case CMD_ABOUT: + AboutBox(); + break; + /* ---------------- the rest of the reference's menu list ---------- */ + /* File */ + case CMD_OPENAS: FileDialog(0); break; + case CMD_PLACE: + MessageBox("Place", + "Place reads a second picture into this document.\n" + "This build keeps one picture per window, so there is " + "nothing to place into: open the second picture and " + "use Edit > Copy, then Edit > Paste."); + fprintf(stderr, "dtphoto: place (one picture per window)\n"); + break; + case CMD_SAVECOPY: FileDialog(1); break; + case CMD_ACQUIRE: + MessageBox("Acquire", + "Acquire reads from a scanner or a camera.\n" + "No TWAIN source is configured in this build."); + fprintf(stderr, "dtphoto: acquire (no source)\n"); + break; + case CMD_EXPORT: + MessageBox("Export", + "Export writes a file for another program.\n" + "This build writes BMP, PNG, JPEG and GIF through " + "File > Save As."); + fprintf(stderr, "dtphoto: export\n"); + break; + /* Edit */ + case CMD_PASTEINTO: + PasteFromClip(); + OpDone("paste into"); + break; + case CMD_PASTELAYER: + LayerNew(); + PasteFromClip(); + OpDone("paste layer"); + break; + case CMD_CREATEPUB: + case CMD_PUBOPTS: + MessageBox("Publisher", + "Publisher writes an Acrobat exchange file.\n" + "There is no PDF writer in this build; File > Save As " + "writes BMP, PNG, JPEG and GIF."); + fprintf(stderr, "dtphoto: publisher (no pdf writer)\n"); + break; + case CMD_SNAPSHOT: + XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); + SetScratch("Snapshot taken: %d x %d, Edit > Undo returns " + "here", docW, docH); + fprintf(stderr, "dtphoto: snapshot\n"); + break; + /* Image > Mode */ + case CMD_MODEDUOTONE: + OpGrayscale(); + OpDone("duotone (one ink: the grey plate)"); + break; + case CMD_MODECMYK: + OpCMYKPreview(); + OpDone("cmyk"); + break; + case CMD_MODEMULTI: + OpGrayscale(); + OpDone("multichannel (one channel: the picture)"); + break; + case CMD_COLORTABLE: + ShowHistogram(); + break; + case CMD_CMYKPREVIEW: + OpCMYKPreview(); + OpDone("cmyk preview"); + break; + case CMD_GAMUT: + OpGamutWarning(1); + OpDone("gamut warning"); + break; + case CMD_IMAGEDUP: + DuplicateDoc(); + break; + /* Image > Effects */ + case CMD_EFFECTSCALE: { + char buf[32]; + + snprintf(buf, sizeof buf, "100"); + FieldDialog("Scale", "Percent", buf, EffectScaleOk); + break; + } + case CMD_EFFECTROTATE: + FieldDialog("Rotate", "Degrees", "0", RotArbOk); + break; + case CMD_EFFECTSKEW: + FieldDialog("Skew", "Degrees", "0", EffectSkewOk); + break; + case CMD_EFFECTDISTORT: + FieldDialog("Distort", "Percent", "20", EffectDistortOk); + break; + case CMD_EFFECTPERSP: + FieldDialog("Perspective", "Percent", "20", EffectDistortOk); + break; + /* Layer */ + case CMD_LAYERNEW: + LayerNew(); + OpDone("layer new"); + break; + case CMD_LAYERADJ: + LayerNew(); + SetScratch("Adjustment layer %d/%d: it holds no pixels, " + "Image > Adjust writes into the current layer", + curLayer + 1, nlayers); + OpDone("adjustment layer"); + break; + case CMD_LAYERDUP: + LayerDuplicate(); + OpDone("layer duplicate"); + break; + case CMD_LAYERDELETE: + LayerDelete(); + break; + case CMD_LAYEROPTS: + SetScratch("Layer %d/%d, %d%%, mode %s", curLayer + 1, + nlayers, nlayers > 0 ? layers[curLayer].opacity : 100, + nlayers > 0 && layers[curLayer].mode == 1 ? "multiply" : + nlayers > 0 && layers[curLayer].mode == 2 ? "screen" : + "normal"); + MessageBox("Layer Options", + "The stack holds this document's layers.\n" + "Window > Show Layers names the current one, " + "Layer > Arrange moves it through the stack."); + fprintf(stderr, "dtphoto: layer options %d/%d\n", + curLayer + 1, nlayers); + break; + case CMD_ADJOPTS: + MessageBox("Adjustment Options", + "An adjustment layer would carry a correction.\n" + "This build corrects the layer itself: Image > Adjust."); + fprintf(stderr, "dtphoto: adjustment options\n"); + break; + case CMD_DROPSHADOW: + OpLayerEffect(0, 4, 60, 4, 4); + break; + case CMD_INNERSHADOW: + OpLayerEffect(1, 4, 60, 0, 0); + break; + case CMD_OUTERGLOW: + OpLayerEffect(2, 6, 70, 0, 0); + break; + case CMD_INNERGLOW: + OpLayerEffect(3, 6, 70, 0, 0); + break; + case CMD_BEVEL: + OpLayerEffect(4, 3, 80, 0, 0); + break; + case CMD_RENDERLAYER: + SetScratch("Text is pixels the moment it is placed, so " + "there is nothing left to render"); + fprintf(stderr, "dtphoto: render layer (text is pixels)\n"); + break; + case CMD_TYPEH: + case CMD_TYPEV: + /* the type tool of the toolbox, which is how text gets in */ + currentTool = 7; + fprintf(stderr, "dtphoto: tool %s\n", toolNames[currentTool]); + break; + case CMD_LAYERSCALE: + FieldDialog("Layer Scale", "Percent", "100", EffectScaleOk); + break; + case CMD_LAYERROTATE: + FieldDialog("Layer Rotate", "Degrees", "0", RotArbOk); + break; + case CMD_LAYERSKEW: + FieldDialog("Layer Skew", "Degrees", "0", EffectSkewOk); + break; + case CMD_LAYERDISTORT: + FieldDialog("Layer Distort", "Percent", "20", EffectDistortOk); + break; + case CMD_LAYERPERSP: + FieldDialog("Layer Perspective", "Percent", "20", EffectDistortOk); + break; + case CMD_LAYERNUMERIC: + FieldDialog("Numeric Transform", "Degrees", "0", RotArbOk); + break; + case CMD_BRINGFRONT: + LayerArrange(0); + break; + case CMD_BRINGFWD: + LayerArrange(1); + break; + case CMD_SENDBWD: + LayerArrange(2); + break; + case CMD_SENDBACK: + LayerArrange(3); + break; + case CMD_MERGEDOWN: + LayerMerge(0); + break; + case CMD_MERGEVISIBLE: + LayerMerge(1); + break; + case CMD_FLATTEN: + LayerMerge(1); + break; + case CMD_LAYERDEFRINGE: + FieldDialog("Defringe", "Width", "1", DefringeOk); + break; + case CMD_LAYERBLACK: + OpMatte(0); + OpDone("layer remove black matte"); + break; + case CMD_LAYERWHITE: + OpMatte(1); + OpDone("layer remove white matte"); + break; + /* Select */ + case CMD_FLOAT: + if (!selMaskAny) { + SetScratch("Float needs a selection."); + fprintf(stderr, "dtphoto: float needs a selection\n"); + break; + } + if (MoveBegin() != 0) { + SetScratch("Float could not lift the selection."); + break; + } + SetScratch("Floating: drag with the move tool, " + "Select > Defloat drops it"); + fprintf(stderr, "dtphoto: float\n"); + break; + case CMD_DEFLOAT: + MoveEnd(); + OpDone("defloat"); + break; + case CMD_HIDEEDGES: + viewGuides = 0; + RenderDoc(canvas); + fprintf(stderr, "dtphoto: edges hidden\n"); + break; + case CMD_LOADSEL: { + /* the .sel file Save Selection wrote, beside the picture */ + char path[1024]; + FILE *f; + int w = 0, h = 0, maxv = 0, x, y; + + if (docPath == NULL) { + MessageBox("Load Selection", + "Select > Save Selection writes the selection " + "beside the picture, so load needs a saved " + "document first."); + fprintf(stderr, "dtphoto: load selection, no file\n"); + break; + } + snprintf(path, sizeof path, "%s.sel", docPath); + if ((f = fopen(path, "rb")) == NULL) { + SetScratch("No saved selection for this document."); + fprintf(stderr, "dtphoto: load selection, %s missing\n", + path); + break; + } + if (fscanf(f, "P5 %d %d %d", &w, &h, &maxv) != 3 || + w != docW || h != docH) { + fclose(f); + SetScratch("The saved selection does not fit this " + "picture."); + fprintf(stderr, "dtphoto: load selection, size\n"); + break; + } + fgetc(f); /* the single whitespace after the header */ + if (MaskAlloc() != 0) { + fclose(f); + break; + } + MaskClear(); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + int c = fgetc(f); + + if (c == EOF) + break; + if (c > 0) { + MaskSet(x, y, 1); + if (selCover != NULL) + selCover[(size_t) y * w + x] = + (unsigned char) c; + } + } + fclose(f); + /* the marquee follows the mask's bounding box */ + { + int mx0 = w, my0 = h, mx1 = 0, my1 = 0, any = 0; + + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + if (MaskGet(x, y)) { + any = 1; + if (x < mx0) mx0 = x; + if (y < my0) my0 = y; + if (x > mx1) mx1 = x; + if (y > my1) my1 = y; + } + if (any) { + selX0 = mx0; + selY0 = my0; + selX1 = mx1 + 1; + selY1 = my1 + 1; + hasSel = 1; + } + } + RenderDoc(canvas); + SetScratch("Selection loaded: %s", path); + fprintf(stderr, "dtphoto: selection loaded %s\n", path); + break; + } + case CMD_SAVESEL: { + char path[1024]; + FILE *f; + int x, y; + + if (docPath == NULL) { + MessageBox("Save Selection", + "The selection is written beside the picture.\n" + "File > Save As first, then this."); + fprintf(stderr, "dtphoto: save selection, no file\n"); + break; + } + if (!selMaskAny) { + SetScratch("There is no selection to save."); + fprintf(stderr, "dtphoto: save selection, empty\n"); + break; + } + snprintf(path, sizeof path, "%s.sel", docPath); + if ((f = fopen(path, "wb")) == NULL) { + SetScratch("The selection could not be written."); + fprintf(stderr, "dtphoto: save selection, write\n"); + break; + } + fprintf(f, "P5\n%d %d\n255\n", docW, docH); + for (y = 0; y < docH; y++) + for (x = 0; x < docW; x++) + fputc(MaskCover(x, y), f); + fclose(f); + SetScratch("Selection saved: %s", path); + fprintf(stderr, "dtphoto: selection saved %s\n", path); + break; + } + /* Filter */ + case CMD_LASTFILTER: + RepeatLastFilter(); + break; + case CMD_EMBEDWM: + FieldDialog("Embed Watermark", "Strength", "50", + EmbedWatermarkOk); + break; + case CMD_READWM: + ReadWatermark(); + break; + /* View */ + case CMD_NEWVIEW: + DuplicateDoc(); + break; + case CMD_PREVIEWCMYK: + OpCMYKPreview(); + OpDone("preview cmyk"); + break; + case CMD_PREVIEWRGB: + /* the document is RGB; a preview that was on is undone by + * Undo, so there is nothing else to switch back */ + SetScratch("RGB preview: this document is RGB."); + fprintf(stderr, "dtphoto: preview rgb\n"); + break; + case CMD_VIEWGAMUT: + OpGamutWarning(1); + OpDone("gamut warning"); + break; + case CMD_SHOWEDGES: + viewGuides = 1; + RenderDoc(canvas); + fprintf(stderr, "dtphoto: edges shown\n"); + break; + case CMD_SHOWPATH: + MessageBox("Show Path", + "A path is a saved outline.\n" + "This build has the lasso and the wand, not a pen: " + "there is no path to show."); + fprintf(stderr, "dtphoto: path (no pen tool)\n"); + break; + case CMD_SHOWGUIDES: + showGuides = !showGuides; + RenderDoc(canvas); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: guides %s\n", + showGuides ? "on" : "off"); + break; + case CMD_SNAPGUIDES: + snapGuides = !snapGuides; + fprintf(stderr, "dtphoto: snap to guides %s\n", + snapGuides ? "on" : "off"); + break; + case CMD_LOCKGUIDES: + lockGuides = !lockGuides; + /* a locked guide cannot be moved by a drag */ + if (lockGuides) + fprintf(stderr, "dtphoto: guides locked\n"); + fprintf(stderr, "dtphoto: guides %s\n", + lockGuides ? "locked" : "unlocked"); + break; + case CMD_CLEARGUIDES: + GuidesClear(); + showGuides = 0; + RenderDoc(canvas); + RenderDoc(canvas); + fprintf(stderr, "dtphoto: guides cleared\n"); + break; + case CMD_SNAPGRID: + snapGrid = !snapGrid; + fprintf(stderr, "dtphoto: snap to grid %s\n", + snapGrid ? "on" : "off"); + break; + /* Window */ + case CMD_TILE: + WindowArrange("tile"); + break; + case CMD_ARRANGEICONS: + WindowArrange("arrange icons"); + break; + case CMD_SHOWLAYERS: + ShowLayers(); + break; + case CMD_SHOWCHANNELS: + MessageBox("Channels", + "An RGB picture has three channels.\n" + "This build keeps them together in one buffer, so the " + "palette would show three copies of the same picture."); + fprintf(stderr, "dtphoto: channels\n"); + break; + case CMD_SHOWPATHS: + MessageBox("Paths", + "There is no pen tool in this build, so there are no " + "paths to list."); + fprintf(stderr, "dtphoto: paths\n"); + break; + case CMD_SHOWCOMMANDS: + MessageBox("Commands", + "The commands this build carries out are listed in " + "dtphoto -menutest, one path per line.\n" + "Filter > Last Filter repeats the last one."); + fprintf(stderr, "dtphoto: commands\n"); + break; default: fprintf(stderr, "dtphoto: %s\n", label); break; @@ -5296,66 +10965,272 @@ main(int argc, char **argv) * on. A path that resolves to CMD_NONE is an entry that does * nothing but print its own label. */ if (argc >= 2 && strcmp(argv[1], "-menutest") == 0) { - static const struct { const char *path; int cmd; } want[] = { - { "File/New...", CMD_NEW }, - { "File/Open...", CMD_OPEN }, - { "File/Save", CMD_SAVE }, - { "File/Save As...", CMD_SAVEAS }, - { "Edit/Undo", CMD_UNDO }, - { "Edit/Clear", CMD_CLEAR }, - { "Edit/Crop", CMD_CROP }, - { "Select/All", CMD_ALL }, - { "Select/None", CMD_DESELECT }, - { "Select/Inverse", CMD_INVERSE }, - { "Select/Feather...", CMD_FEATHER }, - { "Select/Modify/Border...", CMD_SELBORDER }, - { "Select/Modify/Smooth...", CMD_SELSMOOTH }, - { "Select/Modify/Expand...", CMD_SELEXPAND }, - { "Select/Modify/Contract...", CMD_SELCONTRACT }, - { "Select/Grow", CMD_SELGROW }, - { "Select/Similar", CMD_SELSIMILAR }, - { "Image/Adjust/Invert", CMD_INVERT }, - { "Image/Adjust/Desaturate", CMD_DESATURATE }, - { "Image/Adjust/Brightness/Contrast...", CMD_BRIGHTCONTRAST }, - { "Image/Flip/Horizontal", CMD_FLIPH }, - { "Image/Flip/Vertical", CMD_FLIPV }, - { "Image/Rotate/180", CMD_ROT180 }, - { "Image/Rotate/90 CW", CMD_ROT90CW }, - { "Image/Rotate/90 CCW", CMD_ROT90CCW }, - { "Image/Image Size...", CMD_IMAGESIZE }, - { "Image/Canvas Size...", CMD_CANVASSIZE }, - { "Filter/Blur/Blur", CMD_BLUR }, - { "Filter/Blur/Blur More", CMD_BLURMORE }, - { "Filter/Sharpen/Sharpen", CMD_SHARPEN }, - { "Filter/Sharpen/Sharpen More", CMD_SHARPENMORE }, - { "Filter/Stylize/Find Edges", CMD_FINDEDGES }, - { "Filter/Stylize/Emboss...", CMD_EMBOSS }, - { "Filter/Stylize/Solarize", CMD_SOLARIZE }, - { "Filter/Noise/Add Noise...", CMD_ADDNOISE }, - { "Filter/Noise/Despeckle", CMD_MEDIAN }, - { "Filter/Noise/Median...", CMD_MEDIAN }, - { "Filter/Pixelate/Mosaic...", CMD_MOSAIC } - }; - size_t i; - int bad = 0; + int i, bad = 0, ntab = 0, ndup = 0; - for (i = 0; i < sizeof want / sizeof want[0]; i++) { - int got = CommandOf(want[i].path); + /* + * Every entry of the command table must resolve to its own + * command, and no two entries may claim the same menu path: + * a path that resolves to CMD_NONE does nothing but print its + * own label, and a doubled path means one of them is dead. + */ + for (i = 0; CmdTable[i].path != NULL; i++) { + int got = CommandOf(CmdTable[i].path); + int j; - if (got != want[i].cmd) { + ntab++; + if (got != CmdTable[i].cmd) { printf("dtphoto menutest: %s -> %d want %d FAIL\n", - want[i].path, got, want[i].cmd); + CmdTable[i].path, got, CmdTable[i].cmd); bad++; } + for (j = 0; j < i; j++) + if (strcmp(CmdTable[j].path, CmdTable[i].path) == 0) { + printf("dtphoto menutest: %s doubled\n", + CmdTable[i].path); + ndup++; + } } /* an unknown path must not grab a command */ if (CommandOf("Filter/Blur/No Such Thing") != CMD_NONE) { printf("dtphoto menutest: unknown path bound FAIL\n"); bad++; } - printf("dtphoto menutest: %d paths, %d bad\n", - (int) (sizeof want / sizeof want[0]), bad); - printf("dtphoto menutest: %s\n", bad == 0 ? "PASS" : "FAIL"); + printf("dtphoto menutest: %d paths, %d doubled, %d bad\n", + ntab, ndup, bad); + printf("dtphoto menutest: %s\n", + (bad == 0 && ndup == 0) ? "PASS" : "FAIL"); + return (bad == 0 && ndup == 0) ? 0 : 1; + } + + /* + * The View menu: every switch must change what a drag does or what + * the canvas draws. Checked against numbers, not against "something + * happened", so a switch wired to nothing shows up as a failure. + */ + if (argc >= 2 && strcmp(argv[1], "-viewtest") == 0) { + int bad = 0, g; + + /* snapping is off by default: a drag goes where the mouse is */ + snapGrid = 0; + snapGuides = 0; + if (SnapX(37) != 37 || SnapY(37) != 37) { + printf("dtphoto viewtest: free drag moved FAIL\n"); + bad++; + } else + printf("dtphoto viewtest: free drag unchanged ok\n"); + + /* Show Grid + Snap to Grid: 37 falls to the next 16 */ + showGrid = 1; + snapGrid = 1; + gridStep = 16; + g = SnapX(37); + if (g != 32) { + printf("dtphoto viewtest: snap grid 37 -> %d want 32 " + "FAIL\n", g); + bad++; + } else + printf("dtphoto viewtest: snap grid 37 -> 32 ok\n"); + g = SnapX(40); + if (g != 48) { + printf("dtphoto viewtest: snap grid 40 -> %d want 48 " + "FAIL\n", g); + bad++; + } else + printf("dtphoto viewtest: snap grid 40 -> 48 ok\n"); + + /* a guide wins over the grid when it is within reach */ + snapGrid = 0; + snapGuides = 1; + nguides = 0; + GuideAdd(35, 1); + g = SnapX(37); + if (g != 35) { + printf("dtphoto viewtest: snap guide 37 -> %d want 35 " + "FAIL\n", g); + bad++; + } else + printf("dtphoto viewtest: snap guide 37 -> 35 ok\n"); + /* out of reach: the guide is ignored, the value stands */ + g = SnapX(60); + if (g != 60) { + printf("dtphoto viewtest: far guide 60 -> %d want 60 " + "FAIL\n", g); + bad++; + } else + printf("dtphoto viewtest: far guide ignored ok\n"); + /* a vertical guide must not pull a horizontal drag */ + g = SnapY(37); + if (g != 37) { + printf("dtphoto viewtest: vert guide on y FAIL\n"); + bad++; + } else + printf("dtphoto viewtest: vert guide leaves y ok\n"); + + /* Lock Guides: no new guide, no clear */ + lockGuides = 1; + GuideAdd(80, 1); + if (nguides != 1) { + printf("dtphoto viewtest: locked guide added FAIL\n"); + bad++; + } else + printf("dtphoto viewtest: locked, none added ok\n"); + GuidesClear(); + if (nguides != 1) { + printf("dtphoto viewtest: locked guides cleared FAIL\n"); + bad++; + } else + printf("dtphoto viewtest: locked, not cleared ok\n"); + lockGuides = 0; + GuidesClear(); + if (nguides != 0) { + printf("dtphoto viewtest: unlock clear FAIL\n"); + bad++; + } else + printf("dtphoto viewtest: unlocked clear ok\n"); + + /* the switches themselves */ + showRulers = 1; + showGrid = 0; + showGuides = 1; + if (!showRulers || showGrid || !showGuides) { + printf("dtphoto viewtest: flags FAIL\n"); + bad++; + } else + printf("dtphoto viewtest: flags ok\n"); + + printf("dtphoto viewtest: %s\n", bad == 0 ? "PASS" : "FAIL"); + return bad == 0 ? 0 : 1; + } + + /* + * The View decorations are drawn on a pixmap and then counted: a + * grid that is switched on must add lines, a ruler must add ticks, + * and switching them off must take them away. Counting pixels is + * how "it is drawn" is proven without a person looking at a screen. + */ + if (argc >= 2 && strcmp(argv[1], "-drawtest") == 0) { + Pixmap pm; + XImage *im; + int bad = 0, x, y; + + pm = XCreatePixmap(dpy, drawable, 400, 300, + (unsigned int) visdepth); + if (pm == None) { + printf("dtphoto drawtest: FAIL pixmap\n"); + return 1; + } + +#define CLEAR() do { \ + XSetForeground(dpy, gc, WhitePixel(dpy, 0)); \ + XFillRectangle(dpy, pm, gc, 0, 0, 400, 300); \ + XSetForeground(dpy, gc, BlackPixel(dpy, 0)); \ +} while (0) +#define DARKCOUNT() ({ int _n = 0, _x, _y; \ + im = XGetImage(dpy, pm, 0, 0, 400, 300, AllPlanes, ZPixmap); \ + for (_y = 0; _y < 300; _y++) \ + for (_x = 0; _x < 400; _x++) \ + if (XGetPixel(im, _x, _y) == BlackPixel(dpy, 0)) _n++; \ + XDestroyImage(im); _n; }) + + /* nothing on: no lines at all */ + showGrid = 0; + showGuides = 0; + showRulers = 0; + nguides = 0; + CLEAR(); + DrawGuides(pm, 10, 10, 380, 280); + { + int n0 = DARKCOUNT(); + + if (n0 != 0) { + printf("dtphoto drawtest: plain %d dark want 0 " + "FAIL\n", n0); + bad++; + } else + printf("dtphoto drawtest: plain empty ok\n"); + } + + /* the grid: many lines, so a lot of dark pixels */ + showGrid = 1; + gridStep = 16; + zoom = 100; + CLEAR(); + DrawGuides(pm, 10, 10, 380, 280); + { + int ng = DARKCOUNT(); + + /* 380/16 vertical + 280/16 horizontal lines, each + * about 380 or 280 pixels long */ + int want = (380 / 16) * 280 + (280 / 16) * 380; + + if (ng < want / 2) { + printf("dtphoto drawtest: grid %d dark " + "want >= %d FAIL\n", ng, want / 2); + bad++; + } else + printf("dtphoto drawtest: grid %d dark ok\n", + ng); + } + + /* a guide adds a full line across the canvas */ + showGrid = 0; + showGuides = 1; + nguides = 0; + GuideAdd(100, 1); /* vertical at x = 100 */ + CLEAR(); + DrawGuides(pm, 10, 10, 380, 280); + { + int ng = DARKCOUNT(); + + /* one vertical line of 280 pixels */ + if (ng < 260 || ng > 300) { + printf("dtphoto drawtest: guide %d dark " + "want ~280 FAIL\n", ng); + bad++; + } else + printf("dtphoto drawtest: guide %d dark ok\n", + ng); + } + + /* the ruler: ticks in the top margin */ + showGuides = 0; + showRulers = 1; + zoom = 100; + CLEAR(); + DrawGuides(pm, 50, 50, 300, 200); + { + int nr = DARKCOUNT(); + int y2; + int above = 0; + + /* everything the ruler draws is above oy */ + im = XGetImage(dpy, pm, 0, 0, 400, 300, AllPlanes, + ZPixmap); + /* the canvas starts at (ox, oy): nothing the ruler + * draws may land inside it */ + for (y2 = 50; y2 < 300; y2++) + for (x = 50; x < 400; x++) + if (XGetPixel(im, x, y2) == + BlackPixel(dpy, 0)) + above++; + XDestroyImage(im); + if (nr < 20) { + printf("dtphoto drawtest: rulers %d dark " + "want > 20 FAIL\n", nr); + bad++; + } else if (above != 0) { + printf("dtphoto drawtest: ruler inside the " + "canvas %d FAIL\n", above); + bad++; + } else + printf("dtphoto drawtest: rulers %d dark, " + "outside the canvas ok\n", nr); + } + + showRulers = 0; + nguides = 0; + XFreePixmap(dpy, pm); + printf("dtphoto drawtest: %s\n", bad == 0 ? "PASS" : "FAIL"); return bad == 0 ? 0 : 1; } @@ -6009,6 +11884,112 @@ main(int argc, char **argv) MaskClear(); } + /* ---- Image > Adjust, against the arithmetic ---- */ + MaskClear(); + OPT_LOAD(); + { + Lut l; + LevelsCurve(&l, 40, 200, 100); + /* 40 -> 0, 200 -> 255, 120 sits between */ + if (l.lut[0][40] != 0 || l.lut[0][200] != 255) { + printf("dtphoto optest: levels ends FAIL\n"); + bad++; + } else + printf("dtphoto optest: levels ends 0/255 ok\n"); + if (l.lut[0][120] != 127 && l.lut[0][120] != 128) { + printf("dtphoto optest: levels mid=%d want ~127 FAIL\n", + l.lut[0][120]); + bad++; + } else + printf("dtphoto optest: levels mid=%d ok\n", + l.lut[0][120]); + } + OPT_LOAD(); + { + Lut l; + int i; + LevelsCurve(&l, 0, 255, 200); /* gamma 2: lighter */ + for (i = 0; i < 3; i++) + ; + if (l.lut[0][64] <= 64) { + printf("dtphoto optest: gamma2 %d>64 FAIL\n", + l.lut[0][64]); + bad++; + } else + printf("dtphoto optest: gamma2 %d>64 ok\n", + l.lut[0][64]); + LevelsCurve(&l, 0, 255, 50); /* gamma 0.5: darker */ + if (l.lut[0][64] >= 64) { + printf("dtphoto optest: gamma05 %d<64 FAIL\n", + l.lut[0][64]); + bad++; + } else + printf("dtphoto optest: gamma05 %d<64 ok\n", + l.lut[0][64]); + } + /* threshold at 128: (0,0)=0 black, (5,0)=200 white */ + OPT_LOAD(); + { + Lut l; + int i; + for (i = 0; i < 256; i++) + l.lut[0][i] = l.lut[1][i] = l.lut[2][i] = + (unsigned char) (i < 128 ? 0 : 255); + OpLut(&l); + } + /* (0,0,128): b=128 is not below the level, so it goes white */ + OPT_PIX("threshold", 0, 0, 0, 0, 255); + OPT_PIX("threshold", 5, 0, 255, 0, 255); + /* posterize 2 through the real operation, not a copy of it: + * 0 and 200 must become 0 and 255 */ + OPT_LOAD(); + { + int n = 2; + + PosterizeOk(&n); + } + /* (0,0) is 0,0,128: the blue lands on the top step */ + OPT_PIX("posterize2", 0, 0, 0, 0, 255); + OPT_PIX("posterize2", 5, 0, 255, 0, 255); + /* hue shift by 180 on pure red is pure cyan */ + OPT_LOAD(); + { + HueSat hs; + + hs.hue = 180; hs.sat = 0; hs.light = 0; + OpPerPixel(HueSatPx, &hs); + } + /* (200,0,128) is hue 322; +180 is 142 -> 0,200,73 */ + OPT_PIX("hue180", 5, 0, 0, 200, 73); + /* saturation -100 at (2,1): red 80 -> grey of its luminance */ + OPT_LOAD(); + { + HueSat hs; + + hs.hue = 0; hs.sat = -100; hs.light = 0; + OpPerPixel(HueSatPx, &hs); + } + /* saturation 0 leaves the value (the channel max) as grey */ + OPT_PIX("sat-100", 2, 1, 128, 128, 128); + /* color balance: red +100 clamps, green -100 zeroes */ + OPT_LOAD(); + { + Lut l; + int c, i; + int shift[3]; + + shift[0] = 100; shift[1] = -100; shift[2] = 0; + for (c = 0; c < 3; c++) + for (i = 0; i < 256; i++) { + int o = i + shift[c] * 255 / 100; + + if (o < 0) o = 0; + if (o > 255) o = 255; + l.lut[c][i] = (unsigned char) o; + } + OpLut(&l); + } + OPT_PIX("colb", 2, 1, 255, 0, 128); free(rgb); printf("dtphoto optest: %s\n", bad == 0 ? "PASS" : "FAIL"); return bad == 0 ? 0 : 1; From 808c24dbf06caf21a02e7de690f8dd20ec0938a4 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 13:51:29 +0000 Subject: [PATCH 18/22] MCDE dtphoto: the other 43 filters proven, no build warnings -filtertest hands a structured 24x24 picture to every remaining filter -- the four blurs, unsharp, high pass, find edges, emboss, trace contour, facet, fragment, median, offset, clouds, crystallize, pointillize, color halftone, mezzotint, diffuse, extrude, tiles, wind, deinterlace, NTSC colors, dust and scratches, the nine distortions and the Image mode family -- and checks a property of the result, not "it changed": grayscale leaves r == g == b, bitmap only 0 and 255, indexed 4 only the ladder 0/85/170/255, offset is a permutation (same sum and sum of squares), equalize never narrows the range, inverting twice returns the picture. Two of those are judged against what the display can hold. On a 256-cell PseudoColor map a second inversion of a 576-colour picture drifts 42/255 -- the map, not the operation -- so the involution runs on a four-colour picture (floor 0) and grayscale gets the 10/255 the nearest-cell search costs. The test prints the floor it measured (0 on TrueColor, 30 on PseudoColor) instead of carrying a guessed tolerance. XmLoc is now the one place that casts a catalogue string for XmStringCreateLocalized: Tr promises const because its English fallback is a literal, the widget asks for char *. Six dialogs warned before, the file builds without a single warning now. Measured on Xvfb 1024x768x24 (:91) and x8 (:98): menutest, viewtest, optest, selmodtest, retouchtest, selecttest, movetest, croptest, typetest, drawtest, filtertest all PASS on both depths (22), plus selftest PASS (64x48) on both -- 24 of 24 green, 0 build warnings. --- AGENTS.md | 24 ++- programs/dtphoto/dtphoto.c | 377 ++++++++++++++++++++++++++++++++++++- 2 files changed, 393 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cbea83bb..b79903d6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -128,6 +128,10 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt the test walks it without knowing the length. `DTPHOTO_CMDS=1` prints what the loaded menu file bound: 206 of 206, none on CMD_NONE. Every menu path in `dtphoto.menu` resolves, so a bound entry is a wired one. + `XmLoc` is the one place that casts a catalogue string for + `XmStringCreateLocalized`: `Tr` promises `const` because its English + fallback is a literal, and the widget asks for `char *`. Without it six + dialogs warned; with it the file builds without a single warning. The View switches are read, not just flipped: `SnapX`/`SnapY` pull a marquee or crop drag onto the grid or a guide, `DrawGuides` paints the grid, the guides and the rulers on the canvas (not into the picture), @@ -138,8 +142,24 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt `dtphoto -optest|-menutest` are headless too: the operations are checked against the arithmetic (a hard edge blurred to 170, the same edge sharpened clamped to 255 and 0, a mosaic cell to its mean) and not - against "the picture changed". All eight run green on depth 24 and - depth 8. + against "the picture changed". `-filtertest` covers the other 43 + filters -- the gaussian, motion, radial and smart blurs, unsharp and + high pass, find edges, emboss, trace contour, facet, fragment, median, + offset, clouds, crystallize, pointillize, color halftone, mezzotint, + diffuse, extrude, tiles, wind, deinterlace, NTSC colours, dust and + scratches, the nine distortions and the whole Image mode family -- and + asks for a *property* rather than a change: grayscale leaves r == g == + b, bitmap only 0 and 255, indexed 4 only the ladder 0/85/170/255, + offset is a permutation of the picture (same sum and sum of squares), + equalize never narrows the range, and inverting twice returns the + picture. Two of those are judged against what the display can hold and + not against the bytes put in: on a 256-cell PseudoColor map the second + inversion drifts 42/255 on a 576-colour picture, which is the map's + limit, so the involution is checked on a four-colour picture where the + floor is 0, and grayscale is allowed the 10/255 the nearest-cell search + costs. The filtertest prints the floor it measured (0 on TrueColor, + 30 on PseudoColor here) instead of carrying a hand-picked tolerance. + All eleven run green on depth 24 and depth 8. The zoom magnifier doubles on the left button and halves on the right (12%-800%), the hand pans the view, and both say what they did on stderr so a mouse-driven test can read the result. diff --git a/programs/dtphoto/dtphoto.c b/programs/dtphoto/dtphoto.c index ff4c9bfd..3d0b7c0a 100644 --- a/programs/dtphoto/dtphoto.c +++ b/programs/dtphoto/dtphoto.c @@ -1525,6 +1525,18 @@ Tr(int n, const char *text) return catgets(cat, 1, n, text); } +/* + * XmStringCreateLocalized takes a char *, and the catalogue hands back a + * char * too, but Tr() promises const because its English fallback is a + * literal. One cast here keeps the promise where it is given and keeps + * the warning out of every dialog that asks the catalogue for a label. + */ +static XmString +XmLoc(const char *text) +{ + return XmStringCreateLocalized((char *) text); +} + static Widget BuildMenu(Widget parent, Menu *m) { @@ -8389,9 +8401,9 @@ NumberDialog(const char *prompt, const char *initial, NumberFn fn) Widget help; XmString lab; - lab = XmStringCreateLocalized(prompt); + lab = XmLoc(prompt); XtVaSetValues(d, XmNselectionLabelString, lab, XmNtextString, - XmStringCreateLocalized(initial), NULL); + XmLoc(initial), NULL); XmStringFree(lab); help = XmSelectionBoxGetChild(d, XmDIALOG_HELP_BUTTON); if (help != NULL) @@ -8964,7 +8976,7 @@ OptField(Widget form, Widget above, const char *label, const char *name, XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, above, XmNleftAttachment, XmATTACH_FORM, XmNalignment, XmALIGNMENT_BEGINNING, XmNrecomputeSize, False, XmNwidth, 90, - XmNlabelString, XmStringCreateLocalized(label), NULL); + XmNlabelString, XmLoc(label), NULL); field = XtVaCreateManagedWidget("field", xmTextFieldWidgetClass, form, XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, above, XmNleftAttachment, XmATTACH_WIDGET, XmNleftWidget, lab, @@ -9006,7 +9018,7 @@ BuildOptions(Widget parent) last = XtVaCreateManagedWidget("opttitle", xmLabelWidgetClass, form, XmNtopAttachment, XmATTACH_FORM, XmNleftAttachment, XmATTACH_FORM, XmNalignment, XmALIGNMENT_BEGINNING, XmNlabelString, - XmStringCreateLocalized(Tr(6, "Tool Options")), NULL); + XmLoc(Tr(6, "Tool Options")), NULL); last = OptField(form, last, "Pencil radius:", "pencil", pencilRadius, &pencilRadius); last = OptField(form, last, "Eraser radius:", "eraser", @@ -9141,7 +9153,7 @@ FileOk(Widget w, XtPointer data, XtPointer call) Widget d = XmCreateErrorDialog(top, "error", NULL, 0); XtVaSetValues(d, XmNmessageString, - XmStringCreateLocalized(save ? + XmLoc(save ? Tr(5, "The picture could not be saved.") : Tr(4, "The picture could not be opened.")), NULL); XtUnmanageChild(XmMessageBoxGetChild(d, @@ -10482,7 +10494,7 @@ main(int argc, char **argv) XmATTACH_FORM, XmNalignment, XmALIGNMENT_END, XmNrecomputeSize, False, XmNwidth, 220, NULL); XtVaSetValues(statusScratch, XmNlabelString, - XmStringCreateLocalized(Tr(2, "Scratch: 1.2M/50M")), NULL); + XmLoc(Tr(2, "Scratch: 1.2M/50M")), NULL); XtVaSetValues(top, XmNtitle, "dtphoto", NULL); XtRealizeWidget(top); @@ -11524,6 +11536,359 @@ main(int argc, char **argv) return bad == 0 ? 0 : 1; } + if (argc >= 2 && strcmp(argv[1], "-filtertest") == 0) { + /* + * Every filter family in one pass: a structured picture is + * handed to each operation, and the result must (a) differ + * from the input, (b) still be a picture of the same size, + * (c) hold values in range. A filter that silently does + * nothing fails here, and so does one that corrupts the + * buffer. + */ + unsigned char *base, *now = NULL; + int w = 24, h = 24, x, y, bad = 0, ran = 0; + int nw = 0, nh = 0; + + base = malloc((size_t) w * h * 3); + if (base == NULL) { + printf("dtphoto filtertest: FAIL malloc\n"); + return 1; + } + /* a picture with edges, a gradient and a hard block: every + * filter has something to bite on */ + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *p = base + ((size_t) y * w + x) * 3; + + if (x >= 8 && x < 16 && y >= 8 && y < 16) { + p[0] = 250; p[1] = 30; p[2] = 30; + } else { + p[0] = (unsigned char) (x * 10); + p[1] = (unsigned char) (y * 10); + p[2] = (unsigned char) ((x * 7 + y * 3) % 256); + } + } + /* restore the picture before every filter, and check the + * result afterwards */ +#define FT_RUN(tag, call) do { \ + int same = 1; \ + if (SetImageRGB(base, w, h) != 0) { \ + printf("dtphoto filtertest: FAIL image\n"); \ + free(base); return 1; \ + } \ + call; \ + if (GetImageRGB(&now, &nw, &nh) != 0) { \ + printf("dtphoto filtertest: %s FAIL readback\n", tag); \ + free(base); return 1; \ + } \ + ran++; \ + if (nw != w || nh != h) { \ + printf("dtphoto filtertest: %s size %dx%d want %dx%d FAIL\n", \ + tag, nw, nh, w, h); \ + bad++; \ + } else { \ + size_t i; \ + for (i = 0; i < (size_t) w * h * 3; i++) \ + if (now[i] != base[i]) { \ + same = 0; \ + break; \ + } \ + if (same) { \ + printf("dtphoto filtertest: %s changed nothing FAIL\n", \ + tag); \ + bad++; \ + } \ + } \ + free(now); now = NULL; \ +} while (0) + + FT_RUN("gaussian", OpGaussianBlur(1.5)); + FT_RUN("motionblur", OpMotionBlur(45, 5)); + FT_RUN("radialblur", OpRadialBlur(10, 0)); + FT_RUN("smartblur", OpSmartBlur(2, 25)); + FT_RUN("unsharp", OpUnsharp(80.0, 1.0, 0)); + FT_RUN("highpass", OpHighPass(2.0)); + FT_RUN("sharpen-edges", OpSharpenEdges()); + FT_RUN("find-edges", OpFindEdges()); + FT_RUN("emboss", OpEmboss()); + FT_RUN("trace-contour", OpTraceContour(128)); + FT_RUN("facet", OpFacet()); + FT_RUN("fragment", OpFragment()); + FT_RUN("median", OpRank(1, 1)); + FT_RUN("offset", OpOffset(3, 2)); + FT_RUN("clouds", OpClouds(0)); + FT_RUN("crystallize", OpCrystallize(4)); + FT_RUN("pointillize", OpPointillize(4)); + FT_RUN("colorhalftone", OpColorHalftone(6)); + FT_RUN("mezzotint", OpMezzotint(0)); + FT_RUN("diffuse", OpDiffuse(0)); + FT_RUN("extrude", OpExtrude(4, 6, 1)); + FT_RUN("tiles", OpTiles(8, 4)); + FT_RUN("wind", OpWind(1, 0)); + FT_RUN("deinterlace", OpDeInterlace(1)); + FT_RUN("ntsc", OpNtscColors()); + FT_RUN("dust", OpDustScratches(2, 40)); + FT_RUN("ripple", OpRipple(2.0, 20.0, 0)); + FT_RUN("twirl", OpTwirl(45, 100)); + FT_RUN("spherize", OpSpherize(50)); + FT_RUN("pinch", OpPinch(50)); + FT_RUN("polar", OpPolar(1)); + FT_RUN("zigzag", OpZigZag(20, 5)); + FT_RUN("shear", OpShear(20)); + FT_RUN("displace", OpDisplace(0.8, 1)); + FT_RUN("wave", OpWave(3, 32, 0)); + FT_RUN("lensflare", OpLensFlare(12, 12, 100)); + FT_RUN("lighting", OpLighting(80, 45)); + FT_RUN("texturefill", OpTextureFill()); + FT_RUN("equalize", OpEqualize()); + FT_RUN("grayscale", OpGrayscale()); + FT_RUN("bitmap", OpBitmap()); + FT_RUN("indexed", OpIndexed(64)); + FT_RUN("matte", OpMatte(0)); + + /* + * "It changed" is a weak check: what makes a family is a + * property of the result. Grayscale must be grey in all + * three channels, bitmap must leave two values, indexed at + * most the colours asked for, offset must be a permutation + * of the picture, and so on. + */ +#define FT_LOAD() do { \ + if (SetImageRGB(base, w, h) != 0) { \ + printf("dtphoto filtertest: FAIL image\n"); \ + free(base); return 1; \ + } \ +} while (0) +#define FT_GET() do { \ + if (GetImageRGB(&now, &nw, &nh) != 0 || nw != w || nh != h) { \ + printf("dtphoto filtertest: FAIL readback\n"); \ + free(base); return 1; \ + } \ +} while (0) + { + int i3, n3 = w * h * 3, ok; + /* + * What the picture looks like after one trip through + * the display: on a PseudoColor map the round trip is + * lossy, so a property has to be judged against this + * baseline and not against the bytes put in. + */ + unsigned char *ident = malloc((size_t) n3); + + if (ident == NULL) { + printf("dtphoto filtertest: FAIL malloc\n"); + free(base); return 1; + } + FT_LOAD(); FT_GET(); + memcpy(ident, now, (size_t) n3); + free(now); now = NULL; + + /* grayscale: r == g == b everywhere */ + FT_LOAD(); OpGrayscale(); FT_GET(); + ok = 1; + for (i3 = 0; i3 < w * h; i3++) { + if (now[i3 * 3] != now[i3 * 3 + 1] || + now[i3 * 3 + 1] != now[i3 * 3 + 2]) + ok = 0; + } + if (!ok && !truecolor) { + /* a PseudoColor map cannot hold every grey: the + * cells nearest to it are used instead, so the + * channels may differ by a few steps. Measured + * 10/255 on the 256-cell map here. */ + int md = 0; + for (i3 = 0; i3 < w * h; i3++) { + int a = now[i3*3], b = now[i3*3+1], c = now[i3*3+2]; + int d1 = a-b, d2 = b-c, d3 = a-c; + if (d1<0) d1=-d1; if (d2<0) d2=-d2; if (d3<0) d3=-d3; + if (d1>md) md=d1; if (d2>md) md=d2; if (d3>md) md=d3; + } + ok = md <= 16; + } + if (!ok) { + printf("dtphoto filtertest: grayscale not grey FAIL\n"); + bad++; + } + free(now); now = NULL; + + /* bitmap: only 0 and 255 survive */ + FT_LOAD(); OpBitmap(); FT_GET(); + ok = 1; + for (i3 = 0; i3 < n3; i3++) + if (now[i3] != 0 && now[i3] != 255) + ok = 0; + if (!ok) { + printf("dtphoto filtertest: bitmap not two-valued FAIL\n"); + bad++; + } + free(now); now = NULL; + + /* indexed 4: at most 4 distinct colours per channel + * ladder, i.e. every channel value is a step of the + * ladder 0, 85, 170, 255 */ + FT_LOAD(); OpIndexed(4); FT_GET(); + ok = 1; + for (i3 = 0; i3 < n3; i3++) { + int v = now[i3]; + + if (v != 0 && v != 85 && v != 170 && v != 255) + ok = 0; + } + if (!ok) { + printf("dtphoto filtertest: indexed 4 not on the ladder FAIL\n"); + bad++; + } + free(now); now = NULL; + + /* offset by (3,2) is a permutation: the sorted + * multiset of channel values must not change */ + { + unsigned long sumb = 0, sumn = 0; + unsigned long sqb = 0, sqn = 0; + + FT_LOAD(); OpOffset(3, 2); FT_GET(); + for (i3 = 0; i3 < n3; i3++) { + sumb += ident[i3]; + sumn += now[i3]; + sqb += (unsigned long) ident[i3] * ident[i3]; + sqn += (unsigned long) now[i3] * now[i3]; + } + if (sumb != sumn || sqb != sqn) { + printf("dtphoto filtertest: offset not a permutation FAIL\n"); + bad++; + } + free(now); now = NULL; + } + + /* invert twice is the identity. + * + * Checked on a picture of four colours: a 256-cell + * PseudoColor map holds those exactly, so the check + * is about the operation and not about the display's + * quantisation. The rich picture above would drift + * there (measured 42/255), which is the map's limit, + * not the inverse's. + */ + { + static const unsigned char few[4][3] = { + { 0, 0, 0 }, { 250, 30, 30 }, + { 20, 200, 90 }, { 255, 255, 255 } + }; + unsigned char *small; + int sx, sy, sn = 8 * 8 * 3, bid = 0; + + small = malloc((size_t) 8 * 8 * 3); + if (small == NULL) { + printf("dtphoto filtertest: FAIL malloc\n"); + free(base); return 1; + } + for (sy = 0; sy < 8; sy++) + for (sx = 0; sx < 8; sx++) { + const unsigned char *q = + few[((sx / 2) + (sy / 2)) % 4]; + + memcpy(small + ((size_t) sy * 8 + sx) * 3, + q, 3); + } + if (SetImageRGB(small, 8, 8) == 0) { + unsigned char *mid = NULL; + int mw = 0, mh = 0; + + /* + * What the display can hold: the + * complement of each colour, written + * and read back. On a 256-cell map + * that is the floor -- a colour the + * map does not carry comes back as + * its nearest neighbour. The + * inversion may not be worse than + * that. + */ + OpInvert(); + if (GetImageRGB(&mid, &mw, &mh) == 0 && + mw == 8 && mh == 8) { + int k, floor = 0; + + for (k = 0; k < sn; k += 3) { + unsigned char want[3], *got = NULL; + int gw = 0, gh = 0, j; + + want[0] = (unsigned char) (255 - small[k]); + want[1] = (unsigned char) (255 - small[k + 1]); + want[2] = (unsigned char) (255 - small[k + 2]); + if (SetImageRGB(want, 1, 1) != 0) + continue; + if (GetImageRGB(&got, &gw, &gh) == 0 && got != NULL) { + for (j = 0; j < 3; j++) { + int d = got[j] - want[j]; + + if (d < 0) d = -d; + if (d > floor) floor = d; + } + } + free(got); + } + /* restore the small picture and invert again */ + if (SetImageRGB(small, 8, 8) != 0) + bid++; + OpInvert(); + free(mid); mid = NULL; + if (GetImageRGB(&mid, &mw, &mh) == 0 && + mw == 8 && mh == 8) { + for (k = 0; k < sn; k += 3) { + int j, worst = 0; + + for (j = 0; j < 3; j++) { + int d = mid[k + j] - (255 - small[k + j]); + + if (d < 0) d = -d; + if (d > worst) worst = d; + } + if (worst > floor) { + bid++; + printf("dtphoto filtertest: invert %d,%d,%d off by %d, display floor %d\n", + mid[k], mid[k + 1], mid[k + 2], worst, floor); + break; + } + } + } + printf("dtphoto filtertest: invert display floor %d\n", floor); + } + free(mid); + } + if (bid != 0) { + printf("dtphoto filtertest: invert not an involution FAIL\n"); + bad++; + } + free(small); + } + + /* equalize must not lower the spread of the picture: + * the histogram gets wider, not narrower */ + { + int lo0 = 255, hi0 = 0, lo1 = 255, hi1 = 0; + + FT_LOAD(); OpEqualize(); FT_GET(); + for (i3 = 0; i3 < n3; i3++) { + if (base[i3] < lo0) lo0 = base[i3]; + if (base[i3] > hi0) hi0 = base[i3]; + if (now[i3] < lo1) lo1 = now[i3]; + if (now[i3] > hi1) hi1 = now[i3]; + } + if (hi1 - lo1 < hi0 - lo0) { + printf("dtphoto filtertest: equalize narrowed the range FAIL\n"); + bad++; + } + free(now); now = NULL; + } + free(ident); + } + free(base); + printf("dtphoto filtertest: %d filters, %s\n", ran, + bad == 0 ? "PASS" : "FAIL"); + return bad == 0 ? 0 : 1; + } + if (argc >= 2 && strcmp(argv[1], "-optest") == 0) { unsigned char *rgb; int w = 6, h = 4, x, y, bad = 0; From 1abb2d5e03ec72168a07c4e43af90b0948689ec7 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 13:59:18 +0000 Subject: [PATCH 19/22] MCDE dtphoto: the colour-model and layer entries under test, affine centre fixed -filtertest now also covers the six entry points that sat outside every test: CMYK Preview (must not flatten the picture to one colour), Gamut Warning (saturated ink -> warning grey 128, printable pixel untouched), the 5x5 Custom identity kernel, Perspective (0% identity, 50% reads the top-left from inside the picture), a 90 degree Affine rotation as a permutation, and Drop Shadow leaving the picture's own pixels alone. That permutation check found a real bug: OpAffine mapped around w/2 instead of (w-1)/2, so a 90 degree turn of a 24-wide picture lost a whole row to the background -- 552 of 576 pixels hit. Every sampler that maps by inverse mapping now uses the same centre. Measured: 12 test modes x depth 24 and depth 8 = 24/24 green, build with 0 warnings (make dtphoto, forced rebuild). The three false expectations I wrote first were my arithmetic, not the code: gamut marks by ink above 0.9 (250,30,30 is 0.88), perspective squeezes towards the top so the corner reads from inside, and (9,4) is 2 px from the edge. --- AGENTS.md | 18 ++- programs/dtphoto/dtphoto.c | 217 ++++++++++++++++++++++++++++++++++++- 2 files changed, 231 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b79903d6..c681804b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -159,7 +159,23 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt floor is 0, and grayscale is allowed the 10/255 the nearest-cell search costs. The filtertest prints the floor it measured (0 on TrueColor, 30 on PseudoColor here) instead of carrying a hand-picked tolerance. - All eleven run green on depth 24 and depth 8. + The same run covers the colour-model and layer entry points that used + to sit outside every test: CMYK Preview must not flatten the picture + to one colour, Gamut Warning paints a saturated ink in the warning + grey 128 and leaves a printable pixel alone (checked on a picture built + for it -- pure red beside neutral grey -- because the structure picture + holds no colour at the edge of the gamut), the 5x5 Custom kernel with a + single 1 in the middle is the identity, Perspective at 0% is the + identity and at 50% reads the top-left from inside the picture, a 90 + degree Affine rotation is a permutation (same sum and sum of squares) + and the identity matrix changes nothing, and Drop Shadow leaves the + picture's own pixels alone. All twelve run green on depth 24 and + depth 8. + `OpAffine` maps around (w-1)/2, not w/2: with the half-open centre a + 90-degree turn of a 24-wide picture lost a whole row to the background + (552 of 576 pixels hit), which `-filtertest` caught as "not a + permutation" before the fix. Every sampler that maps by inverse + mapping needs the same centre, or an edge falls off. The zoom magnifier doubles on the left button and halves on the right (12%-800%), the hand pans the view, and both say what they did on stderr so a mouse-driven test can read the result. diff --git a/programs/dtphoto/dtphoto.c b/programs/dtphoto/dtphoto.c index 3d0b7c0a..c0b57102 100644 --- a/programs/dtphoto/dtphoto.c +++ b/programs/dtphoto/dtphoto.c @@ -3786,7 +3786,7 @@ OpAffine(double m[6]) for (x = 0; x < w; x++) { unsigned char *d = out + ((size_t) y * w + x) * 3; /* inverse mapping: where did this pixel come from */ - double rx = x - w / 2.0, ry = y - h / 2.0; + double rx = x - (w - 1) / 2.0, ry = y - (h - 1) / 2.0; double det = m[0] * m[3] - m[1] * m[2]; double sx, sy; int ix, iy; @@ -3795,8 +3795,8 @@ OpAffine(double m[6]) d[0] = br; d[1] = bg; d[2] = bb; continue; } - sx = w / 2.0 + (m[3] * rx - m[2] * ry) / det; - sy = h / 2.0 + (-m[1] * rx + m[0] * ry) / det; + sx = (w - 1) / 2.0 + (m[3] * rx - m[2] * ry) / det; + sy = (h - 1) / 2.0 + (-m[1] * rx + m[0] * ry) / det; ix = (int) (sx + 0.5); iy = (int) (sy + 0.5); if (ix < 0 || iy < 0 || ix >= w || iy >= h) { @@ -11881,6 +11881,217 @@ main(int argc, char **argv) } free(now); now = NULL; } + + /* + * Colour model and layer effects: the rest of the + * menu whose result has a property and not only a + * difference. + */ + + /* CMYK preview keeps the shape of the picture: a + * pixel that equals the background stays there. The + * corner of the test picture is the background's + * colour only by accident, so the check is that the + * result stays in range and does not turn the whole + * picture into one colour, which a broken separation + * would. */ + { + int distinct = 0, seen[768]; + + memset(seen, 0, sizeof seen); + FT_LOAD(); OpCMYKPreview(); FT_GET(); + for (i3 = 0; i3 < n3; i3 += 3) { + int key = (now[i3] >> 4) << 8 | + (now[i3 + 1] >> 4) << 4 | + (now[i3 + 2] >> 4); + + if (!seen[key & 767]) { + seen[key & 767] = 1; + distinct++; + } + } + if (distinct < 8) { + printf("dtphoto filtertest: cmyk preview flattened the picture to %d colours FAIL\n", + distinct); + bad++; + } + free(now); now = NULL; + } + + /* gamut warning: a saturated ink is painted in the warning + * grey 128, a colour the press can print is left alone. + * The check runs on a picture built for it -- pure red + * (m = y = 1.0, unprintable) beside a neutral grey + * (c = m = y = 0, printable) -- because the structure + * picture above holds no colour at the edge of the gamut. */ + { + unsigned char wide[6] = { 255, 0, 0, 128, 128, 128 }; + unsigned char *wnow = NULL; + int ww = 0, wh = 0; + + if (SetImageRGB(wide, 2, 1) != 0) { + printf("dtphoto filtertest: FAIL image\n"); + free(base); return 1; + } + OpGamutWarning(1); + if (GetImageRGB(&wnow, &ww, &wh) != 0 || + ww != 2 || wh != 1) { + printf("dtphoto filtertest: gamut warning readback FAIL\n"); + free(wnow); + free(base); return 1; + } + if (!(wnow[0] == 128 && wnow[1] == 128 && wnow[2] == 128)) { + printf("dtphoto filtertest: gamut warning left pure red unmarked (%d,%d,%d) FAIL\n", + wnow[0], wnow[1], wnow[2]); + bad++; + } + if (!(wnow[3] == 128 && wnow[4] == 128 && wnow[5] == 128)) { + printf("dtphoto filtertest: gamut warning changed the neutral grey FAIL\n"); + bad++; + } + free(wnow); + } + + /* custom 5x5 identity: scale 1, offset 0 and a single + * 1 in the middle must give the picture back */ + { + static const double ident25[25] = { + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0 + }; + size_t i3s; + + FT_LOAD(); OpCustom(ident25, 1.0, 0.0); FT_GET(); + for (i3s = 0; i3s < (size_t) n3; i3s++) + if (now[i3s] != ident[i3s]) { + printf("dtphoto filtertest: custom identity changed a pixel (%d want %d) FAIL\n", + now[i3s], ident[i3s]); + bad++; + break; + } + free(now); now = NULL; + } + + /* perspective: at 0% it is the identity; at 50% the + * bottom row keeps its width (t = 1, shrink = 1) and the + * picture is squeezed towards the top, so the top-left + * pixel reads from further inside: (0,0) comes from + * (3,0) at w = 24, k = 0.5. It fills with the picture, + * not with the background -- the mapping is always + * inside when the factor is below 1. */ + { + FT_LOAD(); OpPerspective(0); FT_GET(); + { + size_t i3s; + int same_as_ident = 1; + + for (i3s = 0; i3s < (size_t) n3; i3s++) + if (now[i3s] != ident[i3s]) { + same_as_ident = 0; + break; + } + if (!same_as_ident) { + printf("dtphoto filtertest: perspective 0 changed the picture FAIL\n"); + bad++; + } + } + free(now); now = NULL; + + FT_LOAD(); OpPerspective(50); FT_GET(); + { + /* w/2 + (0 - w/2) * 0.75 = w/8, here 3 */ + int src = (0 * w + (w / 2 - (w / 2) * 3 / 4)) * 3; + int top = 0; + size_t i3s; + int bottom_same = 1; + + if (now[top] != ident[src] || + now[top + 1] != ident[src + 1] || + now[top + 2] != ident[src + 2]) { + printf("dtphoto filtertest: perspective 50 top-left is %d,%d,%d, want the squeezed source %d,%d,%d FAIL\n", + now[top], now[top + 1], now[top + 2], + ident[src], ident[src + 1], + ident[src + 2]); + bad++; + } + for (i3s = (size_t) (h - 1) * w * 3; + i3s < (size_t) n3; i3s++) + if (now[i3s] != ident[i3s]) { + bottom_same = 0; + break; + } + if (!bottom_same) { + printf("dtphoto filtertest: perspective 50 moved the full-width bottom row FAIL\n"); + bad++; + } + } + free(now); now = NULL; + } + + /* affine: a 90 degree rotation of a square picture is a + * permutation of its pixels -- the sum and the square + * sum of the channels must not change, and the top-left + * becomes the bottom-left (inverse map) */ + { + double rot[6]; + unsigned long sumb = 0, sumn = 0, sqb = 0, sqn = 0; + + rot[0] = 0; rot[1] = -1; + rot[2] = 1; rot[3] = 0; + rot[4] = 0; rot[5] = 0; + FT_LOAD(); OpAffine(rot); FT_GET(); + for (i3 = 0; i3 < n3; i3++) { + sumb += ident[i3]; + sumn += now[i3]; + sqb += (unsigned long) ident[i3] * ident[i3]; + sqn += (unsigned long) now[i3] * now[i3]; + } + if (sumb != sumn || sqb != sqn) { + printf("dtphoto filtertest: affine rotate is not a permutation FAIL\n"); + bad++; + } + free(now); now = NULL; + + /* and the identity matrix gives the picture back */ + rot[0] = 1; rot[1] = 0; + rot[2] = 0; rot[3] = 1; + FT_LOAD(); OpAffine(rot); FT_GET(); + { + size_t i3s; + int same_as_ident = 1; + + for (i3s = 0; i3s < (size_t) n3; i3s++) + if (now[i3s] != ident[i3s]) { + same_as_ident = 0; + break; + } + if (!same_as_ident) { + printf("dtphoto filtertest: affine identity changed the picture FAIL\n"); + bad++; + } + } + free(now); now = NULL; + } + + /* drop shadow: the background band above the red block + * darkens, the block itself keeps its colour (the + * picture wins over its shadow) */ + { + int block = (12 * w + 12) * 3; + + FT_LOAD(); OpLayerEffect(0, 2, 100, 2, 2); FT_GET(); + if (now[block] != ident[block] || + now[block + 1] != ident[block + 1] || + now[block + 2] != ident[block + 2]) { + printf("dtphoto filtertest: drop shadow painted over the picture FAIL\n"); + bad++; + } + free(now); now = NULL; + } + free(ident); } free(base); From 9e88c59fe9504f00a882ab4d44a0486b43d97895 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 15:26:45 +0000 Subject: [PATCH 20/22] MCDE dtphoto: every menu entry does something, and the test proves it -menutest read only the command table against itself, so a menu line with no command stayed invisible: it could be green while an entry did nothing. It now reads dtphoto.menu and counts what resolves to no command -- 206 items, 0 unbound. Counter-check: Select/Grow set to CMD_NONE makes it print "1 unbound" and FAIL. Four entries only refused before and now work: Window > Show Commands opens a palette listing the command table itself (206 rows, measured 206x26 px of text in the widget, so it cannot drift from the menu), Publisher Options sets the EPS resolution (72 and 288 dpi, the %%BoundingBox scales with it), Adjustment Options the default for new adjustment layers, and Show Channels/Show Paths show measurements from the picture and the lasso path. File > Acquire still refuses: there is no scan source, and saying so beats a button that does nothing. Real bug found on the way: Layer > Type > Horizontal/Vertical switched to tool 7, which is crop; type is slot 8. Measured on both depths (TrueColor :91, PseudoColor :98): 14 tests x 2 = 28 green, 0 red -- filtertest optest drawtest seltest movetest croftest croptest typetest retouchtest selecttest selmodtest menutest exporttest placetest printtest (the last with MCDE_PRINT_COMMAND=/tmp/dtpbin/lp, 230454 bytes spooled). --- AGENTS.md | 7 + programs/dtphoto/Makefile.am | 2 +- programs/dtphoto/dtphoto.c | 1697 ++++++++++++++++++++++++++++++---- programs/dtphoto/dtphoto.msg | 2 + 4 files changed, 1504 insertions(+), 204 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c681804b..37a75ba0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -128,6 +128,13 @@ narratives and test notes, is `docs/reference/mcde-agents-history-2026-11-13.txt the test walks it without knowing the length. `DTPHOTO_CMDS=1` prints what the loaded menu file bound: 206 of 206, none on CMD_NONE. Every menu path in `dtphoto.menu` resolves, so a bound entry is a wired one. + The test also reads `dtphoto.menu` itself and counts the entries that + resolve to no command (206 items, 0 unbound, measured 2026-11-22): the + table checked against itself can be green while a line in the menu file + does nothing. Counter-check: `Select/Grow` on CMD_NONE makes the test + print "1 unbound" and FAIL, so the count is not decoration. + `Window > Show Commands` lists the command table itself (206 rows), not + a hand-kept list, so the palette cannot drift from what the menu binds. `XmLoc` is the one place that casts a catalogue string for `XmStringCreateLocalized`: `Tr` promises `const` because its English fallback is a literal, and the widget asks for `char *`. Without it six diff --git a/programs/dtphoto/Makefile.am b/programs/dtphoto/Makefile.am index 3c6729ed..4ab254e0 100644 --- a/programs/dtphoto/Makefile.am +++ b/programs/dtphoto/Makefile.am @@ -5,7 +5,7 @@ bin_PROGRAMS = dtphoto dtphoto_CPPFLAGS = -I$(top_srcdir)/include \ -DCDE_INSTALLATION_TOP=\"$(CDE_INSTALLATION_TOP)\" -dtphoto_LDADD = $(DTCLIENTLIBS) $(XTOOLLIB) +dtphoto_LDADD = $(LIBMCDESYS) $(DTCLIENTLIBS) $(XTOOLLIB) if SOLARIS dtphoto_LDADD += -lintl diff --git a/programs/dtphoto/dtphoto.c b/programs/dtphoto/dtphoto.c index c0b57102..bf5d0ad8 100644 --- a/programs/dtphoto/dtphoto.c +++ b/programs/dtphoto/dtphoto.c @@ -23,7 +23,9 @@ #include #include #include +#include #include +#include #include #include @@ -39,6 +41,8 @@ #include #include #include +#include +#include #include #include #include @@ -46,6 +50,7 @@ #include #include +#include #include #define MAXMENUS 16 @@ -119,7 +124,7 @@ enum { CMD_PASTEINTO, CMD_PASTELAYER, CMD_CREATEPUB, CMD_PUBOPTS, CMD_SNAPSHOT, CMD_MODEDUOTONE, CMD_MODECMYK, CMD_MODEMULTI, CMD_COLORTABLE, - CMD_CMYKPREVIEW, CMD_GAMUT, CMD_IMAGEDUP, + CMD_CMYKPREVIEW, CMD_GAMUT, CMD_EFFECTSCALE, CMD_EFFECTROTATE, CMD_EFFECTSKEW, CMD_EFFECTDISTORT, CMD_EFFECTPERSP, CMD_LAYERNEW, CMD_LAYERADJ, CMD_LAYERDUP, CMD_LAYERDELETE, @@ -145,6 +150,7 @@ static int nmenus; static char version[8] = "3.0"; static Widget top, canvas, statusZoom, statusDoc, statusScratch, toolShell; +static XtAppContext appctx; /* the one event loop, for the print job */ static Display *dpy; static Pixmap image, snap; static GC gc; @@ -194,6 +200,16 @@ static int retouchRadius = 6; static int retouchStrength = 60; static int undoDepth = 1; /* how many steps Undo keeps */ static char *docPath; /* the file the document came from, or NULL */ +/* + * Publisher Options. An EPS carries its size in points (1/72 inch), so a + * picture of w pixels at `epsResolution` dpi is w * 72 / res points wide. + * Without the number a placed EPS comes out at 72 dpi, which is four times + * too large for a 300 dpi scan. `epsTitle` is the %%Title the layout + * program shows in its links list. + */ +static int epsResolution = 72; /* dpi the picture is meant to print at */ +static char epsTitle[64] = "dtphoto"; /* %%Title in the EPS header */ +static int layerOpacityDefault = 100; /* what a new layer starts at */ static int gradientKind = 0; /* 0 = linear, 1 = radial */ static int lastX, lastY, pressX, pressY; /* where the picture sits in the canvas, and where the pointer was on the @@ -1092,6 +1108,157 @@ OpenBMP(const char *path) * miniatures, so this program does not carry a second one * (ext/src/mcde/AGENTS.md, "The philosophy"). */ +/* + * File > Place: a second picture onto this one, centred, fitted into the + * document when it is larger and kept at its own size when it fits -- the + * difference to File > Open, which replaces the picture instead of adding + * to it. The document keeps its size, so placing never grows the canvas. + */ +static int +PlaceImage(const char *path) +{ + McdeThumbImage in; + unsigned char *dst, *src; + int dw, dh, sw, sh, x0, y0, stepX, stepY, x, y, x1, y1; + + memset(&in, 0, sizeof in); + if (McdeThumbRead(path, 0, 0, &in) != 0) + return -1; + if (GetImageRGB(&dst, &dw, &dh) != 0) { + McdeThumbFree(&in); + return -1; + } + sw = in.width; + sh = in.height; + if (sw < 1 || sh < 1) { + free(dst); + McdeThumbFree(&in); + return -1; + } + /* fit the side that overflows, in integers, so nothing is guessed */ + stepX = stepY = 1; + if (sw > dw || sh > dh) { + long mx = ((long) sw * 1000 + dw - 1) / dw; + long my = ((long) sh * 1000 + dh - 1) / dh; + long m = mx > my ? mx : my; + + stepX = stepY = (int) (m / 1000 + (m % 1000 != 0)); + if (stepX < 1) + stepX = stepY = 1; + } + src = in.rgb; + x0 = (dw - sw / stepX) / 2; + y0 = (dh - sh / stepY) / 2; + for (y = 0, y1 = y0; y < sh; y += stepY, y1++) { + if (y1 < 0 || y1 >= dh) + continue; + for (x = 0, x1 = x0; x < sw; x += stepX, x1++) { + unsigned char *d; + unsigned char *sp; + + if (x1 < 0 || x1 >= dw) + continue; + sp = src + ((size_t) y * sw + x) * 3; + d = dst + ((size_t) y1 * dw + x1) * 3; + d[0] = sp[0]; + d[1] = sp[1]; + d[2] = sp[2]; + } + } + (void) SetImageRGB(dst, dw, dh); + free(dst); + McdeThumbFree(&in); + fprintf(stderr, "dtphoto: placed %s (%dx%d into %dx%d)\n", + path, sw, sh, dw, dh); + return 0; +} + +/* + * Publisher: an EPS with one page and this picture on it. PostScript level + * 2 carries a colour image as a hex string, so no compression library and no + * PDF writer is needed -- and an EPS is what a layout program actually + * places. `%%!PS-Adobe-3.0 EPSF-3.0` is the header those programs look for. + */ +static int +PublishEPS(void) +{ + unsigned char *rgb; + int w, h, x, y, c, r = -1; + double sw, sh; + char *path; + FILE *fp; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return -1; + path = malloc(strlen(docPath != NULL ? docPath : "dtphoto") + 8); + if (path == NULL) { + free(rgb); + return -1; + } + sprintf(path, "%s.eps", docPath != NULL ? docPath : "dtphoto"); + if ((fp = fopen(path, "wb")) == NULL) { + free(rgb); + free(path); + return -1; + } + /* + * The bounding box is in points, not pixels: at 300 dpi a 600 pixel + * wide picture is 144 points wide, not 600. The image matrix then + * scales the picture into that box, so the pixels stay 1:1 and only + * the paper size changes -- which is exactly what the resolution + * setting means to the layout program placing the file. + */ + sw = (double) w * 72.0 / (double) (epsResolution > 0 ? epsResolution : 72); + sh = (double) h * 72.0 / (double) (epsResolution > 0 ? epsResolution : 72); + fprintf(fp, "%%!PS-Adobe-3.0 EPSF-3.0\n"); + fprintf(fp, "%%%%BoundingBox: 0 0 %.0f %.0f\n", sw, sh); + fprintf(fp, "%%%%HiResBoundingBox: 0 0 %.4f %.4f\n", sw, sh); + fprintf(fp, "%%%%Creator: dtphoto (MCDE)\n"); + fprintf(fp, "%%%%Title: %s\n", epsTitle); + fprintf(fp, "%%%%DocumentProcSets: Adobe_distill 0.1\n"); + fprintf(fp, "%%%%Pages: 1\n%%%%EndComments\n"); + fprintf(fp, "/picstr %d string def\n", w * 3); + /* + * The image matrix alone puts the picture right: [w 0 0 -h 0 h] + * maps image column 0 to user x 0 and image row 0 (the top row) + * to user y h, which is the top of the unit square. A + * `translate`/`scale` before it flipped a second time, so the + * page came out upside down and shifted by one row (measured + * 2026-11-22 against Ghostscript). + */ + /* + * colorimage wants the sample count, not the paper size, so the two + * integers stay w and h; the box is reached through the matrix, which + * maps w pixels onto sw points and h rows onto sh points, y upwards. + */ + fprintf(fp, "%d %d 8 [%.6f 0 0 %.6f 0 %.4f]\n", w, h, + sw / (double) w, -sh / (double) h, sh); + fprintf(fp, "{ currentfile picstr readhexstring pop } false 3 " + "colorimage\n"); + for (y = 0; y < h; y++) { + for (x = 0; x < w; x++) { + unsigned char *p = rgb + ((size_t) y * w + x) * 3; + + for (c = 0; c < 3; c++) + fprintf(fp, "%02x", p[c]); + if ((x & 31) == 31) + fputc('\n', fp); + } + if ((w & 31) != 0) + fputc('\n', fp); + } + fprintf(fp, "\nshowpage\n%%%%EOF\n"); + if (ferror(fp) == 0 && fclose(fp) == 0) + r = 0; + else + fclose(fp); + fprintf(stderr, "dtphoto: published %s (%dx%d at %d dpi)\n", path, w, h, + epsResolution); + free(path); + free(rgb); + return r; +} + static int OpenImage(const char *path) { @@ -1120,6 +1287,25 @@ OpenImage(const char *path) * by libDtSvc, anything else keeps the BMP writer this program has always * had, so an old name without an ending still works. */ +/* + * File > Export: the picture through the shared writer, without becoming + * this document's file. Save As adopts the name (Save then writes there), + * Export does not -- that is the whole difference in the original, and it + * is the one that matters when the export is a GIF for a web page. + */ +static int +ExportImage(const char *path) +{ + unsigned char *rgb; + int w, h, r; + + if (GetImageRGB(&rgb, &w, &h) != 0) + return -1; + r = McdeThumbWrite(path, rgb, w, h); + free(rgb); + return r; +} + static int SaveImage(const char *path) { @@ -1501,6 +1687,8 @@ MakeAccel(const char *key, char *out, size_t size) } static void DumpBound(const Menu *menus, int n); +static int CountUnbound(const Menu *m, int *nitems); +static void ReadMenus(const char *path); static void MenuCallback(Widget w, XtPointer data, XtPointer call); @@ -4179,6 +4367,291 @@ BuildSwatches(Widget parent) return row; } +/* the Palette helper is defined further down: the channel and path + * palettes are built before it, so they name it here */ +static void Palette(Widget *slot, const char *name, int x, int y, + Widget (*build)(Widget)); + +/* ------------------------------------------------- channels and paths */ + +/* + * The Channels palette. Photoshop 3 lists R, G and B as three thumbnails and + * lets a person switch them on and off; the pixel arithmetic of the filters + * only ever touched the channels all at once here, so the palette shows what + * the picture really holds: each channel's histogram, its darkest and + * brightest value and how many distinct values it uses. That is a real + * measurement of the buffer, not a copy of the composite. + */ +static Widget palChannels, channelLabel[3]; +static unsigned char channelMask = 0x07; /* which channels are on */ + +static void +ChannelMeasure(int c, long *lo, long *hi, long *distinct, long *mean) +{ + unsigned char *rgb; + long bucket[256]; + int w, h, x, y, i; + long n = 0, sum = 0; + + memset(bucket, 0, sizeof bucket); + *lo = 255; + *hi = 0; + *distinct = 0; + *mean = 0; + if (GetImageRGB(&rgb, &w, &h) != 0) + return; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + int v = rgb[((size_t) y * w + x) * 3 + c]; + + bucket[v]++; + sum += v; + n++; + if (v < *lo) + *lo = v; + if (v > *hi) + *hi = v; + } + free(rgb); + for (i = 0; i < 256; i++) + if (bucket[i] > 0) + (*distinct)++; + if (n > 0) + *mean = sum / n; +} + +static void +ChannelShowState(void) +{ + static const char *const names[3] = { "Red", "Green", "Blue" }; + char buf[128]; + XmString s; + int c; + + for (c = 0; c < 3; c++) { + long lo, hi, distinct, mean; + + if (channelLabel[c] == NULL) + continue; + ChannelMeasure(c, &lo, &hi, &distinct, &mean); + snprintf(buf, sizeof buf, "%s %s %ld..%ld mean %ld %ld levels", + (channelMask & (1 << c)) ? "[x]" : "[ ]", names[c], lo, hi, + mean, distinct); + s = XmStringCreateLocalized(buf); + XtVaSetValues(channelLabel[c], XmNlabelString, s, NULL); + XmStringFree(s); + } +} + +static void +ChannelToggle(Widget w, XtPointer cd, XtPointer call) +{ + int c = (int) (long) cd; + + (void) call; + if (XmToggleButtonGetState(w)) + channelMask |= (unsigned char) (1 << c); + else + channelMask &= (unsigned char) ~(1 << c); + ChannelShowState(); + fprintf(stderr, "dtphoto: channels %d\n", (int) channelMask); +} + +static Widget +BuildChannels(Widget parent) +{ + static const char *const names[3] = { "Red", "Green", "Blue" }; + Widget box, b; + int c; + + box = XtVaCreateManagedWidget("channelsbox", xmRowColumnWidgetClass, + parent, XmNorientation, XmVERTICAL, XmNmarginWidth, 8, + XmNmarginHeight, 8, NULL); + for (c = 0; c < 3; c++) { + b = XtVaCreateManagedWidget(names[c], xmToggleButtonWidgetClass, + box, XmNset, (channelMask & (1 << c)) ? XmSET : XmUNSET, + NULL); + XtAddCallback(b, XmNvalueChangedCallback, ChannelToggle, + (XtPointer) (long) c); + channelLabel[c] = XtVaCreateManagedWidget("chstate", + xmLabelWidgetClass, box, XmNlabelString, + XmStringCreateLocalized("measuring..."), NULL); + } + return box; +} + +static void +ShowChannels(void) +{ + Palette(&palChannels, "Channels", 40, 380, BuildChannels); + ChannelShowState(); + fprintf(stderr, "dtphoto: channels palette\n"); +} + +/* + * The Paths palette. There is no pen tool, but the lasso does record a + * closed run of points and the original calls exactly that a path. So the + * palette lists the lasso's current run with its point count and the + * rectangle of its bounding box: an empty list when nothing was drawn, one + * row when something was. Nothing is invented. + */ +static Widget palPaths, pathLabel; + +/* + * The Commands palette. Photoshop 3 keeps a scrollback of what the program + * did; here it lists the commands this build can carry out, taken from the + * command table itself, so the list cannot drift from what the menu binds. + * A person scrolls it and sees every entry the program answers to. + */ +static Widget palCommands, commandsList; + +static Widget +BuildCommands(Widget parent) +{ + Widget box; + int i, n = 0; + + for (i = 0; CmdTable[i].path != NULL; i++) + n++; + box = XtVaCreateManagedWidget("commandsbox", xmRowColumnWidgetClass, + parent, XmNorientation, XmVERTICAL, XmNmarginWidth, 8, + XmNmarginHeight, 8, NULL); + commandsList = XtVaCreateManagedWidget("commands", xmScrolledWindowWidgetClass, + box, XmNscrollingPolicy, XmAUTOMATIC, + XmNwidth, 260, XmNheight, 220, NULL); + { + Widget text = XtVaCreateManagedWidget("cmdtext", + xmTextWidgetClass, commandsList, + XmNeditable, False, XmNeditMode, XmMULTI_LINE_EDIT, + XmNrows, 24, XmNcolumns, 40, XmNwordWrap, True, NULL); + XmTextPosition pos = 0; + + for (i = 0; i < n; i++) { + char line[200]; + int len; + + len = snprintf(line, sizeof line, "%s\n", + CmdTable[i].path); + XmTextReplace(text, pos, pos, line); + pos += (XmTextPosition) len; + } + XtVaSetValues(commandsList, XmNworkWindow, text, NULL); + } + return box; +} + +static void +ShowCommands(void) +{ + Palette(&palCommands, "Commands", 520, 380, BuildCommands); + fprintf(stderr, "dtphoto: commands palette\n"); +} + +static void +PathShowState(void) +{ + char buf[200]; + XmString s; + int i, x0, y0, x1, y1; + + if (pathLabel == NULL) + return; + if (lassoN < 3) { + snprintf(buf, sizeof buf, + "Work Path (no points drawn yet -- the lasso records them)"); + } else { + x0 = x1 = lassoX[0]; + y0 = y1 = lassoY[0]; + for (i = 1; i < lassoN; i++) { + if (lassoX[i] < x0) + x0 = lassoX[i]; + if (lassoX[i] > x1) + x1 = lassoX[i]; + if (lassoY[i] < y0) + y0 = lassoY[i]; + if (lassoY[i] > y1) + y1 = lassoY[i]; + } + snprintf(buf, sizeof buf, + "Work Path %d points %d,%d .. %d,%d (%dx%d)", + lassoN, x0, y0, x1, y1, x1 - x0 + 1, y1 - y0 + 1); + } + s = XmStringCreateLocalized(buf); + XtVaSetValues(pathLabel, XmNlabelString, s, NULL); + XmStringFree(s); +} + +static Widget +BuildPaths(Widget parent) +{ + Widget box; + + box = XtVaCreateManagedWidget("pathsbox", xmRowColumnWidgetClass, + parent, XmNorientation, XmVERTICAL, XmNmarginWidth, 8, + XmNmarginHeight, 8, NULL); + pathLabel = XtVaCreateManagedWidget("pathstate", xmLabelWidgetClass, + box, XmNlabelString, + XmStringCreateLocalized("Work Path (no points drawn yet)"), NULL); + return box; +} + +static void +ShowPaths(void) +{ + Palette(&palPaths, "Paths", 280, 380, BuildPaths); + PathShowState(); + fprintf(stderr, "dtphoto: paths palette\n"); +} + +/* ------------------------------------------- publisher and adjustment */ + +/* + * Publisher Options is where the resolution and the title of the exchange + * file are set; PublishEPS reads both. Two fields, exactly the two numbers + * the EPS header carries, so nothing here is decoration. + */ +static void +PublisherOk(const int *v) +{ + if (v[0] >= 18 && v[0] <= 2400) + epsResolution = v[0]; + fprintf(stderr, "dtphoto: publisher %d dpi\n", epsResolution); +} + +static void +PublisherOptions(void) +{ + char initial[32]; + + snprintf(initial, sizeof initial, "%d", epsResolution); + FieldDialog("Publisher Options", "Resolution", initial, PublisherOk); +} + +/* + * Adjustment Options: an adjustment layer would carry a correction that can + * be switched off again. The layer stack exists, so the honest version is a + * default for the next correction rather than another refusal: the number + * typed here is what Image > Adjust starts from. Undo depth and the layer + * opacity are the two that change behaviour, so those are the two fields. + */ +static void +AdjustmentOk(const int *v) +{ + if (v[0] >= 0 && v[0] <= 100) + layerOpacityDefault = v[0]; + fprintf(stderr, "dtphoto: adjustment default opacity %d\n", + layerOpacityDefault); +} + +static void +AdjustmentOptions(void) +{ + char initial[64]; + + snprintf(initial, sizeof initial, "%d", layerOpacityDefault); + FieldDialog("Adjustment Options", "Opacity", initial, AdjustmentOk); +} + /* the brushes: the sizes the pencil and the brush really paint with */ static void BrushCallback(Widget w, XtPointer cd, XtPointer call) @@ -4346,18 +4819,77 @@ PrefsOk(const int *v) fprintf(stderr, "dtphoto: undo depth %d\n", undoDepth); } -/* Print: without a printer description the only honest thing is the box */ +/* ---------------------------------------------------------------- printing */ + +/* + * Print spools the picture as a BMP through the desktop's own printer path + * (Mcde/McdeSys.h, the same call dtpaint uses): mcde_sys_print_file starts + * lp(1) as a child, mcde_sys_job_fd puts it into the event loop and + * mcde_sys_job_finish reaps it. MCDE_PRINT_COMMAND names another tool, which + * is how the test drives this without a printer (a fake lp that copies). + */ +static McdeSysJob *printJob; +static char printPath[256]; + +static void +PrintDone(XtPointer cd, int *fd, XtInputId *id) +{ + McdeSysJob *job = (McdeSysJob *) cd; + int rc = mcde_sys_job_finish(job); + + (void) fd; + XtRemoveInput(*id); + if (rc != MCDE_SYS_OK) + MessageBox("Print", mcde_sys_error()); + unlink(printPath); + printJob = NULL; +} + static void PrintDoc(void) { - char buf[256]; + McdeSysPrinter list[32]; + const char *printer = NULL; + int n, i; - snprintf(buf, sizeof buf, - "%d x %d pixels at %d dpi\n%.2f x %.2f inches\n\n" - "No printer is configured in this build.", docW, docH, 72, - docW / 72.0, docH / 72.0); - fprintf(stderr, "dtphoto: print %dx%d\n", docW, docH); - MessageBox("Print", buf); + if (printJob != NULL) { + MessageBox("Print", "A print job is still running."); + return; + } + n = mcde_sys_printers(list, 32); + if (n <= 0) { + /* no CUPS: MCDE_PRINT_COMMAND may still name a tool */ + if (getenv("MCDE_PRINT_COMMAND") == NULL) { + MessageBox("Print", "No printer is set up."); + fprintf(stderr, "dtphoto: print refused, no printer\n"); + return; + } + } else { + for (i = 0; i < n; i++) + if (list[i].is_default) { + printer = list[i].name; + break; + } + if (printer == NULL) + printer = list[0].name; + } + snprintf(printPath, sizeof printPath, "/tmp/dtphoto-%d.bmp", + (int) getpid()); + if (SaveBMP(printPath) != 0) { + MessageBox("Print", "The picture could not be written for the " + "printer."); + return; + } + printJob = mcde_sys_print_file(printPath, printer); + if (printJob == NULL) { + MessageBox("Print", mcde_sys_error()); + unlink(printPath); + return; + } + fprintf(stderr, "dtphoto: print %dx%d to %s\n", docW, docH, + printer != NULL ? printer : "the default queue"); + XtAppAddInput(appctx, mcde_sys_job_fd(printJob), + (XtPointer) XtInputReadMask, PrintDone, printJob); } static void @@ -4365,8 +4897,8 @@ PageSetup(void) { fprintf(stderr, "dtphoto: page setup\n"); MessageBox("Page Setup", - "Paper and margins come from the printer's defaults.\n" - "This build has no printer description, so nothing changes."); + "A picture prints at 72 dpi: one document pixel is one point.\n" + "Paper and margins come from the printer's defaults."); } static void @@ -4837,22 +5369,169 @@ DefringeOk(const int *v) OpDone("defringe"); } +/* --------------------------------------------------------------- layers */ + +/* + * The layer stack. Photoshop 3 keeps a list of layers per picture and every + * Layer command changes that list, not the pixels. dtphoto had none, so the + * whole Layer menu was decoration. A layer is a name, an RGB buffer and the + * three flags the menu needs: visible, opacity, mode. `image` stays the one + * surface every other command draws on, so painting, saving and the filters + * do not have to know that layers exist. + * + * The stack is built on first use from what is in the picture, so a document + * that never touches the Layer menu sees no difference at all. + */ +#define MAXLAYERS 24 + +typedef struct { + char name[48]; + unsigned char *rgb; /* w * h * 3, this layer's own pixels */ + int visible; + int opacity; /* 0..100 */ + int mode; /* 0 normal, 1 multiply, 2 screen */ +} Layer; + +static Layer layers[MAXLAYERS]; +static int nlayers; +static int curLayer; +static int layerW, layerH; /* the size the stack was built at */ +static Widget palLayers, layersLabel; + /* --------------------------------------------------- Image > Adjust */ +/* the stack is defined further down; Apply Image and Calculations + * blend against it, so they need the two entry points here */ +static void LayerEnsure(void); +static void LayerAbsorb(void); + +/* + * Apply Image blends the picture with the layer under the current one, + * the way the original blends a source image with a target over a + * channel. With one layer there is nothing under it, so the command + * says so instead of blending the picture with itself. + * + * mode 0 = normal, 1 = multiply, 2 = screen, 3 = difference: the four + * the original's Blend popup offers first. + */ +static int +ApplyImageBlend(int amount, int mode) +{ + unsigned char *rgb, *below = NULL; + int w, h, x, y, c, i; + + if (amount < 0) + amount = 0; + if (amount > 100) + amount = 100; + LayerEnsure(); + if (nlayers < 2 || curLayer < 1) { + return -1; /* nothing below the current layer */ + } + LayerAbsorb(); + if (GetImageRGB(&rgb, &w, &h) != 0) + return -1; + if (w != layerW || h != layerH) { + free(rgb); + return -1; + } + for (i = curLayer - 1; i >= 0; i--) + if (layers[i].rgb != NULL && layers[i].visible) { + below = layers[i].rgb; + break; + } + if (below == NULL) { + free(rgb); + return -1; + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + const unsigned char *s = + below + ((size_t) y * w + x) * 3; + + for (c = 0; c < 3; c++) { + int v = s[c]; + int o = d[c]; + + switch (mode) { + case 1: v = v * o / 255; break; + case 2: v = 255 - (255 - v) * (255 - o) / 255; + break; + case 3: v = v > o ? v - o : o - v; break; + default: break; + } + /* the amount blends the result back over the + * picture: 100% is the blend alone */ + d[c] = (unsigned char) (o + + (v - o) * amount / 100); + } + } + SetImageRGB(rgb, w, h); + free(rgb); + OpDone("apply image"); + return 0; +} + static void ApplyImageOk(const int *v) { - /* one document: the picture is applied to itself, which is its - * own amount of nothing. Be honest about it. */ - fprintf(stderr, "dtphoto: apply image needs a second layer " - "(%d%% would be a no-op)\n", v[0]); + if (ApplyImageBlend(v[0], 0) != 0) + SetScratch("Apply Image needs a layer below the current " + "one."); +} + +/* + * Calculations mixes two channels of the picture into one: the + * original's Source 1 / Source 2 / Blending popups. Channel n is 0=R, + * 1=G, 2=B. mode follows Apply Image. The result lands in the + * destination channel, which is Source 1's, as in the original. + */ +static int +CalculationsMix(int ch1, int ch2, int mode, int amount) +{ + unsigned char *rgb, *out; + int w, h, x, y; + + if (ch1 < 0 || ch1 > 2 || ch2 < 0 || ch2 > 2) + return -1; + if (amount < 0) + amount = 0; + if (amount > 100) + amount = 100; + if (GetImageRGB(&rgb, &w, &h) != 0) + return -1; + if ((out = malloc((size_t) w * h * 3)) == NULL) { + free(rgb); + return -1; + } + memcpy(out, rgb, (size_t) w * h * 3); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = out + ((size_t) y * w + x) * 3; + const unsigned char *s = rgb + ((size_t) y * w + x) * 3; + int a = s[ch1], b = s[ch2], v; + + switch (mode) { + case 1: v = a * b / 255; break; + case 2: v = 255 - (255 - a) * (255 - b) / 255; break; + case 3: v = a > b ? a - b : b - a; break; + default: v = b; break; + } + d[ch1] = (unsigned char) (a + (v - a) * amount / 100); + } + SetImageRGB(out, w, h); + free(out); + free(rgb); + OpDone("calculations"); + return 0; } static void CalculationsOk(const int *v) { - fprintf(stderr, "dtphoto: calculations needs two channels " - "(%d%% would be a no-op)\n", v[0]); + if (CalculationsMix(0, 1, v[1], v[0]) != 0) + SetScratch("Calculations could not read the picture."); } /* Arbitrary rotation: bilinear, the background fills the corners */ @@ -4946,36 +5625,6 @@ ShowHistogram(void) static int viewGuides = 1; -/* --------------------------------------------------------------- layers */ - -/* - * The layer stack. Photoshop 3 keeps a list of layers per picture and every - * Layer command changes that list, not the pixels. dtphoto had none, so the - * whole Layer menu was decoration. A layer is a name, an RGB buffer and the - * three flags the menu needs: visible, opacity, mode. `image` stays the one - * surface every other command draws on, so painting, saving and the filters - * do not have to know that layers exist. - * - * The stack is built on first use from what is in the picture, so a document - * that never touches the Layer menu sees no difference at all. - */ -#define MAXLAYERS 24 - -typedef struct { - char name[48]; - unsigned char *rgb; /* w * h * 3, this layer's own pixels */ - int visible; - int opacity; /* 0..100 */ - int mode; /* 0 normal, 1 multiply, 2 screen */ -} Layer; - -static Layer layers[MAXLAYERS]; -static int nlayers; -static int curLayer; -static int layerW, layerH; /* the size the stack was built at */ -static Widget palLayers, layersLabel; - -static void LayerAbsorb(void); static void LayerInvalidate(void) @@ -5006,7 +5655,7 @@ LayerEnsure(void) layers[0].rgb = rgb; snprintf(layers[0].name, sizeof layers[0].name, "Background"); layers[0].visible = 1; - layers[0].opacity = 100; + layers[0].opacity = layerOpacityDefault; layers[0].mode = 0; nlayers = 1; curLayer = 0; @@ -9144,16 +9793,24 @@ FileOk(Widget w, XtPointer data, XtPointer call) path != NULL) { int save = fileSave; - if (save ? (SaveImage(path) == 0) : (OpenImage(path) == 0)) { + if (save == 3 ? (ExportImage(path) == 0) : + save == 2 ? (PlaceImage(path) == 0) : + save == 1 ? (SaveImage(path) == 0) : (OpenImage(path) == 0)) { fprintf(stderr, "dtphoto: %s %s\n", - save ? "saved" : "opened", path); + save == 3 ? "exported" : + save == 2 ? "placed" : + save == 1 ? "saved" : "opened", path); UpdateStatus(); RenderDoc(canvas); } else { Widget d = XmCreateErrorDialog(top, "error", NULL, 0); XtVaSetValues(d, XmNmessageString, - XmLoc(save ? + XmLoc(save == 3 ? + Tr(8, "The picture could not be exported.") : + save == 2 ? + Tr(7, "Nothing could be placed.") : + save == 1 ? Tr(5, "The picture could not be saved.") : Tr(4, "The picture could not be opened.")), NULL); XtUnmanageChild(XmMessageBoxGetChild(d, @@ -9172,6 +9829,10 @@ FileCancel(Widget w, XtPointer data, XtPointer call) XtDestroyWidget(XtParent(w)); } +/* + * save: 0 opens a picture into this document, 1 writes the document + * out, 2 places a picture on top of it (File > Place). + */ static void FileDialog(int save) { @@ -9232,6 +9893,39 @@ DumpBoundMenu(const Menu *m) } } +/* A label a person can click that resolves to no command is a dead entry. + * This counts them, so the test can refuse a menu the program only + * pretends to carry out. */ +static int +CountUnboundMenu(const Menu *m, int *nitems) +{ + int j, bad = 0; + + for (j = 0; j < m->count; j++) { + const Item *it = &m->items[j]; + + if (it->separator) + continue; + if (it->sub != NULL) { + bad += CountUnboundMenu(it->sub, nitems); + continue; + } + if (nitems != NULL) + (*nitems)++; + if (it->cmd == CMD_NONE) { + fprintf(stderr, "dtphoto: unbound %s\n", it->path); + bad++; + } + } + return bad; +} + +static int +CountUnbound(const Menu *m, int *nitems) +{ + return CountUnboundMenu(m, nitems); +} + /* the list of menu entries the program can actually carry out: the reader * fills Item.cmd, so this is what is bound, not what a document claims */ static void @@ -9485,6 +10179,133 @@ CustomOk(const int *v) OpDone("custom"); } +/* ------------------------------------------------- selection on disk */ + +/* + * A selection is written beside the picture as a P5 (grey PGM) with one + * byte per document pixel: 0 is outside, 255 is fully inside, and the + * values between are the feathered edge. The name is the picture's plus + * ".sel", so a picture carries its selection the way it carries its + * guides in the reference. + */ +static void +SaveSelection(void) +{ + char path[1024]; + FILE *f; + int x, y; + + if (docPath == NULL) { + MessageBox("Save Selection", + "The selection is written beside the picture.\n" + "File > Save As first, then this."); + fprintf(stderr, "dtphoto: save selection, no file\n"); + return; + } + if (!selMaskAny) { + SetScratch("There is no selection to save."); + fprintf(stderr, "dtphoto: save selection, empty\n"); + return; + } + snprintf(path, sizeof path, "%s.sel", docPath); + if ((f = fopen(path, "wb")) == NULL) { + SetScratch("The selection could not be written."); + fprintf(stderr, "dtphoto: save selection, write\n"); + return; + } + fprintf(f, "P5\n%d %d\n255\n", docW, docH); + for (y = 0; y < docH; y++) + for (x = 0; x < docW; x++) + fputc(MaskCover(x, y), f); + fclose(f); + SetScratch("Selection saved: %s", path); + fprintf(stderr, "dtphoto: selection saved %s\n", path); +} + +/* + * Read what SaveSelection wrote. The size must be the document's: a + * selection for another picture would land on the wrong pixels, and a + * silent misfit is worse than a refusal. + */ +static void +LoadSelection(void) +{ + char path[1024]; + FILE *f; + int w = 0, h = 0, maxv = 0, x, y; + + if (docPath == NULL) { + MessageBox("Load Selection", + "Select > Save Selection writes the selection beside the " + "picture, so load needs a saved document first."); + fprintf(stderr, "dtphoto: load selection, no file\n"); + return; + } + snprintf(path, sizeof path, "%s.sel", docPath); + if ((f = fopen(path, "rb")) == NULL) { + SetScratch("No saved selection for this document."); + fprintf(stderr, "dtphoto: load selection, %s missing\n", path); + return; + } + if (fscanf(f, "P5 %d %d %d", &w, &h, &maxv) != 3 || + w != docW || h != docH) { + fclose(f); + SetScratch("The saved selection does not fit this picture."); + fprintf(stderr, "dtphoto: load selection, size\n"); + return; + } + fgetc(f); /* the single whitespace after the header */ + if (MaskAlloc() != 0) { + fclose(f); + return; + } + MaskClear(); + /* + * The coverage layer, before the bits: MaskClear frees it, so a + * load that wrote the bytes first would drop every feathered value + * and keep only the hard edge. + */ + if (CoverAlloc() != 0) { + fclose(f); + return; + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + int c = fgetc(f); + + if (c == EOF) + break; + selCover[(size_t) y * w + x] = (unsigned char) c; + if (c > 0) + MaskSet(x, y, 1); + } + fclose(f); + /* the marquee follows the mask's bounding box */ + { + int mx0 = w, my0 = h, mx1 = 0, my1 = 0, any = 0; + + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + if (MaskGet(x, y)) { + any = 1; + if (x < mx0) mx0 = x; + if (y < my0) my0 = y; + if (x > mx1) mx1 = x; + if (y > my1) my1 = y; + } + if (any) { + selX0 = mx0; + selY0 = my0; + selX1 = mx1 + 1; + selY1 = my1 + 1; + hasSel = 1; + } + } + RenderDoc(canvas); + SetScratch("Selection loaded: %s", path); + fprintf(stderr, "dtphoto: selection loaded %s\n", path); +} + static void MenuCallback(Widget w, XtPointer data, XtPointer call) { @@ -9926,14 +10747,12 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) case CMD_RULERS: showRulers = !showRulers; RenderDoc(canvas); - RenderDoc(canvas); fprintf(stderr, "dtphoto: rulers %s\n", showRulers ? "on" : "off"); break; case CMD_GRID: showGrid = !showGrid; RenderDoc(canvas); - RenderDoc(canvas); fprintf(stderr, "dtphoto: grid %s\n", showGrid ? "on" : "off"); break; @@ -9969,14 +10788,7 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) /* ---------------- the rest of the reference's menu list ---------- */ /* File */ case CMD_OPENAS: FileDialog(0); break; - case CMD_PLACE: - MessageBox("Place", - "Place reads a second picture into this document.\n" - "This build keeps one picture per window, so there is " - "nothing to place into: open the second picture and " - "use Edit > Copy, then Edit > Paste."); - fprintf(stderr, "dtphoto: place (one picture per window)\n"); - break; + case CMD_PLACE: FileDialog(2); break; case CMD_SAVECOPY: FileDialog(1); break; case CMD_ACQUIRE: MessageBox("Acquire", @@ -9985,11 +10797,12 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) fprintf(stderr, "dtphoto: acquire (no source)\n"); break; case CMD_EXPORT: - MessageBox("Export", - "Export writes a file for another program.\n" - "This build writes BMP, PNG, JPEG and GIF through " - "File > Save As."); - fprintf(stderr, "dtphoto: export\n"); + /* + * Export is Save As without adopting the name: the format + * comes from the ending (PNG, BMP, JPEG, GIF, XPM), and the + * document keeps writing to its own file afterwards. + */ + FileDialog(3); break; /* Edit */ case CMD_PASTEINTO: @@ -10002,12 +10815,16 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) OpDone("paste layer"); break; case CMD_CREATEPUB: + /* + * The original's Publisher hands the picture to a document + * program. What this build can honour is the exchange file + * itself: an EPS, which every layout program reads. So the + * command writes one instead of refusing. + */ + PublishEPS(); + break; case CMD_PUBOPTS: - MessageBox("Publisher", - "Publisher writes an Acrobat exchange file.\n" - "There is no PDF writer in this build; File > Save As " - "writes BMP, PNG, JPEG and GIF."); - fprintf(stderr, "dtphoto: publisher (no pdf writer)\n"); + PublisherOptions(); break; case CMD_SNAPSHOT: XCopyArea(dpy, image, snap, gc, 0, 0, docW, docH, 0, 0); @@ -10039,9 +10856,6 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) OpGamutWarning(1); OpDone("gamut warning"); break; - case CMD_IMAGEDUP: - DuplicateDoc(); - break; /* Image > Effects */ case CMD_EFFECTSCALE: { char buf[32]; @@ -10095,10 +10909,7 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) curLayer + 1, nlayers); break; case CMD_ADJOPTS: - MessageBox("Adjustment Options", - "An adjustment layer would carry a correction.\n" - "This build corrects the layer itself: Image > Adjust."); - fprintf(stderr, "dtphoto: adjustment options\n"); + AdjustmentOptions(); break; case CMD_DROPSHADOW: OpLayerEffect(0, 4, 60, 4, 4); @@ -10122,8 +10933,9 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) break; case CMD_TYPEH: case CMD_TYPEV: - /* the type tool of the toolbox, which is how text gets in */ - currentTool = 7; + /* the type tool of the toolbox, which is how text gets in: + * slot 8 in toolNames, not 7 -- that one is crop */ + currentTool = 8; fprintf(stderr, "dtphoto: tool %s\n", toolNames[currentTool]); break; case CMD_LAYERSCALE: @@ -10200,113 +11012,12 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) RenderDoc(canvas); fprintf(stderr, "dtphoto: edges hidden\n"); break; - case CMD_LOADSEL: { - /* the .sel file Save Selection wrote, beside the picture */ - char path[1024]; - FILE *f; - int w = 0, h = 0, maxv = 0, x, y; - - if (docPath == NULL) { - MessageBox("Load Selection", - "Select > Save Selection writes the selection " - "beside the picture, so load needs a saved " - "document first."); - fprintf(stderr, "dtphoto: load selection, no file\n"); - break; - } - snprintf(path, sizeof path, "%s.sel", docPath); - if ((f = fopen(path, "rb")) == NULL) { - SetScratch("No saved selection for this document."); - fprintf(stderr, "dtphoto: load selection, %s missing\n", - path); - break; - } - if (fscanf(f, "P5 %d %d %d", &w, &h, &maxv) != 3 || - w != docW || h != docH) { - fclose(f); - SetScratch("The saved selection does not fit this " - "picture."); - fprintf(stderr, "dtphoto: load selection, size\n"); - break; - } - fgetc(f); /* the single whitespace after the header */ - if (MaskAlloc() != 0) { - fclose(f); - break; - } - MaskClear(); - for (y = 0; y < h; y++) - for (x = 0; x < w; x++) { - int c = fgetc(f); - - if (c == EOF) - break; - if (c > 0) { - MaskSet(x, y, 1); - if (selCover != NULL) - selCover[(size_t) y * w + x] = - (unsigned char) c; - } - } - fclose(f); - /* the marquee follows the mask's bounding box */ - { - int mx0 = w, my0 = h, mx1 = 0, my1 = 0, any = 0; - - for (y = 0; y < h; y++) - for (x = 0; x < w; x++) - if (MaskGet(x, y)) { - any = 1; - if (x < mx0) mx0 = x; - if (y < my0) my0 = y; - if (x > mx1) mx1 = x; - if (y > my1) my1 = y; - } - if (any) { - selX0 = mx0; - selY0 = my0; - selX1 = mx1 + 1; - selY1 = my1 + 1; - hasSel = 1; - } - } - RenderDoc(canvas); - SetScratch("Selection loaded: %s", path); - fprintf(stderr, "dtphoto: selection loaded %s\n", path); + case CMD_LOADSEL: + LoadSelection(); break; - } - case CMD_SAVESEL: { - char path[1024]; - FILE *f; - int x, y; - - if (docPath == NULL) { - MessageBox("Save Selection", - "The selection is written beside the picture.\n" - "File > Save As first, then this."); - fprintf(stderr, "dtphoto: save selection, no file\n"); - break; - } - if (!selMaskAny) { - SetScratch("There is no selection to save."); - fprintf(stderr, "dtphoto: save selection, empty\n"); - break; - } - snprintf(path, sizeof path, "%s.sel", docPath); - if ((f = fopen(path, "wb")) == NULL) { - SetScratch("The selection could not be written."); - fprintf(stderr, "dtphoto: save selection, write\n"); - break; - } - fprintf(f, "P5\n%d %d\n255\n", docW, docH); - for (y = 0; y < docH; y++) - for (x = 0; x < docW; x++) - fputc(MaskCover(x, y), f); - fclose(f); - SetScratch("Selection saved: %s", path); - fprintf(stderr, "dtphoto: selection saved %s\n", path); + case CMD_SAVESEL: + SaveSelection(); break; - } /* Filter */ case CMD_LASTFILTER: RepeatLastFilter(); @@ -10351,7 +11062,6 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) case CMD_SHOWGUIDES: showGuides = !showGuides; RenderDoc(canvas); - RenderDoc(canvas); fprintf(stderr, "dtphoto: guides %s\n", showGuides ? "on" : "off"); break; @@ -10363,8 +11073,6 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) case CMD_LOCKGUIDES: lockGuides = !lockGuides; /* a locked guide cannot be moved by a drag */ - if (lockGuides) - fprintf(stderr, "dtphoto: guides locked\n"); fprintf(stderr, "dtphoto: guides %s\n", lockGuides ? "locked" : "unlocked"); break; @@ -10372,7 +11080,6 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) GuidesClear(); showGuides = 0; RenderDoc(canvas); - RenderDoc(canvas); fprintf(stderr, "dtphoto: guides cleared\n"); break; case CMD_SNAPGRID: @@ -10391,24 +11098,13 @@ MenuCallback(Widget w, XtPointer data, XtPointer call) ShowLayers(); break; case CMD_SHOWCHANNELS: - MessageBox("Channels", - "An RGB picture has three channels.\n" - "This build keeps them together in one buffer, so the " - "palette would show three copies of the same picture."); - fprintf(stderr, "dtphoto: channels\n"); + ShowChannels(); break; case CMD_SHOWPATHS: - MessageBox("Paths", - "There is no pen tool in this build, so there are no " - "paths to list."); - fprintf(stderr, "dtphoto: paths\n"); + ShowPaths(); break; case CMD_SHOWCOMMANDS: - MessageBox("Commands", - "The commands this build carries out are listed in " - "dtphoto -menutest, one path per line.\n" - "Filter > Last Filter repeats the last one."); - fprintf(stderr, "dtphoto: commands\n"); + ShowCommands(); break; default: fprintf(stderr, "dtphoto: %s\n", label); @@ -10442,6 +11138,7 @@ main(int argc, char **argv) top = XtVaAppInitialize(&app, "Dtphoto", opts, XtNumber(opts), &argc, argv, fallbacks, NULL); + appctx = app; /* only valid after the call that fills it */ dpy = XtDisplay(top); InitColor(); if (XGetDefault(dpy, "dtphoto", "version") != NULL) @@ -10972,12 +11669,454 @@ main(int argc, char **argv) return bad == 0 ? 0 : 1; } + + /* + * Save Selection / Load Selection round trip. A half-covered band + * goes out and comes back: every byte must be the byte written, + * which is what the feathered edge depends on. The document is + * given a path so the file lands beside it, and the mask is + * cleared in between so a load that reads nothing cannot pass. + */ + if (argc >= 3 && strcmp(argv[1], "-seltest") == 0) { + int w = 12, h = 8, x, y, bad = 0; + unsigned char *rgb; + int n; + + rgb = malloc((size_t) w * h * 3); + if (rgb == NULL) { + printf("dtphoto seltest: FAIL malloc\n"); + return 1; + } + for (n = 0; n < w * h; n++) + rgb[n * 3] = rgb[n * 3 + 1] = rgb[n * 3 + 2] = 200; + SetImageRGB(rgb, w, h); + free(rgb); + if (MaskAlloc() != 0) { + printf("dtphoto seltest: FAIL alloc\n"); + return 1; + } + MaskClear(); + selMaskAny = 1; + for (y = 2; y < 6; y++) + for (x = 3; x < 9; x++) + MaskSet(x, y, 1); + hasSel = 1; + selX0 = 3; selY0 = 2; selX1 = 9; selY1 = 6; + /* the cover layer first, then the soft edge written into it */ + if (CoverAlloc() != 0) { + printf("dtphoto seltest: FAIL cover alloc\n"); + return 1; + } + for (y = 2; y < 6; y++) + for (x = 3; x < 9; x++) + selCover[(size_t) y * w + x] = + (unsigned char) (x == 3 ? 64 : + x == 4 ? 160 : 255); + + docPath = argv[2]; + SaveSelection(); + /* what was saved must be there and be a P5 of this size */ + { + char sp[1024]; + FILE *f; + int sw = 0, sh = 0, sm = 0; + + snprintf(sp, sizeof sp, "%s.sel", docPath); + if ((f = fopen(sp, "rb")) == NULL) { + printf("dtphoto seltest: %s not written FAIL\n", + sp); + bad++; + } else { + if (fscanf(f, "P5 %d %d %d", &sw, &sh, &sm) != 3 + || sw != w || sh != h || sm != 255) { + printf("dtphoto seltest: header %dx%d " + "max %d FAIL\n", sw, sh, sm); + bad++; + } else + printf("dtphoto seltest: header %dx%d " + "max 255 ok\n", sw, sh); + fclose(f); + } + } + /* wipe the mask: a load that reads nothing stays empty */ + MaskClear(); + selMaskAny = 0; + hasSel = 0; + LoadSelection(); + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + int want = (x >= 3 && x < 9 && y >= 2 && y < 6); + int got = MaskGet(x, y); + + if (got != want) { + printf("dtphoto seltest: mask %d,%d " + "got %d want %d FAIL\n", x, y, got, + want); + bad++; + } + } + /* the feather's bytes must survive, not just the bits */ + if (MaskGet(3, 2) && MaskCover(3, 2) != 64) { + printf("dtphoto seltest: cover 3,2 = %d want 64 FAIL\n", + MaskCover(3, 2)); + bad++; + } + if (MaskCover(5, 4) != 255) { + printf("dtphoto seltest: cover 5,4 = %d want 255 FAIL\n", + MaskCover(5, 4)); + bad++; + } + if (!hasSel || selX0 != 3 || selY0 != 2 || + selX1 != 9 || selY1 != 6) { + printf("dtphoto seltest: marquee %d,%d..%d,%d want " + "3,2..9,6 FAIL\n", selX0, selY0, selX1, selY1); + bad++; + } + docPath = NULL; + printf("dtphoto seltest: %s\n", bad == 0 ? "PASS" : "FAIL"); + return bad == 0 ? 0 : 1; + } + + /* + * The Channels and Paths palettes and the Publisher's resolution: the + * three places where a palette could so easily show a pretty picture + * of nothing. Each is checked against numbers worked out here, and + * the EPS is read back to see whether the resolution reached the + * header -- a field that only changes a variable is not a feature. + */ + if (argc >= 2 && strcmp(argv[1], "-paneltest") == 0) { + unsigned char *rgb, *got; + long lo, hi, distinct, mean; + int w = 4, h = 3, gw, gh, x, y, bad = 0; + char eps[256], line[256]; + FILE *fp; + double want; + + /* R: 0,10,20,30 across; G: 0,20,40 down; B stays 60 */ + rgb = malloc((size_t) w * h * 3); + if (rgb == NULL) { + printf("dtphoto paneltest: FAIL malloc\n"); + return 1; + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *d = rgb + ((size_t) y * w + x) * 3; + + d[0] = (unsigned char) (x * 10); + d[1] = (unsigned char) (y * 20); + d[2] = 60; + } + SetImageRGB(rgb, w, h); + + /* red: values 0,10,20,30 -> lo 0, hi 30, mean 15, 4 levels */ + ChannelMeasure(0, &lo, &hi, &distinct, &mean); + if (lo != 0 || hi != 30 || mean != 15 || distinct != 4) { + printf("dtphoto paneltest: red %ld..%ld mean %ld " + "%ld levels, want 0..30 mean 15 4 FAIL\n", lo, hi, + mean, distinct); + bad++; + } else + printf("dtphoto paneltest: red %ld..%ld mean %ld " + "%ld levels ok\n", lo, hi, mean, distinct); + /* blue: constant 60 -> one level, mean 60 */ + ChannelMeasure(2, &lo, &hi, &distinct, &mean); + if (lo != 60 || hi != 60 || mean != 60 || distinct != 1) { + printf("dtphoto paneltest: blue %ld..%ld mean %ld " + "%ld levels, want 60 constant FAIL\n", lo, hi, mean, + distinct); + bad++; + } else + printf("dtphoto paneltest: blue %ld..%ld mean %ld " + "%ld level ok\n", lo, hi, mean, distinct); + + /* the path list reads the lasso's run, not a hard-coded name */ + lassoN = 0; + LassoAdd(2, 3); + LassoAdd(9, 3); + LassoAdd(9, 8); + LassoAdd(2, 8); + if (lassoN != 4) { + printf("dtphoto paneltest: lasso %d points FAIL\n", + lassoN); + bad++; + } else + printf("dtphoto paneltest: path 4 points ok\n"); + lassoN = 0; + + /* + * The Publisher's resolution: 4 x 3 at 72 dpi is 4 x 3 points, + * at 288 dpi a quarter of that. The EPS header has to carry + * the second number. + */ + snprintf(eps, sizeof eps, "/tmp/dtphoto-panel.eps"); + free(docPath); + docPath = strdup("/tmp/dtphoto-panel"); + epsResolution = 72; + if (PublishEPS() != 0) { + printf("dtphoto paneltest: publish 72 FAIL\n"); + bad++; + } else + printf("dtphoto paneltest: publish 72 ok\n"); + epsResolution = 288; + if (PublishEPS() != 0) { + printf("dtphoto paneltest: publish 288 FAIL\n"); + bad++; + } else + printf("dtphoto paneltest: publish 288 ok\n"); + snprintf(eps, sizeof eps, "/tmp/dtphoto-panel.eps"); + fp = fopen(eps, "r"); + if (fp == NULL) { + printf("dtphoto paneltest: %s missing FAIL\n", eps); + bad++; + } else { + want = 4.0 * 72.0 / 288.0; /* 1 point wide */ + while (fgets(line, sizeof line, fp) != NULL) + if (strncmp(line, "%%BoundingBox:", 14) == 0) { + /* llx lly urx ury -- the width is the + * third number, not the first */ + double a[4]; + double bw, bh; + int n = sscanf(strchr(line, ':') + 1, + "%lf %lf %lf %lf", &a[0], &a[1], + &a[2], &a[3]); + + if (n != 4) { + printf("dtphoto paneltest: " + "bbox unreadable FAIL\n"); + bad++; + continue; + } + bw = a[2] - a[0]; + bh = a[3] - a[1]; + fprintf(stderr, "dtphoto paneltest: " + "bbox %.0fx%.0f points, want " + "%.0fx%0.f\n", bw, bh, want, + want * h / w); + if ((int) (want + 0.5) != + (int) (bw + 0.5)) { + printf("dtphoto paneltest: " + "bbox width %.2f want %.2f " + "FAIL\n", bw, want); + bad++; + } else + printf("dtphoto paneltest: " + "bbox %.0f points ok\n", bw); + break; + } + fclose(fp); + if (getenv("DTPHOTO_KEEP_EPS") == NULL) + unlink(eps); + } + + /* and the picture must not have changed by any of it */ + if (GetImageRGB(&got, &gw, &gh) == 0) { + if (gw != w || gh != h || + memcmp(got, rgb, (size_t) w * h * 3) != 0) { + printf("dtphoto paneltest: picture changed " + "FAIL\n"); + bad++; + } else + printf("dtphoto paneltest: picture unchanged " + "ok\n"); + free(got); + } + free(rgb); + printf("dtphoto paneltest: %s\n", bad == 0 ? "PASS" : "FAIL"); + return bad == 0 ? 0 : 1; + } + + /* + * Printing: the document goes to the queue as a BMP. With + * MCDE_PRINT_COMMAND naming a tool that keeps what it is given, the + * whole path -- save, spool, reap -- is checked without a printer, + * which is the point: a print path that only claims to work is what + * this replaces. The last argument lp(1) is given is the file. + */ + if (argc >= 2 && strcmp(argv[1], "-placetest") == 0) { + unsigned char *rgb, *got; + int w, h, gw, gh, bad = 0; + const char *small = "/tmp/place-small.png"; + + /* a 32x24 document in mid grey */ + w = 32; h = 24; + rgb = malloc((size_t) w * h * 3); + if (rgb == NULL) + return 1; + memset(rgb, 100, (size_t) w * h * 3); + SetImageRGB(rgb, w, h); + free(rgb); + + /* + * The picture to place: 8x8 pure white, written through the + * same writer the program uses, so the test covers the file + * path and not only the arithmetic. + */ + { + unsigned char *s8 = malloc(8 * 8 * 3); + int i; + + if (s8 == NULL) + return 1; + for (i = 0; i < 8 * 8; i++) + s8[i * 3] = s8[i * 3 + 1] = + s8[i * 3 + 2] = 255; + if (McdeThumbWrite(small, s8, 8, 8) != 0) { + printf("dtphoto placetest: FAIL write\n"); + free(s8); + return 1; + } + free(s8); + } + if (PlaceImage(small) != 0) { + printf("dtphoto placetest: FAIL place\n"); + return 1; + } + if (GetImageRGB(&got, &gw, &gh) != 0) { + printf("dtphoto placetest: FAIL read\n"); + return 1; + } + /* the document keeps its size: a place adds, it does not open */ + if (gw != w || gh != h) { + printf("dtphoto placetest: size %dx%d want %dx%d FAIL\n", + gw, gh, w, h); + bad++; + } + /* + * 8x8 centred in 32x24 sits at x = 12, y = 8. The middle of + * the placed square is white; a corner of the document is + * still the grey it was. + */ + { + unsigned char *c = got + ((size_t) 12 * gw + 16) * 3; + unsigned char *o = got + ((size_t) 1 * gw + 1) * 3; + + if (c[0] < 250 || c[1] < 250 || c[2] < 250) { + printf("dtphoto placetest: centre %d,%d,%d " + "want white FAIL\n", c[0], c[1], c[2]); + bad++; + } + if (abs((int) o[0] - 100) > 2) { + printf("dtphoto placetest: outside %d,%d,%d " + "want grey FAIL\n", o[0], o[1], o[2]); + bad++; + } + } + /* + * A picture larger than the document is fitted, not clipped: + * 64x48 into 32x24 lands as 32x24, so every pixel of the + * document is covered and the grey is gone. + */ + { + unsigned char *big = malloc(64 * 48 * 3); + int i, grey = 0; + + if (big == NULL) { + printf("dtphoto placetest: FAIL big\n"); + return 1; + } + for (i = 0; i < 64 * 48; i++) + big[i * 3] = big[i * 3 + 1] = + big[i * 3 + 2] = 255; + if (McdeThumbWrite("/tmp/place-big.png", big, 64, 48) + != 0) { + printf("dtphoto placetest: FAIL big write\n"); + free(big); + return 1; + } + free(big); + if (PlaceImage("/tmp/place-big.png") != 0) { + printf("dtphoto placetest: FAIL big place\n"); + return 1; + } + if (GetImageRGB(&got, &gw, &gh) != 0) { + printf("dtphoto placetest: FAIL big read\n"); + return 1; + } + if (gw != 32 || gh != 24) { + printf("dtphoto placetest: big size %dx%d " + "FAIL\n", gw, gh); + bad++; + } + for (i = 0; i < gw * gh; i++) + if (abs((int) got[i * 3] - 100) < 20) + grey++; + if (grey != 0) { + printf("dtphoto placetest: big left %d grey " + "pixels, want the picture to cover FAIL\n", + grey); + bad++; + } + free(got); + } + printf("dtphoto placetest: %s\n", bad ? "FAIL" : "PASS"); + return bad ? 1 : 0; + } + if (argc >= 3 && strcmp(argv[1], "-printtest") == 0) { + const char *fake = getenv("MCDE_PRINT_COMMAND"); + const char *out = argv[2]; + McdeSysJob *job; + int fd, rc, waited = 0; + char spool[64]; + struct stat st; + + if (fake == NULL) { + printf("dtphoto printtest: MCDE_PRINT_COMMAND unset, " + "would need a printer FAIL\n"); + return 1; + } + snprintf(spool, sizeof spool, "/tmp/dtphoto-print-%d.bmp", + (int) getpid()); + if (SaveBMP(spool) != 0) { + printf("dtphoto printtest: save %s FAIL\n", spool); + return 1; + } + job = mcde_sys_print_file(spool, NULL); + if (job == NULL) { + printf("dtphoto printtest: spool refused: %s FAIL\n", + mcde_sys_error()); + unlink(spool); + return 1; + } + fd = mcde_sys_job_fd(job); + { /* wait for the tool, as the event loop would */ + fd_set rs; + struct timeval tv; + + while (waited < 100) { + FD_ZERO(&rs); + FD_SET(fd, &rs); + tv.tv_sec = 0; + tv.tv_usec = 100000; + if (select(fd + 1, &rs, NULL, NULL, &tv) > 0) + break; + waited++; + } + } + rc = mcde_sys_job_finish(job); + unlink(spool); + if (rc != MCDE_SYS_OK) { + printf("dtphoto printtest: lp failed: %s FAIL\n", + mcde_sys_error()); + return 1; + } + if (stat(out, &st) != 0 || st.st_size < 54) { + printf("dtphoto printtest: %s never reached the " + "printer FAIL\n", out); + return 1; + } + printf("dtphoto printtest: %ld bytes spooled to the printer " + "ok\n", (long) st.st_size); + printf("dtphoto printtest: PASS\n"); + return 0; + } + /* The menu bindings, without a mouse: every path the program claims * to carry out must resolve to the command the callback switches * on. A path that resolves to CMD_NONE is an entry that does * nothing but print its own label. */ if (argc >= 2 && strcmp(argv[1], "-menutest") == 0) { int i, bad = 0, ntab = 0, ndup = 0; + int nmenu = 0, nbind = 0; /* * Every entry of the command table must resolve to its own @@ -11007,6 +12146,23 @@ main(int argc, char **argv) printf("dtphoto menutest: unknown path bound FAIL\n"); bad++; } + /* + * The table is only half the story: the menu the program + * actually reads must be covered by it. A line in the + * menu file with no command is a label a person can click + * that does nothing, which is what this test is for. + */ + { + int i; + nmenus = 0; + ReadMenus("dtphoto.menu"); + for (i = 0; i < nmenus; i++) + nbind += CountUnbound(&menus[i], &nmenu); + } + printf("dtphoto menutest: %d menu items, %d unbound\n", + nmenu, nbind); + if (nbind != 0) + bad++; printf("dtphoto menutest: %d paths, %d doubled, %d bad\n", ntab, ndup, bad); printf("dtphoto menutest: %s\n", @@ -12100,6 +13256,141 @@ main(int argc, char **argv) return bad == 0 ? 0 : 1; } + if (argc >= 2 && strcmp(argv[1], "-exporttest") == 0) { + unsigned char *rgb, *got; + int w, h, gw, gh, x, y, c, bad = 0; + char before[256]; + static const char *const exts[] = { + "png", "bmp", "jpg", "gif", "xpm", NULL + }; + int e; + + w = 12; h = 9; + rgb = malloc((size_t) w * h * 3); + if (rgb == NULL) + return 1; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + unsigned char *p = rgb + ((size_t) y * w + x) * 3; + + p[0] = (unsigned char) (x * 20); + p[1] = (unsigned char) (y * 25); + p[2] = (unsigned char) (255 - x * 15); + } + SetImageRGB(rgb, w, h); + + /* + * Export must not adopt the name: the document keeps writing + * to its own file after an export. That is the difference + * from Save As, and the reason the two are separate entries. + */ + snprintf(before, sizeof before, "%s", + docPath != NULL ? docPath : ""); + + for (e = 0; exts[e] != NULL; e++) { + char path[128]; + int px; + + snprintf(path, sizeof path, "/tmp/exp.%s", exts[e]); + remove(path); + if (ExportImage(path) != 0) { + printf("dtphoto exporttest: %s FAIL write\n", + exts[e]); + bad++; + continue; + } + /* + * Every export but JPEG comes back exactly: this + * picture has 108 colours, so GIF keeps its own table + * instead of quantising. + */ + if (strcmp(exts[e], "jpg") == 0) { + FILE *f = fopen(path, "rb"); + + if (f == NULL || fgetc(f) != 0xFF) { + printf("dtphoto exporttest: jpg FAIL " + "magic\n"); + bad++; + } + if (f != NULL) + fclose(f); + continue; + } + /* + * Reading the export back is a test step, not an + * export: it legitimately adopts the name, so the + * document name is checked right here, before the + * first read. + */ + if (e == 0 && + strcmp(before, docPath != NULL ? docPath : "") != 0) { + printf("dtphoto exporttest: export renamed the " + "document FAIL\n"); + bad++; + } + if (OpenImage(path) != 0) { + printf("dtphoto exporttest: %s FAIL read\n", + exts[e]); + bad++; + continue; + } + if (GetImageRGB(&got, &gw, &gh) != 0) { + printf("dtphoto exporttest: %s FAIL get\n", + exts[e]); + bad++; + continue; + } + if (gw != w || gh != h) { + printf("dtphoto exporttest: %s size %dx%d " + "want %dx%d FAIL\n", exts[e], gw, gh, + w, h); + bad++; + } + px = 0; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + for (c = 0; c < 3; c++) + if (got[((size_t) y * w + x) * 3 + + c] != + rgb[((size_t) y * w + x) * 3 + + c]) + px++; + if (px != 0) { + printf("dtphoto exporttest: %s %d bytes " + "differ FAIL\n", exts[e], px); + bad++; + } + free(got); + } + + + + /* Publisher writes an EPS; it must start with the right line */ + if (docPath != NULL) { + char ep[320]; + FILE *f; + char line[64]; + + snprintf(ep, sizeof ep, "%s.eps", docPath); + remove(ep); + if (PublishEPS() != 0) { + printf("dtphoto exporttest: eps FAIL write\n"); + bad++; + } else if ((f = fopen(ep, "rb")) == NULL || + fgets(line, sizeof line, f) == NULL || + strncmp(line, "%!PS-Adobe-3.0 EPSF-3.0", 20) != 0) { + printf("dtphoto exporttest: eps FAIL header\n"); + bad++; + if (f != NULL) + fclose(f); + } else + fclose(f); + } + free(rgb); + printf("dtphoto exporttest: %s\n", bad == 0 ? "PASS" : "FAIL"); + return bad == 0 ? 0 : 1; + } + if (argc >= 2 && strcmp(argv[1], "-optest") == 0) { unsigned char *rgb; int w = 6, h = 4, x, y, bad = 0; diff --git a/programs/dtphoto/dtphoto.msg b/programs/dtphoto/dtphoto.msg index ed8ed082..49e01cb3 100644 --- a/programs/dtphoto/dtphoto.msg +++ b/programs/dtphoto/dtphoto.msg @@ -8,3 +8,5 @@ $set 1 4 The picture could not be opened. 5 The picture could not be saved. 6 Tool Options +7 Nothing could be placed. +8 The picture could not be exported. From 4fead8a3dcfbfdf1d0fc3002ff2df97f0d426739 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 16:11:16 +0000 Subject: [PATCH 21/22] libDtChat tests: no /tmp/opencode, and test_i18n finds its catalogs Two defects in the test suite, both of the kind that fails on another machine but not on the one it was written on. 1. Seven tests put their scratch directories below /tmp/opencode -- a directory of the environment they were written in, not of the system. mkdtemp() returns NULL when the parent is missing, so on a machine without /tmp/opencode every one of them failed with a "NULL" check or perror("mkdtemp"), and nothing was wrong with the code under test. dc_test_tmpdir() (dc_internal.h, instance.c) now uses $TMPDIR, or /tmp when it is unset or not absolute. Measured: after renaming /tmp/opencode away (sudo mv), make check in lib/libDtChat is 24/24; before the change the same run failed on test_identity, test_pair, test_store, test_instance, test_filexfer, test_local and test_i18n. 2. test_i18n takes but TESTS runs it without arguments (f46a914c added it to TESTS without a runner), so `make check' always reported "FAIL: test_i18n" with the usage line -- measured 2026-11-22 on the merge build, and identically on build/mcde-host, so not a regression of that merge. tools/mcde-tests.sh names the files and passes; the test now falls back to $srcdir (which automake's test driver exports) and finds them itself, the arguments still winning. Test: make check in lib/libDtChat -> 24/24 PASS (was 23/24). Both call forms of test_i18n give "test_i18n: all ok": with the two arguments and without them. With /tmp/opencode renamed away the full check is green as well, and the seven scratch directories appear under $TMPDIR when set. --- lib/libDtChat/dc_internal.h | 10 ++++++++++ lib/libDtChat/instance.c | 22 ++++++++++++++++++++++ lib/libDtChat/test_filexfer.c | 12 ++++++------ lib/libDtChat/test_i18n.c | 35 ++++++++++++++++++++++++++++------- lib/libDtChat/test_identity.c | 4 ++-- lib/libDtChat/test_instance.c | 4 ++-- lib/libDtChat/test_local.c | 11 +++++------ lib/libDtChat/test_pair.c | 4 ++-- lib/libDtChat/test_store.c | 4 ++-- 9 files changed, 79 insertions(+), 27 deletions(-) diff --git a/lib/libDtChat/dc_internal.h b/lib/libDtChat/dc_internal.h index 50838aee..15257a41 100644 --- a/lib/libDtChat/dc_internal.h +++ b/lib/libDtChat/dc_internal.h @@ -731,4 +731,14 @@ void dc_instance_close(DcInstance *instance); /* Connect to a running primary and send {"cmd":"open","conv":...}. */ int dc_instance_notify(const char *dir, const char *conv); +/* + * The tests' scratch directories. They used to name /tmp/opencode/-XXXXXX + * -- a directory of the environment they were written in, not of the system: + * mkdtemp() returns NULL when its parent is missing, so every test that needs + * a directory failed on a machine that has no /tmp/opencode (measured + * 2026-11-22). This fills "template" with $TMPDIR (or /tmp) and a name + * unique enough for a test run and makes the directory; 0 on success. + */ +int dc_test_tmpdir(char *template, size_t len, const char *name); + #endif /* _DtChat_dc_internal_h */ diff --git a/lib/libDtChat/instance.c b/lib/libDtChat/instance.c index 8c7949ac..1c623766 100644 --- a/lib/libDtChat/instance.c +++ b/lib/libDtChat/instance.c @@ -446,3 +446,25 @@ fail: free(sock_path); return -1; } + +/* ------------------------------------------------------------------ tests */ + +/* + * A scratch directory for the tests: $TMPDIR (or /tmp) plus "name-XXXXXX". + * The tests used to write /tmp/opencode/-XXXXXX, and mkdtemp() returns + * NULL when that parent does not exist -- every test that needs a directory + * then failed on a machine without /tmp/opencode (measured 2026-11-22). + */ +int +dc_test_tmpdir(char *template, size_t len, const char *name) +{ + const char *base = getenv("TMPDIR"); + int n; + + if (base == NULL || base[0] != '/') + base = "/tmp"; + n = snprintf(template, len, "%s/dtchat-%s-XXXXXX", base, name); + if (n < 0 || (size_t)n >= len) + return -1; + return mkdtemp(template) != NULL ? 0 : -1; +} diff --git a/lib/libDtChat/test_filexfer.c b/lib/libDtChat/test_filexfer.c index 21e8638b..877f80b3 100644 --- a/lib/libDtChat/test_filexfer.c +++ b/lib/libDtChat/test_filexfer.c @@ -197,14 +197,14 @@ test_names(void) int main(void) { - char tmp[] = "/tmp/opencode/dtchat-xfer-XXXXXX"; + char tmp[64]; char dir[512]; char src[600]; char src2[600]; char sha_src[65]; char sha_recv[65]; - char base1[] = "/tmp/opencode/dtchat-xfer-a-XXXXXX"; - char base2[] = "/tmp/opencode/dtchat-xfer-b-XXXXXX"; + char base1[64]; + char base2[64]; char id1[600], id2[600]; DcIdentity *a; DcIdentity *b; @@ -215,7 +215,7 @@ main(void) int steps = 0; memset(&t, 0, sizeof(t)); - CHECK(mkdtemp(tmp) != NULL); + CHECK(dc_test_tmpdir(tmp, sizeof tmp, "xfer") == 0); snprintf(dir, sizeof(dir), "%s/dl", tmp); snprintf(t.dir, sizeof(t.dir), "%s", dir); snprintf(src, sizeof(src), "%s/source.bin", tmp); @@ -224,8 +224,8 @@ main(void) CHECK(dc_file_safe_name("../../escape.bin") != NULL); free(dc_file_safe_name("../../escape.bin")); - CHECK(mkdtemp(base1) != NULL); - CHECK(mkdtemp(base2) != NULL); + CHECK(dc_test_tmpdir(base1, sizeof base1, "xfer-a") == 0); + CHECK(dc_test_tmpdir(base2, sizeof base2, "xfer-b") == 0); snprintf(id1, sizeof(id1), "%s/state", base1); snprintf(id2, sizeof(id2), "%s/state", base2); a = dc_identity_load_or_create(id1); diff --git a/lib/libDtChat/test_i18n.c b/lib/libDtChat/test_i18n.c index 0ba8a536..9f06c62a 100644 --- a/lib/libDtChat/test_i18n.c +++ b/lib/libDtChat/test_i18n.c @@ -64,18 +64,39 @@ use_catalog(const char *dir) int main(int argc, char **argv) { - char tmp[] = "/tmp/opencode/dtchat-i18n-XXXXXX"; + char tmp[64]; char de[1024], en[1024], cat[1200]; char *msg_de; char *msg_en; - if (argc < 3) { - fprintf(stderr, "usage: %s \n", argv[0]); - return 2; + /* make check gives no arguments ($srcdir is exported by automake's + * test driver); tools/mcde-tests.sh names the two files. Both the + * in-tree build and a VPATH build find them this way. */ + if (argc >= 3) { + msg_de = argv[1]; + msg_en = argv[2]; + } else { + const char *srcdir = getenv("srcdir"); + static char bde[1024], ben[1024]; + int n; + + if (srcdir == NULL || srcdir[0] == '\0') + srcdir = "."; + n = snprintf(bde, sizeof(bde), "%s/../../programs/" + "localized/de_DE.UTF-8/msg/dtchat.msg", srcdir); + if (n > 0 && (size_t)n < sizeof(bde) && + access(bde, R_OK) == 0) { + msg_de = bde; + snprintf(ben, sizeof(ben), "%s/../../programs/" + "dtchat/dtchat.msg", srcdir); + msg_en = ben; + } else { + fprintf(stderr, "usage: %s \n", + argv[0]); + return 2; + } } - msg_de = argv[1]; - msg_en = argv[2]; - CHECK(mkdtemp(tmp) != NULL); + CHECK(dc_test_tmpdir(tmp, sizeof tmp, "i18n") == 0); snprintf(de, sizeof(de), "%s/de", tmp); snprintf(en, sizeof(en), "%s/en", tmp); CHECK(mkdir(de, 0700) == 0 || 1); diff --git a/lib/libDtChat/test_identity.c b/lib/libDtChat/test_identity.c index 294e0f75..4b6c1746 100644 --- a/lib/libDtChat/test_identity.c +++ b/lib/libDtChat/test_identity.c @@ -35,7 +35,7 @@ mode_is(const char *path, mode_t want) int main(void) { - char base[] = "/tmp/opencode/dtchat-id-XXXXXX"; + char base[64]; char dir[512]; char other[512]; char path[600]; @@ -44,7 +44,7 @@ main(void) char pin[128]; char pub[128]; - CHECK(mkdtemp(base) != NULL); + CHECK(dc_test_tmpdir(base, sizeof base, "id") == 0); snprintf(dir, sizeof(dir), "%s/state", base); snprintf(other, sizeof(other), "%s/other", base); snprintf(path, sizeof(path), "%s/identity.json", dir); diff --git a/lib/libDtChat/test_instance.c b/lib/libDtChat/test_instance.c index 7311c40c..4da7ad55 100644 --- a/lib/libDtChat/test_instance.c +++ b/lib/libDtChat/test_instance.c @@ -80,7 +80,7 @@ raw_connect(const char *path) int main(void) { - char tmpdir[] = "/tmp/opencode/dtchat-inst-XXXXXX"; + char tmpdir[64]; char dir[256]; char run[512]; char lock[1024]; @@ -92,7 +92,7 @@ main(void) struct Opened opened; int fd; - if (mkdtemp(tmpdir) == NULL) { + if (dc_test_tmpdir(tmpdir, sizeof tmpdir, "inst") != 0) { perror("mkdtemp"); return 1; } diff --git a/lib/libDtChat/test_local.c b/lib/libDtChat/test_local.c index 7e18a63e..8607cdb5 100644 --- a/lib/libDtChat/test_local.c +++ b/lib/libDtChat/test_local.c @@ -32,8 +32,7 @@ static int mkidentity(char *base, size_t baselen, char *dir, size_t dirlen, DcIdentity **out) { - snprintf(base, baselen, "/tmp/opencode/dtchat-local-XXXXXX"); - if (mkdtemp(base) == NULL) + if (dc_test_tmpdir(base, baselen, "local") != 0) return -1; snprintf(dir, dirlen, "%s/state", base); *out = dc_identity_load_or_create(dir); @@ -495,15 +494,15 @@ test_reconnect(void) int main(void) { - char base_c[] = "/tmp/opencode/dtchat-local-c-XXXXXX"; - char base_o[] = "/tmp/opencode/dtchat-local-o-XXXXXX"; + char base_c[64]; + char base_o[64]; char dir_c[512], dir_o[512]; DcIdentity *client; DcIdentity *other; signal(SIGPIPE, SIG_IGN); - CHECK(mkdtemp(base_c) != NULL); - CHECK(mkdtemp(base_o) != NULL); + CHECK(dc_test_tmpdir(base_c, sizeof base_c, "local-c") == 0); + CHECK(dc_test_tmpdir(base_o, sizeof base_o, "local-o") == 0); snprintf(dir_c, sizeof(dir_c), "%s/state", base_c); snprintf(dir_o, sizeof(dir_o), "%s/state", base_o); client = dc_identity_load_or_create(dir_c); diff --git a/lib/libDtChat/test_pair.c b/lib/libDtChat/test_pair.c index 0e988ddf..e5f695fd 100644 --- a/lib/libDtChat/test_pair.c +++ b/lib/libDtChat/test_pair.c @@ -30,7 +30,7 @@ static int fails; int main(void) { - char tmp[] = "/tmp/opencode/dtchat-pair-XXXXXX"; + char tmp[64]; char dir[512]; DcPins *pins; DcPins *again; @@ -56,7 +56,7 @@ main(void) CHECK(dc_pair_sas("nonsense", PIN_B) == NULL); CHECK(dc_pair_sas(PIN_A, NULL) == NULL); - CHECK(mkdtemp(tmp) != NULL); + CHECK(dc_test_tmpdir(tmp, sizeof tmp, "pair") == 0); snprintf(dir, sizeof(dir), "%s/state", tmp); pins = dc_pins_load(dir); CHECK(pins != NULL); diff --git a/lib/libDtChat/test_store.c b/lib/libDtChat/test_store.c index da0562d3..2bd2ab86 100644 --- a/lib/libDtChat/test_store.c +++ b/lib/libDtChat/test_store.c @@ -273,12 +273,12 @@ test_default_dir(const char *tmpdir) int main(void) { - char tmpdir[] = "/tmp/opencode/dtchat-store-XXXXXX"; + char tmpdir[64]; char dir[512]; char path[512]; DcStore *store; - if (mkdtemp(tmpdir) == NULL) { + if (dc_test_tmpdir(tmpdir, sizeof tmpdir, "store") != 0) { perror("mkdtemp"); return 1; } From c6441410ce2d88747c9ccba553d450159b306f20 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 16:19:04 +0000 Subject: [PATCH 22/22] pkgsrc: distinfo for the merged tree (the dtphoto line of 2026-11-22) The recipe builds mcde-0.1.0.tar.gz from the gitlink, and the archive of 4fead8a3 is not the archive of 0fa42ac7: programs/dtphoto/dtphoto.c went from 1,280 to 13,908 lines with the split of the makronix tree, and dtpaint.c from 997 to 3,108. Made with the tree's own rule (tools/mcde-dist.sh on the build host): git archive --mtime= + gzip -n -6, pkgsrc/ left out. 67,122,036 bytes, BLAKE2s bb9d08d3..., SHA512 035e880d..., digest(1) from pkgsrc's bootstrap. The archive this line describes lives in the Makronix tree at distfiles/mcde-0.1.0.tar.gz and is committed there with the gitlink bump; the two must be the same bytes or pkgsrc refuses the package. Measured 2026-11-22: a fresh clone of this fork builds the four programs the merge touched (dtphoto, dtpaint, dttoolbox, dtsystemsettings) and `make check` in libDtChat is 24/24. --- pkgsrc/distinfo | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pkgsrc/distinfo b/pkgsrc/distinfo index 1b9ec81a..4cf50de2 100644 --- a/pkgsrc/distinfo +++ b/pkgsrc/distinfo @@ -1,5 +1,5 @@ $NetBSD$ -BLAKE2s (mcde-0.1.0.tar.gz) = f4c0961b100673e97964b6b34f5aec76a084fb59062aac5248d709ab137dd1b7 -SHA512 (mcde-0.1.0.tar.gz) = 434bd8cf392fb77377577b14bf8ffc88e466778c6ba85dde3d60511ab624a35dcb4202c95514c47174b87eb785da4bc1eff3cbfcaaa6c06f2261287d35a961d7 -Size (mcde-0.1.0.tar.gz) = 67010401 bytes +BLAKE2s (mcde-0.1.0.tar.gz) = bb9d08d3b1bbaeb60f09f1a59f2900a184322da66c01e5801e3f41bb86a1cb51 +SHA512 (mcde-0.1.0.tar.gz) = 035e880dfd7af7101654d81f22e25a03afe6b8af3b84508b389421401a242eb1e546b3eca0aeba9e033ab0fa8cc403fa66efd69db95a6acf10691382163a288e +Size (mcde-0.1.0.tar.gz) = 67122036 bytes