From 208ec91ba91fcb5f8361b6ac36e7584f27465177 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 13:09:53 +0000 Subject: [PATCH] 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. --- docs/MCDE-PROGRAMS.md | 22 +- ext/src/mcde/AGENTS.md | 15 +- ext/src/mcde/programs/dtphoto/dtphoto.c | 6221 ++++++++++++++++++++++- 3 files changed, 6132 insertions(+), 126 deletions(-) diff --git a/docs/MCDE-PROGRAMS.md b/docs/MCDE-PROGRAMS.md index 354e20fe55..1773a6a6cb 100644 --- a/docs/MCDE-PROGRAMS.md +++ b/docs/MCDE-PROGRAMS.md @@ -466,13 +466,27 @@ deshalb laufen sie jetzt ueber `OpPerPixel`, damit eine neue Operation die Maske nicht vergessen kann. Ein Menueeintrag wird ueber seinen vollen Pfad gebunden, nicht ueber das Label: die Referenz hat "Horizontal" in Image > Flip und in Layer > Type. -Belegt ohne Display: `-menutest` (31 Pfade, jeder loest auf den Befehl auf, -den der Callback schaltet) und `-optest` gegen die Arithmetik, nicht gegen +Belegt ohne Display: `-menutest` (206 Pfade, jeder loest auf den Befehl auf, +den der Callback schaltet; kein Pfad doppelt belegt, ein unbekannter Pfad +bleibt CMD_NONE) und `-optest` gegen die Arithmetik, nicht gegen "das Bild hat sich geaendert" -- eine harte Kante wird zu 170 weichgezeichnet, dieselbe Kante zu 255 bzw. 0 geschaerft, eine -Mosaic-Zelle zu ihrem Mittelwert. Alle acht Tests gruen auf Tiefe 24 und +Mosaic-Zelle zu ihrem Mittelwert. Alle Tests gruen auf Tiefe 24 und Tiefe 8, `-selftest` byte-identisch (2.359.350 Bytes, 0 Abweichungen). -Offen: PNG/TIFF/PSD, Distort/Noise-Render, Effekte-Ebene, P3-P6. + +Stand 2026-11-22 (View-Menue): Die Schalter des View-Menues werden nicht +nur gekippt, sondern gelesen. `SnapX`/`SnapY` ziehen einen Marquee- oder +Crop-Zug auf das Gitter oder eine Hilfslinie (eine Linie in Reichweite +gewinnt gegen das Gitter, eine gesperrte Hilfslinie nimmt keine neuen an +und laesst sich nicht loeschen), `DrawGuides` malt Gitter, Hilfslinien und +Lineale auf den Canvas -- nicht ins Bild. Zwei Belege: `-viewtest` prueft +die Snap-Arithmetik (37 -> 32 auf einem 16er Gitter, 40 -> 48, eine +Hilfslinie bei 35 faengt 37, eine vertikale Linie laesst y in Ruhe), und +`-drawtest` zaehlt die Pixel, die die Dekoration auf einem echten Pixmap +hinzufuegt (Gitter 12.509, eine Hilfslinie 280 = die Canvas-Hoehe, Lineal +558 und nichts davon im Canvas). +Offen: PNG/TIFF/PSD als *Ausgabe*, Distort/Noise-Render, Effekte-Ebene, +P3-P6. Stand 2026-11-22 (Auswahl-Morphologie und Optionsleiste): Select > Modify (Border, Smooth, Expand, Contract), Grow, Similar und Feather rechnen auf diff --git a/ext/src/mcde/AGENTS.md b/ext/src/mcde/AGENTS.md index a3d4ddee2c..cbea83bbbb 100644 --- a/ext/src/mcde/AGENTS.md +++ b/ext/src/mcde/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/ext/src/mcde/programs/dtphoto/dtphoto.c b/ext/src/mcde/programs/dtphoto/dtphoto.c index bcc235788f..ff4c9bfdb2 100644 --- a/ext/src/mcde/programs/dtphoto/dtphoto.c +++ b/ext/src/mcde/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;