glib_macros/
lib.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3mod async_test;
4mod boxed_derive;
5mod clone;
6mod closure;
7mod derived_properties_attribute;
8mod downgrade_derive;
9mod enum_derive;
10mod error_domain_derive;
11mod flags_attribute;
12mod object_impl_attributes;
13mod properties;
14mod shared_boxed_derive;
15mod value_delegate_derive;
16mod variant_derive;
17
18mod utils;
19
20use flags_attribute::AttrInput;
21use proc_macro::TokenStream;
22use proc_macro2::Span;
23use syn::{parse_macro_input, DeriveInput};
24use utils::{parse_nested_meta_items_from_stream, NestedMetaItem};
25
26/// Macro for passing variables as strong or weak references into a closure.
27///
28/// This macro can be useful in combination with closures, e.g. signal handlers, to reduce the
29/// boilerplate required for passing strong or weak references into the closure. It will
30/// automatically create the new reference and pass it with the same name into the closure.
31///
32/// If upgrading the weak reference to a strong reference inside the closure is failing, the
33/// closure is immediately returning an optional default return value. If none is provided, `()` is
34/// returned.
35///
36/// **⚠️ IMPORTANT ⚠️**
37///
38/// `glib` needs to be in scope, so unless it's one of the direct crate dependencies, you need to
39/// import it because `clone!` is using it. For example:
40///
41/// ```rust,ignore
42/// use gtk::glib;
43/// ```
44///
45/// ### Debugging
46///
47/// In case something goes wrong inside the `clone!` macro, we use the [`g_debug`] macro. Meaning
48/// that if you want to see these debug messages, you'll have to set the `G_MESSAGES_DEBUG`
49/// environment variable when running your code (either in the code directly or when running the
50/// binary) to either "all" or [`CLONE_MACRO_LOG_DOMAIN`]:
51///
52/// [`g_debug`]: ../glib/macro.g_debug.html
53/// [`CLONE_MACRO_LOG_DOMAIN`]: ../glib/constant.CLONE_MACRO_LOG_DOMAIN.html
54///
55/// ```rust,ignore
56/// use glib::CLONE_MACRO_LOG_DOMAIN;
57///
58/// std::env::set_var("G_MESSAGES_DEBUG", CLONE_MACRO_LOG_DOMAIN);
59/// std::env::set_var("G_MESSAGES_DEBUG", "all");
60/// ```
61///
62/// Or:
63///
64/// ```bash
65/// $ G_MESSAGES_DEBUG=all ./binary
66/// ```
67///
68/// ### Passing a strong reference
69///
70/// ```
71/// use glib;
72/// use glib_macros::clone;
73/// use std::rc::Rc;
74///
75/// let v = Rc::new(1);
76/// let closure = clone!(
77///     #[strong] v,
78///     move |x| {
79///         println!("v: {}, x: {}", v, x);
80///     },
81/// );
82///
83/// closure(2);
84/// ```
85///
86/// ### Passing a weak reference
87///
88/// ```
89/// use glib;
90/// use glib_macros::clone;
91/// use std::rc::Rc;
92///
93/// let u = Rc::new(2);
94/// let closure = clone!(
95///     #[weak]
96///     u,
97///     move |x| {
98///         println!("u: {}, x: {}", u, x);
99///     },
100/// );
101///
102/// closure(3);
103/// ```
104///
105/// #### Allowing a nullable weak reference
106///
107/// In some cases, even if the weak references can't be retrieved, you might want to still have
108/// your closure called. In this case, you need to use `#[weak_allow_none]` instead of `#[weak]`:
109///
110/// ```
111/// use glib;
112/// use glib_macros::clone;
113/// use std::rc::Rc;
114///
115/// let closure = {
116///     // This `Rc` won't be available in the closure because it's dropped at the end of the
117///     // current block
118///     let u = Rc::new(2);
119///     clone!(
120///         #[weak_allow_none]
121///         u,
122///         move |x| {
123///             // We need to use a Debug print for `u` because it'll be an `Option`.
124///             println!("u: {:?}, x: {}", u, x);
125///             true
126///         },
127///     )
128/// };
129///
130/// assert_eq!(closure(3), true);
131/// ```
132///
133/// ### Creating owned values from references (`ToOwned`)
134///
135/// ```
136/// use glib;
137/// use glib_macros::clone;
138///
139/// let v = "123";
140/// let closure = clone!(
141///     #[to_owned] v,
142///     move |x| {
143///         // v is passed as `String` here
144///         println!("v: {}, x: {}", v, x);
145///     },
146/// );
147///
148/// closure(2);
149/// ```
150///
151/// ### Renaming variables
152///
153/// ```
154/// use glib;
155/// use glib_macros::clone;
156/// use std::rc::Rc;
157///
158/// let v = Rc::new(1);
159/// let u = Rc::new(2);
160/// let closure = clone!(
161///     #[strong(rename_to = y)]
162///     v,
163///     #[weak] u,
164///     move |x| {
165///         println!("v as y: {}, u: {}, x: {}", y, u, x);
166///     },
167/// );
168///
169/// closure(3);
170/// ```
171///
172/// ### Providing a return value if upgrading a weak reference fails
173///
174/// By default, `()` is returned if upgrading a weak reference fails. This behaviour can be
175/// adjusted in two different ways:
176///
177/// Either by providing the value yourself using one of
178///
179///   * `#[upgrade_or]`: Requires an expression that returns a `Copy` value of the expected return type,
180///   * `#[upgrade_or_else]`: Requires a closure that returns a value of the expected return type,
181///   * `#[upgrade_or_default]`: Requires that the return type implements `Default` and returns that.
182///
183/// ```
184/// use glib;
185/// use glib_macros::clone;
186/// use std::rc::Rc;
187///
188/// let v = Rc::new(1);
189/// let closure = clone!(
190///     #[weak] v,
191///     #[upgrade_or]
192///     false,
193///     move |x| {
194///         println!("v: {}, x: {}", v, x);
195///         true
196///     },
197/// );
198///
199/// // Drop value so that the weak reference can't be upgraded.
200/// drop(v);
201///
202/// assert_eq!(closure(2), false);
203/// ```
204///
205/// Or by using `#[upgrade_or_panic]`: If the value fails to get upgraded, it'll panic.
206///
207/// ```should_panic
208/// # use glib;
209/// # use glib_macros::clone;
210/// # use std::rc::Rc;
211/// # let v = Rc::new(1);
212/// let closure = clone!(
213///     #[weak] v,
214///     #[upgrade_or_panic]
215///     move |x| {
216///         println!("v: {}, x: {}", v, x);
217///         true
218///     },
219/// );
220/// # drop(v);
221/// # assert_eq!(closure(2), false);
222/// ```
223///
224/// ### Errors
225///
226/// Here is a list of errors you might encounter:
227///
228/// **Missing `#[weak]` or `#[strong]`**:
229///
230/// ```compile_fail
231/// # use glib;
232/// # use glib_macros::clone;
233/// # use std::rc::Rc;
234/// let v = Rc::new(1);
235///
236/// let closure = clone!(
237///     v,
238///     move |x| println!("v: {}, x: {}", v, x),
239/// );
240/// # drop(v);
241/// # closure(2);
242/// ```
243///
244/// **Passing `self` as an argument**:
245///
246/// ```compile_fail
247/// # use glib;
248/// # use glib_macros::clone;
249/// # use std::rc::Rc;
250/// #[derive(Debug)]
251/// struct Foo;
252///
253/// impl Foo {
254///     fn foo(&self) {
255///         let closure = clone!(
256///             #[strong] self,
257///             move |x| {
258///                 println!("self: {:?}", self);
259///             },
260///         );
261///         # closure(2);
262///     }
263/// }
264/// ```
265///
266/// If you want to use `self` directly, you'll need to rename it:
267///
268/// ```
269/// # use glib;
270/// # use glib_macros::clone;
271/// # use std::rc::Rc;
272/// #[derive(Debug)]
273/// struct Foo;
274///
275/// impl Foo {
276///     fn foo(&self) {
277///         let closure = clone!(
278///             #[strong(rename_to = this)]
279///             self,
280///             move |x| {
281///                 println!("self: {:?}", this);
282///             },
283///         );
284///         # closure(2);
285///     }
286/// }
287/// ```
288///
289/// **Passing fields directly**
290///
291/// ```compile_fail
292/// # use glib;
293/// # use glib_macros::clone;
294/// # use std::rc::Rc;
295/// #[derive(Debug)]
296/// struct Foo {
297///     v: Rc<usize>,
298/// }
299///
300/// impl Foo {
301///     fn foo(&self) {
302///         let closure = clone!(
303///             #[strong] self.v,
304///             move |x| {
305///                 println!("self.v: {:?}", v);
306///             },
307///         );
308///         # closure(2);
309///     }
310/// }
311/// ```
312///
313/// You can do it by renaming it:
314///
315/// ```
316/// # use glib;
317/// # use glib_macros::clone;
318/// # use std::rc::Rc;
319/// # struct Foo {
320/// #     v: Rc<usize>,
321/// # }
322/// impl Foo {
323///     fn foo(&self) {
324///         let closure = clone!(
325///             #[strong(rename_to = v)]
326///             self.v,
327///             move |x| {
328///                 println!("self.v: {}", v);
329///             },
330///         );
331///         # closure(2);
332///     }
333/// }
334/// ```
335#[proc_macro]
336pub fn clone(item: TokenStream) -> TokenStream {
337    clone::clone_inner(item)
338}
339
340/// Macro for creating a [`Closure`] object. This is a wrapper around [`Closure::new`] that
341/// automatically type checks its arguments at run-time.
342///
343/// A `Closure` takes [`Value`] objects as inputs and output. This macro will automatically convert
344/// the inputs to Rust types when invoking its callback, and then will convert the output back to a
345/// `Value`. All inputs must implement the [`FromValue`] trait, and outputs must either implement
346/// the [`ToValue`] trait or be the unit type `()`. Type-checking of inputs is done at run-time; if
347/// incorrect types are passed via [`Closure::invoke`] then the closure will panic. Note that when
348/// passing input types derived from [`Object`] or [`Interface`], you must take care to upcast to
349/// the exact object or interface type that is being received.
350///
351/// Similarly to [`clone!`](crate::clone!), this macro can be useful in combination with signal
352/// handlers to reduce boilerplate when passing references. Unique to `Closure` objects is the
353/// ability to watch an object using the `#[watch]` attribute. Only an [`Object`] value can be
354/// passed to `#[watch]`, and only one object can be watched per closure. When an object is watched,
355/// a weak reference to the object is held in the closure. When the object is destroyed, the
356/// closure will become invalidated: all signal handlers connected to the closure will become
357/// disconnected, and any calls to [`Closure::invoke`] on the closure will be silently ignored.
358/// Internally, this is accomplished using [`Object::watch_closure`] on the watched object.
359///
360/// The `#[weak]`, `#[weak_allow_none]`, `#[strong]`, `#[to_owned]` captures are also supported and
361/// behave the same as in [`clone!`](crate::clone!), as is aliasing captures via `rename_to`.
362/// Similarly, upgrade failure of weak references can be adjusted via `#[upgrade_or]`,
363/// `#[upgrade_or_else]`, `#[upgrade_or_default]` and `#[upgrade_or_panic]`.
364///
365/// Notably, these captures are able to reference `Rc` and `Arc` values in addition to `Object`
366/// values.
367///
368/// [`Closure`]: ../glib/closure/struct.Closure.html
369/// [`Closure::new`]: ../glib/closure/struct.Closure.html#method.new
370/// [`Closure::new_local`]: ../glib/closure/struct.Closure.html#method.new_local
371/// [`Closure::invoke`]: ../glib/closure/struct.Closure.html#method.invoke
372/// [`Value`]: ../glib/value/struct.Value.html
373/// [`FromValue`]: ../glib/value/trait.FromValue.html
374/// [`ToValue`]: ../glib/value/trait.ToValue.html
375/// [`Interface`]: ../glib/object/struct.Interface.html
376/// [`Object`]: ../glib/object/struct.Object.html
377/// [`Object::watch_closure`]: ../glib/object/trait.ObjectExt.html#tymethod.watch_closure
378/// **⚠️ IMPORTANT ⚠️**
379///
380/// `glib` needs to be in scope, so unless it's one of the direct crate dependencies, you need to
381/// import it because `closure!` is using it. For example:
382///
383/// ```rust,ignore
384/// use gtk::glib;
385/// ```
386///
387/// ### Using as a closure object
388///
389/// ```
390/// use glib_macros::closure;
391///
392/// let concat_str = closure!(|s: &str| s.to_owned() + " World");
393/// let result = concat_str.invoke::<String>(&[&"Hello"]);
394/// assert_eq!(result, "Hello World");
395/// ```
396///
397/// ### Connecting to a signal
398///
399/// For wrapping closures that can't be sent across threads, the
400/// [`closure_local!`](crate::closure_local!) macro can be used. It has the same syntax as
401/// `closure!`, but instead uses [`Closure::new_local`] internally.
402///
403/// ```
404/// use glib;
405/// use glib::prelude::*;
406/// use glib_macros::closure_local;
407///
408/// let obj = glib::Object::new::<glib::Object>();
409/// obj.connect_closure(
410///     "notify", false,
411///     closure_local!(|_obj: glib::Object, pspec: glib::ParamSpec| {
412///         println!("property notify: {}", pspec.name());
413///     }));
414/// ```
415///
416/// ### Object Watching
417///
418/// ```
419/// use glib;
420/// use glib::prelude::*;
421/// use glib_macros::closure_local;
422///
423/// let closure = {
424///     let obj = glib::Object::new::<glib::Object>();
425///     let closure = closure_local!(
426///         #[watch] obj,
427///         move || {
428///             obj.type_().name()
429///         },
430///     );
431///     assert_eq!(closure.invoke::<String>(&[]), "GObject");
432///     closure
433/// };
434/// // `obj` is dropped, closure invalidated so it always does nothing and returns None
435/// closure.invoke::<()>(&[]);
436/// ```
437///
438/// `#[watch]` has special behavior when connected to a signal:
439///
440/// ```
441/// use glib;
442/// use glib::prelude::*;
443/// use glib_macros::closure_local;
444///
445/// let obj = glib::Object::new::<glib::Object>();
446/// {
447///     let other = glib::Object::new::<glib::Object>();
448///     obj.connect_closure(
449///         "notify", false,
450///         closure_local!(
451///             #[watch(rename_to = b)]
452///             other,
453///             move |a: glib::Object, pspec: glib::ParamSpec| {
454///                 let value = a.property_value(pspec.name());
455///                 b.set_property(pspec.name(), &value);
456///             },
457///         ),
458///     );
459///     // The signal handler will disconnect automatically at the end of this
460///     // block when `other` is dropped.
461/// }
462/// ```
463///
464/// ### Weak and Strong References
465///
466/// ```
467/// use glib;
468/// use glib::prelude::*;
469/// use glib_macros::closure;
470/// use std::sync::Arc;
471///
472/// let closure = {
473///     let a = Arc::new(String::from("Hello"));
474///     let b = Arc::new(String::from("World"));
475///     let c = "!";
476///     let closure = closure!(
477///         #[strong] a,
478///         #[weak_allow_none]
479///         b,
480///         #[to_owned]
481///         c,
482///         move || {
483///             // `a` is Arc<String>, `b` is Option<Arc<String>>, `c` is a `String`
484///             format!("{} {}{}", a, b.as_ref().map(|b| b.as_str()).unwrap_or_else(|| "Moon"), c)
485///         },
486///     );
487///     assert_eq!(closure.invoke::<String>(&[]), "Hello World!");
488///     closure
489/// };
490/// // `a`, `c` still kept alive, `b` is dropped
491/// assert_eq!(closure.invoke::<String>(&[]), "Hello Moon!");
492/// ```
493#[proc_macro]
494pub fn closure(item: TokenStream) -> TokenStream {
495    closure::closure_inner(item, "new")
496}
497
498/// The same as [`closure!`](crate::closure!) but uses [`Closure::new_local`] as a constructor.
499/// This is useful for closures which can't be sent across threads. See the documentation of
500/// [`closure!`](crate::closure!) for details.
501///
502/// [`Closure::new_local`]: ../glib/closure/struct.Closure.html#method.new_local
503#[proc_macro]
504pub fn closure_local(item: TokenStream) -> TokenStream {
505    closure::closure_inner(item, "new_local")
506}
507
508/// Derive macro to register a Rust enum in the GLib type system and derive the
509/// [`glib::Value`] traits.
510///
511/// # Example
512///
513/// ```
514/// use glib::prelude::*;
515/// use glib::subclass::prelude::*;
516///
517/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
518/// #[enum_type(name = "MyEnum")]
519/// enum MyEnum {
520///     Val,
521///     #[enum_value(name = "My Val")]
522///     ValWithCustomName,
523///     #[enum_value(name = "My Other Val", nick = "other")]
524///     ValWithCustomNameAndNick,
525/// }
526/// ```
527///
528/// An enum can be registered as a dynamic type by setting the derive macro
529/// helper attribute `enum_dynamic`:
530///
531/// ```ignore
532/// use glib::prelude::*;
533/// use glib::subclass::prelude::*;
534///
535/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
536/// #[enum_type(name = "MyEnum")]
537/// #[enum_dynamic]
538/// enum MyEnum {
539///     ...
540/// }
541/// ```
542///
543/// As a dynamic type, an enum must be explicitly registered when the system
544/// loads the implementation (see [`TypePlugin`] and [`TypeModule`]).
545/// Therefore, whereas an enum can be registered only once as a static type,
546/// it can be registered several times as a dynamic type.
547///
548/// An enum registered as a dynamic type is never unregistered. The system
549/// calls [`TypePluginExt::unuse`] to unload the implementation. If the
550/// [`TypePlugin`] subclass is a [`TypeModule`], the enum registered as a
551/// dynamic type is marked as unloaded and must be registered again when the
552/// module is reloaded.
553///
554/// The derive macro helper attribute `enum_dynamic` provides two behaviors
555/// when registering an enum as a dynamic type:
556///
557/// - lazy registration: by default an enum is registered as a dynamic type
558///   when the system loads the implementation (e.g. when the module is loaded).
559///   Optionally setting `lazy_registration` to `true` postpones registration on
560///   the first use (when `static_type()` is called for the first time):
561///
562/// ```ignore
563/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
564/// #[enum_type(name = "MyEnum")]
565/// #[enum_dynamic(lazy_registration = true)]
566/// enum MyEnum {
567///     ...
568/// }
569/// ```
570///
571/// - registration within [`TypeModule`] subclass or within [`TypePlugin`]
572///   subclass: an enum is usually registered as a dynamic type within a
573///   [`TypeModule`] subclass:
574///
575/// ```ignore
576/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
577/// #[enum_type(name = "MyModuleEnum")]
578/// #[enum_dynamic]
579/// enum MyModuleEnum {
580///     ...
581/// }
582/// ...
583/// #[derive(Default)]
584/// pub struct MyModule;
585/// ...
586/// impl TypeModuleImpl for MyModule {
587///     fn load(&self) -> bool {
588///         // registers enums as dynamic types.
589///         let my_module = self.obj();
590///         let type_module: &glib::TypeModule = my_module.upcast_ref();
591///         MyModuleEnum::on_implementation_load(type_module)
592///     }
593///     ...
594/// }
595/// ```
596///
597/// Optionally setting `plugin_type` allows to register an enum as a dynamic
598/// type within a [`TypePlugin`] subclass that is not a [`TypeModule`]:
599///
600/// ```ignore
601/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
602/// #[enum_type(name = "MyPluginEnum")]
603/// #[enum_dynamic(plugin_type = MyPlugin)]
604/// enum MyPluginEnum {
605///     ...
606/// }
607/// ...
608/// #[derive(Default)]
609/// pub struct MyPlugin;
610/// ...
611/// impl TypePluginImpl for MyPlugin {
612///     fn use_plugin(&self) {
613///         // register enums as dynamic types.
614///         let my_plugin = self.obj();
615///         MyPluginEnum::on_implementation_load(my_plugin.as_ref());
616///     }
617///     ...
618/// }
619/// ```
620///
621/// [`glib::Value`]: ../glib/value/struct.Value.html
622/// [`TypePlugin`]: ../glib/gobject/type_plugin/struct.TypePlugin.html
623/// [`TypeModule`]: ../glib/gobject/type_module/struct.TypeModule.html
624/// [`TypePluginExt::unuse`]: ../glib/gobject/type_plugin/trait.TypePluginExt.
625#[proc_macro_derive(Enum, attributes(enum_type, enum_dynamic, enum_value))]
626pub fn enum_derive(input: TokenStream) -> TokenStream {
627    let input = parse_macro_input!(input as DeriveInput);
628    enum_derive::impl_enum(&input)
629        .unwrap_or_else(syn::Error::into_compile_error)
630        .into()
631}
632
633/// Attribute macro for defining flags using the `bitflags` crate.
634/// This macro will also define a `GFlags::type_` function and
635/// the [`glib::Value`] traits.
636///
637/// The expected `GType` name has to be passed as macro attribute.
638/// The name and nick of each flag can also be optionally defined.
639/// Default name is the flag identifier in CamelCase and default nick
640/// is the identifier in kebab-case.
641/// Combined flags should not be registered with the `GType` system
642/// and so need to be tagged with the `#[flags_value(skip)]` attribute.
643///
644/// # Example
645///
646/// ```
647/// use glib::prelude::*;
648/// use glib::subclass::prelude::*;
649///
650/// #[glib::flags(name = "MyFlags")]
651/// enum MyFlags {
652///     #[flags_value(name = "Flag A", nick = "nick-a")]
653///     A = 0b00000001,
654///     #[flags_value(name = "Flag B")]
655///     B = 0b00000010,
656///     #[flags_value(skip)]
657///     AB = Self::A.bits() | Self::B.bits(),
658///     C = 0b00000100,
659/// }
660/// ```
661///
662/// The flags can be registered as a dynamic type by setting the macro helper
663/// attribute `flags_dynamic`:
664/// ```ignore
665/// use glib::prelude::*;
666/// use glib::subclass::prelude::*;
667///
668/// #[glib::flags(name = "MyFlags")]
669/// #[flags_dynamic]
670/// enum MyFlags {
671///     ...
672/// }
673/// ```
674///
675/// As a dynamic type, the flags must be explicitly registered when the system
676/// loads the implementation (see [`TypePlugin`] and [`TypeModule`]).
677/// Therefore, whereas the flags can be registered only once as a static type,
678/// they can be registered several times as a dynamic type.
679///
680/// The flags registered as a dynamic type are never unregistered. The system
681/// calls [`TypePluginExt::unuse`] to unload the implementation. If the
682/// [`TypePlugin`] subclass is a [`TypeModule`], the flags registered as a
683/// dynamic type are marked as unloaded and must be registered again when the
684/// module is reloaded.
685///
686/// The macro helper attribute `flags_dynamic` provides two behaviors when
687/// registering the flags as a dynamic type:
688///
689/// - lazy registration: by default the flags are registered as a dynamic type
690///   when the system loads the implementation (e.g. when the module is loaded).
691///   Optionally setting `lazy_registration` to `true` postpones registration on
692///   the first use (when `static_type()` is called for the first time):
693///
694/// ```ignore
695/// #[glib::flags(name = "MyFlags")]
696/// #[flags_dynamic(lazy_registration = true)]
697/// enum MyFlags {
698///     ...
699/// }
700/// ```
701///
702/// - registration within [`TypeModule`] subclass or within [`TypePlugin`]
703///   subclass: the flags are usually registered as a dynamic type within a
704///   [`TypeModule`] subclass:
705///
706/// ```ignore
707/// #[glib::flags(name = "MyModuleFlags")]
708/// #[flags_dynamic]
709/// enum MyModuleFlags {
710///     ...
711/// }
712/// ...
713/// #[derive(Default)]
714/// pub struct MyModule;
715/// ...
716/// impl TypeModuleImpl for MyModule {
717///     fn load(&self) -> bool {
718///         // registers flags as dynamic types.
719///         let my_module = self.obj();
720///         let type_module: &glib::TypeModule = my_module.upcast_ref();
721///         MyModuleFlags::on_implementation_load(type_module)
722///     }
723///     ...
724/// }
725/// ```
726///
727/// Optionally setting `plugin_type` allows to register the flags as a dynamic
728/// type within a [`TypePlugin`] subclass that is not a [`TypeModule`]:
729/// ```ignore
730/// #[glib::flags(name = "MyModuleFlags")]
731/// #[flags_dynamic(plugin_type = MyPlugin)]
732/// enum MyModuleFlags {
733///     ...
734/// }
735/// ...
736/// #[derive(Default)]
737/// pub struct MyPlugin;
738/// ...
739/// impl TypePluginImpl for MyPlugin {
740///     fn use_plugin(&self) {
741///         // register flags as dynamic types.
742///         let my_plugin = self.obj();
743///         MyPluginFlags::on_implementation_load(my_plugin.as_ref());
744///     }
745///     ...
746/// }
747/// ```
748///
749/// [`glib::Value`]: ../glib/value/struct.Value.html
750/// [`TypePlugin`]: ../glib/gobject/type_plugin/struct.TypePlugin.html
751/// [`TypeModule`]: ../glib/gobject/type_module/struct.TypeModule.html
752/// [`TypePluginExt::unuse`]: ../glib/gobject/type_plugin/trait.TypePluginExt.
753#[proc_macro_attribute]
754pub fn flags(attr: TokenStream, item: TokenStream) -> TokenStream {
755    let mut name = NestedMetaItem::<syn::LitStr>::new("name")
756        .required()
757        .value_required();
758    let mut allow_name_conflict_attr =
759        NestedMetaItem::<syn::LitBool>::new("allow_name_conflict").value_optional();
760
761    if let Err(e) = parse_nested_meta_items_from_stream(
762        attr.into(),
763        &mut [&mut name, &mut allow_name_conflict_attr],
764    ) {
765        return e.to_compile_error().into();
766    }
767
768    let allow_name_conflict = allow_name_conflict_attr.found
769        || allow_name_conflict_attr
770            .value
771            .map(|b| b.value())
772            .unwrap_or(false);
773
774    let attr_meta = AttrInput {
775        enum_name: name.value.unwrap(),
776        allow_name_conflict,
777    };
778
779    syn::parse::<syn::ItemEnum>(item)
780        .map_err(|_| syn::Error::new(Span::call_site(), flags_attribute::WRONG_PLACE_MSG))
781        .map(|mut input| flags_attribute::impl_flags(attr_meta, &mut input))
782        .unwrap_or_else(syn::Error::into_compile_error)
783        .into()
784}
785
786/// Derive macro for defining a GLib error domain and its associated
787/// [`ErrorDomain`] trait.
788///
789/// # Example
790///
791/// ```
792/// use glib::prelude::*;
793/// use glib::subclass::prelude::*;
794///
795/// #[derive(Debug, Copy, Clone, glib::ErrorDomain)]
796/// #[error_domain(name = "ex-foo")]
797/// enum Foo {
798///     Blah,
799///     Baaz,
800/// }
801/// ```
802///
803/// [`ErrorDomain`]: ../glib/error/trait.ErrorDomain.html
804#[proc_macro_derive(ErrorDomain, attributes(error_domain))]
805pub fn error_domain_derive(input: TokenStream) -> TokenStream {
806    let input = parse_macro_input!(input as DeriveInput);
807    error_domain_derive::impl_error_domain(&input)
808        .unwrap_or_else(syn::Error::into_compile_error)
809        .into()
810}
811
812/// Derive macro for defining a [`BoxedType`]`::type_` function and
813/// the [`glib::Value`] traits. Optionally, the type can be marked as
814/// `nullable` to get an implementation of `glib::value::ToValueOptional`.
815///
816/// # Example
817///
818/// ```
819/// use glib::prelude::*;
820/// use glib::subclass::prelude::*;
821///
822/// #[derive(Clone, Debug, PartialEq, Eq, glib::Boxed)]
823/// #[boxed_type(name = "MyBoxed")]
824/// struct MyBoxed(String);
825///
826/// #[derive(Clone, Debug, PartialEq, Eq, glib::Boxed)]
827/// #[boxed_type(name = "MyNullableBoxed", nullable)]
828/// struct MyNullableBoxed(String);
829/// ```
830///
831/// [`BoxedType`]: ../glib/subclass/boxed/trait.BoxedType.html
832/// [`glib::Value`]: ../glib/value/struct.Value.html
833#[proc_macro_derive(Boxed, attributes(boxed_type))]
834pub fn boxed_derive(input: TokenStream) -> TokenStream {
835    let input = parse_macro_input!(input as DeriveInput);
836    boxed_derive::impl_boxed(&input)
837        .unwrap_or_else(syn::Error::into_compile_error)
838        .into()
839}
840
841/// Derive macro for defining a [`SharedType`]`::get_type` function and
842/// the [`glib::Value`] traits. Optionally, the type can be marked as
843/// `nullable` to get an implementation of `glib::value::ToValueOptional`.
844///
845/// # Example
846///
847/// ```
848/// use glib::prelude::*;
849/// use glib::subclass::prelude::*;
850///
851/// #[derive(Clone, Debug, PartialEq, Eq)]
852/// struct MySharedInner {
853///   foo: String,
854/// }
855///
856/// #[derive(Clone, Debug, PartialEq, Eq, glib::SharedBoxed)]
857/// #[shared_boxed_type(name = "MySharedBoxed")]
858/// struct MySharedBoxed(std::sync::Arc<MySharedInner>);
859///
860/// #[derive(Clone, Debug, PartialEq, Eq, glib::SharedBoxed)]
861/// #[shared_boxed_type(name = "MyNullableSharedBoxed", nullable)]
862/// struct MyNullableSharedBoxed(std::sync::Arc<MySharedInner>);
863/// ```
864///
865/// [`SharedType`]: ../glib/subclass/shared/trait.SharedType.html
866/// [`glib::Value`]: ../glib/value/struct.Value.html
867#[proc_macro_derive(SharedBoxed, attributes(shared_boxed_type))]
868pub fn shared_boxed_derive(input: TokenStream) -> TokenStream {
869    let input = parse_macro_input!(input as DeriveInput);
870    shared_boxed_derive::impl_shared_boxed(&input)
871        .unwrap_or_else(syn::Error::into_compile_error)
872        .into()
873}
874
875/// Macro for boilerplate of [`ObjectSubclass`] implementations.
876///
877/// This adds implementations for the `type_data()` and `type_()` methods,
878/// which should probably never be defined differently.
879///
880/// It provides default values for the `Instance`, `Class`, and `Interfaces`
881/// type parameters. If these are present, the macro will use the provided value
882/// instead of the default.
883///
884/// Usually the defaults for `Instance` and `Class` will work. `Interfaces` is
885/// necessary for types that implement interfaces.
886///
887/// ```ignore
888/// type Instance = glib::subclass::basic::InstanceStruct<Self>;
889/// type Class = glib::subclass::basic::ClassStruct<Self>;
890/// type Interfaces = ();
891/// ```
892///
893/// If no `new()` or `with_class()` method is provided, the macro adds a `new()`
894/// implementation calling `Default::default()`. So the type needs to implement
895/// `Default`, or this should be overridden.
896///
897/// ```ignore
898/// fn new() -> Self {
899///     Default::default()
900/// }
901/// ```
902///
903/// An object subclass can be registered as a dynamic type by setting the macro
904/// helper attribute `object_class_dynamic`:
905///
906/// ```ignore
907/// #[derive(Default)]
908/// pub struct MyType;
909///
910/// #[glib::object_subclass]
911/// #[object_subclass_dynamic]
912/// impl ObjectSubclass for MyType { ... }
913/// ```
914///
915/// As a dynamic type, an object subclass must be explicitly registered when
916/// the system loads the implementation (see [`TypePlugin`] and [`TypeModule`]).
917/// Therefore, whereas an object subclass can be registered only once as a
918/// static type, it can be registered several times as a dynamic type.
919///
920/// An object subclass registered as a dynamic type is never unregistered. The
921/// system calls [`TypePluginExt::unuse`] to unload the implementation. If the
922/// [`TypePlugin`] subclass is a [`TypeModule`], the object subclass registered
923/// as a dynamic type is marked as unloaded and must be registered again when
924/// the module is reloaded.
925///
926/// The macro helper attribute `object_class_dynamic` provides two behaviors
927/// when registering an object subclass as a dynamic type:
928///
929/// - lazy registration: by default an object subclass is registered as a
930///   dynamic type when the system loads the implementation (e.g. when the module
931///   is loaded). Optionally setting `lazy_registration` to `true` postpones
932///   registration on the first use (when `static_type()` is called for the first
933///   time):
934///
935/// ```ignore
936/// #[derive(Default)]
937/// pub struct MyType;
938///
939/// #[glib::object_subclass]
940/// #[object_subclass_dynamic(lazy_registration = true)]
941/// impl ObjectSubclass for MyType { ... }
942/// ```
943///
944/// - registration within [`TypeModule`] subclass or within [`TypePlugin`]
945///   subclass: an object subclass is usually registered as a dynamic type within
946///   a [`TypeModule`] subclass:
947///
948/// ```ignore
949/// #[derive(Default)]
950/// pub struct MyModuleType;
951///
952/// #[glib::object_subclass]
953/// #[object_subclass_dynamic]
954/// impl ObjectSubclass for MyModuleType { ... }
955/// ...
956/// #[derive(Default)]
957/// pub struct MyModule;
958/// ...
959/// impl TypeModuleImpl for MyModule {
960///     fn load(&self) -> bool {
961///         // registers object subclasses as dynamic types.
962///         let my_module = self.obj();
963///         let type_module: &glib::TypeModule = my_module.upcast_ref();
964///         MyModuleType::on_implementation_load(type_module)
965///     }
966///     ...
967/// }
968/// ```
969///
970/// Optionally setting `plugin_type` allows to register an object subclass as a
971/// dynamic type within a [`TypePlugin`] subclass that is not a [`TypeModule`]:
972///
973/// ```ignore
974/// #[derive(Default)]
975/// pub struct MyPluginType;
976///
977/// #[glib::object_subclass]
978/// #[object_subclass_dynamic(plugin_type = MyPlugin)]
979/// impl ObjectSubclass for MyPluginType { ... }
980/// ...
981/// #[derive(Default)]
982/// pub struct MyPlugin;
983/// ...
984/// impl TypePluginImpl for MyPlugin {
985///     fn use_plugin(&self) {
986///         // register object subclasses as dynamic types.
987///         let my_plugin = self.obj();
988///         MyPluginType::on_implementation_load(my_plugin.as_ref());
989///     }
990///     ...
991/// }
992/// ```
993///
994/// [`ObjectSubclass`]: ../glib/subclass/types/trait.ObjectSubclass.html
995/// [`TypePlugin`]: ../glib/gobject/type_plugin/struct.TypePlugin.html
996/// [`TypeModule`]: ../glib/gobject/type_module/struct.TypeModule.html
997/// [`TypePluginExt::unuse`]: ../glib/gobject/type_plugin/trait.TypePluginExt.html#method.unuse
998#[proc_macro_attribute]
999pub fn object_subclass(_attr: TokenStream, item: TokenStream) -> TokenStream {
1000    let input = parse_macro_input!(item with object_impl_attributes::Input::parse_subclass);
1001    object_impl_attributes::subclass::impl_object_subclass(input).into()
1002}
1003
1004/// Macro for boilerplate of [`ObjectInterface`] implementations.
1005///
1006/// This adds implementations for the `get_type()` method, which should probably never be defined
1007/// differently.
1008///
1009/// It provides default values for the `Prerequisites` type parameter. If this is present, the macro
1010/// will use the provided value instead of the default.
1011///
1012/// `Prerequisites` are interfaces for types that require a specific base class or interfaces.
1013///
1014/// ```ignore
1015/// type Prerequisites = ();
1016/// ```
1017///
1018/// An object interface can be registered as a dynamic type by setting the
1019/// macro helper attribute `object_interface_dynamic`:
1020/// ```ignore
1021/// pub struct MyInterface {
1022///     parent: glib::gobject_ffi::GTypeInterface,
1023/// }
1024/// #[glib::object_interface]
1025/// #[object_interface_dynamic]
1026/// unsafe impl ObjectInterface for MyInterface { ... }
1027/// ```
1028///
1029/// As a dynamic type, an object interface must be explicitly registered when
1030/// the system loads the implementation (see [`TypePlugin`] and [`TypeModule`]).
1031/// Therefore, whereas an object interface can be registered only once as a
1032/// static type, it can be registered several times as a dynamic type.
1033///
1034/// An object interface registered as a dynamic type is never unregistered. The
1035/// system calls [`TypePluginExt::unuse`] to unload the implementation. If the
1036/// [`TypePlugin`] subclass is a [`TypeModule`], the object interface
1037/// registered as a dynamic type is marked as unloaded and must be registered
1038/// again when the module is reloaded.
1039///
1040/// The macro helper attribute `object_interface_dynamic` provides two
1041/// behaviors when registering an object interface as a dynamic type:
1042///
1043/// - lazy registration: by default an object interface is registered as a
1044///   dynamic type when the system loads the implementation (e.g. when the module
1045///   is loaded). Optionally setting `lazy_registration` to `true` postpones
1046///   registration on the first use (when `type_()` is called for the first time):
1047///
1048/// ```ignore
1049/// pub struct MyInterface {
1050///     parent: glib::gobject_ffi::GTypeInterface,
1051/// }
1052/// #[glib::object_interface]
1053/// #[object_interface_dynamic(lazy_registration = true)]
1054/// unsafe impl ObjectInterface for MyInterface { ... }
1055/// ```
1056///
1057/// - registration within [`TypeModule`] subclass or within [`TypePlugin`]
1058///   subclass: an object interface is usually registered as a dynamic type
1059///   within a [`TypeModule`] subclass:
1060///
1061/// ```ignore
1062/// pub struct MyModuleInterface {
1063///     parent: glib::gobject_ffi::GTypeInterface,
1064/// }
1065/// #[glib::object_interface]
1066/// #[object_interface_dynamic]
1067/// unsafe impl ObjectInterface for MyModuleInterface { ... }
1068/// ...
1069/// #[derive(Default)]
1070/// pub struct MyModule;
1071/// ...
1072/// impl TypeModuleImpl for MyModule {
1073///     fn load(&self) -> bool {
1074///         // registers object interfaces as dynamic types.
1075///         let my_module = self.obj();
1076///         let type_module: &glib::TypeModule = my_module.upcast_ref();
1077///         MyModuleInterface::on_implementation_load(type_module)
1078///     }
1079///     ...
1080/// }
1081/// ```
1082///
1083/// Optionally setting `plugin_type` allows to register an object interface as
1084/// a dynamic type within a [`TypePlugin`] subclass that is not a [`TypeModule`]:
1085///
1086/// ```ignore
1087/// pub struct MyPluginInterface {
1088///     parent: glib::gobject_ffi::GTypeInterface,
1089/// }
1090/// #[glib::object_interface]
1091/// #[object_interface_dynamic(plugin_type = MyPlugin)]
1092/// unsafe impl ObjectInterface for MyPluginInterface { ... }
1093/// ...
1094/// #[derive(Default)]
1095/// pub struct MyPlugin;
1096/// ...
1097/// impl TypePluginImpl for MyPlugin {
1098///     fn use_plugin(&self) {
1099///         // register object interfaces as dynamic types.
1100///         let my_plugin = self.obj();
1101///         MyPluginInterface::on_implementation_load(my_plugin.as_ref());
1102///     }
1103///     ...
1104/// }
1105/// ```
1106///
1107/// [`ObjectInterface`]: ../glib/subclass/interface/trait.ObjectInterface.html
1108/// [`TypePlugin`]: ../glib/gobject/type_plugin/struct.TypePlugin.html
1109/// [`TypeModule`]: ../glib/gobject/type_module/struct.TypeModule.html
1110/// [`TypePluginExt::unuse`]: ../glib/gobject/type_plugin/trait.TypePluginExt.html#method.unuse///
1111#[proc_macro_attribute]
1112pub fn object_interface(_attr: TokenStream, item: TokenStream) -> TokenStream {
1113    let input = parse_macro_input!(item with object_impl_attributes::Input::parse_interface);
1114    object_impl_attributes::interface::impl_object_interface(input).into()
1115}
1116
1117/// Macro for deriving implementations of [`glib::clone::Downgrade`] and
1118/// [`glib::clone::Upgrade`] traits and a weak type.
1119///
1120/// # Examples
1121///
1122/// ## New Type Idiom
1123///
1124/// ```rust,ignore
1125/// #[derive(glib::Downgrade)]
1126/// pub struct FancyLabel(gtk::Label);
1127///
1128/// impl FancyLabel {
1129///     pub fn new(label: &str) -> Self {
1130///         Self(gtk::LabelBuilder::new().label(label).build())
1131///     }
1132///
1133///     pub fn flip(&self) {
1134///         self.0.set_angle(180.0 - self.0.angle());
1135///     }
1136/// }
1137///
1138/// let fancy_label = FancyLabel::new("Look at me!");
1139/// let button = gtk::ButtonBuilder::new().label("Click me!").build();
1140/// button.connect_clicked(
1141///     clone!(
1142///         #[weak]
1143///         fancy_label,
1144///         move || fancy_label.flip(),
1145///     ),
1146/// );
1147/// ```
1148///
1149/// ## Generic New Type
1150///
1151/// ```rust,ignore
1152/// #[derive(glib::Downgrade)]
1153/// pub struct TypedEntry<T>(gtk::Entry, std::marker::PhantomData<T>);
1154///
1155/// impl<T: ToString + FromStr> for TypedEntry<T> {
1156///     // ...
1157/// }
1158/// ```
1159///
1160/// ## Structures and Enums
1161///
1162/// ```rust,ignore
1163/// #[derive(Clone, glib::Downgrade)]
1164/// pub struct ControlButtons {
1165///     pub up: gtk::Button,
1166///     pub down: gtk::Button,
1167///     pub left: gtk::Button,
1168///     pub right: gtk::Button,
1169/// }
1170///
1171/// #[derive(Clone, glib::Downgrade)]
1172/// pub enum DirectionButton {
1173///     Left(gtk::Button),
1174///     Right(gtk::Button),
1175///     Up(gtk::Button),
1176///     Down(gtk::Button),
1177/// }
1178/// ```
1179///
1180/// [`glib::clone::Downgrade`]: ../glib/clone/trait.Downgrade.html
1181/// [`glib::clone::Upgrade`]: ../glib/clone/trait.Upgrade.html
1182#[proc_macro_derive(Downgrade)]
1183pub fn downgrade(input: TokenStream) -> TokenStream {
1184    let input = parse_macro_input!(input as DeriveInput);
1185    downgrade_derive::impl_downgrade(input)
1186}
1187
1188/// Derive macro for serializing/deserializing custom structs/enums as [`glib::Variant`]s.
1189///
1190/// # Example
1191///
1192/// ```
1193/// use glib::prelude::*;
1194///
1195/// #[derive(Debug, PartialEq, Eq, glib::Variant)]
1196/// struct Foo {
1197///     some_string: String,
1198///     some_int: i32,
1199/// }
1200///
1201/// let v = Foo { some_string: String::from("bar"), some_int: 1 };
1202/// let var = v.to_variant();
1203/// assert_eq!(var.get::<Foo>(), Some(v));
1204/// ```
1205///
1206/// When storing `Vec`s of fixed size types it is a good idea to wrap these in
1207/// `glib::FixedSizeVariantArray` as serialization/deserialization will be more efficient.
1208///
1209/// # Example
1210///
1211/// ```
1212/// use glib::prelude::*;
1213///
1214/// #[derive(Debug, PartialEq, Eq, glib::Variant)]
1215/// struct Foo {
1216///     some_vec: glib::FixedSizeVariantArray<Vec<u32>, u32>,
1217///     some_int: i32,
1218/// }
1219///
1220/// let v = Foo { some_vec: vec![1u32, 2u32].into(), some_int: 1 };
1221/// let var = v.to_variant();
1222/// assert_eq!(var.get::<Foo>(), Some(v));
1223/// ```
1224///
1225/// Enums are serialized as a tuple `(sv)` with the first value as a [kebab case] string for the
1226/// enum variant, or just `s` if this is a C-style enum. Some additional attributes are supported
1227/// for enums:
1228/// - `#[variant_enum(repr)]` to serialize the enum variant as an integer type instead of `s`.  The
1229///   `#[repr]` attribute must also be specified on the enum with a sized integer type, and the type
1230///   must implement `Copy`.
1231/// - `#[variant_enum(enum)]` uses [`EnumClass`] to serialize/deserialize as nicks. Meant for use
1232///   with [`glib::Enum`](Enum).
1233/// - `#[variant_enum(flags)]` uses [`FlagsClass`] to serialize/deserialize as nicks. Meant for use
1234///   with [`glib::flags`](macro@flags).
1235/// - `#[variant_enum(enum, repr)]` serializes as `i32`. Meant for use with [`glib::Enum`](Enum).
1236///   The type must also implement `Copy`.
1237/// - `#[variant_enum(flags, repr)]` serializes as `u32`. Meant for use with
1238///   [`glib::flags`](macro@flags).
1239///
1240/// # Example
1241///
1242/// ```
1243/// use glib::prelude::*;
1244///
1245/// #[derive(Debug, PartialEq, Eq, glib::Variant)]
1246/// enum Foo {
1247///     MyA,
1248///     MyB(i32),
1249///     MyC { some_int: u32, some_string: String }
1250/// }
1251///
1252/// let v = Foo::MyC { some_int: 1, some_string: String::from("bar") };
1253/// let var = v.to_variant();
1254/// assert_eq!(var.child_value(0).str(), Some("my-c"));
1255/// assert_eq!(var.get::<Foo>(), Some(v));
1256///
1257/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Variant)]
1258/// #[variant_enum(repr)]
1259/// #[repr(u8)]
1260/// enum Bar {
1261///     A,
1262///     B = 3,
1263///     C = 7
1264/// }
1265///
1266/// let v = Bar::B;
1267/// let var = v.to_variant();
1268/// assert_eq!(var.get::<u8>(), Some(3));
1269/// assert_eq!(var.get::<Bar>(), Some(v));
1270///
1271/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum, glib::Variant)]
1272/// #[variant_enum(enum)]
1273/// #[enum_type(name = "MyEnum")]
1274/// enum MyEnum {
1275///     Val,
1276///     #[enum_value(name = "My Val")]
1277///     ValWithCustomName,
1278///     #[enum_value(name = "My Other Val", nick = "other")]
1279///     ValWithCustomNameAndNick,
1280/// }
1281///
1282/// let v = MyEnum::ValWithCustomNameAndNick;
1283/// let var = v.to_variant();
1284/// assert_eq!(var.str(), Some("other"));
1285/// assert_eq!(var.get::<MyEnum>(), Some(v));
1286/// ```
1287///
1288/// [`glib::Variant`]: ../glib/variant/struct.Variant.html
1289/// [`EnumClass`]: ../glib/struct.EnumClass.html
1290/// [`FlagsClass`]: ../glib/struct.FlagsClass.html
1291/// [kebab case]: https://docs.rs/heck/0.4.0/heck/trait.ToKebabCase.html
1292#[proc_macro_derive(Variant, attributes(variant_enum))]
1293pub fn variant_derive(input: TokenStream) -> TokenStream {
1294    let input = parse_macro_input!(input as DeriveInput);
1295    variant_derive::impl_variant(input)
1296        .unwrap_or_else(syn::Error::into_compile_error)
1297        .into()
1298}
1299#[proc_macro]
1300pub fn cstr_bytes(item: TokenStream) -> TokenStream {
1301    syn::parse::Parser::parse2(
1302        |stream: syn::parse::ParseStream<'_>| {
1303            let literal = stream.parse::<syn::LitStr>()?;
1304            stream.parse::<syn::parse::Nothing>()?;
1305            let bytes = std::ffi::CString::new(literal.value())
1306                .map_err(|e| syn::Error::new_spanned(&literal, format!("{e}")))?
1307                .into_bytes_with_nul();
1308            let bytes = proc_macro2::Literal::byte_string(&bytes);
1309            Ok(quote::quote! { #bytes }.into())
1310        },
1311        item.into(),
1312    )
1313    .unwrap_or_else(|e| e.into_compile_error().into())
1314}
1315
1316/// This macro enables you to derive object properties in a quick way.
1317///
1318/// # Supported `#[property]` attributes
1319/// | Attribute | Description | Default | Example |
1320/// | --- | --- | --- | --- |
1321/// | `name = "literal"` | The name of the property | field ident where `_` (leading and trailing `_` are trimmed) is replaced into `-` | `#[property(name = "prop-name")]` |
1322/// | `type = expr` | The type of the property | inferred | `#[property(type = i32)]` |
1323/// | `get [= expr]` | Specify that the property is readable and use [`PropertyGet::get`] [or optionally set a custom internal getter] | | `#[property(get)]`, `#[property(get = get_prop)]`, or `[property(get = \|_\| 2)]` |
1324/// | `set [= expr]` | Specify that the property is writable and use [`PropertySet::set`] [or optionally set a custom internal setter] | | `#[property(set)]`, `#[property(set = set_prop)]`, or `[property(set = \|_, val\| {})]` |
1325/// | `override_class = expr` | The type of class of which to override the property from | | `#[property(override_class = SomeClass)]` |
1326/// | `override_interface = expr` | The type of interface of which to override the property from | | `#[property(override_interface = SomeInterface)]` |
1327/// | `nullable` | Whether to use `Option<T>` in the generated setter method |  | `#[property(nullable)]` |
1328/// | `member = ident` | Field of the nested type where property is retrieved and set | | `#[property(member = author)]` |
1329/// | `construct` | Specify that the property is construct property. Ensures that the property is always set during construction (if not explicitly then the default value is used). The use of a custom internal setter is supported. | | `#[property(get, construct)]` or `#[property(get, set = set_prop, construct)]` |
1330/// | `construct_only` | Specify that the property is construct only. This will not generate a public setter and only allow the property to be set during object construction. The use of a custom internal setter is supported. | | `#[property(get, construct_only)]` or `#[property(get, set = set_prop, construct_only)]` |
1331/// | `builder(<required-params>)[.ident]*` | Used to input required params or add optional Param Spec builder fields | | `#[property(builder(SomeEnum::default()))]`, `#[builder().default_value(1).minimum(0).maximum(5)]`, etc.  |
1332/// | `default` | Sets the `default_value` field of the Param Spec builder | | `#[property(default = 1)]` |
1333/// | `<optional-pspec-builder-fields> = expr` | Used to add optional Param Spec builder fields | | `#[property(minimum = 0)` , `#[property(minimum = 0, maximum = 1)]`, etc. |
1334/// | `<optional-pspec-builder-fields>` | Used to add optional Param Spec builder fields | | `#[property(explicit_notify)]` , `#[property(construct_only)]`, etc. |
1335///
1336/// ## Using Rust keywords as property names
1337/// You might hit a roadblock when declaring properties with this macro because you want to use a name that happens to be a Rust keyword. This may happen with names like `loop`, which is a pretty common name when creating things like animation handlers.
1338/// To use those names, you can make use of the raw identifier feature of Rust. Simply prefix the identifier name with `r#` in the struct declaration. Internally, those `r#`s are stripped so you can use its expected name in [`ObjectExt::property`] or within GtkBuilder template files.
1339///
1340/// # Generated methods
1341/// The following methods are generated on the wrapper type specified on `#[properties(wrapper_type = ...)]`:
1342/// * `$property()`, when the property is readable
1343/// * `set_$property()`, when the property is writable and not construct-only
1344/// * `connect_$property_notify()`
1345/// * `notify_$property()`
1346///
1347/// ## Extension trait
1348/// You can choose to move the method definitions to a trait by using `#[properties(wrapper_type = super::MyType, ext_trait = MyTypePropertiesExt)]`.
1349/// The trait name is optional, and defaults to `MyTypePropertiesExt`, where `MyType` is extracted from the wrapper type.
1350/// Note: The trait is defined in the same module where the `#[derive(Properties)]` call happens, and is implemented on the wrapper type.
1351///
1352/// Notice: You can't reimplement the generated methods on the wrapper type, unless you move them to a trait.
1353/// You can change the behavior of the generated getter/setter methods by using a custom internal getter/setter.
1354///
1355/// # Internal getters and setters
1356/// By default, they are generated for you. However, you can use a custom getter/setter
1357/// by assigning an expression to `get`/`set` `#[property]` attributes: `#[property(get = |_| 2, set)]` or `#[property(get, set = custom_setter_func)]`.
1358///
1359/// # Supported types
1360/// Every type implementing the trait [`Property`] is supported.
1361/// The type `Option<T>` is supported as a property only if `Option<T>` implements [`ToValueOptional`].
1362/// Optional types also require the `nullable` attribute: without it, the generated setter on the wrapper type
1363/// will take `T` instead of `Option<T>`, preventing the user from ever calling the setter with a `None` value.
1364///
1365/// ## Adding support for custom types
1366/// ### Types wrapping an existing <code>T: [ToValue] + [HasParamSpec]</code>
1367/// If you have declared a newtype as
1368/// ```rust
1369/// struct MyInt(i32);
1370/// ```
1371/// you can use it as a property by deriving [`ValueDelegate`].
1372///
1373/// ### Types with inner mutability
1374/// The trait [`Property`] must be implemented.
1375/// The traits [`PropertyGet`] and [`PropertySet`] should be implemented to enable the Properties macro
1376/// to generate a default internal getter/setter.
1377/// If possible, implementing [`PropertySetNested`] is preferred over `PropertySet`, because it
1378/// enables this macro to access the contained type and provide access to its fields,
1379/// using the `member = $structfield` syntax.
1380///
1381/// ### Types without [`HasParamSpec`][HasParamSpec]
1382/// If you have encountered a type <code>T: [ToValue]</code>, inside the gtk-rs crate, which doesn't implement [`HasParamSpec`][HasParamSpec],
1383/// then it's a bug and you should report it.
1384/// If you need to support a `ToValue` type with a [`ParamSpec`] not provided by gtk-rs, then you need to
1385/// implement `HasParamSpec` on that type.
1386///
1387/// # Example
1388/// ```
1389/// use std::cell::RefCell;
1390/// use glib::prelude::*;
1391/// use glib::subclass::prelude::*;
1392/// use glib_macros::Properties;
1393///
1394/// #[derive(Default, Clone)]
1395/// struct Author {
1396///     name: String,
1397///     nick: String,
1398/// }
1399///
1400/// pub mod imp {
1401///     use std::rc::Rc;
1402///
1403///     use super::*;
1404///
1405///     #[derive(Properties, Default)]
1406///     #[properties(wrapper_type = super::Foo)]
1407///     pub struct Foo {
1408///         #[property(get, set = Self::set_fizz)]
1409///         fizz: RefCell<String>,
1410///         #[property(name = "author-name", get, set, type = String, member = name)]
1411///         #[property(name = "author-nick", get, set, type = String, member = nick)]
1412///         author: RefCell<Author>,
1413///         #[property(get, set, explicit_notify, lax_validation)]
1414///         custom_flags: RefCell<String>,
1415///         #[property(get, set, minimum = 0, maximum = 3)]
1416///         numeric_builder: RefCell<u32>,
1417///         #[property(get, set, builder('c'))]
1418///         builder_with_required_param: RefCell<char>,
1419///         #[property(get, set, nullable)]
1420///         optional: RefCell<Option<String>>,
1421///         #[property(get, set)]
1422///         smart_pointer: Rc<RefCell<String>>,
1423///     }
1424///     
1425///     #[glib::derived_properties]
1426///     impl ObjectImpl for Foo {}
1427///
1428///     #[glib::object_subclass]
1429///     impl ObjectSubclass for Foo {
1430///         const NAME: &'static str = "MyFoo";
1431///         type Type = super::Foo;
1432///     }
1433///
1434///     impl Foo {
1435///         fn set_fizz(&self, value: String) {
1436///             *self.fizz.borrow_mut() = format!("custom set: {}", value);
1437///         }
1438///     }
1439/// }
1440///
1441/// glib::wrapper! {
1442///     pub struct Foo(ObjectSubclass<imp::Foo>);
1443/// }
1444///
1445/// fn main() {
1446///   let myfoo: Foo = glib::object::Object::new();
1447///
1448///   myfoo.set_fizz("test value");
1449///   assert_eq!(myfoo.fizz(), "custom set: test value".to_string());
1450/// }
1451/// ```
1452///
1453/// [`Property`]: ../glib/property/trait.Property.html
1454/// [`PropertyGet`]: ../glib/property/trait.PropertyGet.html
1455/// [`PropertyGet::get`]: ../glib/property/trait.PropertyGet.html#tymethod.get
1456/// [`PropertySet`]: ../glib/property/trait.PropertySet.html
1457/// [`PropertySet::set`]: ../glib/property/trait.PropertySet.html#tymethod.set
1458/// [`PropertySetNested`]: ../glib/property/trait.PropertySetNested.html
1459/// [`ObjectExt::property`]: ../glib/object/trait.ObjectExt.html#tymethod.property
1460/// [HasParamSpec]: ../glib/trait.HasParamSpec.html
1461/// [`ParamSpec`]: ../glib/struct.ParamSpec.html
1462/// [`ToValueOptional`]: ../glib/value/trait.ToValueOptional.html
1463/// [ToValue]: ../glib/value/trait.ToValue.html
1464#[allow(clippy::needless_doctest_main)]
1465#[proc_macro_derive(Properties, attributes(properties, property))]
1466pub fn derive_props(input: TokenStream) -> TokenStream {
1467    let input = parse_macro_input!(input as properties::PropsMacroInput);
1468    properties::impl_derive_props(input)
1469}
1470
1471/// When applied to `ObjectImpl`
1472/// ```ignore
1473/// #[glib::derived_properties]
1474/// impl ObjectImpl for CustomObject
1475/// ```
1476/// this macro generates
1477/// ```ignore
1478/// impl ObjectImpl for CustomObject {
1479///     fn properties() -> &'static [glib::ParamSpec] {
1480///         Self::derived_properties()
1481///     }
1482///     fn set_property(&self, id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
1483///         self.derived_set_property(id, value, pspec)
1484///     }
1485///     fn property(&self, id: usize, pspec: &glib::ParamSpec) -> glib::Value {
1486///         self.derived_property(id, pspec)
1487///     }
1488/// }
1489/// ```
1490#[proc_macro_attribute]
1491pub fn derived_properties(_attr: TokenStream, item: TokenStream) -> TokenStream {
1492    syn::parse::<syn::ItemImpl>(item)
1493        .map_err(|_| {
1494            syn::Error::new(
1495                Span::call_site(),
1496                derived_properties_attribute::WRONG_PLACE_MSG,
1497            )
1498        })
1499        .and_then(|input| derived_properties_attribute::impl_derived_properties(&input))
1500        .unwrap_or_else(syn::Error::into_compile_error)
1501        .into()
1502}
1503
1504/// # Example
1505/// ```
1506/// use glib::prelude::*;
1507/// use glib::ValueDelegate;
1508///
1509/// #[derive(ValueDelegate, Debug, PartialEq)]
1510/// struct MyInt(i32);
1511///
1512/// let myv = MyInt(2);
1513/// let convertedv = myv.to_value();
1514/// assert_eq!(convertedv.get::<MyInt>(), Ok(myv));
1515///
1516///
1517/// #[derive(ValueDelegate, Debug, PartialEq)]
1518/// #[value_delegate(from = u32)]
1519/// enum MyEnum {
1520///     Zero,
1521///     NotZero(u32)
1522/// }
1523///
1524/// impl From<u32> for MyEnum {
1525///     fn from(v: u32) -> Self {
1526///         match v {
1527///             0 => MyEnum::Zero,
1528///             x => MyEnum::NotZero(x)
1529///         }
1530///     }
1531/// }
1532/// impl<'a> From<&'a MyEnum> for u32 {
1533///     fn from(v: &'a MyEnum) -> Self {
1534///         match v {
1535///             MyEnum::Zero => 0,
1536///             MyEnum::NotZero(x) => *x
1537///         }
1538///     }
1539/// }
1540/// impl From<MyEnum> for u32 {
1541///     fn from(v: MyEnum) -> Self {
1542///         match v {
1543///             MyEnum::Zero => 0,
1544///             MyEnum::NotZero(x) => x
1545///         }
1546///     }
1547/// }
1548///
1549/// let myv = MyEnum::NotZero(34);
1550/// let convertedv = myv.to_value();
1551/// assert_eq!(convertedv.get::<MyEnum>(), Ok(myv));
1552///
1553///
1554/// // If you want your type to be usable inside an `Option`, you can derive `ToValueOptional`
1555/// // by adding `nullable` as follows
1556/// #[derive(ValueDelegate, Debug, PartialEq)]
1557/// #[value_delegate(nullable)]
1558/// struct MyString(String);
1559///
1560/// let myv = Some(MyString("Hello world".to_string()));
1561/// let convertedv = myv.to_value();
1562/// assert_eq!(convertedv.get::<Option<MyString>>(), Ok(myv));
1563/// let convertedv = None::<MyString>.to_value();
1564/// assert_eq!(convertedv.get::<Option<MyString>>(), Ok(None::<MyString>));
1565/// ```
1566#[proc_macro_derive(ValueDelegate, attributes(value_delegate))]
1567pub fn derive_value_delegate(input: TokenStream) -> TokenStream {
1568    let input = parse_macro_input!(input as value_delegate_derive::ValueDelegateInput);
1569    value_delegate_derive::impl_value_delegate(input).unwrap()
1570}
1571
1572/// An attribute macro for writing asynchronous test functions.
1573///
1574/// This macro is designed to wrap an asynchronous test function and ensure that
1575/// it runs within a `glib::MainContext`. It helps in writing async tests that
1576/// require the use of an event loop for the asynchronous execution.
1577///
1578/// # Example
1579///
1580/// ```
1581/// #[glib::async_test]
1582/// async fn my_async_test() {
1583///     // Test code that runs asynchronously
1584/// }
1585/// ```
1586#[proc_macro_attribute]
1587pub fn async_test(args: TokenStream, item: TokenStream) -> TokenStream {
1588    async_test::async_test(args, item)
1589}