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/// When using the [`Properties`] macro with enums that derive [`Enum`], the default value must be
529/// explicitly set via the `builder` parameter of the `#[property]` attribute. See
530/// [here](Properties#supported-types) for details.
531///
532/// An enum can be registered as a dynamic type by setting the derive macro
533/// helper attribute `enum_dynamic`:
534///
535/// ```ignore
536/// use glib::prelude::*;
537/// use glib::subclass::prelude::*;
538///
539/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
540/// #[enum_type(name = "MyEnum")]
541/// #[enum_dynamic]
542/// enum MyEnum {
543///     ...
544/// }
545/// ```
546///
547/// As a dynamic type, an enum must be explicitly registered when the system
548/// loads the implementation (see [`TypePlugin`] and [`TypeModule`]).
549/// Therefore, whereas an enum can be registered only once as a static type,
550/// it can be registered several times as a dynamic type.
551///
552/// An enum registered as a dynamic type is never unregistered. The system
553/// calls [`TypePluginExt::unuse`] to unload the implementation. If the
554/// [`TypePlugin`] subclass is a [`TypeModule`], the enum registered as a
555/// dynamic type is marked as unloaded and must be registered again when the
556/// module is reloaded.
557///
558/// The derive macro helper attribute `enum_dynamic` provides two behaviors
559/// when registering an enum as a dynamic type:
560///
561/// - lazy registration: by default an enum is registered as a dynamic type
562///   when the system loads the implementation (e.g. when the module is loaded).
563///   Optionally setting `lazy_registration` to `true` postpones registration on
564///   the first use (when `static_type()` is called for the first time):
565///
566/// ```ignore
567/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
568/// #[enum_type(name = "MyEnum")]
569/// #[enum_dynamic(lazy_registration = true)]
570/// enum MyEnum {
571///     ...
572/// }
573/// ```
574///
575/// - registration within [`TypeModule`] subclass or within [`TypePlugin`]
576///   subclass: an enum is usually registered as a dynamic type within a
577///   [`TypeModule`] subclass:
578///
579/// ```ignore
580/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
581/// #[enum_type(name = "MyModuleEnum")]
582/// #[enum_dynamic]
583/// enum MyModuleEnum {
584///     ...
585/// }
586/// ...
587/// #[derive(Default)]
588/// pub struct MyModule;
589/// ...
590/// impl TypeModuleImpl for MyModule {
591///     fn load(&self) -> bool {
592///         // registers enums as dynamic types.
593///         let my_module = self.obj();
594///         let type_module: &glib::TypeModule = my_module.upcast_ref();
595///         MyModuleEnum::on_implementation_load(type_module)
596///     }
597///     ...
598/// }
599/// ```
600///
601/// Optionally setting `plugin_type` allows to register an enum as a dynamic
602/// type within a [`TypePlugin`] subclass that is not a [`TypeModule`]:
603///
604/// ```ignore
605/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum)]
606/// #[enum_type(name = "MyPluginEnum")]
607/// #[enum_dynamic(plugin_type = MyPlugin)]
608/// enum MyPluginEnum {
609///     ...
610/// }
611/// ...
612/// #[derive(Default)]
613/// pub struct MyPlugin;
614/// ...
615/// impl TypePluginImpl for MyPlugin {
616///     fn use_plugin(&self) {
617///         // register enums as dynamic types.
618///         let my_plugin = self.obj();
619///         MyPluginEnum::on_implementation_load(my_plugin.as_ref());
620///     }
621///     ...
622/// }
623/// ```
624///
625/// [`glib::Value`]: ../glib/value/struct.Value.html
626/// [`TypePlugin`]: ../glib/gobject/type_plugin/struct.TypePlugin.html
627/// [`TypeModule`]: ../glib/gobject/type_module/struct.TypeModule.html
628/// [`TypePluginExt::unuse`]: ../glib/gobject/type_plugin/trait.TypePluginExt.
629#[proc_macro_derive(Enum, attributes(enum_type, enum_dynamic, enum_value))]
630pub fn enum_derive(input: TokenStream) -> TokenStream {
631    let input = parse_macro_input!(input as DeriveInput);
632    enum_derive::impl_enum(&input)
633        .unwrap_or_else(syn::Error::into_compile_error)
634        .into()
635}
636
637/// Attribute macro for defining flags using the `bitflags` crate.
638/// This macro will also define a `GFlags::type_` function and
639/// the [`glib::Value`] traits.
640///
641/// The expected `GType` name has to be passed as macro attribute.
642/// The name and nick of each flag can also be optionally defined.
643/// Default name is the flag identifier in CamelCase and default nick
644/// is the identifier in kebab-case.
645/// Combined flags should not be registered with the `GType` system
646/// and so need to be tagged with the `#[flags_value(skip)]` attribute.
647///
648/// # Example
649///
650/// ```
651/// use glib::prelude::*;
652/// use glib::subclass::prelude::*;
653///
654/// #[glib::flags(name = "MyFlags")]
655/// enum MyFlags {
656///     #[flags_value(name = "Flag A", nick = "nick-a")]
657///     A = 0b00000001,
658///     #[flags_value(name = "Flag B")]
659///     B = 0b00000010,
660///     #[flags_value(skip)]
661///     AB = Self::A.bits() | Self::B.bits(),
662///     C = 0b00000100,
663/// }
664/// ```
665///
666/// The flags can be registered as a dynamic type by setting the macro helper
667/// attribute `flags_dynamic`:
668/// ```ignore
669/// use glib::prelude::*;
670/// use glib::subclass::prelude::*;
671///
672/// #[glib::flags(name = "MyFlags")]
673/// #[flags_dynamic]
674/// enum MyFlags {
675///     ...
676/// }
677/// ```
678///
679/// As a dynamic type, the flags must be explicitly registered when the system
680/// loads the implementation (see [`TypePlugin`] and [`TypeModule`]).
681/// Therefore, whereas the flags can be registered only once as a static type,
682/// they can be registered several times as a dynamic type.
683///
684/// The flags registered as a dynamic type are never unregistered. The system
685/// calls [`TypePluginExt::unuse`] to unload the implementation. If the
686/// [`TypePlugin`] subclass is a [`TypeModule`], the flags registered as a
687/// dynamic type are marked as unloaded and must be registered again when the
688/// module is reloaded.
689///
690/// The macro helper attribute `flags_dynamic` provides two behaviors when
691/// registering the flags as a dynamic type:
692///
693/// - lazy registration: by default the flags are registered as a dynamic type
694///   when the system loads the implementation (e.g. when the module is loaded).
695///   Optionally setting `lazy_registration` to `true` postpones registration on
696///   the first use (when `static_type()` is called for the first time):
697///
698/// ```ignore
699/// #[glib::flags(name = "MyFlags")]
700/// #[flags_dynamic(lazy_registration = true)]
701/// enum MyFlags {
702///     ...
703/// }
704/// ```
705///
706/// - registration within [`TypeModule`] subclass or within [`TypePlugin`]
707///   subclass: the flags are usually registered as a dynamic type within a
708///   [`TypeModule`] subclass:
709///
710/// ```ignore
711/// #[glib::flags(name = "MyModuleFlags")]
712/// #[flags_dynamic]
713/// enum MyModuleFlags {
714///     ...
715/// }
716/// ...
717/// #[derive(Default)]
718/// pub struct MyModule;
719/// ...
720/// impl TypeModuleImpl for MyModule {
721///     fn load(&self) -> bool {
722///         // registers flags as dynamic types.
723///         let my_module = self.obj();
724///         let type_module: &glib::TypeModule = my_module.upcast_ref();
725///         MyModuleFlags::on_implementation_load(type_module)
726///     }
727///     ...
728/// }
729/// ```
730///
731/// Optionally setting `plugin_type` allows to register the flags as a dynamic
732/// type within a [`TypePlugin`] subclass that is not a [`TypeModule`]:
733/// ```ignore
734/// #[glib::flags(name = "MyModuleFlags")]
735/// #[flags_dynamic(plugin_type = MyPlugin)]
736/// enum MyModuleFlags {
737///     ...
738/// }
739/// ...
740/// #[derive(Default)]
741/// pub struct MyPlugin;
742/// ...
743/// impl TypePluginImpl for MyPlugin {
744///     fn use_plugin(&self) {
745///         // register flags as dynamic types.
746///         let my_plugin = self.obj();
747///         MyPluginFlags::on_implementation_load(my_plugin.as_ref());
748///     }
749///     ...
750/// }
751/// ```
752///
753/// [`glib::Value`]: ../glib/value/struct.Value.html
754/// [`TypePlugin`]: ../glib/gobject/type_plugin/struct.TypePlugin.html
755/// [`TypeModule`]: ../glib/gobject/type_module/struct.TypeModule.html
756/// [`TypePluginExt::unuse`]: ../glib/gobject/type_plugin/trait.TypePluginExt.
757#[proc_macro_attribute]
758pub fn flags(attr: TokenStream, item: TokenStream) -> TokenStream {
759    let mut name = NestedMetaItem::<syn::LitStr>::new("name")
760        .required()
761        .value_required();
762    let mut allow_name_conflict_attr =
763        NestedMetaItem::<syn::LitBool>::new("allow_name_conflict").value_optional();
764
765    if let Err(e) = parse_nested_meta_items_from_stream(
766        attr.into(),
767        &mut [&mut name, &mut allow_name_conflict_attr],
768    ) {
769        return e.to_compile_error().into();
770    }
771
772    let allow_name_conflict = allow_name_conflict_attr.found
773        || allow_name_conflict_attr
774            .value
775            .map(|b| b.value())
776            .unwrap_or(false);
777
778    let attr_meta = AttrInput {
779        enum_name: name.value.unwrap(),
780        allow_name_conflict,
781    };
782
783    syn::parse::<syn::ItemEnum>(item)
784        .map_err(|_| syn::Error::new(Span::call_site(), flags_attribute::WRONG_PLACE_MSG))
785        .map(|mut input| flags_attribute::impl_flags(attr_meta, &mut input))
786        .unwrap_or_else(syn::Error::into_compile_error)
787        .into()
788}
789
790/// Derive macro for defining a GLib error domain and its associated
791/// [`ErrorDomain`] trait.
792///
793/// # Example
794///
795/// ```
796/// use glib::prelude::*;
797/// use glib::subclass::prelude::*;
798///
799/// #[derive(Debug, Copy, Clone, glib::ErrorDomain)]
800/// #[error_domain(name = "ex-foo")]
801/// enum Foo {
802///     Blah,
803///     Baaz,
804/// }
805/// ```
806///
807/// [`ErrorDomain`]: ../glib/error/trait.ErrorDomain.html
808#[proc_macro_derive(ErrorDomain, attributes(error_domain))]
809pub fn error_domain_derive(input: TokenStream) -> TokenStream {
810    let input = parse_macro_input!(input as DeriveInput);
811    error_domain_derive::impl_error_domain(&input)
812        .unwrap_or_else(syn::Error::into_compile_error)
813        .into()
814}
815
816/// Derive macro for defining a [`BoxedType`]`::type_` function and
817/// the [`glib::Value`] traits. Optionally, the type can be marked as
818/// `nullable` to get an implementation of `glib::value::ToValueOptional`.
819///
820/// # Example
821///
822/// ```
823/// use glib::prelude::*;
824/// use glib::subclass::prelude::*;
825///
826/// #[derive(Clone, Debug, PartialEq, Eq, glib::Boxed)]
827/// #[boxed_type(name = "MyBoxed")]
828/// struct MyBoxed(String);
829///
830/// #[derive(Clone, Debug, PartialEq, Eq, glib::Boxed)]
831/// #[boxed_type(name = "MyNullableBoxed", nullable)]
832/// struct MyNullableBoxed(String);
833/// ```
834///
835/// [`BoxedType`]: ../glib/subclass/boxed/trait.BoxedType.html
836/// [`glib::Value`]: ../glib/value/struct.Value.html
837#[proc_macro_derive(Boxed, attributes(boxed_type))]
838pub fn boxed_derive(input: TokenStream) -> TokenStream {
839    let input = parse_macro_input!(input as DeriveInput);
840    boxed_derive::impl_boxed(&input)
841        .unwrap_or_else(syn::Error::into_compile_error)
842        .into()
843}
844
845/// Derive macro for defining a [`SharedType`]`::get_type` function and
846/// the [`glib::Value`] traits. Optionally, the type can be marked as
847/// `nullable` to get an implementation of `glib::value::ToValueOptional`.
848///
849/// # Example
850///
851/// ```
852/// use glib::prelude::*;
853/// use glib::subclass::prelude::*;
854///
855/// #[derive(Clone, Debug, PartialEq, Eq)]
856/// struct MySharedInner {
857///   foo: String,
858/// }
859///
860/// #[derive(Clone, Debug, PartialEq, Eq, glib::SharedBoxed)]
861/// #[shared_boxed_type(name = "MySharedBoxed")]
862/// struct MySharedBoxed(std::sync::Arc<MySharedInner>);
863///
864/// #[derive(Clone, Debug, PartialEq, Eq, glib::SharedBoxed)]
865/// #[shared_boxed_type(name = "MyNullableSharedBoxed", nullable)]
866/// struct MyNullableSharedBoxed(std::sync::Arc<MySharedInner>);
867/// ```
868///
869/// [`SharedType`]: ../glib/subclass/shared/trait.SharedType.html
870/// [`glib::Value`]: ../glib/value/struct.Value.html
871#[proc_macro_derive(SharedBoxed, attributes(shared_boxed_type))]
872pub fn shared_boxed_derive(input: TokenStream) -> TokenStream {
873    let input = parse_macro_input!(input as DeriveInput);
874    shared_boxed_derive::impl_shared_boxed(&input)
875        .unwrap_or_else(syn::Error::into_compile_error)
876        .into()
877}
878
879/// Macro for boilerplate of [`ObjectSubclass`] implementations.
880///
881/// This adds implementations for the `type_data()` and `type_()` methods,
882/// which should probably never be defined differently.
883///
884/// It provides default values for the `Instance`, `Class`, and `Interfaces`
885/// type parameters. If these are present, the macro will use the provided value
886/// instead of the default.
887///
888/// Usually the defaults for `Instance` and `Class` will work. `Interfaces` is
889/// necessary for types that implement interfaces.
890///
891/// ```ignore
892/// type Instance = glib::subclass::basic::InstanceStruct<Self>;
893/// type Class = glib::subclass::basic::ClassStruct<Self>;
894/// type Interfaces = ();
895/// ```
896///
897/// If no `new()` or `with_class()` method is provided, the macro adds a `new()`
898/// implementation calling `Default::default()`. So the type needs to implement
899/// `Default`, or this should be overridden.
900///
901/// ```ignore
902/// fn new() -> Self {
903///     Default::default()
904/// }
905/// ```
906///
907/// An object subclass can be registered as a dynamic type by setting the macro
908/// helper attribute `object_class_dynamic`:
909///
910/// ```ignore
911/// #[derive(Default)]
912/// pub struct MyType;
913///
914/// #[glib::object_subclass]
915/// #[object_subclass_dynamic]
916/// impl ObjectSubclass for MyType { ... }
917/// ```
918///
919/// As a dynamic type, an object subclass must be explicitly registered when
920/// the system loads the implementation (see [`TypePlugin`] and [`TypeModule`]).
921/// Therefore, whereas an object subclass can be registered only once as a
922/// static type, it can be registered several times as a dynamic type.
923///
924/// An object subclass registered as a dynamic type is never unregistered. The
925/// system calls [`TypePluginExt::unuse`] to unload the implementation. If the
926/// [`TypePlugin`] subclass is a [`TypeModule`], the object subclass registered
927/// as a dynamic type is marked as unloaded and must be registered again when
928/// the module is reloaded.
929///
930/// The macro helper attribute `object_class_dynamic` provides two behaviors
931/// when registering an object subclass as a dynamic type:
932///
933/// - lazy registration: by default an object subclass is registered as a
934///   dynamic type when the system loads the implementation (e.g. when the module
935///   is loaded). Optionally setting `lazy_registration` to `true` postpones
936///   registration on the first use (when `static_type()` is called for the first
937///   time):
938///
939/// ```ignore
940/// #[derive(Default)]
941/// pub struct MyType;
942///
943/// #[glib::object_subclass]
944/// #[object_subclass_dynamic(lazy_registration = true)]
945/// impl ObjectSubclass for MyType { ... }
946/// ```
947///
948/// - registration within [`TypeModule`] subclass or within [`TypePlugin`]
949///   subclass: an object subclass is usually registered as a dynamic type within
950///   a [`TypeModule`] subclass:
951///
952/// ```ignore
953/// #[derive(Default)]
954/// pub struct MyModuleType;
955///
956/// #[glib::object_subclass]
957/// #[object_subclass_dynamic]
958/// impl ObjectSubclass for MyModuleType { ... }
959/// ...
960/// #[derive(Default)]
961/// pub struct MyModule;
962/// ...
963/// impl TypeModuleImpl for MyModule {
964///     fn load(&self) -> bool {
965///         // registers object subclasses as dynamic types.
966///         let my_module = self.obj();
967///         let type_module: &glib::TypeModule = my_module.upcast_ref();
968///         MyModuleType::on_implementation_load(type_module)
969///     }
970///     ...
971/// }
972/// ```
973///
974/// Optionally setting `plugin_type` allows to register an object subclass as a
975/// dynamic type within a [`TypePlugin`] subclass that is not a [`TypeModule`]:
976///
977/// ```ignore
978/// #[derive(Default)]
979/// pub struct MyPluginType;
980///
981/// #[glib::object_subclass]
982/// #[object_subclass_dynamic(plugin_type = MyPlugin)]
983/// impl ObjectSubclass for MyPluginType { ... }
984/// ...
985/// #[derive(Default)]
986/// pub struct MyPlugin;
987/// ...
988/// impl TypePluginImpl for MyPlugin {
989///     fn use_plugin(&self) {
990///         // register object subclasses as dynamic types.
991///         let my_plugin = self.obj();
992///         MyPluginType::on_implementation_load(my_plugin.as_ref());
993///     }
994///     ...
995/// }
996/// ```
997///
998/// [`ObjectSubclass`]: ../glib/subclass/types/trait.ObjectSubclass.html
999/// [`TypePlugin`]: ../glib/gobject/type_plugin/struct.TypePlugin.html
1000/// [`TypeModule`]: ../glib/gobject/type_module/struct.TypeModule.html
1001/// [`TypePluginExt::unuse`]: ../glib/gobject/type_plugin/trait.TypePluginExt.html#method.unuse
1002#[proc_macro_attribute]
1003pub fn object_subclass(_attr: TokenStream, item: TokenStream) -> TokenStream {
1004    let input = parse_macro_input!(item with object_impl_attributes::Input::parse_subclass);
1005    object_impl_attributes::subclass::impl_object_subclass(input).into()
1006}
1007
1008/// Macro for boilerplate of [`ObjectInterface`] implementations.
1009///
1010/// This adds implementations for the `get_type()` method, which should probably never be defined
1011/// differently.
1012///
1013/// It provides default values for the `Prerequisites` type parameter. If this is present, the macro
1014/// will use the provided value instead of the default.
1015///
1016/// `Prerequisites` are interfaces for types that require a specific base class or interfaces.
1017///
1018/// ```ignore
1019/// type Prerequisites = ();
1020/// ```
1021///
1022/// An object interface can be registered as a dynamic type by setting the
1023/// macro helper attribute `object_interface_dynamic`:
1024/// ```ignore
1025/// pub struct MyInterface {
1026///     parent: glib::gobject_ffi::GTypeInterface,
1027/// }
1028/// #[glib::object_interface]
1029/// #[object_interface_dynamic]
1030/// unsafe impl ObjectInterface for MyInterface { ... }
1031/// ```
1032///
1033/// As a dynamic type, an object interface must be explicitly registered when
1034/// the system loads the implementation (see [`TypePlugin`] and [`TypeModule`]).
1035/// Therefore, whereas an object interface can be registered only once as a
1036/// static type, it can be registered several times as a dynamic type.
1037///
1038/// An object interface registered as a dynamic type is never unregistered. The
1039/// system calls [`TypePluginExt::unuse`] to unload the implementation. If the
1040/// [`TypePlugin`] subclass is a [`TypeModule`], the object interface
1041/// registered as a dynamic type is marked as unloaded and must be registered
1042/// again when the module is reloaded.
1043///
1044/// The macro helper attribute `object_interface_dynamic` provides two
1045/// behaviors when registering an object interface as a dynamic type:
1046///
1047/// - lazy registration: by default an object interface is registered as a
1048///   dynamic type when the system loads the implementation (e.g. when the module
1049///   is loaded). Optionally setting `lazy_registration` to `true` postpones
1050///   registration on the first use (when `type_()` is called for the first time):
1051///
1052/// ```ignore
1053/// pub struct MyInterface {
1054///     parent: glib::gobject_ffi::GTypeInterface,
1055/// }
1056/// #[glib::object_interface]
1057/// #[object_interface_dynamic(lazy_registration = true)]
1058/// unsafe impl ObjectInterface for MyInterface { ... }
1059/// ```
1060///
1061/// - registration within [`TypeModule`] subclass or within [`TypePlugin`]
1062///   subclass: an object interface is usually registered as a dynamic type
1063///   within a [`TypeModule`] subclass:
1064///
1065/// ```ignore
1066/// pub struct MyModuleInterface {
1067///     parent: glib::gobject_ffi::GTypeInterface,
1068/// }
1069/// #[glib::object_interface]
1070/// #[object_interface_dynamic]
1071/// unsafe impl ObjectInterface for MyModuleInterface { ... }
1072/// ...
1073/// #[derive(Default)]
1074/// pub struct MyModule;
1075/// ...
1076/// impl TypeModuleImpl for MyModule {
1077///     fn load(&self) -> bool {
1078///         // registers object interfaces as dynamic types.
1079///         let my_module = self.obj();
1080///         let type_module: &glib::TypeModule = my_module.upcast_ref();
1081///         MyModuleInterface::on_implementation_load(type_module)
1082///     }
1083///     ...
1084/// }
1085/// ```
1086///
1087/// Optionally setting `plugin_type` allows to register an object interface as
1088/// a dynamic type within a [`TypePlugin`] subclass that is not a [`TypeModule`]:
1089///
1090/// ```ignore
1091/// pub struct MyPluginInterface {
1092///     parent: glib::gobject_ffi::GTypeInterface,
1093/// }
1094/// #[glib::object_interface]
1095/// #[object_interface_dynamic(plugin_type = MyPlugin)]
1096/// unsafe impl ObjectInterface for MyPluginInterface { ... }
1097/// ...
1098/// #[derive(Default)]
1099/// pub struct MyPlugin;
1100/// ...
1101/// impl TypePluginImpl for MyPlugin {
1102///     fn use_plugin(&self) {
1103///         // register object interfaces as dynamic types.
1104///         let my_plugin = self.obj();
1105///         MyPluginInterface::on_implementation_load(my_plugin.as_ref());
1106///     }
1107///     ...
1108/// }
1109/// ```
1110///
1111/// [`ObjectInterface`]: ../glib/subclass/interface/trait.ObjectInterface.html
1112/// [`TypePlugin`]: ../glib/gobject/type_plugin/struct.TypePlugin.html
1113/// [`TypeModule`]: ../glib/gobject/type_module/struct.TypeModule.html
1114/// [`TypePluginExt::unuse`]: ../glib/gobject/type_plugin/trait.TypePluginExt.html#method.unuse///
1115#[proc_macro_attribute]
1116pub fn object_interface(_attr: TokenStream, item: TokenStream) -> TokenStream {
1117    let input = parse_macro_input!(item with object_impl_attributes::Input::parse_interface);
1118    object_impl_attributes::interface::impl_object_interface(input).into()
1119}
1120
1121/// Macro for deriving implementations of [`glib::clone::Downgrade`] and
1122/// [`glib::clone::Upgrade`] traits and a weak type.
1123///
1124/// # Examples
1125///
1126/// ## New Type Idiom
1127///
1128/// ```rust,ignore
1129/// #[derive(glib::Downgrade)]
1130/// pub struct FancyLabel(gtk::Label);
1131///
1132/// impl FancyLabel {
1133///     pub fn new(label: &str) -> Self {
1134///         Self(gtk::LabelBuilder::new().label(label).build())
1135///     }
1136///
1137///     pub fn flip(&self) {
1138///         self.0.set_angle(180.0 - self.0.angle());
1139///     }
1140/// }
1141///
1142/// let fancy_label = FancyLabel::new("Look at me!");
1143/// let button = gtk::ButtonBuilder::new().label("Click me!").build();
1144/// button.connect_clicked(
1145///     clone!(
1146///         #[weak]
1147///         fancy_label,
1148///         move || fancy_label.flip(),
1149///     ),
1150/// );
1151/// ```
1152///
1153/// ## Generic New Type
1154///
1155/// ```rust,ignore
1156/// #[derive(glib::Downgrade)]
1157/// pub struct TypedEntry<T>(gtk::Entry, std::marker::PhantomData<T>);
1158///
1159/// impl<T: ToString + FromStr> for TypedEntry<T> {
1160///     // ...
1161/// }
1162/// ```
1163///
1164/// ## Structures and Enums
1165///
1166/// ```rust,ignore
1167/// #[derive(Clone, glib::Downgrade)]
1168/// pub struct ControlButtons {
1169///     pub up: gtk::Button,
1170///     pub down: gtk::Button,
1171///     pub left: gtk::Button,
1172///     pub right: gtk::Button,
1173/// }
1174///
1175/// #[derive(Clone, glib::Downgrade)]
1176/// pub enum DirectionButton {
1177///     Left(gtk::Button),
1178///     Right(gtk::Button),
1179///     Up(gtk::Button),
1180///     Down(gtk::Button),
1181/// }
1182/// ```
1183///
1184/// [`glib::clone::Downgrade`]: ../glib/clone/trait.Downgrade.html
1185/// [`glib::clone::Upgrade`]: ../glib/clone/trait.Upgrade.html
1186#[proc_macro_derive(Downgrade)]
1187pub fn downgrade(input: TokenStream) -> TokenStream {
1188    let input = parse_macro_input!(input as DeriveInput);
1189    downgrade_derive::impl_downgrade(input)
1190}
1191
1192/// Derive macro for serializing/deserializing custom structs/enums as [`glib::Variant`]s.
1193///
1194/// # Example
1195///
1196/// ```
1197/// use glib::prelude::*;
1198///
1199/// #[derive(Debug, PartialEq, Eq, glib::Variant)]
1200/// struct Foo {
1201///     some_string: String,
1202///     some_int: i32,
1203/// }
1204///
1205/// let v = Foo { some_string: String::from("bar"), some_int: 1 };
1206/// let var = v.to_variant();
1207/// assert_eq!(var.get::<Foo>(), Some(v));
1208/// ```
1209///
1210/// When storing `Vec`s of fixed size types it is a good idea to wrap these in
1211/// `glib::FixedSizeVariantArray` as serialization/deserialization will be more efficient.
1212///
1213/// # Example
1214///
1215/// ```
1216/// use glib::prelude::*;
1217///
1218/// #[derive(Debug, PartialEq, Eq, glib::Variant)]
1219/// struct Foo {
1220///     some_vec: glib::FixedSizeVariantArray<Vec<u32>, u32>,
1221///     some_int: i32,
1222/// }
1223///
1224/// let v = Foo { some_vec: vec![1u32, 2u32].into(), some_int: 1 };
1225/// let var = v.to_variant();
1226/// assert_eq!(var.get::<Foo>(), Some(v));
1227/// ```
1228///
1229/// Enums are serialized as a tuple `(sv)` with the first value as a [kebab case] string for the
1230/// enum variant, or just `s` if this is a C-style enum. Some additional attributes are supported
1231/// for enums:
1232/// - `#[variant_enum(repr)]` to serialize the enum variant as an integer type instead of `s`.  The
1233///   `#[repr]` attribute must also be specified on the enum with a sized integer type, and the type
1234///   must implement `Copy`.
1235/// - `#[variant_enum(enum)]` uses [`EnumClass`] to serialize/deserialize as nicks. Meant for use
1236///   with [`glib::Enum`](Enum).
1237/// - `#[variant_enum(flags)]` uses [`FlagsClass`] to serialize/deserialize as nicks. Meant for use
1238///   with [`glib::flags`](macro@flags).
1239/// - `#[variant_enum(enum, repr)]` serializes as `i32`. Meant for use with [`glib::Enum`](Enum).
1240///   The type must also implement `Copy`.
1241/// - `#[variant_enum(flags, repr)]` serializes as `u32`. Meant for use with
1242///   [`glib::flags`](macro@flags).
1243///
1244/// # Example
1245///
1246/// ```
1247/// use glib::prelude::*;
1248///
1249/// #[derive(Debug, PartialEq, Eq, glib::Variant)]
1250/// enum Foo {
1251///     MyA,
1252///     MyB(i32),
1253///     MyC { some_int: u32, some_string: String }
1254/// }
1255///
1256/// let v = Foo::MyC { some_int: 1, some_string: String::from("bar") };
1257/// let var = v.to_variant();
1258/// assert_eq!(var.child_value(0).str(), Some("my-c"));
1259/// assert_eq!(var.get::<Foo>(), Some(v));
1260///
1261/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Variant)]
1262/// #[variant_enum(repr)]
1263/// #[repr(u8)]
1264/// enum Bar {
1265///     A,
1266///     B = 3,
1267///     C = 7
1268/// }
1269///
1270/// let v = Bar::B;
1271/// let var = v.to_variant();
1272/// assert_eq!(var.get::<u8>(), Some(3));
1273/// assert_eq!(var.get::<Bar>(), Some(v));
1274///
1275/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum, glib::Variant)]
1276/// #[variant_enum(enum)]
1277/// #[enum_type(name = "MyEnum")]
1278/// enum MyEnum {
1279///     Val,
1280///     #[enum_value(name = "My Val")]
1281///     ValWithCustomName,
1282///     #[enum_value(name = "My Other Val", nick = "other")]
1283///     ValWithCustomNameAndNick,
1284/// }
1285///
1286/// let v = MyEnum::ValWithCustomNameAndNick;
1287/// let var = v.to_variant();
1288/// assert_eq!(var.str(), Some("other"));
1289/// assert_eq!(var.get::<MyEnum>(), Some(v));
1290/// ```
1291///
1292/// [`glib::Variant`]: ../glib/variant/struct.Variant.html
1293/// [`EnumClass`]: ../glib/struct.EnumClass.html
1294/// [`FlagsClass`]: ../glib/struct.FlagsClass.html
1295/// [kebab case]: https://docs.rs/heck/0.4.0/heck/trait.ToKebabCase.html
1296#[proc_macro_derive(Variant, attributes(variant_enum))]
1297pub fn variant_derive(input: TokenStream) -> TokenStream {
1298    let input = parse_macro_input!(input as DeriveInput);
1299    variant_derive::impl_variant(input)
1300        .unwrap_or_else(syn::Error::into_compile_error)
1301        .into()
1302}
1303#[proc_macro]
1304pub fn cstr_bytes(item: TokenStream) -> TokenStream {
1305    syn::parse::Parser::parse2(
1306        |stream: syn::parse::ParseStream<'_>| {
1307            let literal = stream.parse::<syn::LitStr>()?;
1308            stream.parse::<syn::parse::Nothing>()?;
1309            let bytes = std::ffi::CString::new(literal.value())
1310                .map_err(|e| syn::Error::new_spanned(&literal, format!("{e}")))?
1311                .into_bytes_with_nul();
1312            let bytes = proc_macro2::Literal::byte_string(&bytes);
1313            Ok(quote::quote! { #bytes }.into())
1314        },
1315        item.into(),
1316    )
1317    .unwrap_or_else(|e| e.into_compile_error().into())
1318}
1319
1320/// This macro enables you to derive object properties in a quick way.
1321///
1322/// # Supported `#[property]` attributes
1323/// | Attribute | Description | Default | Example |
1324/// | --- | --- | --- | --- |
1325/// | `name = "literal"` | The name of the property | field ident where `_` (leading and trailing `_` are trimmed) is replaced into `-` | `#[property(name = "prop-name")]` |
1326/// | `type = expr` | The type of the property | inferred | `#[property(type = i32)]` |
1327/// | `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)]` |
1328/// | `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\| {})]` |
1329/// | `override_class = expr` | The type of class of which to override the property from | | `#[property(override_class = SomeClass)]` |
1330/// | `override_interface = expr` | The type of interface of which to override the property from | | `#[property(override_interface = SomeInterface)]` |
1331/// | `nullable` | Whether to use `Option<T>` in the generated setter method |  | `#[property(nullable)]` |
1332/// | `member = ident` | Field of the nested type where property is retrieved and set | | `#[property(member = author)]` |
1333/// | `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)]` |
1334/// | `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)]` |
1335/// | `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.  |
1336/// | `default` | Sets the `default_value` field of the Param Spec builder | | `#[property(default = 1)]` |
1337/// | `<optional-pspec-builder-fields> = expr` | Used to add optional Param Spec builder fields | | `#[property(minimum = 0)` , `#[property(minimum = 0, maximum = 1)]`, etc. |
1338/// | `<optional-pspec-builder-fields>` | Used to add optional Param Spec builder fields | | `#[property(explicit_notify)]` , `#[property(construct_only)]`, etc. |
1339///
1340/// ## Using Rust keywords as property names
1341/// 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.
1342/// 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.
1343///
1344/// # Generated methods
1345/// The following methods are generated on the wrapper type specified on `#[properties(wrapper_type = ...)]`:
1346/// * `$property()`, when the property is readable
1347/// * `set_$property()`, when the property is writable and not construct-only
1348/// * `connect_$property_notify()`
1349/// * `notify_$property()`
1350///
1351/// # Documentation
1352///
1353/// Doc comments preceding a `#[property]` attribute will be copied to the generated getter and setter methods. You can specify different comments by the getter and setter by using `# Getter` and `# Setter` headings. The text under the header will be copied to the respective method.
1354///
1355/// ## Extension trait
1356/// You can choose to move the method definitions to a trait by using `#[properties(wrapper_type = super::MyType, ext_trait = MyTypePropertiesExt)]`.
1357/// The trait name is optional, and defaults to `MyTypePropertiesExt`, where `MyType` is extracted from the wrapper type.
1358/// Note: The trait is defined in the same module where the `#[derive(Properties)]` call happens, and is implemented on the wrapper type.
1359///
1360/// Notice: You can't reimplement the generated methods on the wrapper type, unless you move them to a trait.
1361/// You can change the behavior of the generated getter/setter methods by using a custom internal getter/setter.
1362///
1363/// # Internal getters and setters
1364/// By default, they are generated for you. However, you can use a custom getter/setter
1365/// by assigning an expression to `get`/`set` `#[property]` attributes: `#[property(get = |_| 2, set)]` or `#[property(get, set = custom_setter_func)]`.
1366///
1367/// # Supported types
1368/// Every type implementing the trait [`Property`] is supported.
1369/// The type `Option<T>` is supported as a property only if `Option<T>` implements [`ToValueOptional`].
1370/// Optional types also require the `nullable` attribute: without it, the generated setter on the wrapper type
1371/// will take `T` instead of `Option<T>`, preventing the user from ever calling the setter with a `None` value.
1372///
1373/// Notice: For enums that derive [`Enum`] or are C-style enums, you must explicitly specify the
1374/// default value of the enum using the `builder` parameter in the `#[property]` attribute.
1375///
1376/// ## Adding support for custom types
1377/// ### Types wrapping an existing <code>T: [ToValue] + [HasParamSpec]</code>
1378/// If you have declared a newtype as
1379/// ```rust
1380/// struct MyInt(i32);
1381/// ```
1382/// you can use it as a property by deriving [`ValueDelegate`].
1383///
1384/// ### Types with inner mutability
1385/// The trait [`Property`] must be implemented.
1386/// The traits [`PropertyGet`] and [`PropertySet`] should be implemented to enable the Properties macro
1387/// to generate a default internal getter/setter.
1388/// If possible, implementing [`PropertySetNested`] is preferred over `PropertySet`, because it
1389/// enables this macro to access the contained type and provide access to its fields,
1390/// using the `member = $structfield` syntax.
1391///
1392/// ### Types without [`HasParamSpec`][HasParamSpec]
1393/// If you have encountered a type <code>T: [ToValue]</code>, inside the gtk-rs crate, which doesn't implement [`HasParamSpec`][HasParamSpec],
1394/// then it's a bug and you should report it.
1395/// If you need to support a `ToValue` type with a [`ParamSpec`] not provided by gtk-rs, then you need to
1396/// implement `HasParamSpec` on that type.
1397///
1398/// # Example
1399/// ```
1400/// use std::cell::{Cell, RefCell};
1401/// use glib::prelude::*;
1402/// use glib::subclass::prelude::*;
1403/// use glib_macros::Properties;
1404///
1405/// #[derive(Default, Clone)]
1406/// struct Author {
1407///     name: String,
1408///     nick: String,
1409/// }
1410///
1411/// #[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum, Default)]
1412/// #[enum_type(name = "MyEnum")]
1413/// enum MyEnum {
1414///     #[default]
1415///     Val,
1416///     OtherVal
1417/// }
1418///
1419/// pub mod imp {
1420///     use std::rc::Rc;
1421///
1422///     use super::*;
1423///
1424///     #[derive(Properties, Default)]
1425///     #[properties(wrapper_type = super::Foo)]
1426///     pub struct Foo {
1427///         #[property(get, set = Self::set_fizz)]
1428///         fizz: RefCell<String>,
1429///         /// The author's name
1430///         #[property(name = "author-name", get, set, type = String, member = name)]
1431///         /// The author's childhood nickname
1432///         #[property(name = "author-nick", get, set, type = String, member = nick)]
1433///         author: RefCell<Author>,
1434///         #[property(get, set, explicit_notify, lax_validation)]
1435///         custom_flags: RefCell<String>,
1436///         #[property(get, set, minimum = 0, maximum = 3)]
1437///         numeric_builder: RefCell<u32>,
1438///         #[property(get, set, builder('c'))]
1439///         builder_with_required_param: RefCell<char>,
1440///         #[property(get, set, nullable)]
1441///         optional: RefCell<Option<String>>,
1442///         #[property(get, set)]
1443///         smart_pointer: Rc<RefCell<String>>,
1444///         #[property(get, set, builder(MyEnum::Val))]
1445///         my_enum: Cell<MyEnum>,
1446///         /// # Getter
1447///         ///
1448///         /// Get the value of the property `extra_comments`
1449///         ///
1450///         /// # Setter
1451///         ///
1452///         /// This is the comment for the setter of the `extra_comments` field.
1453///         #[property(get, set)]
1454///         extra_comments: RefCell<bool>,
1455///     }
1456///     
1457///     #[glib::derived_properties]
1458///     impl ObjectImpl for Foo {}
1459///
1460///     #[glib::object_subclass]
1461///     impl ObjectSubclass for Foo {
1462///         const NAME: &'static str = "MyFoo";
1463///         type Type = super::Foo;
1464///     }
1465///
1466///     impl Foo {
1467///         fn set_fizz(&self, value: String) {
1468///             *self.fizz.borrow_mut() = format!("custom set: {}", value);
1469///         }
1470///     }
1471/// }
1472///
1473/// glib::wrapper! {
1474///     pub struct Foo(ObjectSubclass<imp::Foo>);
1475/// }
1476///
1477/// fn main() {
1478///   let myfoo: Foo = glib::object::Object::new();
1479///
1480///   myfoo.set_fizz("test value");
1481///   assert_eq!(myfoo.fizz(), "custom set: test value".to_string());
1482/// }
1483/// ```
1484///
1485/// [`Property`]: ../glib/property/trait.Property.html
1486/// [`PropertyGet`]: ../glib/property/trait.PropertyGet.html
1487/// [`PropertyGet::get`]: ../glib/property/trait.PropertyGet.html#tymethod.get
1488/// [`PropertySet`]: ../glib/property/trait.PropertySet.html
1489/// [`PropertySet::set`]: ../glib/property/trait.PropertySet.html#tymethod.set
1490/// [`PropertySetNested`]: ../glib/property/trait.PropertySetNested.html
1491/// [`ObjectExt::property`]: ../glib/object/trait.ObjectExt.html#tymethod.property
1492/// [HasParamSpec]: ../glib/trait.HasParamSpec.html
1493/// [`ParamSpec`]: ../glib/struct.ParamSpec.html
1494/// [`ToValueOptional`]: ../glib/value/trait.ToValueOptional.html
1495/// [ToValue]: ../glib/value/trait.ToValue.html
1496#[allow(clippy::needless_doctest_main)]
1497#[proc_macro_derive(Properties, attributes(properties, property))]
1498pub fn derive_props(input: TokenStream) -> TokenStream {
1499    let input = parse_macro_input!(input as properties::PropsMacroInput);
1500    properties::impl_derive_props(input)
1501}
1502
1503/// When applied to `ObjectImpl`
1504/// ```ignore
1505/// #[glib::derived_properties]
1506/// impl ObjectImpl for CustomObject
1507/// ```
1508/// this macro generates
1509/// ```ignore
1510/// impl ObjectImpl for CustomObject {
1511///     fn properties() -> &'static [glib::ParamSpec] {
1512///         Self::derived_properties()
1513///     }
1514///     fn set_property(&self, id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
1515///         self.derived_set_property(id, value, pspec)
1516///     }
1517///     fn property(&self, id: usize, pspec: &glib::ParamSpec) -> glib::Value {
1518///         self.derived_property(id, pspec)
1519///     }
1520/// }
1521/// ```
1522#[proc_macro_attribute]
1523pub fn derived_properties(_attr: TokenStream, item: TokenStream) -> TokenStream {
1524    syn::parse::<syn::ItemImpl>(item)
1525        .map_err(|_| {
1526            syn::Error::new(
1527                Span::call_site(),
1528                derived_properties_attribute::WRONG_PLACE_MSG,
1529            )
1530        })
1531        .and_then(|input| derived_properties_attribute::impl_derived_properties(&input))
1532        .unwrap_or_else(syn::Error::into_compile_error)
1533        .into()
1534}
1535
1536/// # Example
1537/// ```
1538/// use glib::prelude::*;
1539/// use glib::ValueDelegate;
1540///
1541/// #[derive(ValueDelegate, Debug, PartialEq)]
1542/// struct MyInt(i32);
1543///
1544/// let myv = MyInt(2);
1545/// let convertedv = myv.to_value();
1546/// assert_eq!(convertedv.get::<MyInt>(), Ok(myv));
1547///
1548///
1549/// #[derive(ValueDelegate, Debug, PartialEq)]
1550/// #[value_delegate(from = u32)]
1551/// enum MyEnum {
1552///     Zero,
1553///     NotZero(u32)
1554/// }
1555///
1556/// impl From<u32> for MyEnum {
1557///     fn from(v: u32) -> Self {
1558///         match v {
1559///             0 => MyEnum::Zero,
1560///             x => MyEnum::NotZero(x)
1561///         }
1562///     }
1563/// }
1564/// impl<'a> From<&'a MyEnum> for u32 {
1565///     fn from(v: &'a MyEnum) -> Self {
1566///         match v {
1567///             MyEnum::Zero => 0,
1568///             MyEnum::NotZero(x) => *x
1569///         }
1570///     }
1571/// }
1572/// impl From<MyEnum> for u32 {
1573///     fn from(v: MyEnum) -> Self {
1574///         match v {
1575///             MyEnum::Zero => 0,
1576///             MyEnum::NotZero(x) => x
1577///         }
1578///     }
1579/// }
1580///
1581/// let myv = MyEnum::NotZero(34);
1582/// let convertedv = myv.to_value();
1583/// assert_eq!(convertedv.get::<MyEnum>(), Ok(myv));
1584///
1585///
1586/// // If you want your type to be usable inside an `Option`, you can derive `ToValueOptional`
1587/// // by adding `nullable` as follows
1588/// #[derive(ValueDelegate, Debug, PartialEq)]
1589/// #[value_delegate(nullable)]
1590/// struct MyString(String);
1591///
1592/// let myv = Some(MyString("Hello world".to_string()));
1593/// let convertedv = myv.to_value();
1594/// assert_eq!(convertedv.get::<Option<MyString>>(), Ok(myv));
1595/// let convertedv = None::<MyString>.to_value();
1596/// assert_eq!(convertedv.get::<Option<MyString>>(), Ok(None::<MyString>));
1597/// ```
1598#[proc_macro_derive(ValueDelegate, attributes(value_delegate))]
1599pub fn derive_value_delegate(input: TokenStream) -> TokenStream {
1600    let input = parse_macro_input!(input as value_delegate_derive::ValueDelegateInput);
1601    value_delegate_derive::impl_value_delegate(input).unwrap()
1602}
1603
1604/// An attribute macro for writing asynchronous test functions.
1605///
1606/// This macro is designed to wrap an asynchronous test function and ensure that
1607/// it runs within a `glib::MainContext`. It helps in writing async tests that
1608/// require the use of an event loop for the asynchronous execution.
1609///
1610/// # Example
1611///
1612/// ```
1613/// #[glib::async_test]
1614/// async fn my_async_test() {
1615///     // Test code that runs asynchronously
1616/// }
1617/// ```
1618#[proc_macro_attribute]
1619pub fn async_test(args: TokenStream, item: TokenStream) -> TokenStream {
1620    async_test::async_test(args, item)
1621}