Debian Codegraph @

book/src/config/api.md

raw
1 # API Options
2
3 This mode requires you to write another TOML file.
4 [gtk/Gir.toml](https://github.com/gtk-rs/gtk/blob/main/Gir.toml) is a good example.
5
6 ```toml
7 [options]
8 girs_directories = ["gir-files"]
9 library = "Gtk"
10 version = "3.0"
11 min_cfg_version = "3.4"
12 target_path = "."
13 # Path where objects generated (defaults to <target_path>/src/auto)
14 # auto_path = "src/auto"
15 work_mode = "normal"
16 generate_safety_asserts = true
17 deprecate_by_min_version = true
18 # With this option enabled, versions for gir and gir-files saved only to one file to minimize noise,
19 # can also take path to the directory for saving "versions.txt" or filename with extension.
20 # Relative to target_path
21 single_version_file = true
22 # Trust the nullability information about return values. If this is disabled
23 # then any pointer return type is assumed to be nullable unless there is an
24 # explicit override for it.
25 # This has to be used carefully as many libraries are missing nullable
26 # annotations for return values, which then will cause a panic once an
27 # unexpected NULL is returned.
28 trust_return_value_nullability = false
29 # Disable running `cargo fmt` on generated files
30 # (defaults to false)
31 disable_format = true
32 # Always generate a Builder if possible. This is mostly a convenient setter as most of the
33 # time you might want the Builder to be generated. Ignoring none-desired ones can still be done with per object `generate_builder` configuration.
34 # (defaults to false)
35 generate_builder = true
36 ```
37
38 This mode generates only the specified objects.
39 You can either add the object's fullname to the `generate` array or add it to the `manual` array (but in this case, it won't be generated, just used in other functions/methods instead of generating an "ignored" argument).
40 Example:
41
42 ```toml
43 generate = ["Gtk.Widget", "Gtk.Window"]
44 manual = ["Gtk.Button"]
45 ```
46
47 So in here, both `GtkWidget` and `GtkWindow` will be fully generated and functions/methods using `GtkButton` will be uncommented.
48 To generate code for all global functions, add `Gtk.*` to the `generate` array.
49
50 To also generate a `Builder` struct for a widget, it needs to be set with the `generate_builder` flag in object configuration:
51
52 ```toml
53 [[object]]
54 name = "Gtk.TreeView"
55 status = "generate"
56 generate_builder = true
57 ```
58
59 > If the object doesn't already have a `Default` implementation through a constructor method without arguments, generating a `Builder` struct will add a `Default` implementation for the object.
60
61 If you want to remove warning messages about the not bound `Builders` during the generation you don't want to be generated, you can ignore them with the `generate_builder` flag in object configuration:
62
63 ```toml
64 [[object]]
65 name = "Gtk.TreeView"
66 status = "generate"
67 generate_builder = false
68 ```
69
70 If there is some work which has to be done post-construction before the builder's
71 `build` method returns, you can set the `builder_postprocess` value in the object configuration:
72
73 ```toml
74 [[object]]
75 name = "Gtk.Application"
76 status = "generate"
77 generate_builder = true
78 builder_postprocess = "Application::register_startup_hook(&ret);"
79 ```
80
81 For the duration of the code in `builder_postprocess` the binding `ret` will be the
82 value to be returned from the `build` method.
83
84 Sometimes Gir understands the object definition incorrectly or the `.gir` file contains an incomplete or wrong definition, to fix it, you can use the full object configuration:
85
86 ```toml
87 [[object]]
88 # object's fullname
89 name = "Gtk.SomeClass"
90 # can be also "manual" and "ignore" but it's simpler to just put the object in the same array
91 status = "generate"
92 # replace the parameter name for the child in child properties (instead "child")
93 child_name = "item"
94 # mark object as final type, i.e. one without any further subclasses. this
95 # will not generate trait SomeClassExt for this object, but implement all
96 # functions in impl SomeClass
97 final_type = true
98 # mark the object as a fundamental type in case the GIR file lacks the annotation
99 # note that fundamental types don't make use of IsA/Cast traits and you should
100 # implement something similar manually
101 # gir is only capable for generating the type definitions along with their functions
102 fundamental_type = false
103 # mark the enum as exhaustive. This must only be done if it is impossible for
104 # the C library to add new variants to the enum at a later time but allows
105 # for more optimal code to be generated.
106 exhaustive = false
107 # allow rename result file
108 module_name = "soome_class"
109 # override starting version
110 version = "3.12"
111 # prefixed object in mod.rs with #[cfg(mycond)]
112 cfg_condition = "mycond"
113 # if you want to generate builder with name SomeClassBuilder
114 generate_builder = true
115 # trust return value nullability annotations for this specific type.
116 # See above for details and use with care
117 trust_return_value_nullability = false
118 # Tweak the visibility of the type
119 visibility = "pub" # or 'crate' / 'private' / 'super'
120 # The default value to used for the `Default` implementation. It only
121 # works for flags and enums. You have to pass the "GIR" member name.
122 default_value = "fill"
123 # Change the name of the generated trait to e.g avoid naming conflicts
124 trait_name = "TraitnameExt"
125 # In case you don't want to generate the documentation for this type.
126 generate_doc = false
127 # define overrides for function
128 [[object.function]]
129 # filter functions from object
130 name = "set_website_label"
131 # alternative way to apply override for many functions. Will be used with '^' and '$' on both sides
132 # can be used instead of `name` almost anywhere
133 # pattern = "[gs]et_value"
134 # don't generate function
135 ignore = true
136 # override starting version
137 version = "3.12"
138 # prefixed function with #[cfg(mycond)]
139 cfg_condition = "mycond"
140 # prefixed function with #[doc(hidden)]
141 doc_hidden = true
142 # define a list of function parameters to be ignored when the documentation is generated
143 doc_ignore_parameters = ["some_user_data_param"]
144 # disable length_of autodetection
145 disable_length_detect = true
146 # write function docs to trait other than default "xxxExt",
147 # also works in [object.signal] and [object.property]
148 doc_trait_name = "SocketListenerExtManual"
149 # disable generation of future for async function
150 no_future = true
151 # to rename the generated function
152 rename = "something_else"
153 # to override the default safety assertions: "none", "skip",
154 # "not-initialized", "in-main-thread"
155 assertion = "in-main-thread"
156 # Tweak the visibility of the function
157 visibility = "pub" # or 'crate' / 'private' / 'super'
158 # In case you don't want to generate the documentation for this method.
159 generate_doc = false
160 # override for parameter
161 [[object.function.parameter]]
162 # filter by name
163 name = "website_label"
164 # allow to remove/add Option<>
165 nullable = true
166 # Take the parameter by value instead of by ref
167 move = true
168 # allow to make parameter immutable
169 const = true
170 # parameter is calculated as length of string or array and removed from function declaration
171 # (for length of return value use "return")
172 length_of = "str"
173 # change string type. Variants: "utf8", "filename", "os_string"
174 string_type = "os_string"
175 # make function unsafe to call (emits `fn unsafe`)
176 unsafe = true
177
178 # override for return value
179 [object.function.return]
180 # allow to remove/add Option<> to return value
181 nullable = true
182 # convert bool return types to Result<(), glib::BoolError> with
183 # the given error message on failure
184 bool_return_is_error = "Function failed doing what it is supposed to do"
185 # convert Option return types to Result<T, glib::BoolError> with
186 # the given error message on failure
187 nullable_return_is_error = "Function failed doing what it is supposed to do"
188 # always include the return value of throwing functions in the returned Result<...>,
189 # without this option bool and guint return values are assumed to indicate success or error,
190 # and are not included in the returned Result<...>
191 use_return_for_result = true
192 # change string type. Variants: "utf8", "filename", "os_string"
193 string_type = "os_string"
194 # overwrite type
195 type = "Gtk.Widget"
196
197 # Override callback's parameter
198 [[object.function.parameter.callback_parameter]]
199 name = "name_of_the_callback_parameter"
200 nullable = true
201 # virtual methods support the same configuration for parameters and return types as functions
202 # note that they are not used for code generation yet.
203 [[object.virtual_method]]
204 # filter virtual method from object
205 name = "set_website_label"
206 # alternative way to apply override for many functions. Will be used with '^' and '$' on both sides
207 # can be used instead of `name` almost anywhere
208 # pattern = "[gs]et_value"
209 # don't generate function
210 ignore = true
211 # override starting version
212 version = "3.12"
213 # prefixed function with #[cfg(mycond)]
214 cfg_condition = "mycond"
215 # prefixed function with #[doc(hidden)]
216 doc_hidden = true
217 # define a list of function parameters to be ignored when the documentation is generated
218 doc_ignore_parameters = ["some_user_data_param"]
219 # write function docs to trait other than default "xxxExt",
220 # also works in [object.signal] and [object.property]
221 doc_trait_name = "SocketListenerExtManual"
222 # to rename the generated function
223 rename = "something_else"
224 # In case you don't want to generate the documentation for this method.
225 generate_doc = false
226 [[object.signal]]
227 name = "activate-link"
228 # replace trampoline bool return type with `Inhibit`
229 inhibit = true
230 ignore = true
231 version = "3.10"
232 doc_hidden = true
233 # In case you don't want to generate the documentation for this signal.
234 generate_doc = false
235 [[object.signal.parameter]]
236 name = "path_string"
237 # allow to use different names in closure
238 new_name = "path"
239 # can be also "borrow" and "none": Add some transformation between ffi trampoline parameters and rust closure
240 transformation = "treepath"
241 nullable = true
242 [object.signal.return]
243 nullable = true
244 # override for properties
245 [[object.property]]
246 name = "baseline-position"
247 version = "3.10"
248 ignore = true
249 # In case you don't want to generate the documentation for this property.
250 generate_doc = false
251 [[object.property]]
252 name = "events"
253 # generate only `connect_property_events_notify`, without `get_property_events` and `set_property_events`
254 # supported values: "get", "set", "notify"
255 generate = ["notify"]
256 ```
257
258 Since there are no child properties in `.gir` files, it needs to be added for classes manually:
259
260 ```toml
261 [[object]]
262 name = "Gtk.SomeClassWithChildProperties"
263 status = "generate"
264 # replace parameter name for child in child properties (instead of "child")
265 child_name = "item"
266 # define concrete child type (instead of "Widget")
267 child_type = "Gtk.MenuItem"
268 [[object.child_prop]]
269 name = "position"
270 type = "gint"
271 doc_hidden = true
272 ```
273
274 For enumerations and bitflags, you can configure the members and mark the type
275 as `#[must_use]`:
276
277 ```toml
278 [[object]]
279 name = "Gdk.EventType"
280 status = "generate"
281 # generates #[must_use] attribute for the type
282 must_use = true
283 # override starting version
284 version = "3.12"
285 [[object.member]]
286 name = "2button_press"
287 # allows to skip elements with bad names, other members with same value used instead
288 ignore = true
289 # Allow to add a cfg condition
290 cfg_condition = "target_os = \"linux\""
291 # In case you don't want to generate the documentation for this member.
292 generate_doc = false
293 [[object.member]]
294 name = "touchpad_pinch"
295 # define starting version when member added
296 version = "3.18"
297 ```
298
299 For enumerations, bitflags and boxed types / records, you can configure
300 the `#[derive()]` clauses, optionally conditioned to a `cfg`.
301
302 Providing `#[derive()]` clauses behaves differently depending on the type
303 they are added to:
304
305 * for boxed types / records (except `inline_boxed` types), the provided
306 `#[derive()]` clauses replace all the derives that are normally added
307 by default (i.e. `#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]`);
308 if the default derives are needed, they must be explicitly listed.
309 * for `inline_boxed` types, only the `Debug` trait can be specified (and thus
310 added); providing any other trait will cause gir to fail with an error.
311 * for enumerations, the provided `#[derive()]` clauses replace all the ones
312 that are normally derived by default (i.e. `#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]`)
313 with the exception of `Copy` and `Clone` that are always derived;
314 if the default derives are needed, they must be explicitly listed.
315 * for bitflags, the provided `#[derive()]` clauses are simply added to
316 the derives implemented by default.
317
318 ```toml
319 [[object]]
320 name = "Gst.Format"
321 status = "generate"
322 [[object.derive]]
323 name = "Serialize, Deserialize"
324 cfg_condition = "feature = \"serde\""
325 ```
326
327 For global functions, the members can be configured by configuring the `Gtk.*` object:
328
329 ```toml
330 [[object]]
331 name = "Gtk.*"
332 status = "generate"
333 [[object.function]]
334 name = "stock_list_ids"
335 # allows to ignore global functions
336 ignore = true
337 # allows to define if the function was moved to a trait
338 doc_trait_name = "StockExt"
339 # allows to define if the function was moved to a struct
340 doc_struct_name = "Stock"
341 # In case you don't want to generate the documentation for this function.
342 generate_doc = false
343 ```
344
345 Which will prevent gir from generating `stock_list_ids`.
346 If you want to specify
347 that a function will be manually implemented, you can use:
348
349 ```toml
350 [[object]]
351 name = "Gtk.Entry"
352 status = "generate"
353 [[object.function]]
354 name = "get_invisible_char"
355 manual = true
356 ```
357
358 This will prevent gir from generating `get_invisible_char` and it won't generate
359 `get_property_invisible_char` which would have been generated if we had used
360 "ignore = true".
361
362 Note that you must not place `Gtk.*` into the `generate` array and
363 additionally configure its members.
364
365 You can control the generation of constants in a similar fashion:
366
367 ```toml
368 [[object]]
369 name = "Gtk.*"
370 status = "generate"
371 [[object.constant]]
372 pattern = "*"
373 # No constants will be generated
374 ignore = true
375 # In case you don't want to generate the documentation for this constant.
376 generate_doc = false
377 ```
378
379 Constants also support `version` and `cfg_condition` fields.
380
381 In various cases, GObjects or boxed types can be used from multiple threads
382 and have certain concurrency guarantees.
383 This can be configured with the
384 `concurrency` setting at the top-level options or per object.
385 It will
386 automatically implement the `Send` and `Sync` traits for the resulting object
387 and set appropriate trait bounds for signal callbacks.
388 The default is `none`,
389 and apart from that `send` and `send+sync` are supported.
390
391 ```toml
392 [[object]]
393 # object's fullname
394 name = "Gtk.SomeClass"
395 # can be also "manual" and "ignore" but it's simpler to just put the object in the same array
396 status = "generate"
397 # concurrency of the object, default is set in the top-level options or
398 # otherwise "none". Valid values are "none", "send" and "send+sync"
399 concurrency = "send+sync"
400 ```
401
402 Note that `send` is only valid for types that are either not reference counted
403 (i.e. `clone()` copies the object) or that are read-only (i.e. no API for
404 mutating the object exists).
405 `send+sync` is valid if the type can be sent to
406 different threads and all API allows simultaneous calls from different threads
407 due to internal locking via e.g. a mutex.
408
409 ```toml
410 [[object]]
411 name = "Gtk.Something"
412 status = "manual"
413 # Can also be "ref-mut", "ref-immut"
414 ref_mode = "ref"
415 ```
416
417 When manually generating bindings, it can happen that the reference mode
418 detected by GIR is different than what was implemented and conversion to the C
419 types are wrong in autogenerated functions that have such objects as argument.
420 This can be overridden with the `ref_mode` configuration.
421
422 Getters are automatically renamed to comply with Rust codying style guidelines.
423 However, this can cause name clashes with existing functions.
424 If you want to
425 bypass the automatic renaming mechanism, use `bypass_auto_rename = true`:
426
427 ```toml
428 [[object]]
429 name = "Gtk.TextBuffer"
430 [...]
431 [[object.function]]
432 name = "get_insert"
433 # Avoid clash with the `insert` operation.
434 bypass_auto_rename = true
435 ```
436
437 Some constructors are not annotated as `constructor` in the `gir` files.
438 In
439 order for the naming convention to be applied, you can force a function to be
440 considered as a constructor:
441
442 ```toml
443 [[object.function]]
444 name = "new_for_path"
445 # Not annotated as constructor in Gir => force it to apply naming convention
446 constructor = true
447 ```
448
449 ## conversion_type "Option"
450
451 The `conversion_type` variant `Option` is available for types `T` implementing
452 `glib::TryFromGlib<Error=GlibNoneError>`.
453 As a reminder, this allows
454 implementing `FromGlib` for `Option<T>` and usually goes alongside with `ToGlib`
455 for both `T` and `Option<T>`.
456 In this case, `Option<T>` will be used for return
457 values (including ffi output arguments).
458 For in-arguments, except if the
459 parameter is declared `mandatory`, `impl Into<Option<T>>` so that either an
460 `Option<T>` or `T` can be used.
461
462 Ex. from `gstreamer-rs`:
463
464 ``` rust
465 [[object]]
466 name = "Gst.ClockTime"
467 status = "manual"
468 conversion_type = "Option"
469 ```
470
471 The type `ClockTime` implements `glib::TryFromGlib<Error=GlibNoneError>` (and
472 `OptionToGlib`), which means that its Rust representation can take advantage of
473 `Option<ClockTime>`.
474
475 Additionally, the user can instruct `gir` to `expect` `Some` or `Ok` results for
476 specific arguments or return values.
477 E.g.:
478
479 ``` rust
480 [[object]]
481 name = "Gst.Clock"
482 status = "generate"
483 manual_traits = ["ClockExtManual"]
484 [[object.function]]
485 name = "get_calibration"
486 [[object.function.parameter]]
487 name = "internal"
488 mandatory = true
489 ```
490
491 In the above example, the user instructs gir to consider the `internal` argument (which also happens to be an out argument) with type gir `Gst.ClockTime` can be represented as a `ClockTime` without the `Option`.
492 This argument is actually part of a set of output arguments.
493 With the above gir declaration, the generated signature is the following (the implementation takes care of `expect`ing the value to be defined):
494
495 ``` rust
496 fn get_calibration(
497 &self,
498 ) -> (
499 ClockTime,
500 Option<ClockTime>,
501 Option<ClockTime>,
502 Option<ClockTime>,
503 );
504 ```
505
506 For a return value, the mandatory declaration reads:
507
508 ``` rust
509 [[object.function]]
510 name = "util_get_timestamp"
511 /.../
512 [object.function.return]
513 # always returns a value
514 mandatory = true
515 ```
516
517 ## conversion_type "Result"
518
519 The `conversion_type` variant `Result` is available for types `T` implementing
520 `glib::TryFromGlib<Error=Err>` where `Err` is neither `GlibNoneError` nor
521 `GlibNoneOrInvalidError`.
522 In this case, `Result<T, ErrorType>` will be used for
523 return values (including `ffi` output arguments) and the type itself in argument
524 position.
525
526 In `gstreamer-rs`, the C type `GstStateChangeReturn` can represent both a
527 successful or an error return value.
528 In Rust, the `Result` `enum` is the idiomatic way of returning an error.
529 In `gstreamer-rs`, bindings to functions
530 returning `GstStateChangeReturn` had to be manually implemented so as to return `Result<StateChangeSuccess, StateChangeError>`.
531 Note that in this case, the type implementing `TryFromGlib` is `StateChangeSuccess` and not
532 `GstStateChangeReturn`.
533 These functions can be auto-generated using:
534
535 ``` rust
536 [[object]]
537 name = "Gst.StateChangeReturn"
538 status = "generate"
539 must_use = true
540 [object.conversion_type]
541 variant = "Result"
542 ok_type = "gst::StateChangeSuccess"
543 err_type = "gst::StateChangeError"
544 ```
545
546 ## Boxed types vs. BoxedInline types
547
548 For boxed types / records, gir auto-detects `copy`/`free` or `ref`/`unref`
549 function pairs for memory management on records.
550 It falls back to generic `g_boxed_copy`/`g_boxed_free` if these are not found, based on an existing implementation of `get_type`.
551 Otherwise no record implementation can be generated.
552
553 This works for the majority of boxed types, which are literally boxed: their
554 memory is always allocated on the heap and memory management is left to the C library.
555 Some boxed types, however, are special and in C code they are usually allocated on the stack or inline inside another struct.
556 As such, their struct definition is public and part of the API/ABI.
557 Usually these types are relatively small and allocated regularly, which would make heap allocations costly.
558
559 These special boxed types are usually allocated by the caller of the C
560 functions, and the functions are then only filling in the memory and taking
561 values of this type as `(out caller-allocates)` parameters.
562
563 In most other bindings, heap allocations are used for these boxed types too
564 but in Rust we can do better and actually allocate them on the stack or inline
565 inside another struct.
566
567 Gir calls these special boxed types "boxed inline".
568
569 ```toml
570 [[object]]
571 name = "GLib.TreeIter"
572 status = "generate"
573 boxed_inline = true
574 ```
575
576 For inline-allocated boxed types it is possible to provide Rust expressions in
577 the configuration for initializing newly allocated memory for them, to copy
578 from one value into another one, and to free any resources that might be
579 stored in values of that boxed types.
580
581 By default the memory is zero-initialized and copying is done via
582 `std::ptr::copy()`.
583 If the boxed type contains memory that needs to be freed
584 then these functions must be provided.
585
586 The following configuration is equivalent with the one above.
587
588 ```toml
589 [[object]]
590 name = "GLib.TreeIter"
591 status = "generate"
592 boxed_inline = true
593 init_function_expression = "|_ptr| ()"
594 copy_into_function_expression = "|dest, src| { std::ptr::copy_nonoverlapping(src, dest, 1); }"
595 clear_function_expression = "|_ptr| ()"
596 ```
597
598 ## Generation in API mode
599
600 To generate the Rust-user API level, The command is very similar to the previous one.
601 It's better to not put this output in the same directory as where the FFI files are.
602 Just run:
603
604 ```sh
605 cargo run --release -- -c YourGirFile.toml -d ../gir-files -o the-output-directory
606 ```
607
608 Now it should be done.
609 Just go to the output directory (so `the-output-directory/auto` in our case) and try to build using `cargo build`.
610 Don't forget to update your dependencies in both projects: nothing much to do in the FFI/sys one but the Rust-user API level will need to have a dependency over the FFI/sys one.
611
612 Now, at your crate entry point (generally `lib.rs`), add the following to include all generated files:
613
614 ```rust
615 pub use auto::*;
616 ```
617
618 ## Add manual bindings alongside generated code
619
620 Unfortunately, `gir` isn't perfect (yet) and will certainly not be able to generate all the code on its own.
621 So here's what a `gir` generated folder looks like:
622
623 ```text
624 - your_folder
625 |
626 |- Cargo.toml
627 |- src
628 |
629 |- lib.rs
630 |- auto
631 |
632 |- (all files generated by gir)
633 ```
634
635 You can add your manual bindings directly inside the `src` folder (at the same level as `lib.rs`).
636 Then don't forget to reexport them.
637 Let's say you added a `Color` type in a `color.rs` file.
638 You need to add in `lib.rs`:
639
640 ```rust
641 // We make the type public for the API users.
642 pub use color::Color;
643
644 mod color;
645 ```