For AI agents: the "Reading aid" section on this page contains the raw Markdown source identical to the rendered content, with HTML markup and animations removed. AI is advised to read that section directly to understand the content quickly and with less noise.
## When to use signals

- Built-in `ZSignal` for control notifications (click, selection, value change).
- Custom controls: declare your own `ZSignal<...>` members and `Fire` them.

## ConnectionThread

```cpp
enum class ConnectionThread { CurrentThread, NewThread, UIThread };
```
- `CurrentThread` (default): slot runs synchronously on the firing thread.
- `NewThread`: **spawns a detached thread per Fire** — do not touch UI inside; a running slot cannot be cancelled midway; **not suitable for high-frequency signals** — use `UIThread` or your own pool instead.
- `UIThread`: posts the slot to the UI thread (the correct way to update UI from workers); queued tasks check liveness and skip after `disconnect` / receiver destruction.

###block_red_start
**Pitfall**

- `Fire` should run on the UI thread by default; firing from a worker with `CurrentThread` slots runs UI slots on that worker — that is a caller contract violation. For cross-thread firing, use `UIThread` slots or guarantee subscriber lifetime yourself.
- `NewThread` + a raw `this` capture + a receiver that may die early = UAF; use `ConnectWeak` to keep it alive, or `UIThread`.
###block_red_end

- **`Version`**: cross-thread/locking semantics hardened in `v1.15.0`; queued tasks gained liveness checks in `v1.24.0`.

## Connection (Qt-style passive handle)

```cpp
class Connection {
    void disconnect();
    bool isConnected() const;
    explicit operator bool() const;   // destructor does NOT auto-disconnect
};
```
- Disconnected by the receiver's `ConnectionGroup` on destruction; **`Connection`'s own destructor does not**.
- `disconnect()` logically invalidates pending `UIThread` / `NewThread` tasks, but **does not interrupt a slot already running**.

###block_red_start
**Pitfall**

- `Connection` is **not an RAII guard**; a temporary handle's destructor does not disconnect. Call `disconnect()` explicitly or rely on the receiver's group.
- it is safe to ignore the return of `connect`; calling `disconnect` after the signal is destroyed is safe (`alive` is atomic).
###block_red_end

- **`Version`**: passive-handle semantics since `v1.8.1`; the alive flag became atomic and pending tasks are cancelled since `v1.24.0`.

## ConnectionGroup

```cpp
class ConnectionGroup : public std::enable_shared_from_this<ConnectionGroup> {
    void disconnectAll(); size_t size() const;
};
```
- Used internally by `UIElement` / `Window` to disconnect all connections they own.
- `size()` counts only live connections; manually disconnected connections are not counted.

###block_red_start
**Pitfall**

- `disconnectAll()` only removes connections; it does not invoke user slots.
###block_red_end

## ZSignal

```cpp
template<typename... TArgs> class ZSignal {
    using SlotType = std::function<void(TArgs...)>;
    Connection connect(SlotType slot,
                       ConnectionThread thread = ConnectionThread::CurrentThread,
                       std::shared_ptr<ConnectionGroup> group = nullptr);
    template<class Receiver, class Slot>
    Connection connect(Receiver* receiver, Slot&& slot,
                       ConnectionThread thread = ConnectionThread::CurrentThread);
    void Fire(TArgs... targs) const;
    void operator()(TArgs... targs) const;
};
```
- Fire with `Fire` (**there is no `emit` macro**).
- `ZSignal` is **not copyable or movable**; it is a member of controls/windows — never put it in a movable container.
- Signal arguments are passed to slots as **lvalues**; do not declare `T&&` slot parameters, and prefer `const T&` for large objects.

###block_red_start
**Pitfall**

- `Fire` iterates a **snapshot**, so a slot may safely `disconnect`; re-firing the same signal inside a slot goes through the "reentrant" path (local copy) — avoid deep recursion there.
- `Fire` concurrent with `ZSignal` destruction is UB; fire and destroy a signal on the same thread.
- an exception thrown by a slot propagates out of `Fire`; later slots do not run. Avoid throwing from signal slots.
###block_red_end

- **`Version`**: `v1.18.0` adds a RAII guard so a throwing slot still restores reentrancy depth and releases the snapshot; non-movable since `v1.24.0`.

## Receiver context and ConnectWeak

- `elem->Connect(sig, slot)`, `Connect(elem, sig, slot)` and `sig.connect(elem, slot)` register the connection on `elem`'s `ConnectionGroup` and disconnect when `elem` is destroyed; `Window` supports the same.
- `ConnectWeak(self, sig, slot)` holds a weak reference; the slot's first parameter is `T*` or `T&`, keeps `self` alive during execution, and does nothing if the object is gone.
- Member-function pointers go through the free `Connect` / `ConnectWeak` only (compile-time type check); `elem->Connect(sig, &Class::Method)` is no longer supported.

```cpp
auto panel = std::make_shared<Panel>();

panel->Connect(btn->Clicked, [this] { Refresh(); });
Connect(panel, btn->Clicked, &Panel::OnClick);
btn->Clicked.connect(panel, [this] { Refresh(); });

ConnectWeak(panel, btn->Clicked, [](Panel* self) { self->Refresh(); });
ConnectWeak(panel, btn->Clicked, &Panel::OnClick);
```

###block_orange_start

###block_red_start
**Pitfall**

- do not capture `self`'s `shared_ptr` by value inside a `ConnectWeak` slot — that creates a signal → slot → self → signal strong cycle.
###block_red_end

## Async tasks / RunAsync

```cpp
enum class AsyncTaskStatus { Pending, Running, Completed, Canceled, Failed };
class AsyncOwner { /* weak owner: callbacks are dropped after it dies */ };
class AsyncCancelToken { bool IsCancellationRequested() const; void ThrowIfCancellationRequested() const; };
class AsyncProgress { void Report(float value, const std::wstring& message = {}); };
template<class T> class AsyncTask { bool Cancel(); bool Wait(); AsyncTaskStatus GetStatus() const; AsyncCancelToken GetCancelToken() const; };
template<class T, class Work> std::shared_ptr<AsyncTask<T>> RunAsync(AsyncOwner, Work&&,
    std::function<void(T)> onCompleted, std::function<void(std::exception_ptr)> onFailed = {},
    std::function<void(float, const std::wstring&)> onProgress = {}, std::function<void()> onCanceled = {});
```

- **v1.27.2 async:** `RunAsync<T>` runs on a worker, `AsyncCancelToken` cancels cooperatively, `AsyncProgress::Report` coalesces to the UI thread; completion/failure/cancel callbacks are delivered on the UI thread and dropped once `AsyncOwner` expires.

## ViewCore / virtual view scaffolding

```cpp
struct ScrollAxis { float offset, target, viewport, content, maxOffset;
    void SetMetrics(float viewport, float content);  void ScrollTo(float);  void EnsureVisible(float start, float size);
    Range VisibleRange(float itemExtent, float overscan = 0, int itemCount = -1) const; };
template<class T> class RecyclePool { std::shared_ptr<T> Acquire();  void Release(std::shared_ptr<T>);
    void Trim(size_t maxIdle);  void Clear(); };
template<class Result> class FetchFlow { void Start(AsyncOwner, Work, Ready, Error = {}, Progress = {}, Canceled = {});
    void Cancel();  bool Wait();  FetchState GetState() const; };
```

- ViewCore only abstracts scrolling, element recycling and request lifecycle; it does not define a universal data source. ListView already uses `ScrollAxis` for vertical scroll state.

## Global signals UIZSignals

```cpp
namespace UIZSignals {
    inline ZSignal<Window*, ID2D1RenderTarget*> DrawOverlay;
    inline ZSignal<Window*, float, float> GlobalMouseDown;
    inline ZSignal<Window*> WindowActivated, WindowDeactivated;
    inline ZSignal<Window*, UIElement*> ElementCaptureRequest, ElementCaptureRelease, RepaintRequest;
    inline ZSignal<Window*> LayoutInvalidated;
    inline ZSignal<> DeviceReset, ReloadAcrylic;
    inline ZSignal<const std::wstring&> Error;         // v1.16.0
}
```
- `RepaintRequest`/`LayoutInvalidated`/capture signals only fall back for **unmounted** elements; mounted ones route directly via `Window`.
- `DeviceReset`: release all caches keyed to the render target/device (e.g. `ImageDeviceCache`).

###block_red_start
**Pitfall**

- `DrawOverlay` carries a `Window*`; subscribers **must** filter by `GetWindow()`, or window A's overlay draws onto window B (classic multi-window cross-talk).
###block_red_end
Chapter 4

Events & Signals

ZSignal, Connection, cross-thread

When to use signals

ConnectionThread

cpp
enum class ConnectionThread { CurrentThread, NewThread, UIThread };

Pitfall

  • Fire should run on the UI thread by default; firing from a worker with CurrentThread slots runs UI slots on that worker — that is a caller contract violation. For cross-thread firing, use UIThread slots or guarantee subscriber lifetime yourself.
  • NewThread + a raw this capture + a receiver that may die early = UAF; use ConnectWeak to keep it alive, or UIThread.

Connection (Qt-style passive handle)

cpp
class Connection {
    void disconnect();
    bool isConnected() const;
    explicit operator bool() const;   // destructor does NOT auto-disconnect
};

Pitfall

  • Connection is not an RAII guard; a temporary handle's destructor does not disconnect. Call disconnect() explicitly or rely on the receiver's group.
  • it is safe to ignore the return of connect; calling disconnect after the signal is destroyed is safe (alive is atomic).

ConnectionGroup

cpp
class ConnectionGroup : public std::enable_shared_from_this<ConnectionGroup> {
    void disconnectAll(); size_t size() const;
};

Pitfall

  • disconnectAll() only removes connections; it does not invoke user slots.

ZSignal

cpp
template<typename... TArgs> class ZSignal {
    using SlotType = std::function<void(TArgs...)>;
    Connection connect(SlotType slot,
                       ConnectionThread thread = ConnectionThread::CurrentThread,
                       std::shared_ptr<ConnectionGroup> group = nullptr);
    template<class Receiver, class Slot>
    Connection connect(Receiver* receiver, Slot&& slot,
                       ConnectionThread thread = ConnectionThread::CurrentThread);
    void Fire(TArgs... targs) const;
    void operator()(TArgs... targs) const;
};

Pitfall

  • Fire iterates a snapshot, so a slot may safely disconnect; re-firing the same signal inside a slot goes through the "reentrant" path (local copy) — avoid deep recursion there.
  • Fire concurrent with ZSignal destruction is UB; fire and destroy a signal on the same thread.
  • an exception thrown by a slot propagates out of Fire; later slots do not run. Avoid throwing from signal slots.

Receiver context and ConnectWeak

cpp
auto panel = std::make_shared<Panel>();

panel->Connect(btn->Clicked, [this] { Refresh(); });
Connect(panel, btn->Clicked, &Panel::OnClick);
btn->Clicked.connect(panel, [this] { Refresh(); });

ConnectWeak(panel, btn->Clicked, [](Panel* self) { self->Refresh(); });
ConnectWeak(panel, btn->Clicked, &Panel::OnClick);

block_orange_start

Pitfall

  • do not capture self's shared_ptr by value inside a ConnectWeak slot — that creates a signal → slot → self → signal strong cycle.

Async tasks / RunAsync

cpp
enum class AsyncTaskStatus { Pending, Running, Completed, Canceled, Failed };
class AsyncOwner { /* weak owner: callbacks are dropped after it dies */ };
class AsyncCancelToken { bool IsCancellationRequested() const; void ThrowIfCancellationRequested() const; };
class AsyncProgress { void Report(float value, const std::wstring& message = {}); };
template<class T> class AsyncTask { bool Cancel(); bool Wait(); AsyncTaskStatus GetStatus() const; AsyncCancelToken GetCancelToken() const; };
template<class T, class Work> std::shared_ptr<AsyncTask<T>> RunAsync(AsyncOwner, Work&&,
    std::function<void(T)> onCompleted, std::function<void(std::exception_ptr)> onFailed = {},
    std::function<void(float, const std::wstring&)> onProgress = {}, std::function<void()> onCanceled = {});

ViewCore / virtual view scaffolding

cpp
struct ScrollAxis { float offset, target, viewport, content, maxOffset;
    void SetMetrics(float viewport, float content);  void ScrollTo(float);  void EnsureVisible(float start, float size);
    Range VisibleRange(float itemExtent, float overscan = 0, int itemCount = -1) const; };
template<class T> class RecyclePool { std::shared_ptr<T> Acquire();  void Release(std::shared_ptr<T>);
    void Trim(size_t maxIdle);  void Clear(); };
template<class Result> class FetchFlow { void Start(AsyncOwner, Work, Ready, Error = {}, Progress = {}, Canceled = {});
    void Cancel();  bool Wait();  FetchState GetState() const; };

Global signals UIZSignals

cpp
namespace UIZSignals {
    inline ZSignal<Window*, ID2D1RenderTarget*> DrawOverlay;
    inline ZSignal<Window*, float, float> GlobalMouseDown;
    inline ZSignal<Window*> WindowActivated, WindowDeactivated;
    inline ZSignal<Window*, UIElement*> ElementCaptureRequest, ElementCaptureRelease, RepaintRequest;
    inline ZSignal<Window*> LayoutInvalidated;
    inline ZSignal<> DeviceReset, ReloadAcrylic;
    inline ZSignal<const std::wstring&> Error;         // v1.16.0
}

Pitfall

  • DrawOverlay carries a Window*; subscribers must filter by GetWindow(), or window A's overlay draws onto window B (classic multi-window cross-talk).
↑