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
use crate::app::widget::first_window;
use crate::enums::{Event, Key, Shortcut};
use crate::prelude::*;
use fltk_sys::fl;
use std::{
    cmp,
    ffi::{CStr, CString},
    mem,
    os::raw,
    panic,
};

/// Alias Window ptr
pub type WindowPtr = *mut fltk_sys::window::Fl_Window;

/// Returns the latest captured event
pub fn event() -> Event {
    unsafe { mem::transmute(fl::Fl_event()) }
}

/// Returns the presed key
pub fn event_key() -> Key {
    unsafe { mem::transmute(fl::Fl_event_key()) }
}

/// Returns the original key
pub fn event_original_key() -> Key {
    unsafe { mem::transmute(fl::Fl_event_original_key()) }
}

/// Returns whether the  key is pressed or held down during the last event
pub fn event_key_down(key: Key) -> bool {
    unsafe { fl::Fl_event_key_down(mem::transmute(key)) != 0 }
}

/// Returns a textual representation of the latest event
pub fn event_text() -> String {
    unsafe {
        let text = fl::Fl_event_text();
        if text.is_null() {
            String::from("")
        } else {
            CStr::from_ptr(text as *mut raw::c_char)
                .to_string_lossy()
                .to_string()
        }
    }
}

/// Returns the captured button event.
/// 1 for left key, 2 for middle, 3 for right
pub fn event_button() -> i32 {
    unsafe { fl::Fl_event_button() }
}

/// Defines Mouse buttons
#[repr(i32)]
#[derive(Debug, Copy, Clone, PartialEq)]
#[non_exhaustive]
pub enum MouseButton {
    /// Left mouse button
    Left = 1,
    /// Middle mouse button
    Middle = 2,
    /// Right mouse button
    Right = 3,
}

/// Returns the captured button event
pub fn event_mouse_button() -> MouseButton {
    unsafe { mem::transmute(fl::Fl_event_button()) }
}

/// Returns false for a single click and true for more
pub fn event_clicks() -> bool {
    unsafe { fl::Fl_event_clicks() != 0 }
}

/// Returns the number of clicks - 1
pub fn event_clicks_num() -> i32 {
    unsafe { fl::Fl_event_clicks() }
}

/// Gets the x coordinate of the mouse in the window
pub fn event_x() -> i32 {
    unsafe { fl::Fl_event_x() }
}

/// Gets the y coordinate of the mouse in the window
pub fn event_y() -> i32 {
    unsafe { fl::Fl_event_y() }
}

/// Gets the x coordinate of the mouse in the screen
pub fn event_x_root() -> i32 {
    unsafe { fl::Fl_event_x_root() }
}

/// Gets the y coordinate of the mouse in the screen
pub fn event_y_root() -> i32 {
    unsafe { fl::Fl_event_y_root() }
}

/// Event direction with Mousewheel event
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MouseWheel {
    /// No movement
    None,
    /// Right movement
    Right,
    /// Left movement
    Left,
    /// Up movement
    Up,
    /// Down movement
    Down,
}

/// Returns the current horizontal mouse scrolling associated with the Mousewheel event.
/// Returns `MouseWheel::None`, `Right` or `Left`
pub fn event_dx() -> MouseWheel {
    match 0.cmp(unsafe { &fl::Fl_event_dx() }) {
        cmp::Ordering::Greater => MouseWheel::Right,
        cmp::Ordering::Equal => MouseWheel::None,
        cmp::Ordering::Less => MouseWheel::Left,
    }
}

/// Returns the current horizontal mouse scrolling associated with the Mousewheel event.
/// Returns `MouseWheel::None`, `Up` or `Down`.
/// Doesn't indicate scrolling direction which depends on system preferences
pub fn event_dy() -> MouseWheel {
    match 0.cmp(unsafe { &fl::Fl_event_dy() }) {
        cmp::Ordering::Greater => MouseWheel::Down,
        cmp::Ordering::Equal => MouseWheel::None,
        cmp::Ordering::Less => MouseWheel::Up,
    }
}

/// Returns the x and y coordinates of the captured event
pub fn event_coords() -> (i32, i32) {
    unsafe { (fl::Fl_event_x(), fl::Fl_event_y()) }
}

/// Determines whether an event was a click
pub fn event_is_click() -> bool {
    unsafe { fl::Fl_event_is_click() != 0 }
}

/// Returns the duration of an event
pub fn event_length() -> i32 {
    unsafe { fl::Fl_event_length() as i32 }
}

/// Returns the state of the event
pub fn event_state() -> Shortcut {
    unsafe { mem::transmute(fl::Fl_event_state()) }
}

/// Returns whether an event occured within a widget
pub fn event_inside_widget<Wid: WidgetExt>(wid: &Wid) -> bool {
    assert!(!wid.was_deleted());
    let x = wid.x();
    let y = wid.y();
    let w = wid.width();
    let h = wid.height();
    unsafe { fl::Fl_event_inside(x, y, w, h) != 0 }
}

/// Returns whether an event occured within a region
pub fn event_inside(x: i32, y: i32, w: i32, h: i32) -> bool {
    unsafe { fl::Fl_event_inside(x, y, w, h) != 0 }
}

/**
    Gets the widget that is below the mouse cursor.
    This returns an Option<impl WidgetExt> which can be specified in the function call
    ```rust,no_run
    use fltk::app;
    use fltk::widget;
    let w = app::belowmouse::<widget::Widget>(); // or by specifying a more concrete type
    ```
*/
pub fn belowmouse<Wid: WidgetExt>() -> Option<impl WidgetExt> {
    unsafe {
        let x = fl::Fl_belowmouse() as *mut fltk_sys::fl::Fl_Widget;
        if x.is_null() {
            None
        } else {
            Some(crate::widget::Widget::from_widget_ptr(
                x as *mut fltk_sys::widget::Fl_Widget,
            ))
        }
    }
}

/// Returns whether the event is a shift press
pub fn is_event_shift() -> bool {
    unsafe { fl::Fl_event_shift() != 0 }
}

/// Returns whether the event is a control key press
pub fn is_event_ctrl() -> bool {
    unsafe { fl::Fl_event_ctrl() != 0 }
}

/// Returns whether the event is a command key press
pub fn is_event_command() -> bool {
    unsafe { fl::Fl_event_command() != 0 }
}

/// Returns whether the event is a alt key press
pub fn is_event_alt() -> bool {
    unsafe { fl::Fl_event_alt() != 0 }
}

/// Initiate dnd action
pub fn dnd() {
    unsafe {
        fl::Fl_dnd();
    }
}

/// Get the clipboard content if it's an image
pub fn event_clipboard_image() -> Option<crate::image::RgbImage> {
    unsafe {
        let image = fl::Fl_event_clipboard();
        if image.is_null() {
            None
        } else {
            use std::sync::atomic::AtomicUsize;
            Some(crate::image::RgbImage {
                inner: image as _,
                refcount: AtomicUsize::new(1),
            })
        }
    }
}

/// The event clipboard type
#[derive(Debug, Clone)]
pub enum ClipboardEvent {
    /// Text paste event
    Text(String),
    /// image paste event
    Image(Option<crate::image::RgbImage>),
}

/// Get the clipboard content type
pub fn event_clipboard() -> Option<ClipboardEvent> {
    unsafe {
        let txt = fl::Fl_event_clipboard_type();
        let txt = CStr::from_ptr(txt).to_string_lossy().to_string();
        if txt == "text/plain" {
            Some(ClipboardEvent::Text(event_text()))
        } else if txt == "image" {
            Some(ClipboardEvent::Image(event_clipboard_image()))
        } else {
            None
        }
    }
}

#[allow(clippy::missing_safety_doc)]
/**
    Send a signal to a window pointer from event_dispatch.
    Returns true if the event was handled.
    Returns false if the event was not handled or ignored.
    ```rust,no_run
    use fltk::{prelude::*, *};
    const CHANGE_FRAME: i32 = 100;
    let mut wind = window::Window::default();
    let mut but = button::Button::default();
    let mut frame = frame::Frame::default();
    wind.end();
    wind.show();
    but.set_callback(move |_| {
        let _ = app::handle_main(CHANGE_FRAME).unwrap();
    });

    frame.handle(move |f, ev| {
        if ev == CHANGE_FRAME.into() {
            f.set_label("Hello world");
            true
        } else {
            false
        }
    });
    unsafe {
        app::event_dispatch(|ev, winptr| {
            if ev == CHANGE_FRAME.into() {
                false // ignore CHANGE_FRAME event
            } else {
                app::handle_raw(ev, winptr)
            }
        });
    }
    ```
    # Safety
    The window pointer must be valid
*/
pub unsafe fn handle_raw(event: Event, w: WindowPtr) -> bool {
    fl::Fl_handle_(event.bits(), w as _) != 0
}

#[allow(clippy::missing_safety_doc)]
/**
    The event dispatch function is called after native events are converted to
    FLTK events, but before they are handled by FLTK. If the dispatch function
    handler is set, it is up to the dispatch function to call
    `app::handle2(Event, WindowPtr)` or to ignore the event.

    The dispatch function itself must return false if it ignored the event,
    or true if it used the event. If you call `app::handle2()`, then
    this will return the correct value.
    # Safety
    The window pointer must not be invalidated
*/
pub unsafe fn event_dispatch(f: fn(Event, WindowPtr) -> bool) {
    fl::Fl_event_dispatch(mem::transmute(f));
}

/// Gets the mouse coordinates relative to the screen
pub fn get_mouse() -> (i32, i32) {
    unsafe {
        let mut x: i32 = 0;
        let mut y: i32 = 0;
        fl::Fl_get_mouse(&mut x, &mut y);
        (x, y)
    }
}

/// Types of Clipboard contents
#[derive(Debug, Clone, Copy)]
pub enum ClipboardContent {
    /// Textual content
    Text,
    /// Image content
    Image,
}

/// Check the contents of the clipboard
pub fn clipboard_contains(content: ClipboardContent) -> bool {
    use ClipboardContent::*;
    let txt = match content {
        Text => "text/plain",
        Image => "image",
    };
    let txt = CString::new(txt).unwrap();
    unsafe { fl::Fl_clipboard_contains(txt.as_ptr()) != 0 }
}

/// Pastes content from the clipboard
pub fn paste<T>(widget: &T)
where
    T: WidgetExt,
{
    assert!(!widget.was_deleted());
    if clipboard_contains(ClipboardContent::Text) {
        paste_text(widget)
    } else if clipboard_contains(ClipboardContent::Image) {
        paste_image(widget)
    } else {
        // Do nothing!
    }
}

/// Pastes textual content from the clipboard
pub fn paste_text<T>(widget: &T)
where
    T: WidgetExt,
{
    assert!(!widget.was_deleted());
    unsafe {
        fl::Fl_paste_text(widget.as_widget_ptr() as *mut fltk_sys::fl::Fl_Widget, 1);
    }
}

/// Pastes image content from the clipboard
pub fn paste_image<T>(widget: &T)
where
    T: WidgetExt,
{
    assert!(!widget.was_deleted());
    unsafe {
        fl::Fl_paste_image(widget.as_widget_ptr() as *mut fltk_sys::fl::Fl_Widget, 1);
    }
}

/// Adds a custom handler for unhandled events
pub fn add_handler(cb: fn(Event) -> bool) {
    unsafe {
        let callback: Option<unsafe extern "C" fn(ev: raw::c_int) -> raw::c_int> =
            Some(mem::transmute(move |ev| {
                let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| cb(ev) as i32));
            }));
        fl::Fl_add_handler(callback);
    }
}

/**
    Send a signal to a window.
    Integral values from 0 to 30 are reserved.
    Returns Ok(true) if the event was handled.
    Returns Ok(false) if the event was not handled.
    Returns Err on error or in use of one of the reserved values.
    ```rust,no_run
    use fltk::{prelude::*, *};
    const CHANGE_FRAME: i32 = 100;
    let mut wind = window::Window::default();
    let mut but = button::Button::default();
    let mut frame = frame::Frame::default();
    but.set_callback(move |_| {
        let _ = app::handle(CHANGE_FRAME, &wind).unwrap();
    });
    frame.handle(move |f, ev| {
        if ev == CHANGE_FRAME.into() {
            f.set_label("Hello world");
            true
        } else {
            false
        }
    });
    ```
    # Errors
    Returns Err on error or in use of one of the reserved values.
*/
pub fn handle<I: Into<i32> + Copy + PartialEq + PartialOrd, W: WindowExt>(
    msg: I,
    w: &W,
) -> Result<bool, FltkError> {
    let val = msg.into();
    if (0..=30).contains(&val) {
        Err(FltkError::Internal(FltkErrorKind::FailedOperation))
    } else {
        let ret = unsafe { fl::Fl_handle(val, w.as_widget_ptr() as _) != 0 };
        Ok(ret)
    }
}

/**
    Send a signal to the main window.
    Integral values from 0 to 30 are reserved.
    Returns Ok(true) if the event was handled.
    Returns Ok(false) if the event was not handled.
    ```rust,no_run
    use fltk::{prelude::*, *};
    const CHANGE_FRAME: i32 = 100;
    let mut wind = window::Window::default();
    let mut but = button::Button::default();
    let mut frame = frame::Frame::default();
    but.set_callback(move |_| {
        let _ = app::handle_main(CHANGE_FRAME).unwrap();
    });
    frame.handle(move |f, ev| {
        if ev == CHANGE_FRAME.into() {
            f.set_label("Hello world");
            true
        } else {
            false
        }
    });
    ```
    # Errors
    Returns Err on error or in use of one of the reserved values.
*/
pub fn handle_main<I: Into<i32> + Copy + PartialEq + PartialOrd>(
    msg: I,
) -> Result<bool, FltkError> {
    let val = msg.into();
    if (0..=30).contains(&val) {
        Err(FltkError::Internal(FltkErrorKind::FailedOperation))
    } else {
        first_window().map_or(
            Err(FltkError::Internal(FltkErrorKind::FailedOperation)),
            |win| {
                let ret = unsafe { fl::Fl_handle(val, win.as_widget_ptr() as _) != 0 };
                Ok(ret)
            },
        )
    }
}