flywheel-compositor 0.1.1

A zero-flicker terminal compositor for Agentic CLIs
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
//! C Foreign Function Interface (FFI) for Flywheel.
//!
//! This module provides a C-compatible API for using Flywheel from
//! other programming languages. All functions are `extern "C"` with
//! stable ABI.
//!
//! # Safety
//!
//! All functions that accept pointers require valid, non-null pointers.
//! The caller is responsible for proper memory management of handles.
//!
//! # Example (C)
//!
//! ```c
//! #include "flywheel.h"
//!
//! int main() {
//!     FlywheelEngine* engine = flywheel_engine_new();
//!     if (!engine) return 1;
//!
//!     flywheel_engine_draw_text(engine, 0, 0, "Hello from C!", 0xFFFFFF, 0x000000);
//!     flywheel_engine_request_redraw(engine);
//!
//!     // Main loop...
//!
//!     flywheel_engine_destroy(engine);
//!     return 0;
//! }
//! ```

// FFI modules intentionally use unsafe and no_mangle
#![allow(unsafe_op_in_unsafe_fn)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]

use crate::actor::{Engine, InputEvent, KeyCode};
use crate::buffer::{Cell, Rgb};
use crate::layout::Rect;
use crate::widget::{AppendResult, StreamWidget};
use std::ffi::CStr;
use std::os::raw::{c_char, c_int, c_uint};
use std::ptr;

// =============================================================================
// Opaque Handle Types
// =============================================================================

/// Opaque handle to a Flywheel engine.
pub struct FlywheelEngine(Engine);

/// Opaque handle to a stream widget.
pub struct FlywheelStream(StreamWidget);

// =============================================================================
// Result and Error Codes
// =============================================================================

/// Result codes for FFI functions.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlywheelResult {
    /// Operation succeeded.
    Ok = 0,
    /// Null pointer passed.
    NullPointer = 1,
    /// Invalid UTF-8 string.
    InvalidUtf8 = 2,
    /// I/O error.
    IoError = 3,
    /// Out of bounds.
    OutOfBounds = 4,
    /// Engine not running.
    NotRunning = 5,
}

/// Input event type from polling.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlywheelEventType {
    /// No event available.
    None = 0,
    /// Key press event.
    Key = 1,
    /// Terminal resize event.
    Resize = 2,
    /// Error event.
    Error = 3,
    /// Shutdown event.
    Shutdown = 4,
}

/// Key event data.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct FlywheelKeyEvent {
    /// The character (for printable keys), or 0.
    pub char_code: u32,
    /// Special key code (see `FLYWHEEL_KEY_*` constants).
    pub key_code: c_int,
    /// Modifier flags.
    pub modifiers: c_uint,
}

/// Resize event data.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct FlywheelResizeEvent {
    /// New width.
    pub width: u16,
    /// New height.
    pub height: u16,
}

/// Polled event structure.
#[repr(C)]
pub struct FlywheelEvent {
    /// Event type.
    pub event_type: FlywheelEventType,
    /// Key event data (valid if `event_type` == Key).
    pub key: FlywheelKeyEvent,
    /// Resize event data (valid if `event_type` == Resize).
    pub resize: FlywheelResizeEvent,
}

// Key code constants
/// No special key.
pub const FLYWHEEL_KEY_NONE: c_int = 0;
/// Enter key.
pub const FLYWHEEL_KEY_ENTER: c_int = 1;
/// Escape key.
pub const FLYWHEEL_KEY_ESCAPE: c_int = 2;
/// Backspace key.
pub const FLYWHEEL_KEY_BACKSPACE: c_int = 3;
/// Tab key.
pub const FLYWHEEL_KEY_TAB: c_int = 4;
/// Left arrow.
pub const FLYWHEEL_KEY_LEFT: c_int = 5;
/// Right arrow.
pub const FLYWHEEL_KEY_RIGHT: c_int = 6;
/// Up arrow.
pub const FLYWHEEL_KEY_UP: c_int = 7;
/// Down arrow.
pub const FLYWHEEL_KEY_DOWN: c_int = 8;
/// Home key.
pub const FLYWHEEL_KEY_HOME: c_int = 9;
/// End key.
pub const FLYWHEEL_KEY_END: c_int = 10;
/// Page Up.
pub const FLYWHEEL_KEY_PAGE_UP: c_int = 11;
/// Page Down.
pub const FLYWHEEL_KEY_PAGE_DOWN: c_int = 12;
/// Delete key.
pub const FLYWHEEL_KEY_DELETE: c_int = 13;

// Modifier flags
/// Shift modifier.
pub const FLYWHEEL_MOD_SHIFT: c_uint = 1;
/// Control modifier.
pub const FLYWHEEL_MOD_CTRL: c_uint = 2;
/// Alt modifier.
pub const FLYWHEEL_MOD_ALT: c_uint = 4;
/// Super/Command modifier.
pub const FLYWHEEL_MOD_SUPER: c_uint = 8;

// =============================================================================
// Engine Functions
// =============================================================================

/// Create a new Flywheel engine with default configuration.
///
/// Returns NULL on failure.
#[unsafe(no_mangle)]
pub extern "C" fn flywheel_engine_new() -> *mut FlywheelEngine {
    Engine::new().map_or(
        ptr::null_mut(),
        |engine| Box::into_raw(Box::new(FlywheelEngine(engine)))
    )
}

/// Destroy a Flywheel engine.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_engine_destroy(engine: *mut FlywheelEngine) {
    if !engine.is_null() {
        drop(Box::from_raw(engine));
    }
}

/// Get the terminal width.
#[unsafe(no_mangle)]
pub const unsafe extern "C" fn flywheel_engine_width(engine: *const FlywheelEngine) -> u16 {
    if engine.is_null() {
        return 0;
    }
    (*engine).0.width()
}

/// Get the terminal height.
#[unsafe(no_mangle)]
pub const unsafe extern "C" fn flywheel_engine_height(engine: *const FlywheelEngine) -> u16 {
    if engine.is_null() {
        return 0;
    }
    (*engine).0.height()
}

/// Check if the engine is still running.
#[unsafe(no_mangle)]
pub const unsafe extern "C" fn flywheel_engine_is_running(engine: *const FlywheelEngine) -> bool {
    if engine.is_null() {
        return false;
    }
    (*engine).0.is_running()
}

/// Stop the engine.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_engine_stop(engine: *mut FlywheelEngine) {
    if !engine.is_null() {
        (*engine).0.stop();
    }
}

/// Poll for the next input event.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_engine_poll_event(
    engine: *const FlywheelEngine,
    event_out: *mut FlywheelEvent,
) -> FlywheelEventType {
    if engine.is_null() || event_out.is_null() {
        return FlywheelEventType::None;
    }

    match (*engine).0.poll_input() {
        Some(InputEvent::Key { code, modifiers }) => {
            let (char_code, key_code) = convert_key_code(code);
            let mods = convert_modifiers(modifiers);

            (*event_out).event_type = FlywheelEventType::Key;
            (*event_out).key = FlywheelKeyEvent {
                char_code,
                key_code,
                modifiers: mods,
            };
            FlywheelEventType::Key
        }
        Some(InputEvent::Resize { width, height }) => {
            (*event_out).event_type = FlywheelEventType::Resize;
            (*event_out).resize = FlywheelResizeEvent { width, height };
            FlywheelEventType::Resize
        }
        Some(InputEvent::Shutdown) => {
            (*event_out).event_type = FlywheelEventType::Shutdown;
            FlywheelEventType::Shutdown
        }
        Some(InputEvent::Error(_)) => {
            (*event_out).event_type = FlywheelEventType::Error;
            FlywheelEventType::Error
        }
        _ => {
            (*event_out).event_type = FlywheelEventType::None;
            FlywheelEventType::None
        }
    }
}

/// Handle a resize event.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_engine_handle_resize(
    engine: *mut FlywheelEngine,
    width: u16,
    height: u16,
) {
    if !engine.is_null() {
        (*engine).0.handle_resize(width, height);
    }
}

/// Request a full redraw.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_engine_request_redraw(engine: *const FlywheelEngine) {
    if !engine.is_null() {
        (*engine).0.request_redraw();
    }
}

/// Request a diff-based update.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_engine_request_update(engine: *const FlywheelEngine) {
    if !engine.is_null() {
        (*engine).0.request_update();
    }
}

/// Begin a new frame.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_engine_begin_frame(engine: *mut FlywheelEngine) {
    if !engine.is_null() {
        (*engine).0.begin_frame();
    }
}

/// End a frame and request update.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_engine_end_frame(engine: *mut FlywheelEngine) {
    if !engine.is_null() {
        (*engine).0.end_frame();
    }
}

/// Set a cell at the given position.
#[unsafe(no_mangle)]
#[allow(clippy::cast_sign_loss)] // c_char may be signed
pub unsafe extern "C" fn flywheel_engine_set_cell(
    engine: *mut FlywheelEngine,
    x: u16,
    y: u16,
    c: c_char,
    fg: u32,
    bg: u32,
) {
    if engine.is_null() {
        return;
    }
    let cell = Cell::new(c as u8 as char)
        .with_fg(Rgb::from_u32(fg))
        .with_bg(Rgb::from_u32(bg));
    (*engine).0.set_cell(x, y, cell);
}

/// Draw text at the given position.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_engine_draw_text(
    engine: *mut FlywheelEngine,
    x: u16,
    y: u16,
    text: *const c_char,
    fg: u32,
    bg: u32,
) -> u16 {
    if engine.is_null() || text.is_null() {
        return 0;
    }

    let Ok(text_str) = CStr::from_ptr(text).to_str() else {
        return 0;
    };

    (*engine)
        .0
        .draw_text(x, y, text_str, Rgb::from_u32(fg), Rgb::from_u32(bg))
}

/// Clear the entire buffer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_engine_clear(engine: *mut FlywheelEngine) {
    if !engine.is_null() {
        (*engine).0.clear();
    }
}

/// Fill a rectangle with a character.
#[unsafe(no_mangle)]
#[allow(clippy::cast_sign_loss)] // c_char may be signed
pub unsafe extern "C" fn flywheel_engine_fill_rect(
    engine: *mut FlywheelEngine,
    x: u16,
    y: u16,
    width: u16,
    height: u16,
    c: c_char,
    fg: u32,
    bg: u32,
) {
    if engine.is_null() {
        return;
    }
    let cell = Cell::new(c as u8 as char)
        .with_fg(Rgb::from_u32(fg))
        .with_bg(Rgb::from_u32(bg));
    (*engine).0.fill_rect(Rect::new(x, y, width, height), cell);
}

// =============================================================================
// Stream Widget Functions
// =============================================================================

/// Create a new stream widget.
#[unsafe(no_mangle)]
pub extern "C" fn flywheel_stream_new(x: u16, y: u16, width: u16, height: u16) -> *mut FlywheelStream {
    let widget = StreamWidget::new(Rect::new(x, y, width, height));
    Box::into_raw(Box::new(FlywheelStream(widget)))
}

/// Destroy a stream widget.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_stream_destroy(stream: *mut FlywheelStream) {
    if !stream.is_null() {
        drop(Box::from_raw(stream));
    }
}

/// Append text to the stream widget.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_stream_append(
    stream: *mut FlywheelStream,
    text: *const c_char,
) -> c_int {
    if stream.is_null() || text.is_null() {
        return -1;
    }

    let Ok(text_str) = CStr::from_ptr(text).to_str() else {
        return -1;
    };

    match (*stream).0.append(text_str) {
        AppendResult::FastPath { .. } => 1,
        AppendResult::SlowPath { .. } | AppendResult::Empty => 0,
    }
}

/// Render the stream widget to the engine's buffer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_stream_render(
    stream: *mut FlywheelStream,
    engine: *mut FlywheelEngine,
) {
    if stream.is_null() || engine.is_null() {
        return;
    }
    (*stream).0.render((*engine).0.buffer_mut());
}

/// Clear the stream widget content.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_stream_clear(stream: *mut FlywheelStream) {
    if !stream.is_null() {
        (*stream).0.clear();
    }
}

/// Set the foreground color for subsequent text.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_stream_set_fg(stream: *mut FlywheelStream, color: u32) {
    if !stream.is_null() {
        (*stream).0.set_fg(Rgb::from_u32(color));
    }
}

/// Set the background color for subsequent text.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_stream_set_bg(stream: *mut FlywheelStream, color: u32) {
    if !stream.is_null() {
        (*stream).0.set_bg(Rgb::from_u32(color));
    }
}

/// Scroll the stream widget up.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_stream_scroll_up(stream: *mut FlywheelStream, lines: usize) {
    if !stream.is_null() {
        (*stream).0.scroll_up(lines);
    }
}

/// Scroll the stream widget down.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn flywheel_stream_scroll_down(stream: *mut FlywheelStream, lines: usize) {
    if !stream.is_null() {
        (*stream).0.scroll_down(lines);
    }
}

// =============================================================================
// Color Utilities
// =============================================================================

/// Create an RGB color from components.
#[unsafe(no_mangle)]
#[allow(clippy::cast_lossless)]
pub const extern "C" fn flywheel_rgb(r: u8, g: u8, b: u8) -> u32 {
    ((r as u32) << 16) | ((g as u32) << 8) | (b as u32)
}

// =============================================================================
// Version Information
// =============================================================================

/// Get the Flywheel version string.
#[unsafe(no_mangle)]
pub extern "C" fn flywheel_version() -> *const c_char {
    static VERSION: &[u8] = b"0.1.0\0";
    VERSION.as_ptr().cast::<c_char>()
}

// =============================================================================
// Helper Functions
// =============================================================================

const fn convert_key_code(code: KeyCode) -> (u32, c_int) {
    match code {
        KeyCode::Char(c) => (c as u32, FLYWHEEL_KEY_NONE),
        KeyCode::Enter => (0, FLYWHEEL_KEY_ENTER),
        KeyCode::Esc => (0, FLYWHEEL_KEY_ESCAPE),
        KeyCode::Backspace => (0, FLYWHEEL_KEY_BACKSPACE),
        KeyCode::Tab => (0, FLYWHEEL_KEY_TAB),
        KeyCode::Left => (0, FLYWHEEL_KEY_LEFT),
        KeyCode::Right => (0, FLYWHEEL_KEY_RIGHT),
        KeyCode::Up => (0, FLYWHEEL_KEY_UP),
        KeyCode::Down => (0, FLYWHEEL_KEY_DOWN),
        KeyCode::Home => (0, FLYWHEEL_KEY_HOME),
        KeyCode::End => (0, FLYWHEEL_KEY_END),
        KeyCode::PageUp => (0, FLYWHEEL_KEY_PAGE_UP),
        KeyCode::PageDown => (0, FLYWHEEL_KEY_PAGE_DOWN),
        KeyCode::Delete => (0, FLYWHEEL_KEY_DELETE),
        _ => (0, FLYWHEEL_KEY_NONE),
    }
}

const fn convert_modifiers(mods: crate::actor::KeyModifiers) -> c_uint {
    let mut result = 0;
    if mods.shift {
        result |= FLYWHEEL_MOD_SHIFT;
    }
    if mods.control {
        result |= FLYWHEEL_MOD_CTRL;
    }
    if mods.alt {
        result |= FLYWHEEL_MOD_ALT;
    }
    if mods.super_key {
        result |= FLYWHEEL_MOD_SUPER;
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_flywheel_rgb() {
        assert_eq!(flywheel_rgb(255, 128, 64), 0xFF8040);
        assert_eq!(flywheel_rgb(0, 0, 0), 0x000000);
        assert_eq!(flywheel_rgb(255, 255, 255), 0xFFFFFF);
    }

    #[test]
    fn test_flywheel_version() {
        unsafe {
            let version = flywheel_version();
            let version_str = CStr::from_ptr(version).to_str().unwrap();
            assert_eq!(version_str, "0.1.0");
        }
    }
}