gtk4/editable.rs
1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{ffi::CStr, mem::transmute, slice, str};
4
5use glib::{
6 signal::{SignalHandlerId, connect_raw},
7 translate::*,
8};
9use libc::{c_char, c_int, c_uchar};
10
11use crate::{Editable, prelude::*};
12
13// rustdoc-stripper-ignore-next
14/// Trait containing manually implemented methods of
15/// [`Editable`](crate::Editable).
16pub trait EditableExtManual: IsA<Editable> + 'static {
17 /// Emitted when text is inserted into the widget by the user.
18 ///
19 /// The default handler for this signal will normally be responsible
20 /// for inserting the text, so by connecting to this signal and then
21 /// stopping the signal with g_signal_stop_emission(), it is possible
22 /// to modify the inserted text, or prevent it from being inserted entirely.
23 /// ## `text`
24 /// the new text to insert
25 /// ## `length`
26 /// the length of the new text, in bytes,
27 /// or -1 if new_text is nul-terminated
28 ///
29 /// # Returns
30 ///
31 ///
32 /// ## `position`
33 /// the position, in characters,
34 /// at which to insert the new text. this is an in-out
35 /// parameter. After the signal emission is finished, it
36 /// should point after the newly inserted text.
37 fn connect_insert_text<F>(&self, f: F) -> SignalHandlerId
38 where
39 F: Fn(&Self, &str, &mut i32) + 'static,
40 {
41 unsafe {
42 let f: Box<F> = Box::new(f);
43 connect_raw(
44 self.to_glib_none().0 as *mut _,
45 c"insert-text".as_ptr() as *mut _,
46 Some(transmute::<*const (), unsafe extern "C" fn()>(
47 insert_text_trampoline::<Self, F> as *const (),
48 )),
49 Box::into_raw(f),
50 )
51 }
52 }
53}
54
55impl<O: IsA<Editable>> EditableExtManual for O {}
56
57unsafe extern "C" fn insert_text_trampoline<T, F: Fn(&T, &str, &mut i32) + 'static>(
58 this: *mut crate::ffi::GtkEditable,
59 new_text: *mut c_char,
60 new_text_length: c_int,
61 position: *mut c_int,
62 f: &F,
63) where
64 T: IsA<Editable>,
65{
66 unsafe {
67 let buf = if new_text_length == 0 {
68 &[]
69 } else if new_text_length != -1 {
70 slice::from_raw_parts(new_text as *mut c_uchar, new_text_length as usize)
71 } else {
72 CStr::from_ptr(new_text).to_bytes()
73 };
74 let string = str::from_utf8(buf).unwrap();
75 f(
76 Editable::from_glib_borrow(this).unsafe_cast_ref(),
77 string,
78 &mut *position,
79 );
80 }
81}