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
// Take a look at the license at the top of the repository in the LICENSE file.

// rustdoc-stripper-ignore-next
//! Traits intended for subclassing [`EntryBuffer`](crate::EntryBuffer).

use crate::subclass::prelude::*;
use crate::EntryBuffer;
use glib::translate::*;
use glib::{Cast, GString, ObjectExt};
use once_cell::sync::Lazy;

use super::PtrHolder;

pub trait EntryBufferImpl: EntryBufferImplExt + ObjectImpl {
    fn delete_text(&self, position: u32, n_chars: Option<u32>) -> u32 {
        self.parent_delete_text(position, n_chars)
    }

    fn deleted_text(&self, position: u32, n_chars: Option<u32>) {
        self.parent_deleted_text(position, n_chars)
    }

    #[doc(alias = "get_length")]
    fn length(&self) -> u32 {
        self.parent_length()
    }

    #[doc(alias = "get_text")]
    fn text(&self) -> GString {
        self.parent_text()
    }
    fn insert_text(&self, position: u32, chars: &str) -> u32 {
        self.parent_insert_text(position, chars)
    }

    fn inserted_text(&self, position: u32, chars: &str) {
        self.parent_inserted_text(position, chars)
    }
}

pub trait EntryBufferImplExt: ObjectSubclass {
    fn parent_delete_text(&self, position: u32, n_chars: Option<u32>) -> u32;
    fn parent_deleted_text(&self, position: u32, n_chars: Option<u32>);
    fn parent_length(&self) -> u32;
    fn parent_text(&self) -> GString;
    fn parent_insert_text(&self, position: u32, chars: &str) -> u32;
    fn parent_inserted_text(&self, position: u32, chars: &str);
}

impl<T: EntryBufferImpl> EntryBufferImplExt for T {
    fn parent_delete_text(&self, position: u32, n_chars: Option<u32>) -> u32 {
        unsafe {
            let data = T::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkEntryBufferClass;
            let f = (*parent_class)
                .delete_text
                .expect("No parent class impl for \"delete_text\"");
            f(
                self.obj().unsafe_cast_ref::<EntryBuffer>().to_glib_none().0,
                position,
                n_chars.unwrap_or(u32::MAX),
            )
        }
    }

    fn parent_deleted_text(&self, position: u32, n_chars: Option<u32>) {
        unsafe {
            let data = T::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkEntryBufferClass;
            if let Some(f) = (*parent_class).deleted_text {
                f(
                    self.obj().unsafe_cast_ref::<EntryBuffer>().to_glib_none().0,
                    position,
                    n_chars.unwrap_or(u32::MAX),
                )
            }
        }
    }

    fn parent_length(&self) -> u32 {
        unsafe {
            let data = T::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkEntryBufferClass;
            let f = (*parent_class)
                .get_length
                .expect("No parent class impl for \"get_length\"");
            f(self.obj().unsafe_cast_ref::<EntryBuffer>().to_glib_none().0)
        }
    }

    fn parent_text(&self) -> GString {
        unsafe {
            let data = T::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkEntryBufferClass;
            let f = (*parent_class)
                .get_text
                .expect("No parent class impl for \"get_text\"");
            let mut n_bytes = 0;
            let res = f(
                self.obj().unsafe_cast_ref::<EntryBuffer>().to_glib_none().0,
                &mut n_bytes,
            );
            FromGlibContainer::from_glib_none_num(res, n_bytes as _)
        }
    }

    fn parent_insert_text(&self, position: u32, text: &str) -> u32 {
        unsafe {
            let data = T::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkEntryBufferClass;
            let f = (*parent_class)
                .insert_text
                .expect("No parent class impl for \"insert_text\"");

            f(
                self.obj().unsafe_cast_ref::<EntryBuffer>().to_glib_none().0,
                position,
                text.to_glib_none().0,
                text.chars().count() as u32,
            )
        }
    }

    fn parent_inserted_text(&self, position: u32, text: &str) {
        unsafe {
            let data = T::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkEntryBufferClass;
            if let Some(f) = (*parent_class).inserted_text {
                f(
                    self.obj().unsafe_cast_ref::<EntryBuffer>().to_glib_none().0,
                    position,
                    text.to_glib_none().0,
                    text.chars().count() as u32,
                )
            }
        }
    }
}

unsafe impl<T: EntryBufferImpl> IsSubclassable<T> for EntryBuffer {
    fn class_init(class: &mut glib::Class<Self>) {
        Self::parent_class_init::<T>(class);

        assert!(
            crate::rt::is_initialized(),
            "GTK has to be initialized first"
        );

        let klass = class.as_mut();
        klass.delete_text = Some(entry_buffer_delete_text::<T>);
        klass.deleted_text = Some(entry_buffer_deleted_text::<T>);
        klass.get_length = Some(entry_buffer_get_length::<T>);
        klass.get_text = Some(entry_buffer_get_text::<T>);
        klass.insert_text = Some(entry_buffer_insert_text::<T>);
        klass.inserted_text = Some(entry_buffer_inserted_text::<T>);
    }
}

unsafe extern "C" fn entry_buffer_delete_text<T: EntryBufferImpl>(
    ptr: *mut ffi::GtkEntryBuffer,
    position: u32,
    n_chars: u32,
) -> u32 {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let n_chars = if n_chars == u32::MAX {
        None
    } else {
        Some(n_chars)
    };

    imp.delete_text(position, n_chars)
}

unsafe extern "C" fn entry_buffer_deleted_text<T: EntryBufferImpl>(
    ptr: *mut ffi::GtkEntryBuffer,
    position: u32,
    n_chars: u32,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let n_chars = if n_chars == u32::MAX {
        None
    } else {
        Some(n_chars)
    };

    imp.deleted_text(position, n_chars)
}

static GET_TEXT_QUARK: Lazy<glib::Quark> =
    Lazy::new(|| glib::Quark::from_str("gtk4-rs-subclass-entry-buffer-text"));

unsafe extern "C" fn entry_buffer_get_text<T: EntryBufferImpl>(
    ptr: *mut ffi::GtkEntryBuffer,
    n_bytes: *mut usize,
) -> *const libc::c_char {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let ret = imp.text();
    if !n_bytes.is_null() {
        *n_bytes = ret.len();
    }
    // Ensures that the returned text stays alive for as long as
    // the entry buffer instance
    let fullptr = ret.to_glib_full();
    imp.obj().set_qdata(
        *GET_TEXT_QUARK,
        PtrHolder(fullptr, |ptr| {
            glib::ffi::g_free(ptr as *mut _);
        }),
    );
    fullptr
}

unsafe extern "C" fn entry_buffer_get_length<T: EntryBufferImpl>(
    ptr: *mut ffi::GtkEntryBuffer,
) -> u32 {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.length()
}

unsafe extern "C" fn entry_buffer_insert_text<T: EntryBufferImpl>(
    ptr: *mut ffi::GtkEntryBuffer,
    position: u32,
    charsptr: *const libc::c_char,
    n_chars: u32,
) -> u32 {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let text: Borrowed<GString> = from_glib_borrow(charsptr);

    let chars = text_n_chars(&text, n_chars);
    imp.insert_text(position, chars)
}

unsafe extern "C" fn entry_buffer_inserted_text<T: EntryBufferImpl>(
    ptr: *mut ffi::GtkEntryBuffer,
    position: u32,
    charsptr: *const libc::c_char,
    length: u32,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let text: Borrowed<GString> = from_glib_borrow(charsptr);

    let chars = text_n_chars(&text, length);
    imp.inserted_text(position, chars)
}

#[doc(alias = "get_text_n_chars")]
fn text_n_chars(text: &str, n_chars: u32) -> &str {
    if n_chars != u32::MAX && n_chars > 0 {
        let mut iter = text
            .char_indices()
            .skip((n_chars - 1) as _)
            .map(|(pos, _)| pos);
        iter
            .next()
            .expect(
                "The passed text to EntryBuffer contains fewer characters than what's passed as a length",
            );
        let pos_end = iter.next().unwrap_or(text.len());
        &text[..pos_end]
    } else if n_chars == 0 {
        // Avoid doing skipping to -1 char
        ""
    } else {
        text
    }
}

#[cfg(test)]
mod test {
    use super::text_n_chars;
    #[std::prelude::v1::test]
    fn n_chars_max_length_ascii() {
        assert_eq!(text_n_chars("gtk-rs bindings", 6), "gtk-rs");
        assert_eq!(text_n_chars("gtk-rs bindings", u32::MAX), "gtk-rs bindings");
    }

    #[std::prelude::v1::test]
    #[should_panic]
    fn n_chars_max_length_ascii_panic() {
        assert_eq!(text_n_chars("gtk-rs", 7), "gtk-rs");
    }

    #[std::prelude::v1::test]
    fn n_chars_max_length_utf8() {
        assert_eq!(text_n_chars("👨👩👧👦", 2), "👨👩");
        assert_eq!(text_n_chars("👨👩👧👦", 0), "");
        assert_eq!(text_n_chars("👨👩👧👦", 4), "👨👩👧👦");
        assert_eq!(text_n_chars("👨👩👧👦", u32::MAX), "👨👩👧👦");
        assert_eq!(text_n_chars("كتاب", 2), "كت");
    }

    #[std::prelude::v1::test]
    fn n_chars_max_length_utf8_ascii() {
        assert_eq!(text_n_chars("👨g👩t👧k👦", 2), "👨g");
        assert_eq!(text_n_chars("👨g👩t👧k👦", 5), "👨g👩t👧");
        assert_eq!(text_n_chars("كaتاب", 3), "كaت");
    }

    #[std::prelude::v1::test]
    #[should_panic]
    fn n_chars_max_length_utf8_panic() {
        assert_eq!(text_n_chars("👨👩👧👦", 5), "👨👩");
    }
}