Skip to main content

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