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

use crate::{ContentDeserializer, ContentSerializer};
use glib::object::IsA;
use glib::translate::*;
use std::future;
use std::pin::Pin;
use std::ptr;

#[repr(packed)]
pub struct GRange(pub i32, pub i32);

/// Obtains a clip region which contains the areas where the given ranges
/// of text would be drawn.
///
/// @x_origin and @y_origin are the top left point to center the layout.
/// @index_ranges should contain ranges of bytes in the layout’s text.
///
/// Note that the regions returned correspond to logical extents of the text
/// ranges, not ink extents. So the drawn layout may in fact touch areas out of
/// the clip region.  The clip region is mainly useful for highlightling parts
/// of text, such as when text is selected.
/// ## `layout`
/// a [`pango::Layout`][crate::pango::Layout]
/// ## `x_origin`
/// X pixel where you intend to draw the layout with this clip
/// ## `y_origin`
/// Y pixel where you intend to draw the layout with this clip
/// ## `index_ranges`
/// array of byte indexes into the layout, where even members of array are start indexes and odd elements are end indexes
///
/// # Returns
///
/// a clip region containing the given ranges
#[doc(alias = "gdk_pango_layout_get_clip_region")]
pub fn pango_layout_get_clip_region(
    layout: &pango::Layout,
    x_origin: i32,
    y_origin: i32,
    index_ranges: &[GRange],
) -> cairo::Region {
    assert_initialized_main_thread!();

    let ptr: *const i32 = index_ranges.as_ptr() as _;
    unsafe {
        from_glib_full(ffi::gdk_pango_layout_get_clip_region(
            layout.to_glib_none().0,
            x_origin,
            y_origin,
            ptr,
            (index_ranges.len() / 2) as i32,
        ))
    }
}

/// Read content from the given input stream and deserialize it, asynchronously.
///
/// The default I/O priority is `G_PRIORITY_DEFAULT` (i.e. 0), and lower numbers
/// indicate a higher priority.
///
/// When the operation is finished, @callback will be called. You must then
/// call `content_deserialize_finish()` to get the result of the operation.
/// ## `stream`
/// a `GInputStream` to read the serialized content from
/// ## `mime_type`
/// the mime type to deserialize from
/// ## `type_`
/// the GType to deserialize from
/// ## `io_priority`
/// the I/O priority of the operation
/// ## `cancellable`
/// optional `GCancellable` object
/// ## `callback`
/// callback to call when the operation is done
#[doc(alias = "gdk_content_deserialize_async")]
pub fn content_deserialize_async<R: FnOnce(Result<glib::Value, glib::Error>) + 'static>(
    stream: &impl IsA<gio::InputStream>,
    mime_type: &str,
    type_: glib::types::Type,
    io_priority: glib::Priority,
    cancellable: Option<&impl IsA<gio::Cancellable>>,
    callback: R,
) {
    assert_initialized_main_thread!();
    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<R>> =
        Box::new(glib::thread_guard::ThreadGuard::new(callback));
    unsafe extern "C" fn content_deserialize_async_trampoline<
        R: FnOnce(Result<glib::Value, glib::Error>) + 'static,
    >(
        _source_object: *mut glib::gobject_ffi::GObject,
        res: *mut gio::ffi::GAsyncResult,
        user_data: glib::ffi::gpointer,
    ) {
        let mut error = ptr::null_mut();
        let mut value = glib::Value::uninitialized();
        let _ = ffi::gdk_content_deserialize_finish(res, value.to_glib_none_mut().0, &mut error);
        let result = if error.is_null() {
            Ok(value)
        } else {
            Err(from_glib_full(error))
        };
        let callback: Box<glib::thread_guard::ThreadGuard<R>> = Box::from_raw(user_data as *mut _);
        let callback = callback.into_inner();
        callback(result);
    }
    let callback = content_deserialize_async_trampoline::<R>;
    unsafe {
        ffi::gdk_content_deserialize_async(
            stream.as_ref().to_glib_none().0,
            mime_type.to_glib_none().0,
            type_.into_glib(),
            io_priority.into_glib(),
            cancellable.map(|p| p.as_ref()).to_glib_none().0,
            Some(callback),
            Box::into_raw(user_data) as *mut _,
        );
    }
}

pub fn content_deserialize_future(
    stream: &(impl IsA<gio::InputStream> + Clone + 'static),
    mime_type: &str,
    type_: glib::types::Type,
    io_priority: glib::Priority,
) -> Pin<Box<dyn future::Future<Output = Result<glib::Value, glib::Error>> + 'static>> {
    assert_initialized_main_thread!();

    let stream = stream.clone();
    let mime_type = String::from(mime_type);
    Box::pin(gio::GioFuture::new(&(), move |_obj, cancellable, send| {
        content_deserialize_async(
            &stream,
            &mime_type,
            type_,
            io_priority,
            Some(cancellable),
            move |res| {
                send.resolve(res);
            },
        );
    }))
}

/// Registers a function to deserialize object of a given type.
/// ## `mime_type`
/// the mime type which the function can deserialize from
/// ## `type_`
/// the type of objects that the function creates
/// ## `deserialize`
/// the callback
/// ## `notify`
/// destroy notify for @data
#[doc(alias = "gdk_content_register_deserializer")]
pub fn content_register_deserializer<
    T: 'static,
    P: Fn(&ContentDeserializer, &mut Option<T>) + 'static,
>(
    mime_type: &str,
    type_: glib::types::Type,
    deserialize: P,
) {
    assert_initialized_main_thread!();
    let deserialize_data: Box<P> = Box::new(deserialize);
    unsafe extern "C" fn deserialize_func<
        T: 'static,
        P: Fn(&ContentDeserializer, &mut Option<T>) + 'static,
    >(
        deserializer: *mut ffi::GdkContentDeserializer,
    ) {
        let deserializer: ContentDeserializer = from_glib_full(deserializer);
        let callback: &P =
            &*(ffi::gdk_content_deserializer_get_user_data(deserializer.to_glib_none().0)
                as *mut _);

        let mut task_data: *mut Option<T> =
            ffi::gdk_content_deserializer_get_task_data(deserializer.to_glib_none().0) as *mut _;
        if task_data.is_null() {
            unsafe extern "C" fn notify_func<T: 'static>(data: glib::ffi::gpointer) {
                let _task_data: Box<Option<T>> = Box::from_raw(data as *mut _);
            }
            task_data = Box::into_raw(Box::new(None));
            ffi::gdk_content_deserializer_set_task_data(
                deserializer.to_glib_none().0,
                task_data as *mut _,
                Some(notify_func::<T>),
            );
        }

        (*callback)(&deserializer, &mut *task_data);
    }
    let deserialize = Some(deserialize_func::<T, P> as _);
    unsafe extern "C" fn notify_func<
        T: 'static,
        P: Fn(&ContentDeserializer, &mut Option<T>) + 'static,
    >(
        data: glib::ffi::gpointer,
    ) {
        let _callback: Box<P> = Box::from_raw(data as *mut _);
    }
    let destroy_call4 = Some(notify_func::<T, P> as _);
    let super_callback0: Box<P> = deserialize_data;
    unsafe {
        ffi::gdk_content_register_deserializer(
            mime_type.to_glib_none().0,
            type_.into_glib(),
            deserialize,
            Box::into_raw(super_callback0) as *mut _,
            destroy_call4,
        );
    }
}

/// Registers a function to serialize objects of a given type.
/// ## `type_`
/// the type of objects that the function can serialize
/// ## `mime_type`
/// the mime type to serialize to
/// ## `serialize`
/// the callback
/// ## `notify`
/// destroy notify for @data
#[doc(alias = "gdk_content_register_serializer")]
pub fn content_register_serializer<
    T: 'static,
    P: Fn(&ContentSerializer, &mut Option<T>) + 'static,
>(
    type_: glib::types::Type,
    mime_type: &str,
    serialize: P,
) {
    assert_initialized_main_thread!();
    let serialize_data: Box<P> = Box::new(serialize);
    unsafe extern "C" fn serialize_func<
        T: 'static,
        P: Fn(&ContentSerializer, &mut Option<T>) + 'static,
    >(
        serializer: *mut ffi::GdkContentSerializer,
    ) {
        let serializer: ContentSerializer = from_glib_full(serializer);
        let callback: &P =
            &*(ffi::gdk_content_serializer_get_user_data(serializer.to_glib_none().0) as *mut _);

        let mut task_data: *mut Option<T> =
            ffi::gdk_content_serializer_get_task_data(serializer.to_glib_none().0) as *mut _;
        if task_data.is_null() {
            unsafe extern "C" fn notify_func<T: 'static>(data: glib::ffi::gpointer) {
                let _task_data: Box<Option<T>> = Box::from_raw(data as *mut _);
            }
            task_data = Box::into_raw(Box::new(None));
            ffi::gdk_content_serializer_set_task_data(
                serializer.to_glib_none().0,
                task_data as *mut _,
                Some(notify_func::<T>),
            );
        }

        (*callback)(&serializer, &mut *task_data);
    }
    let serialize = Some(serialize_func::<T, P> as _);
    unsafe extern "C" fn notify_func<
        T: 'static,
        P: Fn(&ContentSerializer, &mut Option<T>) + 'static,
    >(
        data: glib::ffi::gpointer,
    ) {
        let _callback: Box<P> = Box::from_raw(data as *mut _);
    }
    let destroy_call4 = Some(notify_func::<T, P> as _);
    let super_callback0: Box<P> = serialize_data;
    unsafe {
        ffi::gdk_content_register_serializer(
            type_.into_glib(),
            mime_type.to_glib_none().0,
            serialize,
            Box::into_raw(super_callback0) as *mut _,
            destroy_call4,
        );
    }
}

/// Serialize content and write it to the given output stream, asynchronously.
///
/// The default I/O priority is `G_PRIORITY_DEFAULT` (i.e. 0), and lower numbers
/// indicate a higher priority.
///
/// When the operation is finished, @callback will be called. You must then
/// call `content_serialize_finish()` to get the result of the operation.
/// ## `stream`
/// a `GOutputStream` to write the serialized content to
/// ## `mime_type`
/// the mime type to serialize to
/// ## `value`
/// the content to serialize
/// ## `io_priority`
/// the I/O priority of the operation
/// ## `cancellable`
/// optional `GCancellable` object
/// ## `callback`
/// callback to call when the operation is done
#[doc(alias = "gdk_content_serialize_async")]
pub fn content_serialize_async<R: FnOnce(Result<(), glib::Error>) + 'static>(
    stream: &impl IsA<gio::OutputStream>,
    mime_type: &str,
    value: &glib::Value,
    io_priority: glib::Priority,
    cancellable: Option<&impl IsA<gio::Cancellable>>,
    callback: R,
) {
    assert_initialized_main_thread!();
    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<R>> =
        Box::new(glib::thread_guard::ThreadGuard::new(callback));
    unsafe extern "C" fn content_serialize_async_trampoline<
        R: FnOnce(Result<(), glib::Error>) + 'static,
    >(
        _source_object: *mut glib::gobject_ffi::GObject,
        res: *mut gio::ffi::GAsyncResult,
        user_data: glib::ffi::gpointer,
    ) {
        let mut error = ptr::null_mut();
        let _ = ffi::gdk_content_serialize_finish(res, &mut error);
        let result = if error.is_null() {
            Ok(())
        } else {
            Err(from_glib_full(error))
        };
        let callback: Box<glib::thread_guard::ThreadGuard<R>> = Box::from_raw(user_data as *mut _);
        let callback = callback.into_inner();
        callback(result);
    }
    let callback = content_serialize_async_trampoline::<R>;
    unsafe {
        ffi::gdk_content_serialize_async(
            stream.as_ref().to_glib_none().0,
            mime_type.to_glib_none().0,
            value.to_glib_none().0,
            io_priority.into_glib(),
            cancellable.map(|p| p.as_ref()).to_glib_none().0,
            Some(callback),
            Box::into_raw(user_data) as *mut _,
        );
    }
}

pub fn content_serialize_future(
    stream: &(impl IsA<gio::OutputStream> + Clone + 'static),
    mime_type: &str,
    value: &glib::Value,
    io_priority: glib::Priority,
) -> Pin<Box<dyn future::Future<Output = Result<(), glib::Error>> + 'static>> {
    assert_initialized_main_thread!();

    let stream = stream.clone();
    let mime_type = String::from(mime_type);
    let value = value.clone();
    Box::pin(gio::GioFuture::new(&(), move |_obj, cancellable, send| {
        content_serialize_async(
            &stream,
            &mime_type,
            &value,
            io_priority,
            Some(cancellable),
            move |res| {
                send.resolve(res);
            },
        );
    }))
}

/// Obtains a clip region which contains the areas where the given
/// ranges of text would be drawn.
///
/// @x_origin and @y_origin are the top left position of the layout.
/// @index_ranges should contain ranges of bytes in the layout’s text.
/// The clip region will include space to the left or right of the line
/// (to the layout bounding box) if you have indexes above or below the
/// indexes contained inside the line. This is to draw the selection all
/// the way to the side of the layout. However, the clip region is in line
/// coordinates, not layout coordinates.
///
/// Note that the regions returned correspond to logical extents of the text
/// ranges, not ink extents. So the drawn line may in fact touch areas out of
/// the clip region.  The clip region is mainly useful for highlightling parts
/// of text, such as when text is selected.
/// ## `line`
/// a [`pango::LayoutLine`][crate::pango::LayoutLine]
/// ## `x_origin`
/// X pixel where you intend to draw the layout line with this clip
/// ## `y_origin`
/// baseline pixel where you intend to draw the layout line with this clip
/// ## `index_ranges`
/// array of byte indexes into the layout, where even
///   members of array are start indexes and odd elements are end indexes
///
/// # Returns
///
/// a clip region containing the given ranges
#[doc(alias = "gdk_pango_layout_line_get_clip_region")]
pub fn pango_layout_line_get_clip_region(
    line: &pango::LayoutLine,
    x_origin: i32,
    y_origin: i32,
    index_ranges: &[GRange],
) -> cairo::Region {
    assert_initialized_main_thread!();

    let ptr: *const i32 = index_ranges.as_ptr() as _;
    unsafe {
        from_glib_full(ffi::gdk_pango_layout_line_get_clip_region(
            line.to_glib_none().0,
            x_origin,
            y_origin,
            mut_override(ptr),
            (index_ranges.len() / 2) as i32,
        ))
    }
}