Experience
Projects
My Stack
Case studies
Contact me
Open my CV

·6 min read

TaskPad image crop: selection in image pixels, one-field undo, safe save into a .task

TaskPad's image viewer started as a zoomable window you opened and closed. Then I wanted to crop a screenshot without leaving the note it was pasted into, and the viewer turned into an editor with a dirty state, a way back, and a save that has to be careful, because the image it is saving may be sitting inside a ZIP.

Project
TaskPad
Date
Oct 2026
Stack
C#, WPF
Commit
e93d2d6

The selection lives in image space

The viewer already had zoom (_zoom) and pan (_move). The first decision for crop was which coordinate system to keep the selection in. Screen coordinates would be wrong the moment the user zoomed in the middle of a drag, so the selection is stored as a Rect? in image pixels, and mouse positions are converted with one function:

csharp
Point ToImage(Point screen, bool clamp)
{
    double x = (screen.X - _move.X) / _zoom, y = (screen.Y - _move.Y) / _zoom;
    if (clamp) { x = Math.Max(0, Math.Min(_bmp.PixelWidth, x)); y = Math.Max(0, Math.Min(_bmp.PixelHeight, y)); }
    return new Point(Math.Round(x), Math.Round(y));
}

Two details. Clamping means you can drag past the edge of the picture and the selection sticks to the border instead of extending into nothing. And Math.Round snaps to whole pixels at capture time, so the dimensions shown in the label ({(int)s.Width} × {(int)s.Height}) are exactly the ones that will be cut, not a floating-point approximation.

Drawing goes the other way. UpdateOverlay multiplies the image-space rectangle by _zoom and adds _move to get the on-screen rectangle. It is called from the mouse handlers and from SizeChanged, so the frame stays glued to the picture when the window is resized.

One geometry for the dimmed area

To show what will be discarded, I wanted the area outside the selection darkened. The obvious approach is four semi-transparent rectangles around the selection. The viewer uses one Path:

csharp
var image = new Rect(_move.X, _move.Y, _bmp.PixelWidth * _zoom, _bmp.PixelHeight * _zoom);
_mask.Data = new CombinedGeometry(GeometryCombineMode.Exclude,
    new RectangleGeometry(image), new RectangleGeometry(screen));

The image rectangle minus the selection rectangle is exactly the region to dim, with no seams and no four-way arithmetic at the edges. The mask has IsHitTestVisible = false, so it never steals mouse events from the drag that is drawing it, and the dashed frame and the size label are separate elements on the same canvas.

Applying the crop

ApplyCrop is short, because WPF already has the primitive:

csharp
var rect = new Int32Rect((int)s.X, (int)s.Y,
    (int)Math.Min(s.Width,  _bmp.PixelWidth  - s.X),
    (int)Math.Min(s.Height, _bmp.PixelHeight - s.Y));
var cropped = new CroppedBitmap(_bmp, rect);
cropped.Freeze();
_bmp = cropped;
_edited = true;

The Math.Min against the remaining width and height guards Int32Rect against rectangles that extend beyond the bitmap, which would throw. Freeze() makes the result immutable and cheap to share with the rest of the UI. A selection smaller than 2 by 2 pixels is treated as an accidental click and just leaves crop mode.

Nothing is written to disk here. That is the point of the design: crop changes _bmp in memory and sets _edited, which puts a ● in the window title and adds "edited (Ctrl+S to save)" to the info line.

Undo is a pointer swap

The viewer keeps two references: _bmp, the current image, and _original, as loaded from disk. Ctrl+Z calls Revert, which does _bmp = _original and clears the flag. That is a single level of undo, and I chose it on purpose: there is one operation (crop), and a stack would only matter if a second operation existed. Cropping twice and pressing Ctrl+Z once goes back to the file as it was on disk, which is also what "unsaved changes" means to the user.

The same flag guards navigation. GoTo and the window's Closing handler both call ConfirmDiscard, which asks "Save changes to name?" with Yes, No and Cancel, and Cancel cancels the navigation or the close. The new ◀ ▶ navigation steps with modulo arithmetic so it wraps around, and if the next file has disappeared from disk it is removed from the list instead of throwing.

One thing I noticed rereading the code: in Load, the index is Math.Max(0, _list.FindIndex(...)), so a path that is missing from the list resolves to index 0, and the following _index < 0 fallback that would insert it cannot fire. It only fires for an empty list. In practice the list is built from the same note, so it does not bite, but it is the kind of guard that looks like it covers more than it does.

Saving without damaging the original

Save picks an encoder from the extension (JPEG at quality 92, BMP, GIF, TIFF, otherwise PNG) and then does the part I care about:

csharp
var tmp = target + ".saving";
using (var fs = File.Create(tmp)) enc.Save(fs);
if (File.Exists(target)) File.Replace(tmp, target, null); else File.Move(tmp, target);

Encoding to a sibling file first means a failed encode, a full disk or a crash leaves the original image untouched; File.Replace then swaps it in as one operation. The whole thing sits in a try/catch that shows "Cannot save image" and returns false, which ConfirmDiscard reads as "do not proceed".

"Save a copy" opens a SaveFileDialog with -edited.png appended to the name. If the image lives under TaskPad's temp folder, which is where .task notes are unpacked, the dialog starts on the Desktop instead, because a temp folder is not where anyone expects to find a saved file.

The part that is not about images

A pasted image inside a .task note is a file in an unpacked temp folder, and the note is a ZIP. Overwriting the image file alone would change nothing in the note on disk. So after a successful, non-copy save the viewer looks for open documents whose AssetDir contains the image path and marks them dirty:

csharp
foreach (var d in Workspace.Docs.Where(d => d.AssetDir != null &&
         _path.StartsWith(d.AssetDir, StringComparison.OrdinalIgnoreCase)).ToList())
{
    d.Dirty = true;
    if (Workspace.Settings.AutoSave) d.Save(null, false); else d.Raise();
}
foreach (var v in Workspace.AllViews) v.Editor.TextArea.TextView.Redraw();

With autosave on, the note repacks immediately; otherwise it shows as modified like any other edit. The final loop redraws every editor so thumbnails in other windows pick up the cropped version. The README line says the same thing in user terms: images inside a .task note are repacked into it.

What I would keep

Cropping itself is a few calls. The rest of the commit is the part that made it safe to use: a coordinate space that does not depend on the view, an undo that costs one field, a save that cannot half-write, and the bookkeeping that tells the owner of the image its contents changed.

#csharp#wpf#image-editing#undo#file-io

Keep reading

Have a project in mind?