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

use crate::{ffi, UserMessage, WebPage};
use glib::{
    prelude::*,
    signal::{connect_raw, SignalHandlerId},
    translate::*,
};
use std::{boxed::Box as Box_, pin::Pin};

glib::wrapper! {
    /// Represents an extension of the web process.
    ///
    /// WebKitWebProcessExtension is a loadable module for the web process. It allows you to execute code in the
    /// web process and being able to use the DOM API, to change any request or to inject custom
    /// JavaScript code, for example.
    ///
    /// To create a WebKitWebProcessExtension you should write a module with an initialization function that could
    /// be either webkit_web_process_extension_initialize() with prototype #WebKitWebProcessExtensionInitializeFunction or
    /// webkit_web_process_extension_initialize_with_user_data() with prototype #WebKitWebProcessExtensionInitializeWithUserDataFunction.
    /// This function has to be public and it has to use the #G_MODULE_EXPORT macro. It is called when the
    /// web process is initialized.
    ///
    /// **⚠️ The following code is in c ⚠️**
    ///
    /// ```c
    /// static void
    /// web_page_created_callback (WebKitWebProcessExtension *extension,
    ///                            WebKitWebPage             *web_page,
    ///                            gpointer                   user_data)
    /// {
    ///     g_print ("Page %d created for %s\n",
    ///              webkit_web_page_get_id (web_page),
    ///              webkit_web_page_get_uri (web_page));
    /// }
    ///
    /// G_MODULE_EXPORT void
    /// webkit_web_process_extension_initialize (WebKitWebProcessExtension *extension)
    /// {
    ///     g_signal_connect (extension, "page-created",
    ///                       G_CALLBACK (web_page_created_callback),
    ///                       NULL);
    /// }
    /// ```
    ///
    /// The previous piece of code shows a trivial example of an extension that notifies when
    /// a #WebKitWebPage is created.
    ///
    /// WebKit has to know where it can find the created WebKitWebProcessExtension. To do so you
    /// should use the webkit_web_context_set_web_extensions_directory() function. The signal
    /// #WebKitWebContext::initialize-web-extensions is the recommended place to call it.
    ///
    /// To provide the initialization data used by the webkit_web_process_extension_initialize_with_user_data()
    /// function, you have to call webkit_web_context_set_web_extensions_initialization_user_data() with
    /// the desired data as parameter. You can see an example of this in the following piece of code:
    ///
    /// **⚠️ The following code is in c ⚠️**
    ///
    /// ```c
    /// #define WEB_EXTENSIONS_DIRECTORY // ...
    ///
    /// static void
    /// initialize_web_extensions (WebKitWebContext *context,
    ///                            gpointer          user_data)
    /// {
    ///   // Web Extensions get a different ID for each Web Process
    ///   static guint32 unique_id = 0;
    ///
    ///   webkit_web_context_set_web_extensions_directory (
    ///      context, WEB_EXTENSIONS_DIRECTORY);
    ///   webkit_web_context_set_web_extensions_initialization_user_data (
    ///      context, g_variant_new_uint32 (unique_id++));
    /// }
    ///
    /// int main (int argc, char **argv)
    /// {
    ///   g_signal_connect (webkit_web_context_get_default (),
    ///                    "initialize-web-extensions",
    ///                     G_CALLBACK (initialize_web_extensions),
    ///                     NULL);
    ///
    ///   GtkWidget *view = webkit_web_view_new ();
    ///
    ///   // ...
    /// }
    /// ```
    ///
    /// ## Signals
    ///
    ///
    /// #### `page-created`
    ///  This signal is emitted when a new #WebKitWebPage is created in
    /// the Web Process.
    ///
    ///
    ///
    ///
    /// #### `user-message-received`
    ///  This signal is emitted when a #WebKitUserMessage is received from the
    /// #WebKitWebContext corresponding to @extension. Messages sent by #WebKitWebContext
    /// are always broadcasted to all web extensions and they can't be
    /// replied to. Calling webkit_user_message_send_reply() will do nothing.
    ///
    ///
    #[doc(alias = "WebKitWebProcessExtension")]
    pub struct WebProcessExtension(Object<ffi::WebKitWebProcessExtension, ffi::WebKitWebProcessExtensionClass>);

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

impl WebProcessExtension {
    /// Get the web page of the given @page_id.
    /// ## `page_id`
    /// the identifier of the #WebKitWebPage to get
    ///
    /// # Returns
    ///
    /// the #WebKitWebPage for the given @page_id, or [`None`] if the
    ///    identifier doesn't correspond to an existing web page.
    #[doc(alias = "webkit_web_process_extension_get_page")]
    #[doc(alias = "get_page")]
    pub fn page(&self, page_id: u64) -> Option<WebPage> {
        unsafe {
            from_glib_none(ffi::webkit_web_process_extension_get_page(
                self.to_glib_none().0,
                page_id,
            ))
        }
    }

    /// Send @message to the #WebKitWebContext corresponding to @self. If @message is floating, it's consumed.
    ///
    /// If you don't expect any reply, or you simply want to ignore it, you can pass [`None`] as @calback.
    /// When the operation is finished, @callback will be called. You can then call
    /// webkit_web_process_extension_send_message_to_context_finish() to get the message reply.
    /// ## `message`
    /// a #WebKitUserMessage
    /// ## `cancellable`
    /// a #GCancellable or [`None`] to ignore
    /// ## `callback`
    /// A #GAsyncReadyCallback to call when the request is satisfied or [`None`]
    #[doc(alias = "webkit_web_process_extension_send_message_to_context")]
    pub fn send_message_to_context<P: FnOnce(Result<UserMessage, glib::Error>) + 'static>(
        &self,
        message: &UserMessage,
        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 send_message_to_context_trampoline<
            P: FnOnce(Result<UserMessage, 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::webkit_web_process_extension_send_message_to_context_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 = send_message_to_context_trampoline::<P>;
        unsafe {
            ffi::webkit_web_process_extension_send_message_to_context(
                self.to_glib_none().0,
                message.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

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

    /// This signal is emitted when a new #WebKitWebPage is created in
    /// the Web Process.
    /// ## `web_page`
    /// the #WebKitWebPage created
    #[doc(alias = "page-created")]
    pub fn connect_page_created<F: Fn(&Self, &WebPage) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn page_created_trampoline<
            F: Fn(&WebProcessExtension, &WebPage) + 'static,
        >(
            this: *mut ffi::WebKitWebProcessExtension,
            web_page: *mut ffi::WebKitWebPage,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this), &from_glib_borrow(web_page))
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"page-created\0".as_ptr() as *const _,
                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
                    page_created_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    /// This signal is emitted when a #WebKitUserMessage is received from the
    /// #WebKitWebContext corresponding to @extension. Messages sent by #WebKitWebContext
    /// are always broadcasted to all web extensions and they can't be
    /// replied to. Calling webkit_user_message_send_reply() will do nothing.
    /// ## `message`
    /// the #WebKitUserMessage received
    #[doc(alias = "user-message-received")]
    pub fn connect_user_message_received<F: Fn(&Self, &UserMessage) + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn user_message_received_trampoline<
            F: Fn(&WebProcessExtension, &UserMessage) + 'static,
        >(
            this: *mut ffi::WebKitWebProcessExtension,
            message: *mut ffi::WebKitUserMessage,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this), &from_glib_borrow(message))
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"user-message-received\0".as_ptr() as *const _,
                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
                    user_message_received_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}