When to use signals
- Built-in
ZSignalfor control notifications (click, selection, value change). - Custom controls: declare your own
ZSignal<...>members andFirethem.
ConnectionThread
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 — useUIThreador 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 afterdisconnect/ receiver destruction.
Pitfall
Fireshould run on the UI thread by default; firing from a worker withCurrentThreadslots runs UI slots on that worker — that is a caller contract violation. For cross-thread firing, useUIThreadslots or guarantee subscriber lifetime yourself.NewThread+ a rawthiscapture + a receiver that may die early = UAF; useConnectWeakto keep it alive, orUIThread.
Version: cross-thread/locking semantics hardened inv1.15.0; queued tasks gained liveness checks inv1.24.0.
Connection (Qt-style passive handle)
class Connection {
void disconnect();
bool isConnected() const;
explicit operator bool() const; // destructor does NOT auto-disconnect
};
- Disconnected by the receiver's
ConnectionGroupon destruction;Connection's own destructor does not. disconnect()logically invalidates pendingUIThread/NewThreadtasks, but does not interrupt a slot already running.
Pitfall
Connectionis not an RAII guard; a temporary handle's destructor does not disconnect. Calldisconnect()explicitly or rely on the receiver's group.- it is safe to ignore the return of
connect; callingdisconnectafter the signal is destroyed is safe (aliveis atomic).
Version: passive-handle semantics sincev1.8.1; the alive flag became atomic and pending tasks are cancelled sincev1.24.0.
ConnectionGroup
class ConnectionGroup : public std::enable_shared_from_this<ConnectionGroup> {
void disconnectAll(); size_t size() const;
};
- Used internally by
UIElement/Windowto disconnect all connections they own. size()counts only live connections; manually disconnected connections are not counted.
Pitfall
disconnectAll()only removes connections; it does not invoke user slots.
ZSignal
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 noemitmacro). ZSignalis 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 preferconst T&for large objects.
Pitfall
Fireiterates a snapshot, so a slot may safelydisconnect; re-firing the same signal inside a slot goes through the "reentrant" path (local copy) — avoid deep recursion there.Fireconcurrent withZSignaldestruction 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.
Version:v1.18.0adds a RAII guard so a throwing slot still restores reentrancy depth and releases the snapshot; non-movable sincev1.24.0.
Receiver context and ConnectWeak
elem->Connect(sig, slot),Connect(elem, sig, slot)andsig.connect(elem, slot)register the connection onelem'sConnectionGroupand disconnect whenelemis destroyed;Windowsupports the same.ConnectWeak(self, sig, slot)holds a weak reference; the slot's first parameter isT*orT&, keepsselfalive during execution, and does nothing if the object is gone.- Member-function pointers go through the free
Connect/ConnectWeakonly (compile-time type check);elem->Connect(sig, &Class::Method)is no longer supported.
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);
Pitfall
- do not capture
self'sshared_ptrby value inside aConnectWeakslot — that creates a signal → slot → self → signal strong cycle.
Async tasks / RunAsync
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,AsyncCancelTokencancels cooperatively,AsyncProgress::Reportcoalesces to the UI thread; completion/failure/cancel callbacks are delivered on the UI thread and dropped onceAsyncOwnerexpires.
ViewCore / virtual view scaffolding
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
ScrollAxisfor vertical scroll state.
Global signals UIZSignals
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 viaWindow.DeviceReset: release all caches keyed to the render target/device (e.g.ImageDeviceCache).
Pitfall
DrawOverlaycarries aWindow*; subscribers must filter byGetWindow(), or window A's overlay draws onto window B (classic multi-window cross-talk).