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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
// Take a look at the license at the top of the repository in the LICENSE file.

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

use glib::{translate::*, GString};
use pango::AttrList;

use crate::{prelude::*, subclass::prelude::*, IMContext, Widget};

#[allow(clippy::upper_case_acronyms)]
pub trait IMContextImpl: IMContextImplExt + ObjectImpl {
    /// Default handler of the [`commit`][struct@crate::IMContext#commit] signal.
    fn commit(&self, string: &str) {
        self.parent_commit(string)
    }
    /// Asks the widget that the input context is attached to delete
    /// characters around the cursor position by emitting the
    /// `::delete_surrounding` signal.
    ///
    /// Note that @offset and @n_chars are in characters not in bytes
    /// which differs from the usage other places in [`IMContext`][crate::IMContext].
    ///
    /// In order to use this function, you should first call
    /// [`IMContextExt::surrounding()`][crate::prelude::IMContextExt::surrounding()] to get the current context,
    /// and call this function immediately afterwards to make sure that you
    /// know what you are deleting. You should also account for the fact
    /// that even if the signal was handled, the input context might not
    /// have deleted all the characters that were requested to be deleted.
    ///
    /// This function is used by an input method that wants to make
    /// substitutions in the existing text in response to new input.
    /// It is not useful for applications.
    /// ## `offset`
    /// offset from cursor position in chars;
    ///    a negative value means start before the cursor.
    /// ## `n_chars`
    /// number of characters to delete.
    ///
    /// # Returns
    ///
    /// [`true`] if the signal was handled.
    fn delete_surrounding(&self, offset: i32, n_chars: i32) -> bool {
        self.parent_delete_surrounding(offset, n_chars)
    }
    /// Allow an input method to internally handle key press and release
    /// events.
    ///
    /// If this function returns [`true`], then no further processing
    /// should be done for this key event.
    /// ## `event`
    /// the key event
    ///
    /// # Returns
    ///
    /// [`true`] if the input method handled the key event.
    fn filter_keypress(&self, event: &gdk::Event) -> bool {
        self.parent_filter_keypress(event)
    }
    /// Notify the input method that the widget to which this
    /// input context corresponds has gained focus.
    ///
    /// The input method may, for example, change the displayed
    /// feedback to reflect this change.
    fn focus_in(&self) {
        self.parent_focus_in()
    }
    /// Notify the input method that the widget to which this
    /// input context corresponds has lost focus.
    ///
    /// The input method may, for example, change the displayed
    /// feedback or reset the contexts state to reflect this change.
    fn focus_out(&self) {
        self.parent_focus_out()
    }
    /// Retrieve the current preedit string for the input context,
    /// and a list of attributes to apply to the string.
    ///
    /// This string should be displayed inserted at the insertion point.
    ///
    /// # Returns
    ///
    ///
    /// ## `str`
    /// location to store the retrieved
    ///   string. The string retrieved must be freed with g_free().
    ///
    /// ## `attrs`
    /// location to store the retrieved
    ///   attribute list. When you are done with this list, you
    ///   must unreference it with `Pango::AttrList::unref()`.
    ///
    /// ## `cursor_pos`
    /// location to store position of cursor
    ///   (in characters) within the preedit string.
    #[doc(alias = "get_preedit_string")]
    fn preedit_string(&self) -> (GString, AttrList, i32) {
        self.parent_preedit_string()
    }
    /// Retrieves context around the insertion point.
    ///
    /// Input methods typically want context in order to constrain input text
    /// based on existing text; this is important for languages such as Thai
    /// where only some sequences of characters are allowed.
    ///
    /// This function is implemented by emitting the
    /// [`retrieve-surrounding`][struct@crate::IMContext#retrieve-surrounding] signal on the input method;
    /// in response to this signal, a widget should provide as much context as
    /// is available, up to an entire paragraph, by calling
    /// [`IMContextExt::set_surrounding()`][crate::prelude::IMContextExt::set_surrounding()].
    ///
    /// Note that there is no obligation for a widget to respond to the
    /// `::retrieve-surrounding` signal, so input methods must be prepared to
    /// function without context.
    ///
    /// # Deprecated since 4.2
    ///
    /// Use [`IMContextExt::surrounding_with_selection()`][crate::prelude::IMContextExt::surrounding_with_selection()] instead.
    ///
    /// # Returns
    ///
    /// `TRUE` if surrounding text was provided; in this case
    ///    you must free the result stored in `text`.
    ///
    /// ## `text`
    /// location to store a UTF-8 encoded
    ///   string of text holding context around the insertion point.
    ///   If the function returns [`true`], then you must free the result
    ///   stored in this location with g_free().
    ///
    /// ## `cursor_index`
    /// location to store byte index of the insertion
    ///   cursor within @text.
    #[doc(alias = "get_surrounding")]
    fn surrounding(&self) -> Option<(GString, i32)> {
        self.parent_surrounding()
    }
    /// Default handler of the [`preedit-changed`][struct@crate::IMContext#preedit-changed]
    ///   signal.
    fn preedit_changed(&self) {
        self.parent_preedit_changed()
    }
    /// Default handler of the [`preedit-end`][struct@crate::IMContext#preedit-end] signal.
    fn preedit_end(&self) {
        self.parent_preedit_end()
    }
    /// Default handler of the [`preedit-start`][struct@crate::IMContext#preedit-start] signal.
    fn preedit_start(&self) {
        self.parent_preedit_start()
    }
    /// Notify the input method that a change such as a change in cursor
    /// position has been made.
    ///
    /// This will typically cause the input method to clear the preedit state.
    fn reset(&self) {
        self.parent_reset()
    }
    /// Default handler of the
    ///   [`retrieve-surrounding`][struct@crate::IMContext#retrieve-surrounding] signal.
    fn retrieve_surrounding(&self) -> bool {
        self.parent_retrieve_surrounding()
    }
    /// Set the client widget for the input context.
    ///
    /// This is the [`Widget`][crate::Widget] holding the input focus. This widget is
    /// used in order to correctly position status windows, and may
    /// also be used for purposes internal to the input method.
    /// ## `widget`
    /// the client widget. This may be [`None`] to indicate
    ///   that the previous client widget no longer exists.
    fn set_client_widget<P: IsA<Widget>>(&self, widget: Option<&P>) {
        self.parent_set_client_widget(widget)
    }
    /// Notify the input method that a change in cursor
    /// position has been made.
    ///
    /// The location is relative to the client widget.
    /// ## `area`
    /// new location
    fn set_cursor_location(&self, area: &gdk::Rectangle) {
        self.parent_set_cursor_location(area)
    }
    /// Sets surrounding context around the insertion point and preedit
    /// string.
    ///
    /// This function is expected to be called in response to the
    /// [`retrieve-surrounding`][struct@crate::IMContext#retrieve-surrounding] signal, and will
    /// likely have no effect if called at other times.
    ///
    /// # Deprecated since 4.2
    ///
    /// Use [`IMContextExt::set_surrounding_with_selection()`][crate::prelude::IMContextExt::set_surrounding_with_selection()] instead
    /// ## `text`
    /// text surrounding the insertion point, as UTF-8.
    ///   the preedit string should not be included within @text
    /// ## `len`
    /// the length of @text, or -1 if @text is nul-terminated
    /// ## `cursor_index`
    /// the byte index of the insertion cursor within @text.
    #[cfg_attr(feature = "v4_2", deprecated = "Since 4.2")]
    #[allow(deprecated)]
    fn set_surrounding(&self, text: &str, cursor_index: i32) {
        self.parent_set_surrounding(text, cursor_index)
    }
    /// Sets whether the IM context should use the preedit string
    /// to display feedback.
    ///
    /// If @use_preedit is [`false`] (default is [`true`]), then the IM context
    /// may use some other method to display feedback, such as displaying
    /// it in a child of the root window.
    /// ## `use_preedit`
    /// whether the IM context should use the preedit string.
    fn set_use_preedit(&self, use_preedit: bool) {
        self.parent_set_use_preedit(use_preedit)
    }
    #[cfg(feature = "v4_10")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v4_10")))]
    fn activate_osk(&self) {
        self.parent_activate_osk()
    }
    #[cfg(feature = "v4_14")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v4_14")))]
    fn activate_osk_with_event(&self, event: Option<&gdk::Event>) -> bool {
        self.parent_activate_osk_with_event(event)
    }
}

mod sealed {
    pub trait Sealed {}
    impl<T: super::IMContextImplExt> Sealed for T {}
}

#[allow(clippy::upper_case_acronyms)]
pub trait IMContextImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_commit(&self, string: &str) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).commit {
                f(
                    self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0,
                    string.to_glib_none().0,
                );
            }
        }
    }

    // Returns true if the signal was handled
    fn parent_delete_surrounding(&self, offset: i32, n_chars: i32) -> bool {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).delete_surrounding {
                from_glib(f(
                    self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0,
                    offset,
                    n_chars,
                ))
            } else {
                false
            }
        }
    }

    // Returns true if the event was consumed
    fn parent_filter_keypress(&self, event: &gdk::Event) -> bool {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).filter_keypress {
                from_glib(f(
                    self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0,
                    event.to_glib_none().0,
                ))
            } else {
                false
            }
        }
    }

    fn parent_focus_in(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).focus_in {
                f(self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0)
            }
        }
    }

    fn parent_focus_out(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).focus_out {
                f(self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0)
            }
        }
    }

    fn parent_surrounding(&self) -> Option<(GString, i32)> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).get_surrounding {
                let mut text = std::ptr::null_mut();
                let mut cursor_index = std::mem::MaybeUninit::uninit();
                let ret = from_glib(f(
                    self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0,
                    &mut text,
                    cursor_index.as_mut_ptr(),
                ));
                if ret {
                    return Some((from_glib_full(text), cursor_index.assume_init()));
                }
            }
            None
        }
    }

    fn parent_preedit_string(&self) -> (GString, AttrList, i32) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            let f = (*parent_class)
                .get_preedit_string
                .expect("No parent class impl for \"get_preedit_string\"");
            let mut string = std::ptr::null_mut();
            let mut attrs = std::ptr::null_mut();
            let mut cursor_pos = std::mem::MaybeUninit::uninit();
            f(
                self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0,
                &mut string,
                &mut attrs,
                cursor_pos.as_mut_ptr(),
            );
            (
                from_glib_full(string),
                from_glib_full(attrs),
                cursor_pos.assume_init(),
            )
        }
    }

    fn parent_preedit_changed(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).preedit_changed {
                f(self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0)
            }
        }
    }

    fn parent_preedit_end(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).preedit_end {
                f(self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0)
            }
        }
    }

    fn parent_preedit_start(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).preedit_start {
                f(self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0)
            }
        }
    }

    fn parent_reset(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).reset {
                f(self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0)
            }
        }
    }

    // Returns true if the signal was handled
    fn parent_retrieve_surrounding(&self) -> bool {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).retrieve_surrounding {
                from_glib(f(self
                    .obj()
                    .unsafe_cast_ref::<IMContext>()
                    .to_glib_none()
                    .0))
            } else {
                false
            }
        }
    }

    fn parent_set_client_widget<P: IsA<Widget>>(&self, widget: Option<&P>) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).set_client_widget {
                f(
                    self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0,
                    widget.map(|p| p.as_ref()).to_glib_none().0,
                )
            }
        }
    }

    fn parent_set_cursor_location(&self, area: &gdk::Rectangle) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).set_cursor_location {
                f(
                    self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0,
                    area.to_glib_none().0 as *mut _,
                );
            }
        }
    }

    #[cfg_attr(feature = "v4_2", deprecated = "Since 4.2")]
    #[allow(deprecated)]
    fn parent_set_surrounding(&self, text: &str, cursor_index: i32) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).set_surrounding {
                f(
                    self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0,
                    text.to_glib_none().0,
                    text.len() as i32,
                    cursor_index,
                )
            }
        }
    }

    fn parent_set_use_preedit(&self, use_preedit: bool) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).set_use_preedit {
                f(
                    self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0,
                    use_preedit.into_glib(),
                )
            }
        }
    }

    #[cfg(feature = "v4_10")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v4_10")))]
    fn parent_activate_osk(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).activate_osk {
                f(self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0)
            }
        }
    }

    #[cfg(feature = "v4_14")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v4_14")))]
    fn parent_activate_osk_with_event(&self, event: Option<&gdk::Event>) -> bool {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GtkIMContextClass;
            if let Some(f) = (*parent_class).activate_osk_with_event {
                from_glib(f(
                    self.obj().unsafe_cast_ref::<IMContext>().to_glib_none().0,
                    event.to_glib_none().0,
                ))
            } else {
                false
            }
        }
    }
}

impl<T: IMContextImpl> IMContextImplExt for T {}

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

        assert_initialized_main_thread!();

        let klass = class.as_mut();
        klass.commit = Some(im_context_commit::<T>);
        klass.delete_surrounding = Some(im_context_delete_surrounding::<T>);
        klass.filter_keypress = Some(im_context_filter_keypress::<T>);
        klass.focus_in = Some(im_context_focus_in::<T>);
        klass.focus_out = Some(im_context_focus_out::<T>);
        klass.get_preedit_string = Some(im_context_get_preedit_string::<T>);
        klass.get_surrounding = Some(im_context_get_surrounding::<T>);
        klass.preedit_changed = Some(im_context_preedit_changed::<T>);
        klass.preedit_end = Some(im_context_preedit_end::<T>);
        klass.preedit_start = Some(im_context_preedit_start::<T>);
        klass.reset = Some(im_context_reset::<T>);
        klass.retrieve_surrounding = Some(im_context_retrieve_surrounding::<T>);
        klass.set_client_widget = Some(im_context_set_client_widget::<T>);
        klass.set_cursor_location = Some(im_context_set_cursor_location::<T>);
        klass.set_surrounding = Some(im_context_set_surrounding::<T>);
        klass.set_use_preedit = Some(im_context_set_use_preedit::<T>);
        #[cfg(feature = "v4_10")]
        #[cfg_attr(docsrs, doc(cfg(feature = "v4_10")))]
        {
            klass.activate_osk = Some(im_context_activate_osk::<T>);
        };
        #[cfg(feature = "v4_14")]
        #[cfg_attr(docsrs, doc(cfg(feature = "v4_14")))]
        {
            klass.activate_osk_with_event = Some(im_context_activate_osk_with_event::<T>);
        };
    }
}

unsafe extern "C" fn im_context_commit<T: IMContextImpl>(
    ptr: *mut ffi::GtkIMContext,
    stringptr: *const libc::c_char,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let string: Borrowed<GString> = from_glib_borrow(stringptr);

    imp.commit(string.as_str())
}

unsafe extern "C" fn im_context_delete_surrounding<T: IMContextImpl>(
    ptr: *mut ffi::GtkIMContext,
    offset: i32,
    n_chars: i32,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.delete_surrounding(offset, n_chars).into_glib()
}

unsafe extern "C" fn im_context_filter_keypress<T: IMContextImpl>(
    ptr: *mut ffi::GtkIMContext,
    eventptr: *mut gdk::ffi::GdkEvent,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let event: Borrowed<gdk::Event> = from_glib_borrow(eventptr);
    imp.filter_keypress(&event).into_glib()
}

unsafe extern "C" fn im_context_focus_in<T: IMContextImpl>(ptr: *mut ffi::GtkIMContext) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.focus_in()
}

unsafe extern "C" fn im_context_focus_out<T: IMContextImpl>(ptr: *mut ffi::GtkIMContext) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.focus_out()
}

unsafe extern "C" fn im_context_get_preedit_string<T: IMContextImpl>(
    ptr: *mut ffi::GtkIMContext,
    text_ptr: *mut *mut libc::c_char,
    attrs_ptr: *mut *mut pango::ffi::PangoAttrList,
    cursor_index_ptr: *mut libc::c_int,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let (text, attrs, cursor_idx) = imp.preedit_string();

    *text_ptr = text.into_glib_ptr();
    *cursor_index_ptr = cursor_idx;
    *attrs_ptr = attrs.into_glib_ptr();
}

unsafe extern "C" fn im_context_get_surrounding<T: IMContextImpl>(
    ptr: *mut ffi::GtkIMContext,
    text_ptr: *mut *mut libc::c_char,
    cursor_index_ptr: *mut libc::c_int,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    if let Some((text, cursor_idx)) = imp.surrounding() {
        *text_ptr = text.into_glib_ptr();
        *cursor_index_ptr = cursor_idx;
        true.into_glib()
    } else {
        *text_ptr = std::ptr::null_mut();
        *cursor_index_ptr = 0;
        false.into_glib()
    }
}

unsafe extern "C" fn im_context_preedit_changed<T: IMContextImpl>(ptr: *mut ffi::GtkIMContext) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.preedit_changed()
}

unsafe extern "C" fn im_context_preedit_end<T: IMContextImpl>(ptr: *mut ffi::GtkIMContext) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.preedit_end()
}

unsafe extern "C" fn im_context_preedit_start<T: IMContextImpl>(ptr: *mut ffi::GtkIMContext) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.preedit_start()
}

unsafe extern "C" fn im_context_reset<T: IMContextImpl>(ptr: *mut ffi::GtkIMContext) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.reset()
}

unsafe extern "C" fn im_context_retrieve_surrounding<T: IMContextImpl>(
    ptr: *mut ffi::GtkIMContext,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.retrieve_surrounding().into_glib()
}

unsafe extern "C" fn im_context_set_client_widget<T: IMContextImpl>(
    ptr: *mut ffi::GtkIMContext,
    widgetptr: *mut ffi::GtkWidget,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let widget: Borrowed<Option<Widget>> = from_glib_borrow(widgetptr);

    imp.set_client_widget(widget.as_ref().as_ref());
}

unsafe extern "C" fn im_context_set_cursor_location<T: IMContextImpl>(
    ptr: *mut ffi::GtkIMContext,
    areaptr: *mut gdk::ffi::GdkRectangle,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let area = from_glib_borrow(areaptr);

    imp.set_cursor_location(&area);
}

unsafe extern "C" fn im_context_set_surrounding<T: IMContextImpl>(
    ptr: *mut ffi::GtkIMContext,
    textptr: *const libc::c_char,
    length: i32,
    cursor_index: i32,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let text: Borrowed<GString> = from_glib_borrow(textptr);

    // length == -1 if text is null-terminated
    let text = if length == -1 {
        &text[..]
    } else {
        &text[0..(length as usize)]
    };

    imp.set_surrounding(text, cursor_index)
}

unsafe extern "C" fn im_context_set_use_preedit<T: IMContextImpl>(
    ptr: *mut ffi::GtkIMContext,
    use_preedit: glib::ffi::gboolean,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.set_use_preedit(from_glib(use_preedit))
}

#[cfg(feature = "v4_10")]
#[cfg_attr(docsrs, doc(cfg(feature = "v4_10")))]
unsafe extern "C" fn im_context_activate_osk<T: IMContextImpl>(ptr: *mut ffi::GtkIMContext) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.activate_osk()
}

#[cfg(feature = "v4_14")]
#[cfg_attr(docsrs, doc(cfg(feature = "v4_14")))]
unsafe extern "C" fn im_context_activate_osk_with_event<T: IMContextImpl>(
    ptr: *mut ffi::GtkIMContext,
    eventptr: *mut gdk::ffi::GdkEvent,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let event: Borrowed<Option<gdk::Event>> = from_glib_borrow(eventptr);

    imp.activate_osk_with_event(event.as_ref().as_ref())
        .into_glib()
}