Skip to main content

json_glib/auto/
generator.rs

1// This file was generated by gir (https://github.com/gtk-rs/gir)
2// from gir
3// from gtk-girs (https://github.com/gtk-rs/gir-files)
4// DO NOT EDIT
5
6use crate::{Node, ffi};
7use glib::{
8    prelude::*,
9    signal::{SignalHandlerId, connect_raw},
10    translate::*,
11};
12use std::boxed::Box as Box_;
13
14glib::wrapper! {
15    /// `JsonGenerator` provides an object for generating a JSON data stream
16    /// from a tree of [`Node`][crate::Node] instances, and put it into a buffer
17    /// or a file.
18    ///
19    /// ## Properties
20    ///
21    ///
22    /// #### `indent`
23    ///  Number of spaces to be used to indent when pretty printing.
24    ///
25    /// Readable | Writeable
26    ///
27    ///
28    /// #### `indent-char`
29    ///  The character that should be used when indenting in pretty print.
30    ///
31    /// Readable | Writeable
32    ///
33    ///
34    /// #### `pretty`
35    ///  Whether the output should be "pretty-printed", with indentation and
36    /// newlines.
37    ///
38    /// The indentation level can be controlled by using the
39    /// [`indent`][struct@crate::Generator#indent] property.
40    ///
41    /// Readable | Writeable
42    ///
43    ///
44    /// #### `root`
45    ///  The root node to be used when constructing a JSON data
46    /// stream.
47    ///
48    /// Readable | Writeable
49    ///
50    /// # Implements
51    ///
52    /// [`GeneratorExt`][trait@crate::prelude::GeneratorExt], [`trait@glib::ObjectExt`]
53    #[doc(alias = "JsonGenerator")]
54    pub struct Generator(Object<ffi::JsonGenerator, ffi::JsonGeneratorClass>);
55
56    match fn {
57        type_ => || ffi::json_generator_get_type(),
58    }
59}
60
61impl Generator {
62    pub const NONE: Option<&'static Generator> = None;
63
64    /// Creates a new `JsonGenerator`.
65    ///
66    /// You can use this object to generate a JSON data stream starting from a
67    /// data object model composed by [`Node`][crate::Node]s.
68    ///
69    /// # Returns
70    ///
71    /// the newly created generator instance
72    #[doc(alias = "json_generator_new")]
73    pub fn new() -> Generator {
74        assert_initialized_main_thread!();
75        unsafe { from_glib_full(ffi::json_generator_new()) }
76    }
77
78    // rustdoc-stripper-ignore-next
79    /// Creates a new builder-pattern struct instance to construct [`Generator`] objects.
80    ///
81    /// This method returns an instance of [`GeneratorBuilder`](crate::builders::GeneratorBuilder) which can be used to create [`Generator`] objects.
82    pub fn builder() -> GeneratorBuilder {
83        GeneratorBuilder::new()
84    }
85}
86
87impl Default for Generator {
88    fn default() -> Self {
89        Self::new()
90    }
91}
92
93// rustdoc-stripper-ignore-next
94/// A [builder-pattern] type to construct [`Generator`] objects.
95///
96/// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
97#[must_use = "The builder must be built to be used"]
98pub struct GeneratorBuilder {
99    builder: glib::object::ObjectBuilder<'static, Generator>,
100}
101
102impl GeneratorBuilder {
103    fn new() -> Self {
104        Self {
105            builder: glib::object::Object::builder(),
106        }
107    }
108
109    /// Number of spaces to be used to indent when pretty printing.
110    pub fn indent(self, indent: u32) -> Self {
111        Self {
112            builder: self.builder.property("indent", indent),
113        }
114    }
115
116    /// The character that should be used when indenting in pretty print.
117    pub fn indent_char(self, indent_char: u32) -> Self {
118        Self {
119            builder: self.builder.property("indent-char", indent_char),
120        }
121    }
122
123    /// Whether the output should be "pretty-printed", with indentation and
124    /// newlines.
125    ///
126    /// The indentation level can be controlled by using the
127    /// [`indent`][struct@crate::Generator#indent] property.
128    pub fn pretty(self, pretty: bool) -> Self {
129        Self {
130            builder: self.builder.property("pretty", pretty),
131        }
132    }
133
134    /// The root node to be used when constructing a JSON data
135    /// stream.
136    pub fn root(self, root: &Node) -> Self {
137        Self {
138            builder: self.builder.property("root", root.clone()),
139        }
140    }
141
142    // rustdoc-stripper-ignore-next
143    /// Build the [`Generator`].
144    #[must_use = "Building the object from the builder is usually expensive and is not expected to have side effects"]
145    pub fn build(self) -> Generator {
146        assert_initialized_main_thread!();
147        self.builder.build()
148    }
149}
150
151/// Trait containing all [`struct@Generator`] methods.
152///
153/// # Implementors
154///
155/// [`Generator`][struct@crate::Generator]
156pub trait GeneratorExt: IsA<Generator> + 'static {
157    /// Retrieves the value set using [`set_indent()`][Self::set_indent()].
158    ///
159    /// # Returns
160    ///
161    /// the number of repetitions per indentation level
162    #[doc(alias = "json_generator_get_indent")]
163    #[doc(alias = "get_indent")]
164    fn indent(&self) -> u32 {
165        unsafe { ffi::json_generator_get_indent(self.as_ref().to_glib_none().0) }
166    }
167
168    /// Retrieves the value set using [`set_indent_char()`][Self::set_indent_char()].
169    ///
170    /// # Returns
171    ///
172    /// the character to be used when indenting
173    #[doc(alias = "json_generator_get_indent_char")]
174    #[doc(alias = "get_indent_char")]
175    #[doc(alias = "indent-char")]
176    fn indent_char(&self) -> char {
177        unsafe {
178            std::convert::TryFrom::try_from(ffi::json_generator_get_indent_char(
179                self.as_ref().to_glib_none().0,
180            ))
181            .expect("conversion from an invalid Unicode value attempted")
182        }
183    }
184
185    /// Retrieves the value set using [`set_pretty()`][Self::set_pretty()].
186    ///
187    /// # Returns
188    ///
189    /// `TRUE` if the generated JSON should be pretty-printed, and
190    ///   `FALSE` otherwise
191    #[doc(alias = "json_generator_get_pretty")]
192    #[doc(alias = "get_pretty")]
193    #[doc(alias = "pretty")]
194    fn is_pretty(&self) -> bool {
195        unsafe {
196            from_glib(ffi::json_generator_get_pretty(
197                self.as_ref().to_glib_none().0,
198            ))
199        }
200    }
201
202    /// Retrieves a pointer to the root node set using
203    /// [`set_root()`][Self::set_root()].
204    ///
205    /// # Returns
206    ///
207    /// the root node
208    #[doc(alias = "json_generator_get_root")]
209    #[doc(alias = "get_root")]
210    fn root(&self) -> Option<Node> {
211        unsafe { from_glib_none(ffi::json_generator_get_root(self.as_ref().to_glib_none().0)) }
212    }
213
214    /// Sets the number of repetitions for each indentation level.
215    /// ## `indent_level`
216    /// the number of repetitions of the indentation character
217    ///   that should be applied when pretty printing
218    #[doc(alias = "json_generator_set_indent")]
219    #[doc(alias = "indent")]
220    fn set_indent(&self, indent_level: u32) {
221        unsafe {
222            ffi::json_generator_set_indent(self.as_ref().to_glib_none().0, indent_level);
223        }
224    }
225
226    /// Sets the character to be used when indenting.
227    /// ## `indent_char`
228    /// a Unicode character to be used when indenting
229    #[doc(alias = "json_generator_set_indent_char")]
230    #[doc(alias = "indent-char")]
231    fn set_indent_char(&self, indent_char: char) {
232        unsafe {
233            ffi::json_generator_set_indent_char(
234                self.as_ref().to_glib_none().0,
235                indent_char.into_glib(),
236            );
237        }
238    }
239
240    /// Sets whether the generated JSON should be pretty printed.
241    ///
242    /// Pretty printing will use indentation character specified in the
243    /// [`indent-char`][struct@crate::Generator#indent-char] property and the spacing
244    /// specified in the [`indent`][struct@crate::Generator#indent] property.
245    /// ## `is_pretty`
246    /// whether the generated string should be pretty printed
247    #[doc(alias = "json_generator_set_pretty")]
248    #[doc(alias = "pretty")]
249    fn set_pretty(&self, is_pretty: bool) {
250        unsafe {
251            ffi::json_generator_set_pretty(self.as_ref().to_glib_none().0, is_pretty.into_glib());
252        }
253    }
254
255    /// Sets the root of the JSON data stream to be serialized by
256    /// the given generator.
257    ///
258    /// The passed `node` is copied by the generator object, so it can be
259    /// safely freed after calling this function.
260    /// ## `node`
261    /// the root node
262    #[doc(alias = "json_generator_set_root")]
263    #[doc(alias = "root")]
264    fn set_root(&self, node: &Node) {
265        unsafe {
266            ffi::json_generator_set_root(self.as_ref().to_glib_none().0, node.to_glib_none().0);
267        }
268    }
269
270    /// Sets the root of the JSON data stream to be serialized by
271    /// the given generator.
272    ///
273    /// The ownership of the passed `node` is transferred to the generator object.
274    /// ## `node`
275    /// the root node
276    #[cfg(feature = "v1_10")]
277    #[cfg_attr(docsrs, doc(cfg(feature = "v1_10")))]
278    #[doc(alias = "json_generator_take_root")]
279    fn take_root(&self, node: Option<Node>) {
280        unsafe {
281            ffi::json_generator_take_root(self.as_ref().to_glib_none().0, node.into_glib_ptr());
282        }
283    }
284
285    /// Generates a JSON data stream from @self and returns it as a
286    /// buffer.
287    ///
288    /// # Returns
289    ///
290    /// a newly allocated string holding a JSON data stream
291    ///
292    /// ## `length`
293    /// return location for the length of the returned
294    ///   buffer
295    #[doc(alias = "json_generator_to_data")]
296    fn to_data(&self) -> (glib::GString, usize) {
297        unsafe {
298            let mut length = std::mem::MaybeUninit::uninit();
299            let ret = from_glib_full(ffi::json_generator_to_data(
300                self.as_ref().to_glib_none().0,
301                length.as_mut_ptr(),
302            ));
303            (ret, length.assume_init())
304        }
305    }
306
307    /// Creates a JSON data stream and puts it inside `filename`, overwriting
308    /// the file's current contents.
309    ///
310    /// This operation is atomic, in the sense that the data is written to a
311    /// temporary file which is then renamed to the given `filename`.
312    /// ## `filename`
313    /// the path to the target file
314    ///
315    /// # Returns
316    ///
317    /// [`true`] if saving was successful.
318    #[doc(alias = "json_generator_to_file")]
319    fn to_file(&self, filename: impl AsRef<std::path::Path>) -> Result<(), glib::Error> {
320        unsafe {
321            let mut error = std::ptr::null_mut();
322            let is_ok = ffi::json_generator_to_file(
323                self.as_ref().to_glib_none().0,
324                filename.as_ref().to_glib_none().0,
325                &mut error,
326            );
327            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
328            if error.is_null() {
329                Ok(())
330            } else {
331                Err(from_glib_full(error))
332            }
333        }
334    }
335
336    // TODO: Find a way around converting glib::ffi::GString to glib::GString
337    // #[cfg(feature = "v1_4")]
338    // #[cfg_attr(docsrs, doc(cfg(feature = "v1_4")))]
339    // #[doc(alias = "json_generator_to_gstring")]
340    // fn to_gstring(&self, string: &mut String) -> glib::GString {
341    //     unsafe {
342    //         from_glib_none(ffi::json_generator_to_gstring(
343    //             self.as_ref().to_glib_none().0,
344    //             string.as_gstr().to_glib_none().0,
345    //         ))
346    //     }
347    // }
348
349    /// Outputs JSON data and writes it (synchronously) to the given stream.
350    /// ## `stream`
351    /// the output stream used to write the JSON data
352    /// ## `cancellable`
353    /// a `GCancellable`
354    ///
355    /// # Returns
356    ///
357    /// whether the write operation was successful
358    #[doc(alias = "json_generator_to_stream")]
359    fn to_stream(
360        &self,
361        stream: &impl IsA<gio::OutputStream>,
362        cancellable: Option<&impl IsA<gio::Cancellable>>,
363    ) -> Result<(), glib::Error> {
364        unsafe {
365            let mut error = std::ptr::null_mut();
366            let is_ok = ffi::json_generator_to_stream(
367                self.as_ref().to_glib_none().0,
368                stream.as_ref().to_glib_none().0,
369                cancellable.map(|p| p.as_ref()).to_glib_none().0,
370                &mut error,
371            );
372            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
373            if error.is_null() {
374                Ok(())
375            } else {
376                Err(from_glib_full(error))
377            }
378        }
379    }
380
381    #[doc(alias = "indent")]
382    fn connect_indent_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
383        unsafe extern "C" fn notify_indent_trampoline<P: IsA<Generator>, F: Fn(&P) + 'static>(
384            this: *mut ffi::JsonGenerator,
385            _param_spec: glib::ffi::gpointer,
386            f: glib::ffi::gpointer,
387        ) {
388            let f: &F = &*(f as *const F);
389            f(Generator::from_glib_borrow(this).unsafe_cast_ref())
390        }
391        unsafe {
392            let f: Box_<F> = Box_::new(f);
393            connect_raw(
394                self.as_ptr() as *mut _,
395                c"notify::indent".as_ptr() as *const _,
396                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
397                    notify_indent_trampoline::<Self, F> as *const (),
398                )),
399                Box_::into_raw(f),
400            )
401        }
402    }
403
404    #[doc(alias = "indent-char")]
405    fn connect_indent_char_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
406        unsafe extern "C" fn notify_indent_char_trampoline<
407            P: IsA<Generator>,
408            F: Fn(&P) + 'static,
409        >(
410            this: *mut ffi::JsonGenerator,
411            _param_spec: glib::ffi::gpointer,
412            f: glib::ffi::gpointer,
413        ) {
414            let f: &F = &*(f as *const F);
415            f(Generator::from_glib_borrow(this).unsafe_cast_ref())
416        }
417        unsafe {
418            let f: Box_<F> = Box_::new(f);
419            connect_raw(
420                self.as_ptr() as *mut _,
421                c"notify::indent-char".as_ptr() as *const _,
422                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
423                    notify_indent_char_trampoline::<Self, F> as *const (),
424                )),
425                Box_::into_raw(f),
426            )
427        }
428    }
429
430    #[doc(alias = "pretty")]
431    fn connect_pretty_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
432        unsafe extern "C" fn notify_pretty_trampoline<P: IsA<Generator>, F: Fn(&P) + 'static>(
433            this: *mut ffi::JsonGenerator,
434            _param_spec: glib::ffi::gpointer,
435            f: glib::ffi::gpointer,
436        ) {
437            let f: &F = &*(f as *const F);
438            f(Generator::from_glib_borrow(this).unsafe_cast_ref())
439        }
440        unsafe {
441            let f: Box_<F> = Box_::new(f);
442            connect_raw(
443                self.as_ptr() as *mut _,
444                c"notify::pretty".as_ptr() as *const _,
445                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
446                    notify_pretty_trampoline::<Self, F> as *const (),
447                )),
448                Box_::into_raw(f),
449            )
450        }
451    }
452
453    #[doc(alias = "root")]
454    fn connect_root_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
455        unsafe extern "C" fn notify_root_trampoline<P: IsA<Generator>, F: Fn(&P) + 'static>(
456            this: *mut ffi::JsonGenerator,
457            _param_spec: glib::ffi::gpointer,
458            f: glib::ffi::gpointer,
459        ) {
460            let f: &F = &*(f as *const F);
461            f(Generator::from_glib_borrow(this).unsafe_cast_ref())
462        }
463        unsafe {
464            let f: Box_<F> = Box_::new(f);
465            connect_raw(
466                self.as_ptr() as *mut _,
467                c"notify::root".as_ptr() as *const _,
468                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
469                    notify_root_trampoline::<Self, F> as *const (),
470                )),
471                Box_::into_raw(f),
472            )
473        }
474    }
475}
476
477impl<O: IsA<Generator>> GeneratorExt for O {}