1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
// Take a look at the license at the top of the repository in the LICENSE file. mod clone; mod downgrade_derive; mod gboxed_derive; mod gboxed_shared_derive; mod genum_derive; mod gerror_domain_derive; mod gflags_attribute; mod object_interface_attribute; mod object_subclass_attribute; mod utils; use proc_macro::TokenStream; use proc_macro_error::proc_macro_error; use syn::{parse_macro_input, DeriveInput, LitStr}; /// Macro for passing variables as strong or weak references into a closure. /// /// This macro can be useful in combination with closures, e.g. signal handlers, to reduce the /// boilerplate required for passing strong or weak references into the closure. It will /// automatically create the new reference and pass it with the same name into the closure. /// /// If upgrading the weak reference to a strong reference inside the closure is failing, the /// closure is immediately returning an optional default return value. If none is provided, `()` is /// returned. /// /// **⚠️ IMPORTANT ⚠️** /// /// `glib` needs to be in scope, so unless it's one of the direct crate dependencies, you need to /// import it because `clone!` is using it. For example: /// /// ```rust,ignore /// use gtk::glib; /// ``` /// /// ### Debugging /// /// In case something goes wrong inside the `clone!` macro, we use the [`g_debug`] macro. Meaning /// that if you want to see these debug messages, you'll have to set the `G_MESSAGES_DEBUG` /// environment variable when running your code (either in the code directly or when running the /// binary) to either "all" or [`CLONE_MACRO_LOG_DOMAIN`]: /// /// [`g_debug`]: https://gtk-rs.org/gtk-rs-core/stable/latest/docs/glib/macro.g_debug.html /// [`CLONE_MACRO_LOG_DOMAIN`]: https://gtk-rs.org/gtk-rs-core/stable/latest/docs/glib/constant.CLONE_MACRO_LOG_DOMAIN.html /// /// ```rust,ignore /// use glib::CLONE_MACRO_LOG_DOMAIN; /// /// std::env::set_var("G_MESSAGES_DEBUG", CLONE_MACRO_LOG_DOMAIN); /// std::env::set_var("G_MESSAGES_DEBUG", "all"); /// ``` /// /// Or: /// /// ```bash /// $ G_MESSAGES_DEBUG=all ./binary /// ``` /// /// ### Passing a strong reference /// /// ``` /// use glib; /// use glib_macros::clone; /// use std::rc::Rc; /// /// let v = Rc::new(1); /// let closure = clone!(@strong v => move |x| { /// println!("v: {}, x: {}", v, x); /// }); /// /// closure(2); /// ``` /// /// ### Passing a weak reference /// /// ``` /// use glib; /// use glib_macros::clone; /// use std::rc::Rc; /// /// let u = Rc::new(2); /// let closure = clone!(@weak u => move |x| { /// println!("u: {}, x: {}", u, x); /// }); /// /// closure(3); /// ``` /// /// #### Allowing a nullable weak reference /// /// In some cases, even if the weak references can't be retrieved, you might want to still have /// your closure called. In this case, you need to use `@weak-allow-none`: /// /// ``` /// use glib; /// use glib_macros::clone; /// use std::rc::Rc; /// /// let closure = { /// // This `Rc` won't be available in the closure because it's dropped at the end of the /// // current block /// let u = Rc::new(2); /// clone!(@weak-allow-none u => @default-return false, move |x| { /// // We need to use a Debug print for `u` because it'll be an `Option`. /// println!("u: {:?}, x: {}", u, x); /// true /// }) /// }; /// /// assert_eq!(closure(3), true); /// ``` /// /// ### Renaming variables /// /// ``` /// use glib; /// use glib_macros::clone; /// use std::rc::Rc; /// /// let v = Rc::new(1); /// let u = Rc::new(2); /// let closure = clone!(@strong v as y, @weak u => move |x| { /// println!("v as y: {}, u: {}, x: {}", y, u, x); /// }); /// /// closure(3); /// ``` /// /// ### Providing a default return value if upgrading a weak reference fails /// /// You can do it in two different ways: /// /// Either by providing the value yourself using `@default-return`: /// /// ``` /// use glib; /// use glib_macros::clone; /// use std::rc::Rc; /// /// let v = Rc::new(1); /// let closure = clone!(@weak v => @default-return false, move |x| { /// println!("v: {}, x: {}", v, x); /// true /// }); /// /// // Drop value so that the weak reference can't be upgraded. /// drop(v); /// /// assert_eq!(closure(2), false); /// ``` /// /// Or by using `@default-panic` (if the value fails to get upgraded, it'll panic): /// /// ```should_panic /// # use glib; /// # use glib_macros::clone; /// # use std::rc::Rc; /// # let v = Rc::new(1); /// let closure = clone!(@weak v => @default-panic, move |x| { /// println!("v: {}, x: {}", v, x); /// true /// }); /// # drop(v); /// # assert_eq!(closure(2), false); /// ``` /// /// ### Errors /// /// Here is a list of errors you might encounter: /// /// **Missing `@weak` or `@strong`**: /// /// ```compile_fail /// # use glib; /// # use glib_macros::clone; /// # use std::rc::Rc; /// let v = Rc::new(1); /// /// let closure = clone!(v => move |x| println!("v: {}, x: {}", v, x)); /// # drop(v); /// # closure(2); /// ``` /// /// **Passing `self` as an argument**: /// /// ```compile_fail /// # use glib; /// # use glib_macros::clone; /// # use std::rc::Rc; /// #[derive(Debug)] /// struct Foo; /// /// impl Foo { /// fn foo(&self) { /// let closure = clone!(@strong self => move |x| { /// println!("self: {:?}", self); /// }); /// # closure(2); /// } /// } /// ``` /// /// If you want to use `self` directly, you'll need to rename it: /// /// ``` /// # use glib; /// # use glib_macros::clone; /// # use std::rc::Rc; /// #[derive(Debug)] /// struct Foo; /// /// impl Foo { /// fn foo(&self) { /// let closure = clone!(@strong self as this => move |x| { /// println!("self: {:?}", this); /// }); /// # closure(2); /// } /// } /// ``` /// /// **Passing fields directly** /// /// ```compile_fail /// # use glib; /// # use glib_macros::clone; /// # use std::rc::Rc; /// #[derive(Debug)] /// struct Foo { /// v: Rc<usize>, /// } /// /// impl Foo { /// fn foo(&self) { /// let closure = clone!(@strong self.v => move |x| { /// println!("self.v: {:?}", v); /// }); /// # closure(2); /// } /// } /// ``` /// /// You can do it by renaming it: /// /// ``` /// # use glib; /// # use glib_macros::clone; /// # use std::rc::Rc; /// # struct Foo { /// # v: Rc<usize>, /// # } /// impl Foo { /// fn foo(&self) { /// let closure = clone!(@strong self.v as v => move |x| { /// println!("self.v: {}", v); /// }); /// # closure(2); /// } /// } /// ``` #[proc_macro] #[proc_macro_error] pub fn clone(item: TokenStream) -> TokenStream { clone::clone_inner(item) } #[proc_macro_derive(GEnum, attributes(genum))] #[proc_macro_error] pub fn genum_derive(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let gen = genum_derive::impl_genum(&input); gen.into() } /// Derive macro for defining a GLib error domain and its associated /// [`ErrorDomain`] trait. /// /// # Example /// /// ``` /// use glib::prelude::*; /// use glib::subclass::prelude::*; /// /// #[derive(Debug, Copy, Clone, glib::GErrorDomain)] /// #[gerror_domain(name = "ExFoo")] /// enum Foo { /// Blah, /// Baaz, /// } /// ``` /// /// [`ErrorDomain`]: error/trait.ErrorDomain.html #[proc_macro_derive(GErrorDomain, attributes(gerror_domain))] #[proc_macro_error] pub fn gerror_domain_derive(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let gen = gerror_domain_derive::impl_gerror_domain(&input); gen.into() } /// Derive macro for defining a [`BoxedType`]`::type_` function and /// the [`glib::Value`] traits. /// /// # Example /// /// ``` /// use glib::prelude::*; /// use glib::subclass::prelude::*; /// /// #[derive(Clone, Debug, PartialEq, Eq, glib::GBoxed)] /// #[gboxed(type_name = "MyBoxed")] /// struct MyBoxed(String); /// ``` /// /// [`BoxedType`]: subclass/boxed/trait.BoxedType.html /// [`glib::Value`]: value/struct.Value.html #[proc_macro_derive(GBoxed, attributes(gboxed))] #[proc_macro_error] pub fn gboxed_derive(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let gen = gboxed_derive::impl_gboxed(&input); gen.into() } /// Derive macro for defining a [`SharedType`]`::get_type` function and /// the [`glib::Value`] traits. /// /// # Example /// /// ``` /// use glib::prelude::*; /// use glib::subclass::prelude::*; /// /// #[derive(Clone, Debug, PartialEq, Eq)] /// struct MySharedInner { /// foo: String, /// } /// #[derive(Clone, Debug, PartialEq, Eq, glib::GSharedBoxed)] /// #[gshared_boxed(type_name = "MyShared")] /// struct MyShared(std::sync::Arc<MySharedInner>); /// ``` /// /// [`SharedType`]: subclass/shared/trait.SharedType.html /// [`glib::Value`]: value/struct.Value.html #[proc_macro_derive(GSharedBoxed, attributes(gshared_boxed))] #[proc_macro_error] pub fn gshared_boxed_derive(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let gen = gboxed_shared_derive::impl_gshared_boxed(&input); gen.into() } /// Attribute macro for defining flags using the `bitflags` crate. /// This macro will also define a `GFlags::type_` function and /// the [`glib::Value`] traits. /// /// The expected `GType` name has to be passed as macro attribute. /// The name and nick of each flag can also be optionally defined. /// Default name is the flag identifier in CamelCase and default nick /// is the identifier in kebab-case. /// Combined flags should not be registered with the `GType` system /// and so needs to be tagged with the `#[gflags(skip)]` attribute. /// /// # Example /// /// ``` /// use glib::prelude::*; /// use glib::subclass::prelude::*; /// /// #[glib::gflags("MyFlags")] /// enum MyFlags { /// #[gflags(name = "Flag A", nick = "nick-a")] /// A = 0b00000001, /// #[gflags(name = "Flag B")] /// B = 0b00000010, /// #[gflags(skip)] /// AB = Self::A.bits() | Self::B.bits(), /// C = 0b00000100, /// } /// ``` /// /// [`glib::Value`]: value/struct.Value.html #[proc_macro_attribute] #[proc_macro_error] pub fn gflags(attr: TokenStream, item: TokenStream) -> TokenStream { let input = parse_macro_input!(item as DeriveInput); let gtype_name = parse_macro_input!(attr as LitStr); let gen = gflags_attribute::impl_gflags(&input, >ype_name); gen.into() } /// Macro for boilerplate of [`ObjectSubclass`] implementations. /// /// This adds implementations for the `type_data()` and `type_()` methods, /// which should probably never be defined differently. /// /// It provides default values for the `Instance`, `Class`, and `Interfaces` /// type parameters. If these are present, the macro will use the provided value /// instead of the default. /// /// Usually the defaults for `Instance` and `Class` will work. `Interfaces` is /// necessary for types that implement interfaces. /// /// ```ignore /// type Instance = glib::subclass::simple::InstanceStruct<Self>; /// type Class = glib::subclass::simple::ClassStruct<Self>; /// type Interfaces = (); /// ``` /// /// If no `new()` or `with_class()` method is provide, the macro adds a `new()` /// implementation calling `Default::default()`. So the type needs to implement /// `Default`, or this should be overridden. /// /// ```ignore /// fn new() -> Self { /// Default::default() /// } /// ``` /// /// [`ObjectSubclass`]: subclass/types/trait.ObjectSubclass.html #[proc_macro_attribute] #[proc_macro_error] pub fn object_subclass(_attr: TokenStream, item: TokenStream) -> TokenStream { use proc_macro_error::abort_call_site; match syn::parse::<syn::ItemImpl>(item) { Ok(input) => object_subclass_attribute::impl_object_subclass(&input).into(), Err(_) => abort_call_site!(object_subclass_attribute::WRONG_PLACE_MSG), } } /// Macro for boilerplate of [`ObjectInterface`] implementations. /// /// This adds implementations for the `get_type()` method, which should probably never be defined /// differently. /// /// It provides default values for the `Prerequisites` type parameter. If this present, the macro /// will use the provided value instead of the default. /// /// `Prerequisites` is interfaces for types that require a specific base class or interfaces. /// /// ```ignore /// type Prerequisites = (); /// ``` /// /// [`ObjectInterface`]: interface/types/trait.ObjectInterface.html #[proc_macro_attribute] #[proc_macro_error] pub fn object_interface(_attr: TokenStream, item: TokenStream) -> TokenStream { use proc_macro_error::abort_call_site; match syn::parse::<syn::ItemImpl>(item) { Ok(input) => object_interface_attribute::impl_object_interface(&input).into(), Err(_) => abort_call_site!(object_interface_attribute::WRONG_PLACE_MSG), } } /// Macro for deriving implementations of [`glib::clone::Downgrade`] and /// [`glib::clone::Upgrade`] traits and a weak type. /// /// # Examples /// /// ## New Type Idiom /// /// ```rust,ignore /// #[derive(glib::Downgrade)] /// pub struct FancyLabel(gtk::Label); /// /// impl FancyLabel { /// pub fn new(label: &str) -> Self { /// Self(gtk::LabelBuilder::new().label(label).build()) /// } /// /// pub fn flip(&self) { /// self.0.set_angle(180.0 - self.0.angle()); /// } /// } /// /// let fancy_label = FancyLabel::new("Look at me!"); /// let button = gtk::ButtonBuilder::new().label("Click me!").build(); /// button.connect_clicked(clone!(@weak fancy_label => move || fancy_label.flip())); /// ``` /// /// ## Generic New Type /// /// ```rust,ignore /// #[derive(glib::Downgrade)] /// pub struct TypedEntry<T>(gtk::Entry, std::marker::PhantomData<T>); /// /// impl<T: ToString + FromStr> for TypedEntry<T> { /// // ... /// } /// ``` /// /// ## Structures and Enums /// /// ```rust,ignore /// #[derive(Clone, glib::Downgrade)] /// pub struct ControlButtons { /// pub up: gtk::Button, /// pub down: gtk::Button, /// pub left: gtk::Button, /// pub right: gtk::Button, /// } /// /// #[derive(Clone, glib::Downgrade)] /// pub enum DirectionButton { /// Left(gtk::Button), /// Right(gtk::Button), /// Up(gtk::Button), /// Down(gtk::Button), /// } /// ``` /// /// [`glib::clone::Downgrade`]: clone/trait.Downgrade.html /// [`glib::clone::Upgrade`]: clone/trait.Upgrade.html #[proc_macro_derive(Downgrade)] pub fn downgrade(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); downgrade_derive::impl_downgrade(input) }