Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
chart.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4#include <array>
5#include <cmath>
6#include <functional>
7#include <portals/canvas.hpp>
8#include <portals/layout.hpp>
9#include <portals/model.hpp>
10#include <vector>
11
12namespace portals {
14struct Ohlc {
15 double open{};
16 double high{};
17 double low{};
18 double close{};
19};
20
26public:
31 bool add(double price) noexcept;
35 std::optional<Ohlc> value() const noexcept;
37 void reset() noexcept;
38
39private:
40 std::optional<Ohlc> value_;
41};
42
44struct ChartRange {
45 double minimum{};
46 double maximum{};
47};
48
49enum class ChartMode {
52};
53
59
63
64 std::optional<ChartRange> y_range;
66 CellStyle line{RgbColor{80, 180, 240}, {}, false, false, false};
67 CellStyle rising{RgbColor{60, 200, 120}, {}, false, false, false};
68 CellStyle falling{RgbColor{230, 90, 90}, {}, false, false, false};
71 std::int32_t candle_gap{};
72};
73
75namespace detail {
76struct ChartGlyphs {
77 GraphemeText line;
78 GraphemeText wick;
79 GraphemeText body;
80 GraphemeText doji;
81};
82
83std::expected<ChartGlyphs, TreeError> chartGlyphs(WidthPolicy policy, ChartGlyphSet symbols = ChartGlyphSet::ASCII);
84bool validOhlc(const Ohlc &value) noexcept;
85bool validChartOptions(ChartOptions options) noexcept;
86std::expected<void, TreeError> paintChart(PaintContext &context, CellSize viewport, ChartOptions options,
87 std::span<const std::optional<Ohlc>> samples, const ChartGlyphs &glyphs);
88} // namespace detail
89
91
92template <class T> class Chart;
106template <class T>
107std::expected<std::optional<ModelRequest<T>>, TreeError> prepareChart(WidgetTree &tree, Node<Chart<T>> node,
108 const ModelFrame<T> &frame, CellSize viewport,
109 std::uint64_t first = 0);
110
117template <class T> class Chart : public SizedWidget {
118public:
125 Chart(ModelConsumer<T> consumer, std::function<std::optional<Ohlc>(const T &)> accessor, ChartOptions options = {},
127 : SizedWidget(policy), consumer_(std::move(consumer)), accessor_(std::move(accessor)), options_(options) {
128 }
129
131 ~Chart() override {
132 request_.cancel();
133 }
134
136 RangeState rangeState() const noexcept {
137 return prepared_ ? prepared_->range.state() : RangeState::PENDING;
138 }
139
141 std::uint64_t dataRevision() const noexcept {
142 return prepared_ ? prepared_->frame.dataRevision() : 0;
143 }
144
146
147 RowRange visibleRange() const noexcept {
148 return prepared_ ? prepared_->interval : RowRange{};
149 }
150
154 std::expected<CellSize, TreeError> measure(CellSize available) override {
155 return available.normalized();
156 }
157
161 std::expected<void, TreeError> arrange(CellRect local) override {
162 arranged_ = local.size();
163
164 return {};
165 }
166
171 std::expected<void, TreeError> paint(PaintContext &context) override {
172 if (!prepared_) {
173 return std::unexpected(TreeError::WOULD_BLOCK);
174 }
175
176 if (arranged_ != prepared_->viewport) {
177 return std::unexpected(TreeError::INVALID_GEOMETRY);
178 }
179
180 auto options = options_;
181
182 if (const auto &style = computedStyle()) {
183 options.background = style->normal;
184 }
185
186 // Every text cell replaces its complete style. Inherit the plot background
187 // for brushes without an explicit fill, otherwise terminal defaults leak through.
188 for (auto *brush : {&options.line, &options.rising, &options.falling}) {
189 if (!brush->background) {
190 brush->background = options.background.background;
191 }
192 }
193
194 return detail::paintChart(context, arranged_, options, prepared_->samples, prepared_->glyphs);
195 }
196
198 ComputedStyle styleDefaults() const override {
199 ComputedStyle result;
200
201 result.normal = options_.background;
202
203 return result;
204 }
205
206private:
207 template <class U>
208 friend std::expected<std::optional<ModelRequest<U>>, TreeError>
209 prepareChart(WidgetTree &, Node<Chart<U>>, const ModelFrame<U> &, CellSize, std::uint64_t);
210
211 struct Prepared {
212 Prepared(const ModelFrame<T> &pin, ModelRange<T> rows, CellSize size, RowRange visible, detail::ChartGlyphs symbols)
213 : frame(pin), range(std::move(rows)), viewport(size), interval(visible), glyphs(std::move(symbols)) {
214 }
215
216 ModelFrame<T> frame;
217 ModelRange<T> range;
218 CellSize viewport;
219
220 RowRange interval;
221 detail::ChartGlyphs glyphs;
222 // The count constructor may throw; MSVC Debug's noexcept default constructor can allocate a proxy.
223 std::vector<std::optional<Ohlc>> samples = std::vector<std::optional<Ohlc>>(0);
224 };
225
226 std::expected<std::optional<ModelRequest<T>>, TreeError> prepare(const ModelFrame<T> &frame, CellSize viewport,
227 std::uint64_t first) {
228 if (preparing_) {
229 return std::unexpected(TreeError::WOULD_BLOCK);
230 }
231
232 struct Guard {
233 bool &value;
234
235 explicit Guard(bool &v) : value(v) {
236 value = true;
237 }
238
239 ~Guard() {
240 value = false;
241 }
242 } guard(preparing_);
243
244 auto consumer_range = frame.range(consumer_.id());
245 auto range = consumer_range;
246
247 if (!range) {
248 return std::unexpected(range.error());
249 }
250
251 if (!accessor_ || !detail::validChartOptions(options_) || viewport.width < 0 || viewport.height < 0) {
252 return std::unexpected(TreeError::INVALID_ARGUMENT);
253 }
254
255 first = std::min(first, frame.rowCount());
256
257 const auto stride = options_.mode == ChartMode::CANDLES ? std::int64_t{options_.candle_gap} + 1 : 1;
258 const auto columns = (std::int64_t{viewport.width} + stride - 1) / stride;
259 const RowRange interval{
260 first,
261 viewport.height == 0 ? 0 : static_cast<std::size_t>(std::min<std::uint64_t>(columns, frame.rowCount() - first))};
262
263 try {
264 if (interval.count == 0) {
265 range = ModelRange<T>{};
266 } else if (range->range() != interval || range->state() == RangeState::PENDING) {
267 range = frame.read(interval);
268 }
269
270 if (!range) {
271 return std::unexpected(range.error());
272 }
273
274 if (range->state() == RangeState::PENDING && interval.count != 0) {
275 auto cached = frame.readCached(*consumer_range, prepared_ ? &prepared_->range : nullptr, interval);
276
277 if (!cached) {
278 return std::unexpected(cached.error());
279 }
280
281 if (cached->dataRevision() != 0) {
282 range = std::move(cached);
283 }
284 }
285
286 auto glyphs = detail::chartGlyphs(options_.width_policy, options_.glyph_set);
287
288 if (!glyphs) {
289 return std::unexpected(glyphs.error());
290 }
291
292 auto next = std::make_unique<Prepared>(frame, *range, viewport, interval, std::move(*glyphs));
293
294 next->samples.reserve(range->rows().size());
295
296 for (const auto &row : range->rows()) {
297 auto sample = accessor_(row.value);
298
299 if (sample && !detail::validOhlc(*sample)) {
300 sample.reset();
301 }
302
303 next->samples.push_back(sample);
304 }
305
306 std::optional<ModelRequest<T>> dispatch;
307
308 if (interval.count && range->state() == RangeState::PENDING &&
309 (request_.stopRequested() || request_.range() != interval ||
310 request_.dataRevision() != frame.dataRevision())) {
311 request_.cancel();
312 request_ = {};
313
314 auto work = consumer_.request(interval);
315
316 if (!work) {
317 return std::unexpected(work.error());
318 }
319
320 dispatch = *work;
321 request_ = std::move(*work);
322 } else if (!interval.count || range->state() != RangeState::PENDING) {
323 request_.cancel();
324 request_ = {};
325 }
326
327 prepared_.swap(next);
328
329 return dispatch;
330 } catch (const std::bad_alloc &) {
331 return std::unexpected(TreeError::NO_MEMORY);
332 } catch (const std::length_error &) {
333 return std::unexpected(TreeError::INVALID_ARGUMENT);
334 } catch (...) {
335 return std::unexpected(TreeError::CALLBACK_FAILED);
336 }
337 }
338
339 ModelConsumer<T> consumer_;
340 std::function<std::optional<Ohlc>(const T &)> accessor_;
341 ChartOptions options_;
342 ModelRequest<T> request_;
343 std::unique_ptr<Prepared> prepared_;
344 CellSize arranged_;
345 bool preparing_{};
346};
347
348template <class T>
349std::expected<std::optional<ModelRequest<T>>, TreeError> prepareChart(WidgetTree &tree, Node<Chart<T>> node,
350 const ModelFrame<T> &frame, CellSize viewport,
351 std::uint64_t first) {
352 std::expected<std::optional<ModelRequest<T>>, TreeError> result;
353 auto edited = tree.edit(node, [&](Chart<T> &chart) {
354 result = chart.prepare(frame, viewport, first);
355 });
356
357 if (!edited) {
358 return std::unexpected(edited.error());
359 }
360
361 if (result) {
362 auto invalidated = tree.invalidate(node, Invalidation::PAINT);
363
364 if (!invalidated) {
365 return std::unexpected(invalidated.error());
366 }
367 }
368
369 return result;
370}
371} // namespace portals
An owning, invariant-preserving half-open cell rectangle.
Definition geometry.hpp:81
CellSize size() const noexcept
Return the normalized cell extents by value; no errors.
UI-owned retained plot of a bounded immutable model range. Accessors run only in prepareChart,...
Definition chart.hpp:117
RowRange visibleRange() const noexcept
Definition chart.hpp:147
std::expected< void, TreeError > paint(PaintContext &context) override
Definition chart.hpp:171
std::uint64_t dataRevision() const noexcept
Definition chart.hpp:141
~Chart() override
Cancel outstanding work on UI without waiting.
Definition chart.hpp:131
std::expected< CellSize, TreeError > measure(CellSize available) override
Definition chart.hpp:154
ComputedStyle styleDefaults() const override
Definition chart.hpp:198
std::expected< void, TreeError > arrange(CellRect local) override
Definition chart.hpp:161
RangeState rangeState() const noexcept
Definition chart.hpp:136
Chart(ModelConsumer< T > consumer, std::function< std::optional< Ohlc >(const T &)> accessor, ChartOptions options={}, SizePolicy policy=DEFAULT_VIEWPORT_POLICY)
Own one range consumer and the typed projection.
Definition chart.hpp:125
Move-only UI-owned range slot. Equal/overlapping consumers are independent. Close/destruction retires...
Definition model.hpp:698
One immutable model revision retained by the frame owner for all its views. Obtain once before Widget...
Definition model.hpp:400
Independent owner for borrowed rows and provider error text.
Definition model.hpp:175
Copyable typed observer; never owns or exposes an unchecked widget pointer.
Definition widget.hpp:92
Constant-storage domain aggregation, performed before display snapshot coalescing....
Definition chart.hpp:25
bool add(double price) noexcept
Add an ordered price tick without dropping its effect.
void reset() noexcept
Begin the next caller-defined bucket; no queued or published state is affected.
std::optional< Ohlc > value() const noexcept
Copy the current aggregate.
Borrowed synchronous command sink supplied by the frame owner. submit must consume commands immediate...
Definition widget_types.hpp:66
Widget with owning policies, changed only through setSizePolicy on UI.
Definition layout.hpp:68
SizedWidget(SizePolicy policy={})
Own the supplied policies; checked by layout.
Exclusive parent/child ownership on Scheduler's UI thread. Scheduler must outlive this object....
Definition widget.hpp:179
std::expected< void, TreeError > edit(Node< T > node, Callback &&callback)
Borrow T only during a void callback; nested edit/removal is supported. Forbidden during measure/arra...
Definition widget.hpp:310
std::expected< void, TreeError > invalidate(Node< Widget > node, Invalidation kind)
Coalesce one frame request.
const std::shared_ptr< const StyleSnapshot > & computedStyle() const noexcept
Inspect the last atomically installed theme inside tree.read/frame.
Public Portals API.
Definition action.hpp:8
ChartMode
Retained chart rendering mode.
Definition chart.hpp:49
@ LINE
Join consecutive finite closes, leaving gaps disconnected.
Definition chart.hpp:50
@ CANDLES
Draw high-low wick and open-close body in each occupied column.
Definition chart.hpp:51
std::expected< std::optional< ModelRequest< T > >, TreeError > prepareChart(WidgetTree &tree, Node< Chart< T > > node, const ModelFrame< T > &frame, CellSize viewport, std::uint64_t first=0)
Prepare at most one domain bucket per viewport column between frames. Shares the caller's ModelFrame ...
Definition chart.hpp:349
RangeState
Observable asynchronous range readiness.
Definition model.hpp:45
@ PENDING
Data is not ready; reading must not block or start work.
Definition model.hpp:46
constexpr SizePolicy DEFAULT_VIEWPORT_POLICY
A bounded data viewport fills both axes without requesting the whole model extent.
Definition layout.hpp:53
ChartGlyphSet
Candle brushes; Unicode falls back to ASCII when the width policy requires wide symbols.
Definition chart.hpp:55
@ BOX_DRAWING
Thin wick, filled block body and horizontal doji, each exactly one cell.
Definition chart.hpp:57
@ ASCII
Portable vertical bar and hash brushes.
Definition chart.hpp:56
@ PAINT
Painting is required; arranged geometry remains usable.
Definition widget_types.hpp:43
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
@ INVALID_GEOMETRY
Required arranged geometry is absent or translation overflowed.
Definition widget_types.hpp:38
@ WOULD_BLOCK
The current frame/reentry boundary or finite queue/work budget rejects this operation.
Definition widget_types.hpp:32
An owning available extent in terminal columns/rows.
Definition geometry.hpp:44
CellSize normalized() const noexcept
Return an owning nonnegative extent; no errors or invalidation.
Small owning paint value, independent of themes and text metrics.
Definition cell_buffer.hpp:35
std::optional< RgbColor > background
Background RGB, or the terminal default when absent.
Definition cell_buffer.hpp:39
Owning chart settings, validated during preparation.
Definition chart.hpp:61
std::int32_t candle_gap
Nonnegative empty columns between candles; ignored in LINE mode.
Definition chart.hpp:71
CellStyle falling
Close < open candle style.
Definition chart.hpp:68
ChartGlyphSet glyph_set
Candle appearance; ASCII preserves the portable default.
Definition chart.hpp:70
ChartMode mode
Render closes or OHLC candles.
Definition chart.hpp:62
std::optional< ChartRange > y_range
Explicit finite scale, or automatic visible-only scale.
Definition chart.hpp:64
CellStyle line
Line and isolated point style.
Definition chart.hpp:66
WidthPolicy width_policy
Captured text policy; frame renderer must use the same policy.
Definition chart.hpp:69
CellStyle background
Clear the complete local viewport with this style.
Definition chart.hpp:65
CellStyle rising
Close >= open candle style.
Definition chart.hpp:67
Inclusive logical Y range, increasing upward. Equal endpoints center finite samples.
Definition chart.hpp:44
double minimum
Finite lower bound.
Definition chart.hpp:45
double maximum
Finite upper bound, not less than minimum.
Definition chart.hpp:46
Owning resolved presentation; no actions or model state are encoded.
Definition style_types.hpp:169
CellStyle normal
Ordinary text and fill.
Definition style_types.hpp:170
One domain bucket; finite values satisfy low <= open/close <= high.
Definition chart.hpp:14
double low
Minimum accepted tick.
Definition chart.hpp:17
double open
First accepted tick in the domain bucket.
Definition chart.hpp:15
double close
Last accepted tick.
Definition chart.hpp:18
double high
Maximum accepted tick.
Definition chart.hpp:16
Owning RGB color; terminal encoding belongs to the output adapter.
Definition cell_buffer.hpp:20
Half-open logical row interval; arithmetic is checked before provider access.
Definition model.hpp:35
Owning independent policies for width and height.
Definition layout.hpp:35
Owning deterministic width policy; no font or terminal matching promise.
Definition text.hpp:42