Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Images

A program running in your terminal can send images and ask you to draw them. Today that means the Kitty graphics protocol.

Images don’t fit in cells, so the render state’s rows can’t carry them. There are two parts instead. The terminal keeps every image a program sends in an image storage, and that’s where the pixels are. The render state works out what to draw, where, how big and in what order. You read the list from the render state and the pixels from the storage, and you never have to track a cell yourself.

If you don’t draw images, you can skip this page. Just know that the protocol is on by default, so programs can fill the storage even if you never read it. Set the limit below to zero to turn it off.

Setting up

Kitty graphics are on by default with a 10 MB storage limit. Change the limit with Terminal::set_kitty_image_storage_limit(). A limit of zero disables the protocol and deletes every stored image and placement. If Kitty graphics were disabled at build time, this option returns Error::Unsupported.

terminal.set_kitty_image_storage_limit(Some(64 * 1024 * 1024))?; // 64 MiB

The terminal also needs a cell size. Image sizes depend on the size of a cell in pixels, which you set with Terminal::resize(). Without it there’s nothing to draw and the image list is empty.

Programs can send image data directly in the sequence. Loading it from a file, a temporary file or shared memory is off by default. Turn those on with Terminal::set_kitty_image_from_file_allowed(), Terminal::set_kitty_image_temp_file_dir() and Terminal::set_kitty_image_from_shared_mem_allowed().

Each screen, main and alternate, has its own storage. Get a handle to the active one with Terminal::kitty_graphics(). The handle is borrowed, so see Lifetime before you keep one.

Decoding PNGs

We don’t ship a PNG decoder. You bring your own, so use whatever library you already have. Without one, PNG images are rejected.

Install it with kitty::graphics::set_png_decoder(). This is a process-global setting, not a terminal one. Set it at startup, before you use anything that depends on it. This isn’t thread-safe, so call it before any other thread uses the library, and never while one does. Passing None clears the decoder and turns PNG support off again.

The callback gets the PNG bytes and fills in a kitty::graphics::DecodedImage. Pixels are 8-bit RGBA, row by row from the top-left, with no padding, so a complete image is width * height * 4 bytes. Allocate them with Bytes::new_zeroed_with_alloc() and the allocator we pass you, and return it. We own the buffer after that.

That allocator limits how much memory one image can use, so Bytes::new_zeroed_with_alloc() can return None for a very large image. Treat that as a failure: free anything you allocated and return None, and the image is rejected. kitty::graphics::DecodePng has the rest of the contract.

This example shows the shape of a decoder, but it doesn’t actually decode anything. It hardcodes one red pixel.

/// Minimal PNG decoder callback for the sys interface.
///
/// A real implementation would use a PNG library (libpng, stb_image, etc.)
/// to decode the PNG data. This example uses a hardcoded 1x1 red pixel
/// since we know exactly what image we're sending.
///
/// WARNING: This is only an example for providing a callback, it DOES NOT
/// actually decode the PNG it is passed. It hardcodes a response.
struct StubPngDecoder {
    decode_count: Arc<AtomicUsize>,
}

impl graphics::DecodePng for StubPngDecoder {
    fn decode_png<'alloc>(
        &mut self,
        alloc: &'alloc Allocator<'_>,
        data: &[u8],
    ) -> Option<graphics::DecodedImage<'alloc>> {
        _ = self.decode_count.fetch_add(1, Ordering::SeqCst);
        let count = self.decode_count.load(Ordering::SeqCst);

        println!("  decode_png called (size={}, call #{count})", data.len());

        // Allocate RGBA pixel data through the provided allocator.
        let mut data = Bytes::new_zeroed_with_alloc(alloc, 4).ok()?;

        // Fill with red (R=255, G=0, B=0, A=255).
        data.copy_from_slice(&[255, 0, 0, 255]);
        Some(graphics::DecodedImage {
            width: 1,
            height: 1,
            data,
        })
    }
}

Full program: rust-vt-kitty-graphics/src/main.rs

Drawing images

The render state gives you the images to draw as a list of placements, which you read with a ImageIterator. Each placement is one rectangle of one image:

  • What to draw: the image’s protocol and ID, plus a source rectangle that selects part of the image in image pixels.
  • Where to draw it: the top-left cell, relative to the viewport, plus a pixel offset within that cell.
  • How big to draw it: a destination size in pixels. The image is already scaled to fit its cells.
  • In what order to draw it: a layer (below cell backgrounds, below text, or above text) and a z-index within the layer.

These values mean the same thing for every protocol, so one drawing routine handles all of them. The only part that depends on the protocol is getting the pixels. Use the placement’s protocol to pick the right storage and its image ID to look the image up.

Later versions may add more protocols and more kinds of placements. Skip any placement whose protocol you don’t support, and your renderer keeps working when that happens.

// Create the iterator once and reuse it for every frame.
let mut images = ImageIterator::new()?;

// Each frame, after `RenderState::update`.
let snapshot = render_state.update(&terminal)?;
let mut image_it = images.update(&snapshot)?;

while let Some(image) = image_it.next() {
    let protocol = image.protocol()?,
    let id = image.image_id()?;
    let gen = image.image_generation()?;

    // Your renderer: find the texture for this image. Only read the
    // pixels when you don't have a texture for this protocol, ID and
    // generation yet.
    let texture = match texture_cache_find(protocol, id, gen) {
        Some(texture) => texture,
        None => match protocol {
            // Look up image_id with ghostty_kitty_graphics_image(), read its
            // pixels with ghostty_kitty_graphics_image_get(), and upload.
            ImageProtocol::Kitty => upload_kitty_image(id, gen),

            // A protocol this renderer doesn't support yet.
            else => continue,
        }
    };

    // The destination rectangle in pixels, relative to the top-left
    // corner of the viewport. It can start above or left of the
    // viewport, so clip it when drawing.
    let x = image.viewport_col()? * cell_width + image.cell_offset_x()? as i32;
    let y = image.viewport_row()? * cell_height + image.cell_offset_y()? as i32;

    // Queue the image. Sort the queue by layer and then z before
    // drawing, since iteration order is not drawing order.
    queue_image(texture, image.layer()?, image.z()?, x, y,
                image.pixel_width()?, image.pixel_height(),
                image.source_x()?, image.source_y()?,
                image.source_width()?, image.source_height()?);
}

Like rows, they belong to the render state and can be read without access to the terminal. After each update, fill the iterator again before you read it.

The pixels are different, because the render state doesn’t copy them. It only knows where to draw. Read pixels from the terminal while you still have access to it, for example right after the update while you hold your terminal lock.

Each entry has an image ID. Look it up with Graphics::image(), then read the image’s size, pixel format and pixels with various getters on Image. The pixels are always decoded and uncompressed, so you can upload them as they are. This example reads a list and prints what it would draw, including the pixels:

/// Read the render state's image list, the way a renderer builds its list
/// of images to draw. Returns the number of images, or -1 on error.
///
/// The list holds every Kitty image on screen, however the program placed
/// it, with its position, size and draw order worked out. The Kitty
/// graphics storage is only used to read pixels.
///
/// A real renderer would find or upload a texture for each image and
/// queue it for drawing, sorted by layer and then z. This example prints
/// what it would draw instead.
fn draw_images<'alloc>(
    snapshot: &Snapshot<'alloc, '_>,
    images: &mut ImageIterator<'alloc>,
    terminal: &Terminal<'alloc, '_>,
) -> Result<usize, Error> {
    // Fill the iterator from the last update.
    let mut image_it = images.update(snapshot)?;

    // The storage is only needed to read pixels.
    let graphics = terminal.kitty_graphics()?;

    let mut count = 0usize;
    while let Some(image) = image_it.next() {
        // Skip protocols this renderer doesn't support.
        let Ok(ImageProtocol::Kitty) = image.protocol() else {
            continue;
        };
        count += 1;

        println!(
            "  image {count}: kind={:?} image_id={} placement_id={:?}",
            image.kitty_kind()?,
            image.image_id()?,
            image.kitty_placement_id()?
        );
        println!(
            "    layer={:?} z={} cell=({},{}) cells={}x{} offset=({},{})",
            image.layer()?,
            image.z()?,
            image.viewport_col()?,
            image.viewport_row()?,
            image.grid_cols()?,
            image.grid_rows()?,
            image.cell_offset_x()?,
            image.cell_offset_y()?,
        );
        println!(
            "    size={}x{} source=({},{} {}x{})",
            image.pixel_width()?,
            image.pixel_height()?,
            image.source_x()?,
            image.source_y()?,
            image.source_width()?,
            image.source_height()?,
        );

        // Read the pixels to upload them as a texture. A real renderer keys
        // its textures by protocol, image ID and image generation, and only
        // gets here when it has no texture for that key yet. The generation
        // changes whenever the pixels do, so most frames skip this.
        let Some(image) = graphics.image(image.image_id()?) else {
            continue;
        };
        println!(
            "    pixels: {}x{} format={:?} data_len={} generation={}",
            image.width()?,
            image.height()?,
            image.format()?,
            image.data_len()?,
            image.generation()?,
        );
    }
    Ok(count)
}

Full program: rust-vt-kitty-graphics/src/main.rs

The list holds every Kitty image on screen, however the program placed it. Earlier versions left some images out, so renderers had to draw them from the storage’s placement iterator. That’s no longer needed. If your renderer still draws from that iterator, stop, or those images are drawn twice. See Inspecting the storage for what it’s for.

Images partly outside the captured rows

An image is in the list when any part of it is in the captured rows, which are the viewport plus any overscan rows. See Overscan.

Images shown with placeholder cells are split into one placement per row of cells, so each of those placements is always inside the captured rows.

Every other placement is reported at its full size, even when only part of it can be seen. Its ImageIteration::viewport_col() can be negative, and its ImageIteration::viewport_row() can be above the first overscan row. It can also extend past the right or bottom edge. So clip what you draw to the viewport, or to the captured rows if you draw overscan rows. Most graphics APIs can do this for you with a scissor or clip rectangle.

For example, with no overscan, an image 4 rows tall whose top row scrolled 2 rows above the viewport has a row of -2 and covers 4 rows. Draw it at its full size starting 2 rows above the viewport, clipped to the viewport. Its bottom 2 rows show at the top of the viewport.

Knowing what changed

Most frames don’t change any image. A program prints text or moves the cursor, and every image stays where it was. So a renderer can skip most of its image work. Two values tell you what to redo.

Snapshot::image_placements_generation() belongs to the render state’s whole list. It tells you when to read the list again. After each update, compare it with the value from the last time you read the list. If they match, the list is the same as before, and you can keep drawing what you built last time:

// Kept by your renderer between frames. The flag makes sure the first
// frame always reads the list.
let mut last_generation = 0u64;
let mut have_draw_list = false;

// Each frame, after `RenderState::update`:
let snapshot = render_state.update(&terminal)?;
let generation = snapshot.image_placements_generation()?;

if !have_draw_list || generation != last_generation {
  last_generation = generation;
  have_draw_list = true;

  // Your renderer: read the iterator as in the example above and
  // build a new queue of images to draw.
  rebuild_image_queue(&snapshot, images);
}
draw_image_queue();

The value changes when an update adds or removes an image, moves one, changes which part of one is shown, or changes the pixels of one. It stays the same when only text changes, as long as the changed rows had no placeholder cells before or after the change.

A new value means “read the list again”. It doesn’t promise that anything on screen moved. The value can change even when every image ends up exactly where it was, for example:

  • When a program rewrites a row that has placeholder cells.
  • When a program changes any image or placement while images shown with placeholder cells are on screen.

Only compare the value for equality, and only with the last value you read from the same render state. It wraps around, so a larger value doesn’t mean a newer one. It’s always 0 when Kitty graphics are disabled.

Image::generation() belongs to a single image. It tells you when to upload that image’s pixels again. It changes when a program sends the image again and on every animation frame. The render state reports the same value for each entry as ImageIteration::image_generation(), so you can check your texture cache without touching the storage, and most frames don’t touch the terminal at all.

Use the image generation as part of your texture cache key. Don’t rely on the image’s size or data length instead. A program can send new pixels with the same size under the same ID.

Here’s a frame loop that reads the list only when it changed:

/// Draw three frames, reading the image list only when it changed.
///
/// Each frame updates the render state and compares the placements
/// generation with the one from the last time the list was read. The
/// first frame always reads the list. The second frame changes nothing,
/// so it keeps the list it has. Before the third frame, new output
/// scrolls the screen by two rows, which moves both images, so the third
/// frame reads the list again.
fn run_frames(terminal: &mut Terminal<'_, '_>) -> Result<(), Error> {
    // Create the render state and the image iterator once, and reuse them.
    let mut state = RenderState::new()?;
    let mut images = ImageIterator::new()?;

    // The flag makes sure the first frame always reads the list.
    let mut last_generation = 0u64;
    let mut have_draw_list = false;

    for frame in 1..=3 {
        if frame == 3 {
            // Move to the bottom row and print two newlines to scroll.
            terminal.vt_write(b"\x1b[24;1H\r\n\r\n");
        }
        let snapshot = state.update(terminal)?;
        let generation = snapshot.image_placements_generation()?;

        if have_draw_list && generation == last_generation {
            println!("\nFrame {frame}: no image changed, keep drawing the last list");
            continue;
        }
        last_generation = generation;
        have_draw_list = true;

        println!("\nFrame {frame}: images changed, reading the list:");

        let count = draw_images(&snapshot, &mut images, terminal)?;
        println!("Total images: {count}");
    }

    Ok(())
}

Full program: rust-vt-kitty-graphics/src/main.rs

The storage also has a generation of its own, Graphics::generation(). It changes whenever a program sends, places or deletes an image, but not when images only move on screen. So it can’t tell you when to read the render state’s list again. It’s useful for work that only depends on what the storage holds, such as freeing the textures of deleted images.

The two storage generations are never reused, not even across the main and alternate screens, terminal resets, or different terminals. That makes either one safe to use as a cache key on its own.

Placements at a cell

You draw every placement the same way, so you can skip the next three sections unless you’re curious how a list entry got there, or you’re reading ImageIteration::kitty_kind().

A program can place an image at a cell on the screen. The image is attached to that cell, so it moves when the text moves: when new output scrolls the screen, when a program scrolls part of the screen, and when the viewport scrolls through the scrollback.

The render state finds the position of these images during each update, so you don’t need to track the cells yourself. This costs very little on a typical frame, including frames where the viewport scrolls.

Placeholders

A program can also place an image with text. It creates a virtual placement, which has no position of its own, and prints placeholder characters (U+10EEEE) wherever the image should appear. Each placeholder cell says which image it shows and which piece of that image belongs in the cell. Programs such as tmux use this so that images scroll, move and disappear along with the text around them.

Only the cells know where these images are, so the storage can’t tell you where to draw them. The render state works it out during each update. It finds the placeholder cells, groups neighboring cells that show the same image into runs, and calculates which part of the image each run shows. It only looks at rows that changed, so this costs very little on a typical frame.

A virtual placement usually turns into several entries in the list, one for each row of placeholder cells. For example, an image shown in a block of 10 columns by 4 rows of placeholders gives 4 entries, each 10 cells wide and 1 cell tall, and each drawing a quarter of the image. Drawn together, they form the whole image.

Relative placements

A program can place an image relative to another placement, its parent. The image is drawn a number of cells to the right of and below its parent. Negative numbers move it left or up. The parent can be relative to another placement too, so placements can form a chain.

The render state follows the chain to the placement at its start and positions the image from there:

  • If the chain starts at an image placed at a cell, the image is drawn from that cell, and moves whenever that cell moves.
  • If the chain starts at a virtual placement, the image is drawn from the top-left corner of that placement’s placeholder cells. If none of those cells are in the captured rows, the image isn’t in the list.

For example, an image placed 3 columns right of and 2 rows below a parent at column 2, row 1 is drawn at column 5, row 3. Like other placements, it’s in the list when any part of it is in the captured rows, even if its parent isn’t.

Animation

Programs can send images with several frames and ask the terminal to play them, much like an animated GIF. The terminal stores every frame, but it has no timer of its own. You drive playback by calling Graphics::tick_animation().

Each call shows whichever frame is due at the time you pass in. When an image moves to a new frame, Image::data() returns the pixels of the new frame and Image::generation() returns a new value. If you already cache textures by image generation, new frames appear without any extra work.

The tick also tells you when the next frame is due. Use that time to schedule a single redraw instead of calling the tick in a loop:

  1. Call the tick each time you prepare a frame to draw, as long as the storage holds at least one image.
  2. If it returns Ok(time), schedule one redraw at the returned time. Don’t schedule it sooner than your shortest frame interval, for example 8 ms for a 120 Hz display.
  3. If it returns None, nothing is playing. Don’t schedule anything.

You never need to watch for animations starting. A program starts or resumes playback by writing a command to the terminal, and that write already gives you a reason to redraw. The tick on that redraw picks up the animation. A terminal with no playing animations costs nothing extra.

Here’s a helper that follows these steps. A renderer calls it once per frame and uses the result to schedule the next redraw:

/// Advance any playing animations while preparing a frame to draw.
///
/// Call this once per frame, before drawing images. It returns how many
/// milliseconds to wait before the next redraw, or -1 if no animation is
/// playing. In that case, don't schedule a redraw for animations at all.
/// A program that starts an animation does so by writing to the
/// terminal, which already causes a redraw.
///
/// `now_ms` comes from a clock you choose, such as milliseconds since
/// your app started. Always use the same clock with the same starting
/// point.
fn tick_animations(graphics: &mut Graphics<'_>, now_ms: u64) -> Option<u64> {
    /// The shortest time between two redraws. About 8 ms suits a 120 Hz display.
    pub const MIN_FRAME_INTERVAL_MS: u64 = 8;

    let Ok(Some(next_ms)) = graphics.tick_animation(now_ms) else {
        return None;
    };

    // next_ms is an absolute time. Turn it into a delay from now.
    Some(next_ms.saturating_sub(now_ms).min(MIN_FRAME_INTERVAL_MS))
}

Full program: rust-vt-kitty-graphics/src/main.rs

This plays a two-frame animation with that helper. It uses a pretend clock so that it runs instantly:

/// Print the first pixel and the generation of an image.
fn print_image(graphics: &Graphics<'_>, image_id: u32) {
    let Some(image) = graphics.image(image_id) else {
        return;
    };

    // The image may be gone, and the first pixel below needs three bytes.
    let Ok(Some([p0, p1, p2, ..])) = image.data() else {
        print!("no pixels");
        return;
    };

    let generation = image.generation().unwrap_or(0);
    print!("pixel=({p0},{p1},{p2}) generation={generation}");
}

/// Play a two-frame animation using tick_animations().
///
/// A real app waits for the delay that tick_animations() returns. To keep
/// this example quick, a pretend clock jumps ahead by that delay instead.
fn run_animation(terminal: &mut Terminal<'_, '_>) -> Result<(), Error> {
    // These commands set up the animation:
    //
    //   a=T  Send a red 1x1 RGBA image with ID 2 and display it.
    //   a=f  Add a blue second frame that shows for 40 ms.
    //   a=a  Make the first frame show for 30 ms. It starts at 0 ms,
    //        which would mean the frame is skipped.
    //   a=a  Start playing on a loop (s=3).
    //
    // q=2 tells the terminal not to send replies.
    terminal.vt_write(b"\x1b_Ga=T,f=32,i=2,s=1,v=1,q=2;/wAA/w==\x1b\\");
    terminal.vt_write(b"\x1b_Ga=f,f=32,i=2,s=1,v=1,z=40,q=2;AAD//w==\x1b\\");
    terminal.vt_write(b"\x1b_Ga=a,i=2,r=1,z=30,q=2\x1b\\");
    terminal.vt_write(b"\x1b_Ga=a,i=2,s=3,q=2\x1b\\");

    // Draw three frames, following each delay.
    let mut graphics = terminal.kitty_graphics()?;
    let mut now_ms = 0u64;
    for _ in 0..3 {
        let delay_ms = tick_animations(&mut graphics, now_ms).expect("tick should succeed");

        // The tick invalidates image handles, so print_image() looks the
        // image up again. The generation changes whenever the frame does.
        print!("  t={now_ms} ms: ");
        print_image(&graphics, 2);
        println!(", next redraw in {delay_ms} ms");

        now_ms += delay_ms;
    }

    // Stop playback (s=1). Once stopped, the tick asks for no redraws.
    terminal.vt_write(b"\x1b_Ga=a,i=2,s=1,q=2\x1b\\");

    // Writing to the terminal invalidates the storage handle. Get it again.
    let mut graphics = terminal.kitty_graphics()?;
    if tick_animations(&mut graphics, now_ms).is_none() {
        println!("  t={now_ms} ms: stopped, no redraw needed");
    }

    Ok(())
}

Full program: rust-vt-kitty-graphics/src/main.rs

Inspecting the storage

A renderer doesn’t need this section. A kitty::graphics::PlacementIterator lists every placement in the storage, including placements that are off screen and virtual placements. It’s for tools such as debuggers or tests that need to see what the storage holds.

  1. Create an iterator with PlacementIterator::new().
  2. Fill it from the storage with PlacementIterator::update and obtain a PlacementIteration.
  3. Optionally limit it to one layer with PlacementIteration::set_layer().
  4. Move to each placement with PlacementIteration::next() and read its values with the various getters.

These functions work out the geometry of the iterator’s current placement from the storage:

They only know about placements at a cell and placements relative to one. They can’t find virtual placements, or placements relative to a virtual placement, because those depend on the cells. The render state gives the same values for every entry in its list, so prefer it whenever you’re drawing.

Lifetime

Everything borrowed from the terminal is short-lived. Graphics and Image handles stay valid until the next call that changes the terminal, such as Terminal::vt_write() or Terminal::reset(). So get them again after each of those.

Graphics::tick_animation() changes the storage too. It invalidates image handles and image data slices, so look images up again afterward.

The placement iterator belongs to you, but the values it returns are only valid until the terminal changes.

Putting it together

This creates a terminal, places one image at a cell and another with placeholder cells, lists both from the render state, and reads each image’s pixels from the storage.

fn main() -> Result<(), Error> {
    // Install the PNG decoder.
    let decode_count = Arc::new(AtomicUsize::new(0));
    unsafe {
        graphics::set_png_decoder(Some(Box::new(StubPngDecoder {
            decode_count: Arc::clone(&decode_count),
        })))?;
    }

    // Create a terminal with Kitty graphics enabled.
    let mut terminal = Terminal::new(80, 24)?;

    // Set the cell size in pixels. Image sizes depend on it.
    terminal.resize(80, 24, 8, 16)?;

    // Set a storage limit to enable Kitty graphics.
    terminal.set_kitty_image_storage_limit(Some(64 * 1024 * 1024))?; // 64 MiB

    // Install write_pty to see the protocol response.
    // The Kitty graphics protocol sends an APC response back to the pty
    // when an image is loaded (unless suppressed with q=2).
    terminal.on_pty_write(|_term, data| {
        println!("  response ({} bytes): {}", data.len(), data.escape_ascii());
    })?;

    // Move the cursor to row 10 so the images have room to scroll up.
    terminal.vt_write(b"\x1b[10;1H");

    // Send a 1x1 PNG image and place it at the cursor. The image is
    // attached to that cell, so it moves when the text moves.
    //
    // The escape sequence is:
    //   ESC _G a=T,f=100,q=1; <base64 PNG data> ESC \
    //
    // Where:
    //   a=T    transmit the image and place it
    //   f=100  the data is a PNG
    //   q=1    only reply on errors (q=0 would also reply on success)
    println!("Sending Kitty graphics PNG image:");
    terminal.vt_write(b"\x1b_Ga=T,f=100,q=1;");
    terminal.vt_write(b"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAA");
    terminal.vt_write(b"DUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==");
    terminal.vt_write(b"\x1b\\");

    println!("PNG decode calls: {}", decode_count.load(Ordering::SeqCst));

    // Show a second image with placeholder cells. First send a green 1x1
    // image with ID 3 and give it a virtual placement 2 columns wide and
    // 1 row tall (U=1). Then, on the next row, print two placeholder
    // characters (U+10EEEE) where the image should appear:
    //
    //   ESC[38;5;3m    the foreground color says which image: ID 3
    //   U+0305 U+0305  the first cell shows row 0, column 0 of the image
    //   U+0305 U+030D  the second cell shows row 0, column 1
    //
    // The image moves with those cells, like text.
    terminal.vt_write(b"\x1b_Ga=T,U=1,f=32,i=3,s=1,v=1,c=2,r=1,q=2;AP8A/w==\x1b\\");
    terminal.vt_write(b"\r\n\x1b[38;5;3m");
    terminal.vt_write(b"\xf4\x8e\xbb\xae\xcc\x85\xcc\x85");
    terminal.vt_write(b"\xf4\x8e\xbb\xae\xcc\x85\xcc\x8d");
    terminal.vt_write(b"\x1b[39m");

    // The storage has a generation of its own. It changes when a program
    // sends, places or deletes an image, but not when images only move on
    // screen. That is why the frames below use the render state's
    // placements generation to know when to read the list again.
    let graphics = terminal.kitty_graphics()?;
    let storage_generation = graphics.generation()?;
    println!("\nStorage generation: {storage_generation}");

    // Find what to draw from the render state, over three frames.
    run_frames(&mut terminal)?;

    // Animate a second image by driving the animation tick.
    println!("\nPlaying an animation:");
    run_animation(&mut terminal)?;

    Ok(())
}

Full program: rust-vt-kitty-graphics/src/main.rs