gpui-cc Course handbook
CHAPTER 02 / STAGE 06COURSE

Fill a clipped rectangle

Paint exactly the intended pixels, including at the edges.

raster-rect
On this page

Learn: width and stride measure different things

The window is now a destination you can see. The buffer is where the fill happens. Width counts visible columns; stride is distance from one row’s start to the next, which can include padding. Use window-local coordinates, x right and y down. A half-open rectangle [left,right) × [top,bottom) includes top and left but not right or bottom; touching edges do not overlap.

Run it: change one pixel in two padded rows

Terminal
./build/examples/core-lab padded-row
C++ · core-lab.cpp
void padded_row() {
    constexpr int stride = 4;
    std::array pixels{0, 0, 0, 99, 0, 0, 0, 99};
    pixels[1 * stride + 1] = 7;
    for (std::size_t i = 0; i < pixels.size(); ++i) {
        std::cout << pixels[i] << ((i + 1) % stride == 0 ? '\n' : ' ');
    }
}

Expected rows: 0 0 0 99 and 0 7 0 99. The last entry of each row is padding. Try it: use 3 as the multiplier while keeping the stored rows at stride 4; it lands in the wrong column. That is a wrong address even though the array access itself still fits.

Build it: make clipping a memory-safety rule

Your challenge: Introduce a small Point, Size, bounds representation, and a writable borrowed surface view. Implement a clipped opaque fill in the core, independent of X11.

Use signed coordinates for offscreen positions. Choose endpoint bounds or compute endpoints with a wider type and check before narrowing. First intersect with the valid surface and any requested clip (max of starts, min of ends on each axis); empty intersections change nothing. Only then index the storage. If stride is in pixels, the offset is y * stride + x; a byte-based view needs both row bytes and bytes per pixel. Validate length and stride at the boundary. The owner keeps the storage; the fill only borrows it. Move the pure operation out of the native file so both native rendering and tests call the same code.

Check it

Test a 3 × 2 surface with stride 4, zero contents and sentinel 99 in both padding slots. Fill [-1,2) × [1,4) with 7: expected rows 0 0 0 99, 7 7 0 99. Add one case for each edge, negative-origin, fully offscreen, empty, and exactly-on-right/bottom. Invalid storage length or stride must be rejected before modifying pixels.

Terminal
python3 course/check_core.py raster-rect

Hints and troubleshooting

Hint: a neighbor or sentinel changed

Print the clipped interval before the loop. Ask whether the end means the last selected column or the first excluded one. Check the units for stride and whether the loop accidentally used the original negative origin.