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
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT

use crate::{ffi, CompletionCell, CompletionContext, CompletionProposal};
use glib::{prelude::*, translate::*};
use std::{boxed::Box as Box_, pin::Pin};

glib::wrapper! {
    /// Completion provider interface.
    ///
    /// You must implement this interface to provide proposals to [`Completion`][crate::Completion].
    ///
    /// In most cases, implementations of this interface will want to use
    /// `vfunc::CompletionProvider::populate_async` to asynchronously populate the results
    /// to avoid blocking the main loop.
    ///
    /// # Implements
    ///
    /// [`CompletionProviderExt`][trait@crate::prelude::CompletionProviderExt]
    #[doc(alias = "GtkSourceCompletionProvider")]
    pub struct CompletionProvider(Interface<ffi::GtkSourceCompletionProvider, ffi::GtkSourceCompletionProviderInterface>);

    match fn {
        type_ => || ffi::gtk_source_completion_provider_get_type(),
    }
}

impl CompletionProvider {
    pub const NONE: Option<&'static CompletionProvider> = None;
}

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

/// Trait containing all [`struct@CompletionProvider`] methods.
///
/// # Implementors
///
/// [`CompletionProvider`][struct@crate::CompletionProvider], [`CompletionSnippets`][struct@crate::CompletionSnippets], [`CompletionWords`][struct@crate::CompletionWords]
pub trait CompletionProviderExt: IsA<CompletionProvider> + sealed::Sealed + 'static {
    /// This function requests @proposal to be activated by the
    /// #GtkSourceCompletionProvider.
    ///
    /// What the provider does to activate the proposal is specific to that
    /// provider. Many providers may choose to insert a #GtkSourceSnippet with
    /// edit points the user may cycle through.
    ///
    /// See also: [`Snippet`][crate::Snippet], [`SnippetChunk`][crate::SnippetChunk], `View::push_snippet()`
    /// ## `context`
    /// a #GtkSourceCompletionContext
    /// ## `proposal`
    /// a #GtkSourceCompletionProposal
    #[doc(alias = "gtk_source_completion_provider_activate")]
    fn activate(&self, context: &CompletionContext, proposal: &impl IsA<CompletionProposal>) {
        unsafe {
            ffi::gtk_source_completion_provider_activate(
                self.as_ref().to_glib_none().0,
                context.to_glib_none().0,
                proposal.as_ref().to_glib_none().0,
            );
        }
    }

    /// This function requests that the #GtkSourceCompletionProvider prepares
    /// @cell to display the contents of @proposal.
    ///
    /// Based on @cells column type, you may want to display different information.
    ///
    /// This allows for columns of information among completion proposals
    /// resulting in better alignment of similar content (icons, return types,
    /// method names, and parameter lists).
    /// ## `context`
    /// a #GtkSourceCompletionContext
    /// ## `proposal`
    /// a #GtkSourceCompletionProposal
    /// ## `cell`
    /// a #GtkSourceCompletionCell
    #[doc(alias = "gtk_source_completion_provider_display")]
    fn display(
        &self,
        context: &CompletionContext,
        proposal: &impl IsA<CompletionProposal>,
        cell: &CompletionCell,
    ) {
        unsafe {
            ffi::gtk_source_completion_provider_display(
                self.as_ref().to_glib_none().0,
                context.to_glib_none().0,
                proposal.as_ref().to_glib_none().0,
                cell.to_glib_none().0,
            );
        }
    }

    /// This function should return the priority of @self in @context.
    ///
    /// The priority is used to sort groups of completion proposals by
    /// provider so that higher priority providers results are shown
    /// above lower priority providers.
    ///
    /// Higher value indicates higher priority.
    /// ## `context`
    /// a #GtkSourceCompletionContext
    #[doc(alias = "gtk_source_completion_provider_get_priority")]
    #[doc(alias = "get_priority")]
    fn priority(&self, context: &CompletionContext) -> i32 {
        unsafe {
            ffi::gtk_source_completion_provider_get_priority(
                self.as_ref().to_glib_none().0,
                context.to_glib_none().0,
            )
        }
    }

    /// Gets the title of the completion provider, if any.
    ///
    /// Currently, titles are not displayed in the completion results, but may be
    /// at some point in the future when non-[`None`].
    ///
    /// # Returns
    ///
    /// a title for the provider or [`None`]
    #[doc(alias = "gtk_source_completion_provider_get_title")]
    #[doc(alias = "get_title")]
    fn title(&self) -> Option<glib::GString> {
        unsafe {
            from_glib_full(ffi::gtk_source_completion_provider_get_title(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// This function is used to determine if a character inserted into the text
    /// editor should cause a new completion request to be triggered.
    ///
    /// An example would be period '.' which might indicate that the user wants
    /// to complete method or field names of an object.
    ///
    /// This method will only trigger when text is inserted into the #GtkTextBuffer
    /// while the completion list is visible and a proposal is selected. Incremental
    /// key-presses (like shift, control, or alt) are not triggerable.
    /// ## `iter`
    /// a #GtkTextIter
    /// ## `ch`
    /// a #gunichar of the character inserted
    #[doc(alias = "gtk_source_completion_provider_is_trigger")]
    fn is_trigger(&self, iter: &gtk::TextIter, ch: char) -> bool {
        unsafe {
            from_glib(ffi::gtk_source_completion_provider_is_trigger(
                self.as_ref().to_glib_none().0,
                iter.to_glib_none().0,
                ch.into_glib(),
            ))
        }
    }

    /// This function is used to determine if a key typed by the user should
    /// activate @proposal (resulting in committing the text to the editor).
    ///
    /// This is useful when using languages where convention may lead to less
    /// typing by the user. One example may be the use of "." or "-" to expand
    /// a field access in the C programming language.
    /// ## `context`
    /// a #GtkSourceCompletionContext
    /// ## `proposal`
    /// a #GtkSourceCompletionProposal
    /// ## `keyval`
    /// a keyval such as `Gdk::KEY_period`
    /// ## `state`
    /// a #GdkModifierType or 0
    #[doc(alias = "gtk_source_completion_provider_key_activates")]
    fn key_activates(
        &self,
        context: &CompletionContext,
        proposal: &impl IsA<CompletionProposal>,
        keyval: u32,
        state: gdk::ModifierType,
    ) -> bool {
        unsafe {
            from_glib(ffi::gtk_source_completion_provider_key_activates(
                self.as_ref().to_glib_none().0,
                context.to_glib_none().0,
                proposal.as_ref().to_glib_none().0,
                keyval,
                state.into_glib(),
            ))
        }
    }

    /// Providers should return a list of alternates to @proposal or [`None`] if
    /// there are no alternates available.
    ///
    /// This can be used by the completion view to allow the user to move laterally
    /// through similar proposals, such as overrides of methods by the same name.
    /// ## `context`
    /// a #GtkSourceCompletionContext
    /// ## `proposal`
    /// a #GtkSourceCompletionProposal
    ///
    /// # Returns
    ///
    ///
    ///   a #GPtrArray of #GtkSourceCompletionProposal or [`None`].
    #[doc(alias = "gtk_source_completion_provider_list_alternates")]
    fn list_alternates(
        &self,
        context: &CompletionContext,
        proposal: &impl IsA<CompletionProposal>,
    ) -> Vec<CompletionProposal> {
        unsafe {
            FromGlibPtrContainer::from_glib_full(
                ffi::gtk_source_completion_provider_list_alternates(
                    self.as_ref().to_glib_none().0,
                    context.to_glib_none().0,
                    proposal.as_ref().to_glib_none().0,
                ),
            )
        }
    }

    /// Asynchronously requests that the provider populates the completion
    /// results for @context.
    ///
    /// For providers that would like to populate a [`gio::ListModel`][crate::gio::ListModel] while those
    /// results are displayed to the user,
    /// [`CompletionContext::set_proposals_for_provider()`][crate::CompletionContext::set_proposals_for_provider()] may be used
    /// to reduce latency until the user sees results.
    /// ## `context`
    /// a #GtkSourceCompletionContext
    /// ## `cancellable`
    /// a #GCancellable or [`None`]
    /// ## `callback`
    /// a callback to execute upon completion
    #[doc(alias = "gtk_source_completion_provider_populate_async")]
    fn populate_async<P: FnOnce(Result<gio::ListModel, glib::Error>) + 'static>(
        &self,
        context: &CompletionContext,
        cancellable: Option<&impl IsA<gio::Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn populate_async_trampoline<
            P: FnOnce(Result<gio::ListModel, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut gio::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = std::ptr::null_mut();
            let ret = ffi::gtk_source_completion_provider_populate_finish(
                _source_object as *mut _,
                res,
                &mut error,
            );
            let result = if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = populate_async_trampoline::<P>;
        unsafe {
            ffi::gtk_source_completion_provider_populate_async(
                self.as_ref().to_glib_none().0,
                context.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn populate_future(
        &self,
        context: &CompletionContext,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<gio::ListModel, glib::Error>> + 'static>>
    {
        let context = context.clone();
        Box_::pin(gio::GioFuture::new(self, move |obj, cancellable, send| {
            obj.populate_async(&context, Some(cancellable), move |res| {
                send.resolve(res);
            });
        }))
    }

    /// This function can be used to filter results previously provided to
    /// the [`CompletionContext`][crate::CompletionContext] by the #GtkSourceCompletionProvider.
    ///
    /// This can happen as the user types additional text onto the word so
    /// that previously matched items may be removed from the list instead of
    /// generating new [`gio::ListModel`][crate::gio::ListModel] of results.
    /// ## `context`
    /// a #GtkSourceCompletionContext
    /// ## `model`
    /// a #GListModel
    #[doc(alias = "gtk_source_completion_provider_refilter")]
    fn refilter(&self, context: &CompletionContext, model: &impl IsA<gio::ListModel>) {
        unsafe {
            ffi::gtk_source_completion_provider_refilter(
                self.as_ref().to_glib_none().0,
                context.to_glib_none().0,
                model.as_ref().to_glib_none().0,
            );
        }
    }
}

impl<O: IsA<CompletionProvider>> CompletionProviderExt for O {}