Debian Codegraph @

src/lib.rs

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