ratatui_ffi 0.2.6

C ABI bindings for Ratatui (Rust TUI) to consume from C/C#/etc.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
// Widget split placeholder: Chart
// Move from src/lib.rs:
// - FFI externs: ratatui_chart_new, ratatui_chart_free
// - Adders: ratatui_chart_add_line, ratatui_chart_add_dataset_with_type, ratatui_chart_add_datasets
// - Setters: ratatui_chart_set_axes_titles, ratatui_chart_set_bounds, ratatui_chart_set_legend_position,
//            ratatui_chart_set_hidden_legend_constraints, ratatui_chart_set_axis_styles,
//            ratatui_chart_set_x_labels_spans, ratatui_chart_set_y_labels_spans,
//            ratatui_chart_set_labels_alignment
// - Block helpers (macros invoked here):
//   ratatui_block_title_fn!(ratatui_chart_set_block_title, FfiChart)
//   ratatui_block_title_spans_fn!(ratatui_chart_set_block_title_spans, FfiChart)
//   ratatui_block_adv_fn!(ratatui_chart_set_block_adv, FfiChart)
// - Draw helpers: ratatui_terminal_draw_chart_in, ratatui_headless_render_chart
// Types used: FfiChart, FfiChartDataset, FfiChartDatasetSpec

// use crate::*; // enable when moving implementations

use crate::{
    ratatui_block_adv_fn, ratatui_block_title_fn, ratatui_block_title_spans_fn,
    ratatui_set_style_fn, FfiLineSpans, FfiRect, FfiStyle, FfiTerminal,
};
use ratatui::buffer::Buffer;
use ratatui::layout::{Alignment, Constraint, Rect};
use ratatui::prelude::{Line, Style};
use ratatui::widgets::{
    Axis as RtAxis, Block, Chart as RtChart, Dataset as RtDataset, GraphType as RtGraphType,
    LegendPosition as RtLegendPosition,
};
use std::ffi::{c_char, CStr, CString};

#[repr(C)]
pub struct FfiChartDataset {
    pub name: String,
    pub points: Vec<(f64, f64)>,
    pub style: Option<Style>,
    pub kind: u32,
}

#[repr(C)]
pub struct FfiChartDatasetSpec {
    pub name_utf8: *const c_char,
    pub points_xy: *const f64,
    pub len_pairs: usize,
    pub style: FfiStyle,
    pub kind: u32,
}

#[repr(C)]
pub struct FfiChart {
    pub datasets: Vec<FfiChartDataset>,
    pub x_title: Option<String>,
    pub y_title: Option<String>,
    pub block: Option<Block<'static>>,
    pub x_min: Option<f64>,
    pub x_max: Option<f64>,
    pub y_min: Option<f64>,
    pub y_max: Option<f64>,
    pub legend_pos: Option<u32>,
    pub hidden_legend_kinds: Option<[u32; 2]>,
    pub hidden_legend_values: Option<[u16; 2]>,
    pub chart_style: Option<Style>,
    pub x_axis_style: Option<Style>,
    pub y_axis_style: Option<Style>,
    pub x_labels: Option<Vec<Line<'static>>>,
    pub y_labels: Option<Vec<Line<'static>>>,
    pub x_labels_align: Option<Alignment>,
    pub y_labels_align: Option<Alignment>,
}

// ----- Chart -----

ratatui_set_style_fn!(ratatui_chart_set_style, FfiChart, chart_style);
ratatui_block_title_fn!(ratatui_chart_set_block_title, FfiChart);
ratatui_block_title_spans_fn!(ratatui_chart_set_block_title_spans, FfiChart);
ratatui_block_adv_fn!(ratatui_chart_set_block_adv, FfiChart);

#[no_mangle]
pub extern "C" fn ratatui_chart_new() -> *mut FfiChart {
    Box::into_raw(Box::new(FfiChart {
        datasets: Vec::new(),
        x_title: None,
        y_title: None,
        block: None,
        x_min: None,
        x_max: None,
        y_min: None,
        y_max: None,
        legend_pos: None,
        hidden_legend_kinds: None,
        hidden_legend_values: None,
        chart_style: None,
        x_axis_style: None,
        y_axis_style: None,
        x_labels: None,
        y_labels: None,
        x_labels_align: None,
        y_labels_align: None,
    }))
}

#[no_mangle]
pub extern "C" fn ratatui_chart_free(c: *mut FfiChart) {
    if c.is_null() {
        return;
    }
    unsafe {
        drop(Box::from_raw(c));
    }
}

#[no_mangle]
pub extern "C" fn ratatui_chart_add_line(
    c: *mut FfiChart,
    name_utf8: *const c_char,
    points_xy: *const f64,
    len_pairs: usize,
    style: FfiStyle,
) {
    if c.is_null() {
        return;
    }
    let ch = unsafe { &mut *c };
    let name = if name_utf8.is_null() {
        String::new()
    } else {
        unsafe { CStr::from_ptr(name_utf8) }
            .to_str()
            .unwrap_or("")
            .to_string()
    };
    let sty = crate::style_from_ffi(style);
    let pts = if points_xy.is_null() || len_pairs == 0 {
        Vec::new()
    } else {
        let slice = unsafe { std::slice::from_raw_parts(points_xy, len_pairs * 2) };
        let mut pts = Vec::with_capacity(len_pairs);
        for i in 0..len_pairs {
            pts.push((slice[i * 2], slice[i * 2 + 1]));
        }
        pts
    };
    ch.datasets.push(FfiChartDataset {
        name,
        points: pts,
        style: Some(sty),
        kind: 0,
    });
}

#[no_mangle]
pub extern "C" fn ratatui_chart_add_dataset_with_type(
    c: *mut FfiChart,
    name_utf8: *const c_char,
    points_xy: *const f64,
    len_pairs: usize,
    style: FfiStyle,
    kind: u32,
) {
    if c.is_null() {
        return;
    }
    let ch = unsafe { &mut *c };
    let name = if name_utf8.is_null() {
        String::new()
    } else {
        unsafe { CStr::from_ptr(name_utf8) }
            .to_str()
            .unwrap_or("")
            .to_string()
    };
    let sty = crate::style_from_ffi(style);
    let pts = if points_xy.is_null() || len_pairs == 0 {
        Vec::new()
    } else {
        let slice = unsafe { std::slice::from_raw_parts(points_xy, len_pairs * 2) };
        let mut pts = Vec::with_capacity(len_pairs);
        for i in 0..len_pairs {
            pts.push((slice[i * 2], slice[i * 2 + 1]));
        }
        pts
    };
    ch.datasets.push(FfiChartDataset {
        name,
        points: pts,
        style: Some(sty),
        kind,
    });
}

#[no_mangle]
pub extern "C" fn ratatui_chart_add_datasets(
    c: *mut FfiChart,
    specs: *const FfiChartDatasetSpec,
    len: usize,
) {
    if c.is_null() || specs.is_null() || len == 0 {
        return;
    }
    let ch = unsafe { &mut *c };
    let slice = unsafe { std::slice::from_raw_parts(specs, len) };
    for s in slice.iter() {
        let name = if s.name_utf8.is_null() {
            String::new()
        } else {
            unsafe { CStr::from_ptr(s.name_utf8) }
                .to_str()
                .unwrap_or("")
                .to_string()
        };
        let pts = if s.points_xy.is_null() || s.len_pairs == 0 {
            Vec::new()
        } else {
            let slice2 = unsafe { std::slice::from_raw_parts(s.points_xy, s.len_pairs * 2) };
            let mut pts = Vec::with_capacity(s.len_pairs);
            for i in 0..s.len_pairs {
                pts.push((slice2[i * 2], slice2[i * 2 + 1]));
            }
            pts
        };
        ch.datasets.push(FfiChartDataset {
            name,
            points: pts,
            style: Some(crate::style_from_ffi(s.style)),
            kind: s.kind,
        });
    }
}

#[no_mangle]
pub extern "C" fn ratatui_chart_set_axes_titles(
    c: *mut FfiChart,
    x_utf8: *const c_char,
    y_utf8: *const c_char,
) {
    if c.is_null() {
        return;
    }
    let ch = unsafe { &mut *c };
    ch.x_title = if x_utf8.is_null() {
        None
    } else {
        unsafe { CStr::from_ptr(x_utf8) }
            .to_str()
            .ok()
            .map(|s| s.to_string())
    };
    ch.y_title = if y_utf8.is_null() {
        None
    } else {
        unsafe { CStr::from_ptr(y_utf8) }
            .to_str()
            .ok()
            .map(|s| s.to_string())
    };
}

#[no_mangle]
pub extern "C" fn ratatui_chart_set_bounds(
    c: *mut FfiChart,
    x_min: f64,
    x_max: f64,
    y_min: f64,
    y_max: f64,
) {
    if c.is_null() {
        return;
    }
    let ch = unsafe { &mut *c };
    ch.x_min = Some(x_min);
    ch.x_max = Some(x_max);
    ch.y_min = Some(y_min);
    ch.y_max = Some(y_max);
}

#[no_mangle]
pub extern "C" fn ratatui_chart_set_legend_position(c: *mut FfiChart, pos: u32) {
    if c.is_null() {
        return;
    }
    let ch = unsafe { &mut *c };
    ch.legend_pos = Some(pos);
}

#[no_mangle]
pub extern "C" fn ratatui_chart_set_hidden_legend_constraints(
    c: *mut FfiChart,
    kinds2: *const u32,
    values2: *const u16,
) {
    if c.is_null() || kinds2.is_null() || values2.is_null() {
        return;
    }
    let ch = unsafe { &mut *c };
    let kinds = unsafe { std::slice::from_raw_parts(kinds2, 2) };
    let vals = unsafe { std::slice::from_raw_parts(values2, 2) };
    ch.hidden_legend_kinds = Some([kinds[0], kinds[1]]);
    ch.hidden_legend_values = Some([vals[0], vals[1]]);
}

#[no_mangle]
pub extern "C" fn ratatui_chart_set_axis_styles(
    c: *mut FfiChart,
    x_style: FfiStyle,
    y_style: FfiStyle,
) {
    if c.is_null() {
        return;
    }
    let ch = unsafe { &mut *c };
    ch.x_axis_style = Some(crate::style_from_ffi(x_style));
    ch.y_axis_style = Some(crate::style_from_ffi(y_style));
}

#[no_mangle]
pub extern "C" fn ratatui_chart_set_x_labels_spans(
    c: *mut FfiChart,
    labels: *const FfiLineSpans,
    len: usize,
) {
    if c.is_null() {
        return;
    }
    let ch = unsafe { &mut *c };
    if labels.is_null() || len == 0 {
        ch.x_labels = None;
        return;
    }
    let slice = unsafe { std::slice::from_raw_parts(labels, len) };
    let mut lines: Vec<Line<'static>> = Vec::with_capacity(len);
    for ls in slice.iter() {
        if ls.spans.is_null() || ls.len == 0 {
            lines.push(Line::default());
            continue;
        }
        if let Some(sp) = crate::spans_from_ffi(ls.spans, ls.len) {
            lines.push(Line::from(sp));
        } else {
            lines.push(Line::default());
        }
    }
    ch.x_labels = Some(lines);
}

#[no_mangle]
pub extern "C" fn ratatui_chart_set_y_labels_spans(
    c: *mut FfiChart,
    labels: *const FfiLineSpans,
    len: usize,
) {
    if c.is_null() {
        return;
    }
    let ch = unsafe { &mut *c };
    if labels.is_null() || len == 0 {
        ch.y_labels = None;
        return;
    }
    let slice = unsafe { std::slice::from_raw_parts(labels, len) };
    let mut lines: Vec<Line<'static>> = Vec::with_capacity(len);
    for ls in slice.iter() {
        if ls.spans.is_null() || ls.len == 0 {
            lines.push(Line::default());
            continue;
        }
        if let Some(sp) = crate::spans_from_ffi(ls.spans, ls.len) {
            lines.push(Line::from(sp));
        } else {
            lines.push(Line::default());
        }
    }
    ch.y_labels = Some(lines);
}

#[no_mangle]
pub extern "C" fn ratatui_terminal_draw_chart_in(
    term: *mut FfiTerminal,
    c: *const FfiChart,
    rect: FfiRect,
) -> bool {
    crate::guard_bool("ratatui_terminal_draw_chart_in", || {
        if term.is_null() || c.is_null() {
            return false;
        }
        let t = unsafe { &mut *term };
        let ch = unsafe { &*c };
        let area = Rect {
            x: rect.x,
            y: rect.y,
            width: rect.width,
            height: rect.height,
        };
        let mut datasets: Vec<RtDataset> = Vec::new();
        for ds in &ch.datasets {
            let mut d = RtDataset::default().name(ds.name.clone()).data(&ds.points);
            if let Some(sty) = &ds.style {
                d = d.style(sty.clone());
            }
            d = d.graph_type(match ds.kind {
                1 => RtGraphType::Bar,
                2 => RtGraphType::Scatter,
                _ => RtGraphType::Line,
            });
            datasets.push(d);
        }
        let mut w = RtChart::new(datasets);
        let mut x_axis = RtAxis::default();
        let mut y_axis = RtAxis::default();
        if let Some(ti) = &ch.x_title {
            x_axis = x_axis.title(ti.clone());
        }
        if let Some(ti) = &ch.y_title {
            y_axis = y_axis.title(ti.clone());
        }
        if let (Some(min), Some(max)) = (ch.x_min, ch.x_max) {
            x_axis = x_axis.bounds([min, max]);
        }
        if let (Some(min), Some(max)) = (ch.y_min, ch.y_max) {
            y_axis = y_axis.bounds([min, max]);
        }
        if let Some(lbls) = &ch.x_labels {
            x_axis = x_axis.labels(lbls.clone());
        }
        if let Some(lbls) = &ch.y_labels {
            y_axis = y_axis.labels(lbls.clone());
        }
        if let Some(al) = ch.x_labels_align {
            x_axis = x_axis.labels_alignment(al);
        }
        if let Some(al) = ch.y_labels_align {
            y_axis = y_axis.labels_alignment(al);
        }
        w = w.x_axis(x_axis).y_axis(y_axis);
        if let Some(lp) = ch.legend_pos {
            w = w.legend_position(Some(match lp {
                1 => RtLegendPosition::Top,
                2 => RtLegendPosition::Bottom,
                3 => RtLegendPosition::Left,
                4 => RtLegendPosition::Right,
                5 => RtLegendPosition::TopLeft,
                6 => RtLegendPosition::TopRight,
                7 => RtLegendPosition::BottomLeft,
                8 => RtLegendPosition::BottomRight,
                _ => RtLegendPosition::Right,
            }));
        }
        if let (Some(k), Some(v)) = (ch.hidden_legend_kinds, ch.hidden_legend_values) {
            let to_cons = |kind: u32, val: u16| -> Constraint {
                match kind {
                    1 => Constraint::Percentage(val),
                    2 => Constraint::Min(val),
                    _ => Constraint::Length(val),
                }
            };
            w = w.hidden_legend_constraints([to_cons(k[0], v[0]), to_cons(k[1], v[1])].into());
        }
        if let Some(b) = &ch.block {
            w = w.block(b.clone());
        }
        let res = t.terminal.draw(|frame| {
            frame.render_widget(w.clone(), area);
        });
        res.is_ok()
    })
}

#[no_mangle]
pub extern "C" fn ratatui_headless_render_chart(
    width: u16,
    height: u16,
    c: *const FfiChart,
    out_text_utf8: *mut *mut c_char,
) -> bool {
    if c.is_null() || out_text_utf8.is_null() {
        return false;
    }
    let ch = unsafe { &*c };
    let area = Rect {
        x: 0,
        y: 0,
        width,
        height,
    };
    let mut buf = Buffer::empty(area);
    let mut datasets: Vec<RtDataset> = Vec::new();
    for ds in &ch.datasets {
        let mut d = RtDataset::default().name(ds.name.clone()).data(&ds.points);
        if let Some(sty) = &ds.style {
            d = d.style(sty.clone());
        }
        d = d.graph_type(match ds.kind {
            1 => RtGraphType::Bar,
            2 => RtGraphType::Scatter,
            _ => RtGraphType::Line,
        });
        datasets.push(d);
    }
    let mut w = RtChart::new(datasets);
    let mut x_axis = RtAxis::default();
    let mut y_axis = RtAxis::default();
    if let Some(ti) = &ch.x_title {
        x_axis = x_axis.title(ti.clone());
    }
    if let Some(ti) = &ch.y_title {
        y_axis = y_axis.title(ti.clone());
    }
    if let Some(st) = &ch.x_axis_style {
        x_axis = x_axis.style(st.clone());
    }
    if let Some(st) = &ch.y_axis_style {
        y_axis = y_axis.style(st.clone());
    }
    if let (Some(min), Some(max)) = (ch.x_min, ch.x_max) {
        x_axis = x_axis.bounds([min, max]);
    }
    if let (Some(min), Some(max)) = (ch.y_min, ch.y_max) {
        y_axis = y_axis.bounds([min, max]);
    }
    if let Some(lbls) = &ch.x_labels {
        x_axis = x_axis.labels(lbls.clone());
    }
    if let Some(lbls) = &ch.y_labels {
        y_axis = y_axis.labels(lbls.clone());
    }
    if let Some(al) = ch.x_labels_align {
        x_axis = x_axis.labels_alignment(al);
    }
    if let Some(al) = ch.y_labels_align {
        y_axis = y_axis.labels_alignment(al);
    }
    w = w.x_axis(x_axis).y_axis(y_axis);
    if let Some(lp) = ch.legend_pos {
        w = w.legend_position(Some(match lp {
            1 => RtLegendPosition::Top,
            2 => RtLegendPosition::Bottom,
            3 => RtLegendPosition::Left,
            4 => RtLegendPosition::Right,
            5 => RtLegendPosition::TopLeft,
            6 => RtLegendPosition::TopRight,
            7 => RtLegendPosition::BottomLeft,
            8 => RtLegendPosition::BottomRight,
            _ => RtLegendPosition::Right,
        }));
    }
    if let (Some(k), Some(v)) = (ch.hidden_legend_kinds, ch.hidden_legend_values) {
        let to_cons = |kind: u32, val: u16| -> Constraint {
            match kind {
                1 => Constraint::Percentage(val),
                2 => Constraint::Min(val),
                _ => Constraint::Length(val),
            }
        };
        w = w.hidden_legend_constraints([to_cons(k[0], v[0]), to_cons(k[1], v[1])].into());
    }
    if let Some(b) = &ch.block {
        w = w.block(b.clone());
    }
    if let Some(st) = &ch.chart_style {
        w = w.style(st.clone());
    }
    ratatui::widgets::Widget::render(w, area, &mut buf);
    let mut s = String::new();
    for y in 0..height {
        for x in 0..width {
            let cell = &buf[(x, y)];
            s.push_str(cell.symbol());
        }
        if y + 1 < height {
            s.push('\n');
        }
    }
    match CString::new(s) {
        Ok(cstr) => {
            unsafe {
                *out_text_utf8 = cstr.into_raw();
            }
            true
        }
        Err(_) => false,
    }
}