# kscreen

LVGL on the Kode Dot's glass for an Active Object of your own: the display, the flush, the touch feed and the render pass, with the display_lvgl example.

## What it is

kscreen puts an LVGL screen on the Kode Dot. LVGL is the library that draws the interface, and getting it onto the panel takes the same four jobs in every firmware that draws:

1. Create the display.
2. Hand each rendered rectangle to the owner of the panel.
3. Feed the touch samples to LVGL.
4. Run the render pass.

kscreen does those four, so you write the screens and nothing else.

kscreen is a struct inside an Active Object, the **owner**: the Active Object of your app that builds the screens. The owner hands kscreen the events it needs and keeps everything else for itself, including its state machine, its buttons and its data. Only the owner's thread calls LVGL, so LVGL needs no lock.

An app that names kscreen gets the UI kit (`sdk/kui`) and LVGL with it, and `kscreen_open()` calls `kui_init()` on the display it creates, so the kit's styles are ready when the owner builds its screens.

kodeOS's own interface does not use kscreen: kgui drives LVGL itself. The example `examples/display_lvgl` runs on it.

## How it is connected

```mermaid
flowchart LR
  touch["AO_Touch"]
  subgraph mine["Your app"]
    owner["Your owner AO"] -- "kscreen_touch()" --> ks["kscreen"]
    owner -- "kscreen_tick()" --> ks
    ks -- "lv_timer_handler()" --> lvgl["LVGL + kui"]
  end
  touch -- "TOUCH_EVT_SIG" --> owner
  ks -- "DISPLAY_FLUSH_SIG<br/>+ FlushEvt" --> disp["AO_Display"]
  disp --> panel["CO5300 panel"]
  class touch ao
  class disp ao
  class owner app
  class panel chip
```

*Who talks to whom when the glass draws*

The owner touches kscreen in five places, and the rest of the owner is yours:

1. **The constructor** calls `kscreen_ctor(&me->screen, &me->super, APP_TICK_SIG)`, binding the renderer to its owner and naming the owner's private tick signal (a number from `MAX_SIG` up).
2. **The initial transition** calls `kscreen_start(&me->screen)`, which subscribes the owner to `DISPLAY_STATE_SIG`, `DISPLAY_REPAINT_SIG`, `DISPLAY_PARK_SIG`, `POWER_CRITICAL_SIG` and `TOUCH_EVT_SIG` in that order, then asks AO_Display to announce the panel. The subscriptions come first because the answer can arrive the instant the request is posted.
3. **On `DISPLAY_STATE_SIG`** the owner calls `kscreen_open(&me->screen, Q_EVT_CAST(DisplayStateEvt))`. On `KODE_OK` it builds its screens and moves to the state that draws.
4. **While drawing**, `APP_TICK_SIG` goes to `kscreen_tick()`, `TOUCH_EVT_SIG` to `kscreen_touch()`, `DISPLAY_REPAINT_SIG` to `kscreen_repaint()`, `DISPLAY_PARK_SIG` to `kscreen_park(&me->screen, Q_EVT_CAST(DisplayParkEvt)->seq)` and `POWER_CRITICAL_SIG` to `kscreen_critical(&me->screen, Q_EVT_CAST(PowerCriticalEvt))`.
5. **At start**, the owner is started at `KODE_PRIO_USER_GUI`, the level the SDK keeps for a renderer, after `kode_init()` has returned.

### Ask, do not wait

The panel is announced once, from inside `kode_init()`, and the bus keeps no copy. `kscreen_start()` therefore asks, and the answer says whether the panel came up at all, which is how "late" and "never" are told apart. A later `DISPLAY_STATE_SIG`, the answer to someone else's `display_state_request()`, finds the renderer open, and `kscreen_open()` returns `KODE_EXISTS`.

### The display

LVGL gets a display of the glass's size in RGB565. When the panel offers two framebuffers, LVGL draws straight into them in direct mode: one is on the glass while LVGL draws the next frame in the other, and kscreen starts the two in step so that LVGL always draws in the buffer the panel is not showing. LVGL repaints only what changed and copies the rest over itself.

A panel driver with a single framebuffer gets two draw buffers instead, a tenth of the glass each, in PSRAM, and LVGL renders into them one part at a time.

Every buffer kscreen names is whole cache lines of 64 bytes (`KDRV_DISPLAY_CACHE_LINE`), because the P4's pixel accelerator, the PPA, refuses an output whose size is not a multiple of the cache line. LVGL's own draw unit for the PPA (`LV_USE_PPA`) stays off and is not supported, because AO_Display owns the accelerator. An app composes with the accelerator through kscreen's compose calls instead, which the section on composing below describes. In direct mode LVGL is told the framebuffers' real size, `KDRV_DISPLAY_FB_BYTES` (411,648 bytes, the 410 x 502 picture rounded up), and draws the picture and nothing past it. A partial buffer is its rows rounded up the same way, which is less than one row more, so LVGL still draws a tenth of the glass into it.

### The flush

kscreen posts one `FlushEvt` to AO_Display for each frame in direct mode. It names the framebuffer and the rows that changed. AO_Display owns the panel, flips to that framebuffer at the next refresh, and copies nothing. The rows tell it what to write back from the cache and what to give the screenshot and the mirror.

LVGL waits for a flush inside its own render call, so this thread is not reading its queue while it waits. The wait is a blocking take on the semaphore of `kdrv_display_flush_wait()` instead of a spin loop, and it is one of the SDK's three documented exceptions to "everything is an event". It lasts 500 ms at most.

When the end of a flush never comes, the frame is lost, one error line is logged and the screen keeps working. The alternative is a renderer that never runs again with the board healthy underneath.

### The touch feed

kscreen creates a pointer input in LVGL's event mode: LVGL reads the pointer when kscreen asks, once for each `TOUCH_EVT_SIG` sample, and once more in each render pass while a finger rests on the glass.

The default 33 ms read timer against AO_Touch's 30 ms sampling would read some samples twice and skip others, so a drag's measured speed would jump between 0, 1 and 2 times the real one. With the event mode, a drag that stops before the lift does not throw.

### The render pass

A one-shot timer starts each pass. `kscreen_tick()` runs `lv_timer_handler()`, which says how long until LVGL's next timer is due, and re-arms the timer for that long plus one tick, never later than `KODE_GUI_TICK_MS` (10 ms).

It is never periodic. A periodic timer would keep posting while a slow frame renders, and a full queue is a QP assert. LVGL's clock is `khal_time_ms()`, so a pass that overruns costs nothing and animations do not drift.

### The frame rate

The panel refreshes every 16.8 ms (59.4 Hz), and a frame reaches the glass only at a refresh. A frame drawn in under 16.8 ms keeps the refresh rate, and one that needs longer waits for the next refresh.

LVGL draws a frame on both cores with two draw threads that start in `lv_init()`, each with a 32 KB stack in PSRAM, at `KODE_PRIO_USER_GUI`. A `_Static_assert` in `kscreen.c` keeps `LV_DRAW_THREAD_PRIO` equal to that level, because a draw thread above it would stall everything the renderer yields to.

### The repaint

AO_Display publishes `DISPLAY_REPAINT_SIG` after the display row of the production test (`test component=display`). During that row it ends every flush without showing its pixels, so the glass holds the row's last field while LVGL believes it is up to date. `kscreen_repaint()` realigns the buffers, invalidates the screen and the top layer, and the next pass paints everything back.

### The park

Before the glass sleeps for the app (`kode_sys_screen_sleep()`, `sdk/kaos/display`), AO_Display publishes `DISPLAY_PARK_SIG`, because the link it takes down frees the framebuffers LVGL draws in. `kscreen_park(s, seq)` stops the render pass, sets `parked` and answers with `kode_sys_screen_parked(seq)`, which lets the glass sleep. Nothing is drawn until `DISPLAY_REPAINT_SIG`. Then `kscreen_repaint()` takes the panel's framebuffers again, which the link brought back new, and starts the render pass.

While parked, a press reaches LVGL as a contact to wait out: it clicks nothing, also when the finger stays down past the repaint. The owner still hears `TOUCH_EVT_SIG` itself, so a touch can be what wakes the glass. Before `kscreen_open()` has succeeded nothing answers a park, and the glass stays lit.

### The critical battery notice

AO_Power publishes `POWER_CRITICAL_SIG` when the cell is critical on battery, once per fall and before the readings that switch the board off, and again when it is over (`sdk/kaos/power`). `kscreen_critical(s, e)` answers it. With `critical` true it puts a card of the UI kit (`kui_sheet_create()`) on LVGL's top layer, over whatever the app draws: the power glyph and "Critical" in the danger colour, the title "Battery", "Plug in the cable" over "before it switches off.", and "Tap to close." The card's handle is hidden, and a shield over the whole card takes every press, so a tap anywhere closes the notice and presses nothing of the app's underneath. The log says `critical battery: notice up`, and after a tap `critical battery: notice closed by a tap`.

With `critical` false, because a cable came or the level climbed back, the notice comes down by itself and the log says `critical battery over: notice down`. Before `kscreen_open()` has succeeded nothing is shown, and the log says `critical battery said before the glass is open; no notice`.

Handing the event to `kscreen_critical()` is what shows the notice. An app with a notice of its own handles `POWER_CRITICAL_SIG` itself and never calls it. The standard layer's screen (`kode_screen_new()`, `sdk/kode`) hands the event on, so an app that draws with it shows the notice too.

### Composing with the pixel accelerator

With `CONFIG_KODE_COMPOSE=y` in the app's `sdkconfig.defaults`, the owner can move whole pictures with the P4's pixel accelerator instead of having LVGL draw them: the frame on the glass copied, a picture scaled, dimmed or laid over another, and the result shown by an LVGL object. AO_Display owns the accelerator, and each call asks it for one pass (`display_compose_run()`) and returns when the pixels are there, as the render pass waits for a flush. This is the supported way to use the accelerator from an app: `kscreen_pic_*` for the pictures and the passes, `kscreen_frame_create()` to show a picture, and `test component=compose` to check them on a board.

A picture (`kscreen_pic_t`) is RGB565 in PSRAM, no side longer than 502 pixels, and its `buf` is LVGL's own view of it: an image's source, a canvas or a snapshot's target. The calls run from the owner's thread, after `kscreen_open()` has succeeded. Without the option, and while the glass is asleep, every pass is refused.

A call returns only when no pass of its own can still write a picture. `KODE_TIMEOUT` says the pass never started and never will, so the pictures may be deleted. A pass that had started when the 500 ms ran out (`KSCREEN_COMPOSE_TIMEOUT_MS`) is waited for, 2 s more at most, and its own answer returned. The one exception is `KODE_IO_ERROR`, an accelerator that stopped in the middle of a pass: do not delete the pictures of that call.

**The frame object.** `kscreen_frame_create()` makes the image object that shows a picture. Left plain, it covers what is under it, and LVGL draws nothing there. Plain means its own picture at its size, at full opacity, with no recolour, rotation, scale, offset, radius or other blend mode. With the option on, the accelerator copies the frame when LVGL draws it straight into the panel's framebuffer in direct mode, on an unturned glass, with no other draw task waiting or running in any layer. The copy is one 1:1 pass through AO_Display's compose door, and LVGL's own drawing of the object is skipped. Anything else is drawn by LVGL, as it is without the option: a turned glass, partial mode, or other drawing still pending.

LVGL draws the glass in tiles, and a tile where other drawing is still pending is drawn by LVGL. That happens with an object over the frame in the tile before, or the screen around a frame smaller than the area redrawn, so the gain depends on what sits above and around the frame. `frame_copied` and `frame_drawn` in `kscreen_t` count the draws each way, and a frame drawn as two tiles counts two. With `log_level tag="kscreen" level=d`, the log says `frame: <reason>` each time the lasting reason changes, such as `frame: copied by the accelerator` or `frame: drawn by LVGL: not into the unturned framebuffer`.

The first pass that is not done hands every frame back to LVGL until the next boot, and the log says it once. A pass that never ended is an error, `frame: a copy never ended; LVGL draws frames from now on`. Any other refusal is a warning, `frame: the accelerator answered <n>; LVGL draws frames from now on`.

### Presenting a whole frame

A game that draws its whole frame itself, in software, shows it with `kscreen_present(s, pic, sixteenths, border)`. One pass of the accelerator scales the picture, centred, straight into the panel's back framebuffer, and the panel flips to that buffer at its next refresh. Nothing goes through LVGL and no full-screen picture sits in between, which saves the second pass and the LVGL refresh that a frame object costs each frame.

The call returns once the flip is posted, so the game can draw its next frame in the same picture at once. The next present waits for that flip before it writes the back buffer, because until then the panel may still be reading it.

The first present takes the glass from LVGL. LVGL's refresh stops while its timers and its input go on, and `kscreen_tick()` keeps running and draws nothing. `kscreen_present_end(s)` gives the glass back, pointing LVGL at the framebuffers again and having it redraw the whole screen. The critical battery notice, a turn of the glass and the E5 test's screens end the present first, so that LVGL can draw them, and a pass that fails gives the glass back too. A present is refused, with nothing changed, while the notice is up and with the glass asleep or turned.

The glass round the picture is painted `border` in each framebuffer once, when the glass is taken, after a repaint, and when the scaled size or the colour changes. A picture that fills the glass leaves no border, and 272 x 332 at x1.5 (24 sixteenths) lands as 408 x 498 with one column of border on each side and two rows above and below.

Touch still reaches LVGL, and the owner reads `TOUCH_EVT_SIG` itself for the game's own input. A screenshot, `kscreen_pic_grab()` and the mirror read the frame on the glass, so they show the presented frame.

On a Kode Dot DVT on 2026-11-19, with ESP-IDF v6.1 and the app built at `-O2`, a 272 x 332 frame drawn in software in 27.8 ms and shown at x1.5 ran at 26.4 frames a second through `kscreen_pic_scale()` and a frame object, and at 31.2 through `kscreen_present()`. Showing each frame took 9.3 ms the first way and 3.8 ms the second. A frame drawn in 3.4 ms kept the panel's 59.4 frames a second either way.

### An app that computes its frames

The board file names no optimisation level, so an app builds with ESP-IDF's default, `-Og` (`CONFIG_COMPILER_OPTIMIZATION_DEBUG`), which keeps the code close to the source for a debugger and runs slower. kodeOS builds at `-Os`. An app whose frames cost computation, such as a game that draws in software, builds its own code, LVGL and the SDK at `-O2` with one line in its own `sdkconfig.defaults`:

```
CONFIG_COMPILER_OPTIMIZATION_PERF=y
```

The board file keeps the default because a level set there would reach every app, its debugging and its use of internal RAM.

The game draws its frame in a picture from `kscreen_pic_create()`, which lives in PSRAM, where the accelerator reads it.

## Specifications

### The files

The files of the component.

| File | What it does |
| --- | --- |
| `include/kscreen.h` | `kscreen_t`, the nine calls of the renderer and the calls that compose |
| `src/kscreen.c` | The display and its modes, the flush and its wait, the pointer, the render pass, the repaint, the park, the critical battery notice and the rotation |
| `src/kscreen_compose.c` | The pictures, the passes asked of AO_Display and the present |
| `src/kscreen_geom.c`, `src/kscreen_geom.h` | A composed picture's arithmetic: sizes, areas, points and the turn, whether a frame object covers and is copied, and where a presented picture lands with the border round it, with no LVGL in it. The host tests cover it |
| `src/kscreen_priv.h` | The renderer that opened a display, for the frame object's counts, and the flush that a present shares with LVGL |
| `Kconfig` | `KSCREEN_ROTATE_PAD` |
| `README.md`, `CMakeLists.txt`, `idf_component.yml` | The component's guide, build and manifest |

`kode_sys` and `kui` are required publicly, because `kscreen.h` speaks their types: `QActive` and `QTimeEvt`, the panel's events, `lv_display_t`.

kdrv, khal and kbsp are private: the flush completion is `kdrv_display`'s semaphore, the clock and the PSRAM heap are khal's, and the glass's size is a board fact. `kscreen.h` includes `kode_sys.h` and `lvgl.h`.

### The calls

The nine calls of the renderer, in the order an owner uses them.

| Call | When | What it does |
| --- | --- | --- |
| `kscreen_ctor(s, owner, tick_sig)` | The owner's constructor | Binds the renderer to its owner and to the owner's private tick signal |
| `kscreen_start(s)` | The owner's initial transition, which runs after `kode_init()` has returned | Subscribes to `DISPLAY_STATE_SIG`, `DISPLAY_REPAINT_SIG`, `DISPLAY_PARK_SIG`, `POWER_CRITICAL_SIG` and `TOUCH_EVT_SIG`, then calls `display_state_request()` |
| `kscreen_open(s, d)` | On `DISPLAY_STATE_SIG` | `lv_init()`, the display, the flush, the touch feed in event mode, then `kui_init()`, and arms the tick for `KODE_GUI_TICK_MS`. `KODE_OK` when LVGL is up; `KODE_DENIED` when `d` says the panel is not up; `KODE_EXISTS` when already open; `KODE_NO_RESOURCES` when the draw buffers, the display or the input could not be had. Every failure is logged, leaves nothing allocated and does not arm the tick |
| `kscreen_tick(s)` | On the tick signal | One extra input read while a finger rests, one `lv_timer_handler()`, then re-arms the one-shot. Does nothing before a successful open |
| `kscreen_touch(s, t)` | On `TOUCH_EVT_SIG` | Feeds one sample to LVGL. While parked a press clicks nothing |
| `kscreen_repaint(s)` | On `DISPLAY_REPAINT_SIG` | Invalidates the screen and the top layer. A parked renderer takes the framebuffers again and starts its render pass |
| `kscreen_park(s, seq)` | On `DISPLAY_PARK_SIG`, with the event's `seq` | Stops the render pass until `DISPLAY_REPAINT_SIG`, then answers with `kode_sys_screen_parked(seq)`. Nothing answers before a successful open |
| `kscreen_critical(s, e)` | On `POWER_CRITICAL_SIG`, with the `PowerCriticalEvt` | Puts the critical battery notice on the top layer when `critical` is true, and takes it down when it is false. A tap closes it. Nothing is shown before a successful open. An app with a notice of its own handles the signal and never calls it |
| `kscreen_set_rotation(s, rot)` | Any time after open, from the owner's thread, outside `kscreen_tick()` | Turns the glass to `LV_DISPLAY_ROTATION_0`, `_90`, `_180` or `_270`, back to 0 included. The screen is redrawn whole. `KODE_OK` when the glass is turned that way (already, or now); `KODE_DENIED` before open or for another value; `KODE_NO_RESOURCES` when the buffers could not be had, with the glass left as it was |

### The calls that compose

With `CONFIG_KODE_COMPOSE`, from the owner's thread after a successful open. Every call that runs a pass answers as `kscreen_pic_grab()` does, and logs each failure.

| Call | What it does |
| --- | --- |
| `kscreen_pic_create(w, h)` | A black picture of 1 to 502 pixels a side, in PSRAM. NULL, logged, for a size out of range or no PSRAM |
| `kscreen_pic_delete(pic)` | Gives a picture back. No object may still show it; NULL does nothing |
| `kscreen_pic_grab(s, dst)` | Copies the frame on the glass into `dst` as the glass shows it, turned with a turned glass. `dst` is 410 by 502, or 502 by 410 at 90 or 270 degrees. `KODE_OK`; `KODE_DENIED` before open, for another size, with the glass asleep or without the option; `KODE_NO_RESOURCES` with one framebuffer, the link down, no accelerator or no room in AO_Display's queue; `KODE_TIMEOUT` when AO_Display did not take the request in 500 ms; `KODE_ERROR` when the accelerator refused; `KODE_IO_ERROR` when a pass never ended |
| `kscreen_pic_fill(dst, area, colour)` | Paints an area one colour; NULL is the whole picture. `KODE_DENIED` for an area outside it |
| `kscreen_pic_scale(dst, x, y, src, from, sixteenths)` | Copies an area of `src` into `dst` at `x`, `y`, scaled by 1 to 256 sixteenths (`KSCREEN_SCALE_MIN`, `_MAX`); 16 (`KSCREEN_SCALE_ONE`) is a copy. A size rounds down, so 410 pixels at 15 are 384. Nothing is clipped: the result must fit `dst`, which is never `src` |
| `kscreen_pic_blend(dst, x, y, fg, from, opa)` | Lays an area of `fg` over `dst` in place, at an opacity from `LV_OPA_TRANSP` (no change) to `LV_OPA_COVER` (replaced) |
| `kscreen_pic_dim(dst, src, level)` | Writes `src` into `dst` dimmed towards black, in two passes. `LV_OPA_COVER` is `src` as it is, `LV_OPA_TRANSP` black. Two sizes, or one picture given twice, are refused with nothing painted |
| `kscreen_frame_create(parent, pic)` | An LVGL image object the size of the picture that shows it. Left plain it covers what is under it, and the accelerator copies it when the frame object's conditions hold. After composing into the picture, `lv_obj_invalidate()` it, and delete it before the picture. NULL when LVGL had no memory for it |
| `kscreen_present(s, pic, sixteenths, border)` | Shows `pic` scaled by `sixteenths` and centred, with the rest of the glass `border`, in one pass into the panel's back framebuffer and a flip, and takes the glass from LVGL on its first call. `KODE_OK` once the flip is posted. `KODE_DENIED`, with nothing changed, before open, with the glass asleep or turned, while the critical battery notice is up, without the option, for a picture `kscreen_pic_create()` did not make, or for a scale out of range or whose result is empty or larger than the glass (410 by 502). `KODE_NO_RESOURCES`, with nothing changed, with one framebuffer or the link down. A pass that fails answers as `kscreen_pic_grab()` and gives the glass back to LVGL |
| `kscreen_present_end(s)` | Gives the glass back to LVGL, which redraws the whole screen. Does nothing when no present has the glass, and is there in every build |

### The E5 test's screens

A build with `CONFIG_KODE_TEST_DOT` adds one call. `kscreen_start()` also subscribes the owner to `TEST_DOT_SCREEN_REQ_SIG`, and the owner passes each request to `kscreen_test_dot_event(s, e)`. The call deletes the canvas the last request built, builds the screen or the pattern the request names on LVGL's top layer with `kui_test_dot` (`sdk/kui`), draws and flushes it at once, and answers with `test_dot_screen_done(kind, seq)`. An automatic screen over an automatic screen repaints only the cells that changed. The request for no screen deletes the canvas and answers nothing. Before `kscreen_open()` has succeeded nothing is shown and nothing answers, and AO_TestDot's wait runs out. The test itself is on `sdk/kaos/test-dot`.

### The renderer

`kscreen_t` lives inside the owner's struct. The owner may read some fields and never writes any. The table lists the fields.

| Field | For the owner? | Meaning |
| --- | --- | --- |
| `disp` | read | The `lv_display_t`; NULL until `kscreen_open()` succeeds. For settings of your own, a scroll throw or a theme |
| `indev` | read | The pointer input, in event mode |
| `pressed`, `x`, `y` | read | Whether a finger is down, and the last sample's coordinates, for gestures |
| `tick` | kscreen's | The `QTimeEvt` of the render pass |
| `owner` | kscreen's | The Active Object this lives in; the sender of every `FlushEvt` |
| `direct`, `posted`, `band_y1`, `band_y2` | kscreen's | Direct mode, a flush with AO_Display not yet waited for, the changed rows of the frame being drawn |
| `rot`, `part_buf[2]`, `rot_buf` | kscreen's | The turn of the glass, the two partial-mode draw buffers, and where a band is turned before it goes to the panel |
| `parked` | kscreen's | `DISPLAY_PARK_SIG` stopped the render pass until `DISPLAY_REPAINT_SIG` |
| `critical` | kscreen's | The critical battery notice while it is up, else NULL |
| `frame_copied`, `frame_drawn` | kscreen's | Draws of a `kscreen_frame_create()` object since `kscreen_ctor()`, the accelerator's copies and the ones LVGL drew instead. A frame drawn as two tiles counts two |
| `presenting`, `border_owed`, `border`, `present_w`, `present_h` | kscreen's | A present has the glass, the framebuffers still to get the border (0 to 2), the border's colour, and the scaled size presented last |

### The display modes

The three ways LVGL draws and flushes.

| Mode | LVGL draws into | The flush |
| --- | --- | --- |
| Direct (panel with two framebuffers, glass unturned) | The panel's back framebuffer, a whole frame (410 x 502 x 2 bytes, about 402 KB, in a `KDRV_DISPLAY_FB_BYTES` allocation of 411,648 bytes) in PSRAM | One `FlushEvt` per frame with the changed rows, `last` set. AO_Display flips at the next refresh and copies nothing |
| Partial (a panel with one framebuffer) | Two draw buffers of `KBSP_LCD_V_RES / 10` rows, 41,024 bytes each (41,000 rounded up to whole cache lines), in PSRAM | One `FlushEvt` per band |
| Turned (90, 180 or 270 degrees) | The same two partial buffers | Each band is turned into a third buffer, packed at the turned band's own width, then flushed as the rectangle it covers on the panel |

A turned screen redraws more slowly: a change of the whole screen runs at about 20 frames a second against 59 unturned, and a smaller change faster. The three buffers, 41,024 bytes each in PSRAM, are taken on the first turn and kept.

Touch follows by itself, because LVGL turns every point. The pad follows when `CONFIG_KSCREEN_ROTATE_PAD` is on: at 270 degrees the pad's right reads as up, through `buttons_rotation_request()`. TOP and BOT are side buttons and never turn.

The partial buffers are PSRAM and never internal RAM, whatever it costs a redraw, because the radio stack needs the internal pool. The launcher's full redraw measured 54 ms with 2 x 40 KB in PSRAM against 37 ms in internal RAM.

### The numbers and the options

The timings, sizes and the options.

| Thing | Value |
| --- | --- |
| `KSCREEN_FLUSH_TIMEOUT_MS` | 500: the longest LVGL waits for the panel to finish one flush |
| `KODE_GUI_TICK_MS` | 10: the longest between two render passes |
| Panel refresh | 16.8 ms, 59.4 Hz |
| `LV_DEF_REFR_PERIOD` | 16 ms (board file) |
| LVGL draw units | 2, each with a 32 KB stack in PSRAM, at priority 3 (`KODE_PRIO_USER_GUI`) |
| Owner priority | `KODE_PRIO_USER_GUI`, 3. The level holds a single Active Object, so one kscreen per image |
| `KSCREEN_ROTATE_PAD` | y: the four pad buttons publish the direction they point on a turned glass. Off, the app gets the buttons as wired and maps them itself |
| `KSCREEN_COMPOSE_TIMEOUT_MS` | 500: the longest a compose call waits for AO_Display to take its pass |
| `CONFIG_KODE_COMPOSE` | n by default, a kaos option: the app sets it to y to compose (`sdk/kaos/display`) |

### The example

`examples/display_lvgl` shows a title, a counter at 0 and a hint. TOP or a tap anywhere adds one, and BOT goes home to kodeOS. With the console up, `screenshot` shows what the Active Object drew. It needs no microSD card, radio or network.

Its files:

| File | What it does |
| --- | --- |
| `main/display_lvgl_main.c` | `app_main()`: `kode_init()`, then the constructor and start of the one Active Object. Declares `KODE_APP_MANIFEST("Display", "example")` |
| `main/display_lvgl_ao.c`, `main/display_lvgl_ao.h` | The Active Object: a `running` parent that sends BOT home, a `waiting` state until the panel is announced, a `drawing` state that builds the screen and feeds kscreen |
| `main/CMakeLists.txt`, `main/idf_component.yml` | `REQUIRES kode`, `PRIV_REQUIRES kdrv kscreen`; pins `kodediy/kode` and `kodediy/kscreen` at one tag |
| `sdkconfig.defaults` | The partition table path, the app boot role, the console kept, `KODEOS_RADIO=n`, `ESP_HOSTED_ENABLED=n`, `BT_ENABLED=n`, and Montserrat 28 and 48 for the example's own labels, because the board compiles only Montserrat 14 |

## Gotchas

> **WARNING**
>
> **A state that handles the tick signal and never calls `kscreen_tick()` stops the screen for good.** The tick is a one-shot that `kscreen_tick()` re-arms, so skipping the call ends the render pass while the Active Object keeps running and answers other events. A child state that needs the tick returns `Q_SUPER()` to the state that calls `kscreen_tick()`, and never transitions away while handling it.

> **WARNING**
>
> **Turn the glass through `kscreen_set_rotation()` only.** Calling `lv_display_set_rotation()` on `disp`, or replacing its flush callback, draws a sheared or striped screen, because kscreen turns each band itself before it goes to the panel.

> **NOTE**
>
> **Call `lv_*` from the owner's thread only.** A task of yours that wants the screen to change sends the owner an event, or leaves a copy of the data that the owner reads on its tick. LVGL has no lock here. The same holds for the fields of `kscreen_t`: read them from the owner and write none.

> **NOTE**
>
> **A frame object with a `DRAW_MAIN` callback of yours is drawn by LVGL.** A copy takes the object's `LV_EVENT_DRAW_MAIN` and ends it, so a callback added for `LV_EVENT_DRAW_MAIN` or `LV_EVENT_ALL` keeps the copy off. The frame still covers, and LVGL copies its rows. Catch clicks with `LV_EVENT_CLICKED`, or any other code, to keep the copy. A `PREPROCESS` callback on `DRAW_MAIN` or `LV_EVENT_ALL`, or `lv_obj_set_send_draw_task_events()`, can change how LVGL draws the picture, and the frame then neither covers nor is copied. `LV_OBJ_FLAG_EVENT_BUBBLE` changes none of this, because in LVGL 9.6 `DRAW_MAIN` reaches no parent and no child.

> **NOTE**
>
> **While a present has the glass, LVGL shows nothing new.** An object created or changed after the first `kscreen_present()` reaches the glass only after `kscreen_present_end()`, which redraws the whole screen. A game that shows a menu between rounds ends the present before it builds the menu.

> **NOTE**
>
> **Another LVGL stops kscreen's build.** The frame object's copy reads LVGL 9.6's layers and draw task lists, so with any LVGL but 9.6 `kscreen_compose.c` stops with `#error "kscreen's frame object is written against LVGL 9.6's draw pipeline"`. That holds with or without `CONFIG_KODE_COMPOSE`.

> **NOTE**
>
> **One kscreen per image.** LVGL has one clock and one display here, and `KODE_PRIO_USER_GUI` holds a single Active Object. A second `QACTIVE_START` at a taken level is a QP assertion and a reset.

## Example code

An Active Object that renders with kscreen and draws one pill of the UI kit in the middle of the glass. The Kode Dot shows a rounded grey row reading "Hello" over "from the kit". It handles the panel's announcement and the tick. A full owner also routes `TOUCH_EVT_SIG` to `kscreen_touch()` and `DISPLAY_REPAINT_SIG` to `kscreen_repaint()`, as `display_lvgl` does, and `POWER_CRITICAL_SIG` to `kscreen_critical()` to show the critical battery notice. An owner whose app puts the glass to sleep also routes `DISPLAY_PARK_SIG` to `kscreen_park()`: unanswered, the sleep fails with `KODE_TIMEOUT`, "the renderer did not stop drawing".

```c
/*
 * kscreen_hello.c - from Kode with love
 *
 * Renders with kscreen from an Active Object of your own and draws one pill
 * of the UI kit in the middle of the glass: "Hello" over "from the kit".
 */
#include "kscreen.h"
#include "kui.h"
enum { TICK_SIG = MAX_SIG };
static QActive     s_ao;
static kscreen_t   s_screen;
static QEvtPtr     s_queue[KQP_AO_QUEUE_LEN];
static StackType_t s_stack[KQP_AO_STACK_BYTES / sizeof(StackType_t)];
/* Open the display on the panel's announcement, then render on each tick. */
static QState Hello_running(QActive * const me, QEvt const * const e) {
    (void)me;
    if ((e->sig == DISPLAY_STATE_SIG) &&
        (kscreen_open(&s_screen, (DisplayStateEvt const *)e) == KODE_OK)) {
        lv_obj_add_style(lv_screen_active(), &kui_style_screen, 0);
        lv_obj_center(kui_pill_create(lv_screen_active(), "Hello", "from the kit"));
    } else if (e->sig == TICK_SIG) {
        kscreen_tick(&s_screen);
    }
    return Q_HANDLED();
}
/* Subscribe, and ask the panel to announce itself. */
static QState Hello_initial(QActive * const me, void const * const par) {
    (void)me;
    (void)par;
    kscreen_start(&s_screen);
    return Q_TRAN(&Hello_running);
}
/* Bring the system up, then start the renderer at its own priority. */
void app_main(void) {
    kode_init();
    QActive_ctor(&s_ao, Q_STATE_CAST(&Hello_initial));
    kscreen_ctor(&s_screen, &s_ao, TICK_SIG);
    QACTIVE_START(&s_ao, KODE_PRIO_USER_GUI, s_queue, Q_DIM(s_queue),
                  s_stack, sizeof(s_stack), (void *)0);
}
```

Compiled against the SDK with ESP-IDF v6.1 on 2026-10-28.

## In the SDK

- [`components/kscreen`](https://github.com/kodediy/kode-sdk/tree/main/components/kscreen): the component, `include/kscreen.h` and `src/kscreen.c`.
- [`examples/display_lvgl`](https://github.com/kodediy/kode-sdk/tree/main/examples/display_lvgl): a counter on the glass, with touch, a button and BOT to go home.
- [`components/kui`](https://github.com/kodediy/kode-sdk/tree/main/components/kui): the UI kit that kscreen brings with it.
