Add `#[inline]` to all builder-pattern functions (#3557)

Better performance and maybe code size
This commit is contained in:
Emil Ernerfeldt 2023-11-16 13:50:05 +01:00 committed by GitHub
parent 4886c8c8c0
commit a243180600
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 398 additions and 35 deletions

View File

@ -90,6 +90,7 @@ impl Area {
}
}
#[inline]
pub fn id(mut self, id: Id) -> Self {
self.id = id;
self
@ -103,12 +104,14 @@ impl Area {
/// and widgets will be shown grayed out.
/// You won't be able to move the window.
/// Default: `true`.
#[inline]
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// moveable by dragging the area?
#[inline]
pub fn movable(mut self, movable: bool) -> Self {
self.movable = movable;
self.interactable |= movable;
@ -125,6 +128,7 @@ impl Area {
/// If false, clicks goes straight through to what is behind us.
/// Good for tooltips etc.
#[inline]
pub fn interactable(mut self, interactable: bool) -> Self {
self.interactable = interactable;
self.movable &= interactable;
@ -132,17 +136,20 @@ impl Area {
}
/// `order(Order::Foreground)` for an Area that should always be on top
#[inline]
pub fn order(mut self, order: Order) -> Self {
self.order = order;
self
}
#[inline]
pub fn default_pos(mut self, default_pos: impl Into<Pos2>) -> Self {
self.default_pos = Some(default_pos.into());
self
}
/// Positions the window and prevents it from being moved
#[inline]
pub fn fixed_pos(mut self, fixed_pos: impl Into<Pos2>) -> Self {
self.new_pos = Some(fixed_pos.into());
self.movable = false;
@ -150,6 +157,7 @@ impl Area {
}
/// Constrains this area to the screen bounds.
#[inline]
pub fn constrain(mut self, constrain: bool) -> Self {
self.constrain = constrain;
self
@ -158,6 +166,7 @@ impl Area {
/// Constrain the movement of the window to the given rectangle.
///
/// For instance: `.constrain_to(ctx.screen_rect())`.
#[inline]
pub fn constrain_to(mut self, constrain_rect: Rect) -> Self {
self.constrain = true;
self.constrain_rect = Some(constrain_rect);
@ -165,6 +174,7 @@ impl Area {
}
#[deprecated = "Use `constrain_to` instead"]
#[inline]
pub fn drag_bounds(mut self, constrain_rect: Rect) -> Self {
self.constrain_rect = Some(constrain_rect);
self
@ -177,12 +187,14 @@ impl Area {
/// corner of the area.
///
/// Default: [`Align2::LEFT_TOP`].
#[inline]
pub fn pivot(mut self, pivot: Align2) -> Self {
self.pivot = pivot;
self
}
/// Positions the window but you can still move it.
#[inline]
pub fn current_pos(mut self, current_pos: impl Into<Pos2>) -> Self {
self.new_pos = Some(current_pos.into());
self
@ -199,6 +211,7 @@ impl Area {
/// Anchoring also makes the window immovable.
///
/// It is an error to set both an anchor and a position.
#[inline]
pub fn anchor(mut self, align: Align2, offset: impl Into<Vec2>) -> Self {
self.anchor = Some((align, offset.into()));
self.movable(false)

View File

@ -390,6 +390,7 @@ impl CollapsingHeader {
/// By default, the [`CollapsingHeader`] is collapsed.
/// Call `.default_open(true)` to change this.
#[inline]
pub fn default_open(mut self, open: bool) -> Self {
self.default_open = open;
self
@ -400,6 +401,7 @@ impl CollapsingHeader {
/// Calling `.open(Some(false))` will make the collapsing header close this frame (or stay closed).
///
/// Calling `.open(None)` has no effect (default).
#[inline]
pub fn open(mut self, open: Option<bool>) -> Self {
self.open = open;
self
@ -407,6 +409,7 @@ impl CollapsingHeader {
/// Explicitly set the source of the [`Id`] of this widget, instead of using title label.
/// This is useful if the title label is dynamic or not unique.
#[inline]
pub fn id_source(mut self, id_source: impl Hash) -> Self {
self.id_source = Id::new(id_source);
self
@ -415,6 +418,7 @@ impl CollapsingHeader {
/// If you set this to `false`, the [`CollapsingHeader`] will be grayed out and un-clickable.
///
/// This is a convenience for [`Ui::set_enabled`].
#[inline]
pub fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
@ -422,6 +426,7 @@ impl CollapsingHeader {
/// Can the [`CollapsingHeader`] be selected by clicking it? Default: `false`.
#[deprecated = "Use the more powerful egui::collapsing_header::CollapsingState::show_header"] // Deprecated in 2022-04-28, before egui 0.18
#[inline]
pub fn selectable(mut self, selectable: bool) -> Self {
self.selectable = selectable;
self
@ -443,6 +448,7 @@ impl CollapsingHeader {
/// # });
/// ```
#[deprecated = "Use the more powerful egui::collapsing_header::CollapsingState::show_header"] // Deprecated in 2022-04-28, before egui 0.18
#[inline]
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
@ -456,6 +462,7 @@ impl CollapsingHeader {
/// ui.visuals_mut().collapsing_header_frame = true;
/// # });
/// ```
#[inline]
pub fn show_background(mut self, show_background: bool) -> Self {
self.show_background = show_background;
self
@ -478,6 +485,7 @@ impl CollapsingHeader {
/// .show(ui, |ui| { ui.label("Hi!"); });
/// # });
/// ```
#[inline]
pub fn icon(mut self, icon_fn: impl FnOnce(&mut Ui, f32, &Response) + 'static) -> Self {
self.icon = Some(Box::new(icon_fn));
self

View File

@ -78,12 +78,14 @@ impl ComboBox {
}
/// Set the outer width of the button and menu.
#[inline]
pub fn width(mut self, width: f32) -> Self {
self.width = Some(width);
self
}
/// What we show as the currently selected value
#[inline]
pub fn selected_text(mut self, selected_text: impl Into<WidgetText>) -> Self {
self.selected_text = selected_text.into();
self
@ -129,6 +131,7 @@ impl ComboBox {
}
/// Controls whether text wrap is used for the selected text
#[inline]
pub fn wrap(mut self, wrap: bool) -> Self {
self.wrap_enabled = wrap;
self

View File

@ -164,6 +164,7 @@ impl Frame {
self
}
#[inline]
pub fn multiply_with_opacity(mut self, opacity: f32) -> Self {
self.fill = self.fill.linear_multiply(opacity);
self.stroke.color = self.stroke.color.linear_multiply(opacity);

View File

@ -135,6 +135,7 @@ impl SidePanel {
/// * A [`Separator`].
/// * A [`TextEdit`].
/// * …
#[inline]
pub fn resizable(mut self, resizable: bool) -> Self {
self.resizable = resizable;
self
@ -143,12 +144,14 @@ impl SidePanel {
/// Show a separator line, even when not interacting with it?
///
/// Default: `true`.
#[inline]
pub fn show_separator_line(mut self, show_separator_line: bool) -> Self {
self.show_separator_line = show_separator_line;
self
}
/// The initial wrapping width of the [`SidePanel`].
#[inline]
pub fn default_width(mut self, default_width: f32) -> Self {
self.default_width = default_width;
self.width_range = Rangef::new(
@ -159,18 +162,21 @@ impl SidePanel {
}
/// Minimum width of the panel.
#[inline]
pub fn min_width(mut self, min_width: f32) -> Self {
self.width_range = Rangef::new(min_width, self.width_range.max.at_least(min_width));
self
}
/// Maximum width of the panel.
#[inline]
pub fn max_width(mut self, max_width: f32) -> Self {
self.width_range = Rangef::new(self.width_range.min.at_most(max_width), max_width);
self
}
/// The allowable width range for the panel.
#[inline]
pub fn width_range(mut self, width_range: impl Into<Rangef>) -> Self {
let width_range = width_range.into();
self.default_width = clamp_to_range(self.default_width, width_range);
@ -179,6 +185,7 @@ impl SidePanel {
}
/// Enforce this exact width.
#[inline]
pub fn exact_width(mut self, width: f32) -> Self {
self.default_width = width;
self.width_range = Rangef::point(width);
@ -186,6 +193,7 @@ impl SidePanel {
}
/// Change the background color, margins, etc.
#[inline]
pub fn frame(mut self, frame: Frame) -> Self {
self.frame = Some(frame);
self
@ -582,6 +590,7 @@ impl TopBottomPanel {
/// * A [`Separator`].
/// * A [`TextEdit`].
/// * …
#[inline]
pub fn resizable(mut self, resizable: bool) -> Self {
self.resizable = resizable;
self
@ -590,6 +599,7 @@ impl TopBottomPanel {
/// Show a separator line, even when not interacting with it?
///
/// Default: `true`.
#[inline]
pub fn show_separator_line(mut self, show_separator_line: bool) -> Self {
self.show_separator_line = show_separator_line;
self
@ -597,6 +607,7 @@ impl TopBottomPanel {
/// The initial height of the [`SidePanel`].
/// Defaults to [`style::Spacing::interact_size`].y.
#[inline]
pub fn default_height(mut self, default_height: f32) -> Self {
self.default_height = Some(default_height);
self.height_range = Rangef::new(
@ -607,18 +618,21 @@ impl TopBottomPanel {
}
/// Minimum height of the panel.
#[inline]
pub fn min_height(mut self, min_height: f32) -> Self {
self.height_range = Rangef::new(min_height, self.height_range.max.at_least(min_height));
self
}
/// Maximum height of the panel.
#[inline]
pub fn max_height(mut self, max_height: f32) -> Self {
self.height_range = Rangef::new(self.height_range.min.at_most(max_height), max_height);
self
}
/// The allowable height range for the panel.
#[inline]
pub fn height_range(mut self, height_range: impl Into<Rangef>) -> Self {
let height_range = height_range.into();
self.default_height = self
@ -629,6 +643,7 @@ impl TopBottomPanel {
}
/// Enforce this exact height.
#[inline]
pub fn exact_height(mut self, height: f32) -> Self {
self.default_height = Some(height);
self.height_range = Rangef::point(height);
@ -636,6 +651,7 @@ impl TopBottomPanel {
}
/// Change the background color, margins, etc.
#[inline]
pub fn frame(mut self, frame: Frame) -> Self {
self.frame = Some(frame);
self
@ -994,6 +1010,7 @@ pub struct CentralPanel {
impl CentralPanel {
/// Change the background color, margins, etc.
#[inline]
pub fn frame(mut self, frame: Frame) -> Self {
self.frame = Some(frame);
self

View File

@ -60,12 +60,14 @@ impl Default for Resize {
impl Resize {
/// Assign an explicit and globally unique id.
#[inline]
pub fn id(mut self, id: Id) -> Self {
self.id = Some(id);
self
}
/// A source for the unique [`Id`], e.g. `.id_source("second_resize_area")` or `.id_source(loop_index)`.
#[inline]
pub fn id_source(mut self, id_source: impl std::hash::Hash) -> Self {
self.id_source = Some(Id::new(id_source));
self
@ -77,6 +79,7 @@ impl Resize {
/// * if the contents is text, this will decide where we break long lines.
/// * if the contents is a canvas, this decides the width of it,
/// * if the contents is some buttons, this is ignored and we will auto-size.
#[inline]
pub fn default_width(mut self, width: f32) -> Self {
self.default_size.x = width;
self
@ -89,47 +92,55 @@ impl Resize {
/// * if the contents is a canvas, this decides the height of it,
/// * if the contents is text and buttons, then the `default_height` is ignored
/// and the height is picked automatically..
#[inline]
pub fn default_height(mut self, height: f32) -> Self {
self.default_size.y = height;
self
}
#[inline]
pub fn default_size(mut self, default_size: impl Into<Vec2>) -> Self {
self.default_size = default_size.into();
self
}
/// Won't shrink to smaller than this
#[inline]
pub fn min_size(mut self, min_size: impl Into<Vec2>) -> Self {
self.min_size = min_size.into();
self
}
/// Won't shrink to smaller than this
#[inline]
pub fn min_width(mut self, min_width: f32) -> Self {
self.min_size.x = min_width;
self
}
/// Won't shrink to smaller than this
#[inline]
pub fn min_height(mut self, min_height: f32) -> Self {
self.min_size.y = min_height;
self
}
/// Won't expand to larger than this
#[inline]
pub fn max_size(mut self, max_size: impl Into<Vec2>) -> Self {
self.max_size = max_size.into();
self
}
/// Won't expand to larger than this
#[inline]
pub fn max_width(mut self, max_width: f32) -> Self {
self.max_size.x = max_width;
self
}
/// Won't expand to larger than this
#[inline]
pub fn max_height(mut self, max_height: f32) -> Self {
self.max_size.y = max_height;
self
@ -140,6 +151,7 @@ impl Resize {
/// Note that a window can still auto-resize.
///
/// Default is `true`.
#[inline]
pub fn resizable(mut self, resizable: bool) -> Self {
self.resizable = resizable;
self
@ -157,6 +169,7 @@ impl Resize {
.resizable(false)
}
#[inline]
pub fn fixed_size(mut self, size: impl Into<Vec2>) -> Self {
let size = size.into();
self.default_size = size;
@ -166,6 +179,7 @@ impl Resize {
self
}
#[inline]
pub fn with_stroke(mut self, with_stroke: bool) -> Self {
self.with_stroke = with_stroke;
self

View File

@ -64,6 +64,7 @@ impl<'open> Window<'open> {
}
/// Assign a unique id to the Window. Required if the title changes, or is shared with another window.
#[inline]
pub fn id(mut self, id: Id) -> Self {
self.area = self.area.id(id);
self
@ -74,24 +75,28 @@ impl<'open> Window<'open> {
/// * If `*open == false`, the window will not be visible.
/// * If `*open == true`, the window will have a close button.
/// * If the close button is pressed, `*open` will be set to `false`.
#[inline]
pub fn open(mut self, open: &'open mut bool) -> Self {
self.open = Some(open);
self
}
/// If `false` the window will be grayed out and non-interactive.
#[inline]
pub fn enabled(mut self, enabled: bool) -> Self {
self.area = self.area.enabled(enabled);
self
}
/// If `false` the window will be non-interactive.
#[inline]
pub fn interactable(mut self, interactable: bool) -> Self {
self.area = self.area.interactable(interactable);
self
}
/// If `false` the window will be immovable.
#[inline]
pub fn movable(mut self, movable: bool) -> Self {
self.area = self.area.movable(movable);
self
@ -99,6 +104,7 @@ impl<'open> Window<'open> {
/// Usage: `Window::new(…).mutate(|w| w.resize = w.resize.auto_expand_width(true))`
// TODO(emilk): I'm not sure this is a good interface for this.
#[inline]
pub fn mutate(mut self, mutate: impl Fn(&mut Self)) -> Self {
mutate(&mut self);
self
@ -106,48 +112,56 @@ impl<'open> Window<'open> {
/// Usage: `Window::new(…).resize(|r| r.auto_expand_width(true))`
// TODO(emilk): I'm not sure this is a good interface for this.
#[inline]
pub fn resize(mut self, mutate: impl Fn(Resize) -> Resize) -> Self {
self.resize = mutate(self.resize);
self
}
/// Change the background color, margins, etc.
#[inline]
pub fn frame(mut self, frame: Frame) -> Self {
self.frame = Some(frame);
self
}
/// Set minimum width of the window.
#[inline]
pub fn min_width(mut self, min_width: f32) -> Self {
self.resize = self.resize.min_width(min_width);
self
}
/// Set minimum height of the window.
#[inline]
pub fn min_height(mut self, min_height: f32) -> Self {
self.resize = self.resize.min_height(min_height);
self
}
/// Set minimum size of the window, equivalent to calling both `min_width` and `min_height`.
#[inline]
pub fn min_size(mut self, min_size: impl Into<Vec2>) -> Self {
self.resize = self.resize.min_size(min_size);
self
}
/// Set maximum width of the window.
#[inline]
pub fn max_width(mut self, max_width: f32) -> Self {
self.resize = self.resize.max_width(max_width);
self
}
/// Set maximum height of the window.
#[inline]
pub fn max_height(mut self, max_height: f32) -> Self {
self.resize = self.resize.max_height(max_height);
self
}
/// Set maximum size of the window, equivalent to calling both `max_width` and `max_height`.
#[inline]
pub fn max_size(mut self, max_size: impl Into<Vec2>) -> Self {
self.resize = self.resize.max_size(max_size);
self
@ -155,18 +169,21 @@ impl<'open> Window<'open> {
/// Set current position of the window.
/// If the window is movable it is up to you to keep track of where it moved to!
#[inline]
pub fn current_pos(mut self, current_pos: impl Into<Pos2>) -> Self {
self.area = self.area.current_pos(current_pos);
self
}
/// Set initial position of the window.
#[inline]
pub fn default_pos(mut self, default_pos: impl Into<Pos2>) -> Self {
self.area = self.area.default_pos(default_pos);
self
}
/// Sets the window position and prevents it from being dragged around.
#[inline]
pub fn fixed_pos(mut self, pos: impl Into<Pos2>) -> Self {
self.area = self.area.fixed_pos(pos);
self
@ -177,6 +194,7 @@ impl<'open> Window<'open> {
/// To change the area to constrain to, use [`Self::constrain_to`].
///
/// Default: `true`.
#[inline]
pub fn constrain(mut self, constrain: bool) -> Self {
self.area = self.area.constrain(constrain);
self
@ -185,12 +203,14 @@ impl<'open> Window<'open> {
/// Constrain the movement of the window to the given rectangle.
///
/// For instance: `.constrain_to(ctx.screen_rect())`.
#[inline]
pub fn constrain_to(mut self, constrain_rect: Rect) -> Self {
self.area = self.area.constrain_to(constrain_rect);
self
}
#[deprecated = "Use `constrain_to` instead"]
#[inline]
pub fn drag_bounds(mut self, constrain_rect: Rect) -> Self {
#![allow(deprecated)]
@ -205,6 +225,7 @@ impl<'open> Window<'open> {
/// corner of the window.
///
/// Default: [`Align2::LEFT_TOP`].
#[inline]
pub fn pivot(mut self, pivot: Align2) -> Self {
self.area = self.area.pivot(pivot);
self
@ -221,36 +242,42 @@ impl<'open> Window<'open> {
/// Anchoring also makes the window immovable.
///
/// It is an error to set both an anchor and a position.
#[inline]
pub fn anchor(mut self, align: Align2, offset: impl Into<Vec2>) -> Self {
self.area = self.area.anchor(align, offset);
self
}
/// Set initial collapsed state of the window
#[inline]
pub fn default_open(mut self, default_open: bool) -> Self {
self.default_open = default_open;
self
}
/// Set initial size of the window.
#[inline]
pub fn default_size(mut self, default_size: impl Into<Vec2>) -> Self {
self.resize = self.resize.default_size(default_size);
self
}
/// Set initial width of the window.
#[inline]
pub fn default_width(mut self, default_width: f32) -> Self {
self.resize = self.resize.default_width(default_width);
self
}
/// Set initial height of the window.
#[inline]
pub fn default_height(mut self, default_height: f32) -> Self {
self.resize = self.resize.default_height(default_height);
self
}
/// Sets the window size and prevents it from being resized by dragging its edges.
#[inline]
pub fn fixed_size(mut self, size: impl Into<Vec2>) -> Self {
self.resize = self.resize.fixed_size(size);
self
@ -271,12 +298,14 @@ impl<'open> Window<'open> {
/// Note that even if you set this to `false` the window may still auto-resize.
///
/// Default is `true`.
#[inline]
pub fn resizable(mut self, resizable: bool) -> Self {
self.resize = self.resize.resizable(resizable);
self
}
/// Can the window be collapsed by clicking on its title?
#[inline]
pub fn collapsible(mut self, collapsible: bool) -> Self {
self.collapsible = collapsible;
self
@ -284,6 +313,7 @@ impl<'open> Window<'open> {
/// Show title bar on top of the window?
/// If `false`, the window will not be collapsible nor have a close-button.
#[inline]
pub fn title_bar(mut self, title_bar: bool) -> Self {
self.with_title_bar = title_bar;
self
@ -292,6 +322,7 @@ impl<'open> Window<'open> {
/// Not resizable, just takes the size of its contents.
/// Also disabled scrolling.
/// Text will not wrap, but will instead make your window width expand.
#[inline]
pub fn auto_sized(mut self) -> Self {
self.resize = self.resize.auto_sized();
self.scroll = ScrollArea::neither();
@ -299,18 +330,21 @@ impl<'open> Window<'open> {
}
/// Enable/disable horizontal/vertical scrolling. `false` by default.
#[inline]
pub fn scroll2(mut self, scroll: impl Into<Vec2b>) -> Self {
self.scroll = self.scroll.scroll2(scroll);
self
}
/// Enable/disable horizontal scrolling. `false` by default.
#[inline]
pub fn hscroll(mut self, hscroll: bool) -> Self {
self.scroll = self.scroll.hscroll(hscroll);
self
}
/// Enable/disable vertical scrolling. `false` by default.
#[inline]
pub fn vscroll(mut self, vscroll: bool) -> Self {
self.scroll = self.scroll.vscroll(vscroll);
self
@ -319,6 +353,7 @@ impl<'open> Window<'open> {
/// Enable/disable scrolling on the window by dragging with the pointer. `true` by default.
///
/// See [`ScrollArea::drag_to_scroll`] for more.
#[inline]
pub fn drag_to_scroll(mut self, drag_to_scroll: bool) -> Self {
self.scroll = self.scroll.drag_to_scroll(drag_to_scroll);
self

View File

@ -319,6 +319,7 @@ impl Grid {
}
/// Setting this will allow for dynamic coloring of rows of the grid object
#[inline]
pub fn with_row_color<F>(mut self, color_picker: F) -> Self
where
F: Send + Sync + Fn(usize, &Style) -> Option<Color32> + 'static,
@ -328,6 +329,7 @@ impl Grid {
}
/// Setting this will allow the last column to expand to take up the rest of the space of the parent [`Ui`].
#[inline]
pub fn num_columns(mut self, num_columns: usize) -> Self {
self.num_columns = Some(num_columns);
self
@ -352,6 +354,7 @@ impl Grid {
/// Set minimum width of each column.
/// Default: [`crate::style::Spacing::interact_size`]`.x`.
#[inline]
pub fn min_col_width(mut self, min_col_width: f32) -> Self {
self.min_col_width = Some(min_col_width);
self
@ -359,12 +362,14 @@ impl Grid {
/// Set minimum height of each row.
/// Default: [`crate::style::Spacing::interact_size`]`.y`.
#[inline]
pub fn min_row_height(mut self, min_row_height: f32) -> Self {
self.min_row_height = Some(min_row_height);
self
}
/// Set soft maximum width (wrapping width) of each column.
#[inline]
pub fn max_col_width(mut self, max_col_width: f32) -> Self {
self.max_cell_size.x = max_col_width;
self
@ -372,6 +377,7 @@ impl Grid {
/// Set spacing between columns/rows.
/// Default: [`crate::style::Spacing::item_spacing`].
#[inline]
pub fn spacing(mut self, spacing: impl Into<Vec2>) -> Self {
self.spacing = Some(spacing.into());
self
@ -379,6 +385,7 @@ impl Grid {
/// Change which row number the grid starts on.
/// This can be useful when you have a large [`Grid`] inside of [`ScrollArea::show_rows`].
#[inline]
pub fn start_row(mut self, start_row: usize) -> Self {
self.start_row = start_row;
self

View File

@ -453,6 +453,7 @@ impl SubMenuButton {
}
}
#[inline]
pub fn icon(mut self, icon: impl Into<WidgetText>) -> Self {
self.icon = icon.into();
self

View File

@ -482,6 +482,7 @@ impl Response {
/// The highlight takes one frame to take effect if you call this after the widget has been fully rendered.
///
/// See also [`Context::highlight_widget`].
#[inline]
pub fn highlight(mut self) -> Self {
self.ctx.highlight_widget(self.id);
self.highlighted = true;

View File

@ -85,6 +85,7 @@ impl<'a> Button<'a> {
/// Override background fill color. Note that this will override any on-hover effects.
/// Calling this will also turn on the frame.
#[inline]
pub fn fill(mut self, fill: impl Into<Color32>) -> Self {
self.fill = Some(fill.into());
self.frame = Some(true);
@ -93,6 +94,7 @@ impl<'a> Button<'a> {
/// Override button stroke. Note that this will override any on-hover effects.
/// Calling this will also turn on the frame.
#[inline]
pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self {
self.stroke = Some(stroke.into());
self.frame = Some(true);
@ -100,6 +102,7 @@ impl<'a> Button<'a> {
}
/// Make this a small button, suitable for embedding into text.
#[inline]
pub fn small(mut self) -> Self {
if let Some(text) = self.text {
self.text = Some(text.text_style(TextStyle::Body));
@ -109,6 +112,7 @@ impl<'a> Button<'a> {
}
/// Turn off the frame
#[inline]
pub fn frame(mut self, frame: bool) -> Self {
self.frame = Some(frame);
self
@ -116,18 +120,21 @@ impl<'a> Button<'a> {
/// By default, buttons senses clicks.
/// Change this to a drag-button with `Sense::drag()`.
#[inline]
pub fn sense(mut self, sense: Sense) -> Self {
self.sense = sense;
self
}
/// Set the minimum size of the button.
#[inline]
pub fn min_size(mut self, min_size: Vec2) -> Self {
self.min_size = min_size;
self
}
/// Set the rounding of the button.
#[inline]
pub fn rounding(mut self, rounding: impl Into<Rounding>) -> Self {
self.rounding = Some(rounding.into());
self
@ -138,12 +145,14 @@ impl<'a> Button<'a> {
/// Designed for menu buttons, for setting a keyboard shortcut text (e.g. `Ctrl+S`).
///
/// The text can be created with [`Context::format_shortcut`].
#[inline]
pub fn shortcut_text(mut self, shortcut_text: impl Into<WidgetText>) -> Self {
self.shortcut_text = shortcut_text.into();
self
}
/// If `true`, mark this button as "selected".
#[inline]
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
@ -565,24 +574,28 @@ impl<'a> ImageButton<'a> {
}
/// Select UV range. Default is (0,0) in top-left, (1,1) bottom right.
#[inline]
pub fn uv(mut self, uv: impl Into<Rect>) -> Self {
self.image = self.image.uv(uv);
self
}
/// Multiply image color with this. Default is WHITE (no tint).
#[inline]
pub fn tint(mut self, tint: impl Into<Color32>) -> Self {
self.image = self.image.tint(tint);
self
}
/// If `true`, mark this button as "selected".
#[inline]
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
/// Turn off the frame
#[inline]
pub fn frame(mut self, frame: bool) -> Self {
self.frame = frame;
self
@ -590,6 +603,7 @@ impl<'a> ImageButton<'a> {
/// By default, buttons senses clicks.
/// Change this to a drag-button with `Sense::drag()`.
#[inline]
pub fn sense(mut self, sense: Sense) -> Self {
self.sense = sense;
self
@ -598,6 +612,7 @@ impl<'a> ImageButton<'a> {
/// Set rounding for the `ImageButton`.
/// If the underlying image already has rounding, this
/// will override that value.
#[inline]
pub fn rounding(mut self, rounding: impl Into<Rounding>) -> Self {
self.image = self.image.rounding(rounding.into());
self

View File

@ -101,24 +101,28 @@ impl<'a> DragValue<'a> {
}
/// How much the value changes when dragged one point (logical pixel).
#[inline]
pub fn speed(mut self, speed: impl Into<f64>) -> Self {
self.speed = speed.into();
self
}
/// Clamp incoming and outgoing values to this range.
#[inline]
pub fn clamp_range<Num: emath::Numeric>(mut self, clamp_range: RangeInclusive<Num>) -> Self {
self.clamp_range = clamp_range.start().to_f64()..=clamp_range.end().to_f64();
self
}
/// Show a prefix before the number, e.g. "x: "
#[inline]
pub fn prefix(mut self, prefix: impl ToString) -> Self {
self.prefix = prefix.to_string();
self
}
/// Add a suffix to the number, this can be e.g. a unit ("°" or " m")
#[inline]
pub fn suffix(mut self, suffix: impl ToString) -> Self {
self.suffix = suffix.to_string();
self
@ -128,6 +132,7 @@ impl<'a> DragValue<'a> {
/// Set a minimum number of decimals to display.
/// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you.
/// Regardless of precision the slider will use "smart aim" to help the user select nice, round values.
#[inline]
pub fn min_decimals(mut self, min_decimals: usize) -> Self {
self.min_decimals = min_decimals;
self
@ -138,11 +143,13 @@ impl<'a> DragValue<'a> {
/// Values will also be rounded to this number of decimals.
/// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you.
/// Regardless of precision the slider will use "smart aim" to help the user select nice, round values.
#[inline]
pub fn max_decimals(mut self, max_decimals: usize) -> Self {
self.max_decimals = Some(max_decimals);
self
}
#[inline]
pub fn max_decimals_opt(mut self, max_decimals: Option<usize>) -> Self {
self.max_decimals = max_decimals;
self
@ -152,6 +159,7 @@ impl<'a> DragValue<'a> {
/// Values will also be rounded to this number of decimals.
/// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you.
/// Regardless of precision the slider will use "smart aim" to help the user select nice, round values.
#[inline]
pub fn fixed_decimals(mut self, num_decimals: usize) -> Self {
self.min_decimals = num_decimals;
self.max_decimals = Some(num_decimals);
@ -238,6 +246,7 @@ impl<'a> DragValue<'a> {
/// }));
/// # });
/// ```
#[inline]
pub fn custom_parser(mut self, parser: impl 'a + Fn(&str) -> Option<f64>) -> Self {
self.custom_parser = Some(Box::new(parser));
self
@ -360,6 +369,7 @@ impl<'a> DragValue<'a> {
///
/// Default: `true`.
/// If `false`, the value will only be updated when user presses enter or deselects the value.
#[inline]
pub fn update_while_editing(mut self, update: bool) -> Self {
self.update_while_editing = update;
self

View File

@ -107,6 +107,7 @@ impl Hyperlink {
}
/// Always open this hyperlink in a new browser tab.
#[inline]
pub fn open_in_new_tab(mut self, new_tab: bool) -> Self {
self.new_tab = new_tab;
self

View File

@ -85,6 +85,7 @@ impl Label {
/// }
/// # });
/// ```
#[inline]
pub fn sense(mut self, sense: Sense) -> Self {
self.sense = Some(sense);
self

View File

@ -32,30 +32,35 @@ impl ProgressBar {
}
/// The desired width of the bar. Will use all horizontal space if not set.
#[inline]
pub fn desired_width(mut self, desired_width: f32) -> Self {
self.desired_width = Some(desired_width);
self
}
/// The desired height of the bar. Will use the default interaction size if not set.
#[inline]
pub fn desired_height(mut self, desired_height: f32) -> Self {
self.desired_height = Some(desired_height);
self
}
/// The fill color of the bar.
#[inline]
pub fn fill(mut self, color: Color32) -> Self {
self.fill = Some(color);
self
}
/// A custom text to display on the progress bar.
#[inline]
pub fn text(mut self, text: impl Into<WidgetText>) -> Self {
self.text = Some(ProgressBarText::Custom(text.into()));
self
}
/// Show the progress in percent on the progress bar.
#[inline]
pub fn show_percentage(mut self) -> Self {
self.text = Some(ProgressBarText::Percentage);
self
@ -64,6 +69,7 @@ impl ProgressBar {
/// Whether to display a loading animation when progress `< 1`.
/// Note that this will cause the UI to be redrawn.
/// Defaults to `false`.
#[inline]
pub fn animate(mut self, animate: bool) -> Self {
self.animate = animate;
self

View File

@ -36,6 +36,7 @@ impl Separator {
///
/// In a horizontal layout, with a vertical Separator,
/// this is the width of the separator widget.
#[inline]
pub fn spacing(mut self, spacing: f32) -> Self {
self.spacing = spacing;
self
@ -45,6 +46,7 @@ impl Separator {
///
/// By default you will get a horizontal line in vertical layouts,
/// and a vertical line in horizontal layouts.
#[inline]
pub fn horizontal(mut self) -> Self {
self.is_horizontal_line = Some(true);
self
@ -54,6 +56,7 @@ impl Separator {
///
/// By default you will get a horizontal line in vertical layouts,
/// and a vertical line in horizontal layouts.
#[inline]
pub fn vertical(mut self) -> Self {
self.is_horizontal_line = Some(false);
self
@ -64,6 +67,7 @@ impl Separator {
/// The default is to take up the available width/height of the parent.
///
/// This will make the line extend outside the parent ui.
#[inline]
pub fn grow(mut self, extra: f32) -> Self {
self.grow += extra;
self
@ -74,6 +78,7 @@ impl Separator {
/// The default is to take up the available width/height of the parent.
///
/// This effectively adds margins to the line.
#[inline]
pub fn shrink(mut self, shrink: f32) -> Self {
self.grow -= shrink;
self

View File

@ -138,41 +138,48 @@ impl<'a> Slider<'a> {
/// Control whether or not the slider shows the current value.
/// Default: `true`.
#[inline]
pub fn show_value(mut self, show_value: bool) -> Self {
self.show_value = show_value;
self
}
/// Show a prefix before the number, e.g. "x: "
#[inline]
pub fn prefix(mut self, prefix: impl ToString) -> Self {
self.prefix = prefix.to_string();
self
}
/// Add a suffix to the number, this can be e.g. a unit ("°" or " m")
#[inline]
pub fn suffix(mut self, suffix: impl ToString) -> Self {
self.suffix = suffix.to_string();
self
}
/// Show a text next to the slider (e.g. explaining what the slider controls).
#[inline]
pub fn text(mut self, text: impl Into<WidgetText>) -> Self {
self.text = text.into();
self
}
#[inline]
pub fn text_color(mut self, text_color: Color32) -> Self {
self.text = self.text.color(text_color);
self
}
/// Vertical or horizontal slider? The default is horizontal.
#[inline]
pub fn orientation(mut self, orientation: SliderOrientation) -> Self {
self.orientation = orientation;
self
}
/// Make this a vertical slider.
#[inline]
pub fn vertical(mut self) -> Self {
self.orientation = SliderOrientation::Vertical;
self
@ -182,6 +189,7 @@ impl<'a> Slider<'a> {
/// This is great for when the slider spans a huge range,
/// e.g. from one to a million.
/// The default is OFF.
#[inline]
pub fn logarithmic(mut self, logarithmic: bool) -> Self {
self.spec.logarithmic = logarithmic;
self
@ -190,6 +198,7 @@ impl<'a> Slider<'a> {
/// For logarithmic sliders that includes zero:
/// what is the smallest positive value you want to be able to select?
/// The default is `1` for integer sliders and `1e-6` for real sliders.
#[inline]
pub fn smallest_positive(mut self, smallest_positive: f64) -> Self {
self.spec.smallest_positive = smallest_positive;
self
@ -198,6 +207,7 @@ impl<'a> Slider<'a> {
/// For logarithmic sliders, the largest positive value we are interested in
/// before the slider switches to `INFINITY`, if that is the higher end.
/// Default: INFINITY.
#[inline]
pub fn largest_finite(mut self, largest_finite: f64) -> Self {
self.spec.largest_finite = largest_finite;
self
@ -205,6 +215,7 @@ impl<'a> Slider<'a> {
/// If set to `true`, all incoming and outgoing values will be clamped to the slider range.
/// Default: `true`.
#[inline]
pub fn clamp_to_range(mut self, clamp_to_range: bool) -> Self {
self.clamp_to_range = clamp_to_range;
self
@ -212,6 +223,7 @@ impl<'a> Slider<'a> {
/// Turn smart aim on/off. Default is ON.
/// There is almost no point in turning this off.
#[inline]
pub fn smart_aim(mut self, smart_aim: bool) -> Self {
self.smart_aim = smart_aim;
self
@ -223,6 +235,7 @@ impl<'a> Slider<'a> {
/// and `clamp_to_range` is enabled, you would not have the ability to change the value.
///
/// Default: `0.0` (disabled).
#[inline]
pub fn step_by(mut self, step: f64) -> Self {
self.step = if step != 0.0 { Some(step) } else { None };
self
@ -236,6 +249,7 @@ impl<'a> Slider<'a> {
/// By default this is the same speed as when dragging the slider,
/// but you can change it here to for instance have a much finer control
/// by dragging the slider value rather than the slider itself.
#[inline]
pub fn drag_value_speed(mut self, drag_value_speed: f64) -> Self {
self.drag_value_speed = Some(drag_value_speed);
self
@ -246,6 +260,7 @@ impl<'a> Slider<'a> {
///
/// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you.
/// Regardless of precision the slider will use "smart aim" to help the user select nice, round values.
#[inline]
pub fn min_decimals(mut self, min_decimals: usize) -> Self {
self.min_decimals = min_decimals;
self
@ -257,6 +272,7 @@ impl<'a> Slider<'a> {
/// Values will also be rounded to this number of decimals.
/// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you.
/// Regardless of precision the slider will use "smart aim" to help the user select nice, round values.
#[inline]
pub fn max_decimals(mut self, max_decimals: usize) -> Self {
self.max_decimals = Some(max_decimals);
self
@ -267,6 +283,7 @@ impl<'a> Slider<'a> {
/// Values will also be rounded to this number of decimals.
/// Normally you don't need to pick a precision, as the slider will intelligently pick a precision for you.
/// Regardless of precision the slider will use "smart aim" to help the user select nice, round values.
#[inline]
pub fn fixed_decimals(mut self, num_decimals: usize) -> Self {
self.min_decimals = num_decimals;
self.max_decimals = Some(num_decimals);
@ -279,6 +296,7 @@ impl<'a> Slider<'a> {
/// Toggling it here will override the above setting ONLY for this individual slider.
///
/// The fill color will be taken from `selection.bg_fill` in your [`Visuals`], the same as a [`ProgressBar`].
#[inline]
pub fn trailing_fill(mut self, trailing_fill: bool) -> Self {
self.trailing_fill = Some(trailing_fill);
self
@ -362,6 +380,7 @@ impl<'a> Slider<'a> {
/// }));
/// # });
/// ```
#[inline]
pub fn custom_parser(mut self, parser: impl 'a + Fn(&str) -> Option<f64>) -> Self {
self.custom_parser = Some(Box::new(parser));
self

View File

@ -21,12 +21,14 @@ impl Spinner {
/// Sets the spinner's size. The size sets both the height and width, as the spinner is always
/// square. If the size isn't set explicitly, the active style's `interact_size` is used.
#[inline]
pub fn size(mut self, size: f32) -> Self {
self.size = Some(size);
self
}
/// Sets the spinner's color.
#[inline]
pub fn color(mut self, color: impl Into<Color32>) -> Self {
self.color = Some(color.into());
self

View File

@ -139,12 +139,14 @@ impl<'t> TextEdit<'t> {
}
/// Use if you want to set an explicit [`Id`] for this widget.
#[inline]
pub fn id(mut self, id: Id) -> Self {
self.id = Some(id);
self
}
/// A source for the unique [`Id`], e.g. `.id_source("second_text_edit_field")` or `.id_source(loop_index)`.
#[inline]
pub fn id_source(mut self, id_source: impl std::hash::Hash) -> Self {
self.id_source = Some(Id::new(id_source));
self
@ -171,18 +173,21 @@ impl<'t> TextEdit<'t> {
/// painter.galley(output.text_draw_pos, galley);
/// # });
/// ```
#[inline]
pub fn hint_text(mut self, hint_text: impl Into<WidgetText>) -> Self {
self.hint_text = hint_text.into();
self
}
/// If true, hide the letters from view and prevent copying from the field.
#[inline]
pub fn password(mut self, password: bool) -> Self {
self.password = password;
self
}
/// Pick a [`FontId`] or [`TextStyle`].
#[inline]
pub fn font(mut self, font_selection: impl Into<FontSelection>) -> Self {
self.font_selection = font_selection.into();
self
@ -193,11 +198,13 @@ impl<'t> TextEdit<'t> {
self.font(text_style)
}
#[inline]
pub fn text_color(mut self, text_color: Color32) -> Self {
self.text_color = Some(text_color);
self
}
#[inline]
pub fn text_color_opt(mut self, text_color: Option<Color32>) -> Self {
self.text_color = text_color;
self
@ -226,6 +233,7 @@ impl<'t> TextEdit<'t> {
/// ui.add(egui::TextEdit::multiline(&mut my_code).layouter(&mut layouter));
/// # });
/// ```
#[inline]
pub fn layouter(mut self, layouter: &'t mut dyn FnMut(&Ui, &str, f32) -> Arc<Galley>) -> Self {
self.layouter = Some(layouter);
@ -235,18 +243,21 @@ impl<'t> TextEdit<'t> {
/// Default is `true`. If set to `false` then you cannot interact with the text (neither edit or select it).
///
/// Consider using [`Ui::add_enabled`] instead to also give the [`TextEdit`] a greyed out look.
#[inline]
pub fn interactive(mut self, interactive: bool) -> Self {
self.interactive = interactive;
self
}
/// Default is `true`. If set to `false` there will be no frame showing that this is editable text!
#[inline]
pub fn frame(mut self, frame: bool) -> Self {
self.frame = frame;
self
}
/// Set margin of text. Default is [4.0,2.0]
#[inline]
pub fn margin(mut self, margin: Vec2) -> Self {
self.margin = margin;
self
@ -254,6 +265,7 @@ impl<'t> TextEdit<'t> {
/// Set to 0.0 to keep as small as possible.
/// Set to [`f32::INFINITY`] to take up all available space (i.e. disable automatic word wrap).
#[inline]
pub fn desired_width(mut self, desired_width: f32) -> Self {
self.desired_width = Some(desired_width);
self
@ -262,6 +274,7 @@ impl<'t> TextEdit<'t> {
/// Set the number of rows to show by default.
/// The default for singleline text is `1`.
/// The default for multiline text is `4`.
#[inline]
pub fn desired_rows(mut self, desired_height_rows: usize) -> Self {
self.desired_height_rows = desired_height_rows;
self
@ -272,6 +285,7 @@ impl<'t> TextEdit<'t> {
///
/// When `true`, the widget will keep the focus and pressing TAB
/// will insert the `'\t'` character.
#[inline]
pub fn lock_focus(mut self, tab_will_indent: bool) -> Self {
self.event_filter.tab = tab_will_indent;
self
@ -280,6 +294,7 @@ impl<'t> TextEdit<'t> {
/// When `true` (default), the cursor will initially be placed at the end of the text.
///
/// When `false`, the cursor will initially be placed at the beginning of the text.
#[inline]
pub fn cursor_at_end(mut self, b: bool) -> Self {
self.cursor_at_end = b;
self
@ -290,6 +305,7 @@ impl<'t> TextEdit<'t> {
/// When `false`, widget width will expand to make all text visible.
///
/// This only works for singleline [`TextEdit`].
#[inline]
pub fn clip_text(mut self, b: bool) -> Self {
// always show everything in multiline
if !self.multiline {
@ -301,24 +317,28 @@ impl<'t> TextEdit<'t> {
/// Sets the limit for the amount of characters can be entered
///
/// This only works for singleline [`TextEdit`]
#[inline]
pub fn char_limit(mut self, limit: usize) -> Self {
self.char_limit = limit;
self
}
/// Set the horizontal align of the inner text.
#[inline]
pub fn horizontal_align(mut self, align: Align) -> Self {
self.align.0[0] = align;
self
}
/// Set the vertical align of the inner text.
#[inline]
pub fn vertical_align(mut self, align: Align) -> Self {
self.align.0[1] = align;
self
}
/// Set the minimum size of the [`TextEdit`].
#[inline]
pub fn min_size(mut self, min_size: Vec2) -> Self {
self.min_size = min_size;
self

View File

@ -33,36 +33,42 @@ impl<'a> DatePickerButton<'a> {
/// Add id source.
/// Must be set if multiple date picker buttons are in the same Ui.
#[inline]
pub fn id_source(mut self, id_source: &'a str) -> Self {
self.id_source = Some(id_source);
self
}
/// Show combo boxes in date picker popup. (Default: true)
#[inline]
pub fn combo_boxes(mut self, combo_boxes: bool) -> Self {
self.combo_boxes = combo_boxes;
self
}
/// Show arrows in date picker popup. (Default: true)
#[inline]
pub fn arrows(mut self, arrows: bool) -> Self {
self.arrows = arrows;
self
}
/// Show calendar in date picker popup. (Default: true)
#[inline]
pub fn calendar(mut self, calendar: bool) -> Self {
self.calendar = calendar;
self
}
/// Show calendar week in date picker popup. (Default: true)
#[inline]
pub fn calendar_week(mut self, week: bool) -> Self {
self.calendar_week = week;
self
}
/// Show the calendar icon on the button. (Default: true)
#[inline]
pub fn show_icon(mut self, show_icon: bool) -> Self {
self.show_icon = show_icon;
self

View File

@ -112,6 +112,7 @@ impl RetainedImage {
/// let image = RetainedImage::from_color_image("my_image", color_image)
/// .with_options(TextureOptions::NEAREST);
/// ```
#[inline]
pub fn with_options(mut self, options: TextureOptions) -> Self {
self.options = options;

View File

@ -47,6 +47,7 @@ impl Size {
}
/// Won't shrink below this size (in points).
#[inline]
pub fn at_least(mut self, minimum: f32) -> Self {
match &mut self {
Self::Absolute { range, .. }
@ -59,6 +60,7 @@ impl Size {
}
/// Won't grow above this size (in points).
#[inline]
pub fn at_most(mut self, maximum: f32) -> Self {
match &mut self {
Self::Absolute { range, .. }

View File

@ -61,24 +61,28 @@ impl<'a> StripBuilder<'a> {
}
/// Should we clip the contents of each cell? Default: `false`.
#[inline]
pub fn clip(mut self, clip: bool) -> Self {
self.clip = clip;
self
}
/// What layout should we use for the individual cells?
#[inline]
pub fn cell_layout(mut self, cell_layout: egui::Layout) -> Self {
self.cell_layout = cell_layout;
self
}
/// Allocate space for one column/row.
#[inline]
pub fn size(mut self, size: Size) -> Self {
self.sizing.add(size);
self
}
/// Allocate space for several columns/rows at once.
#[inline]
pub fn sizes(mut self, size: Size, count: usize) -> Self {
for _ in 0..count {
self.sizing.add(size);

View File

@ -90,6 +90,7 @@ impl Column {
///
/// If you don't call this, the fallback value of
/// [`TableBuilder::resizable`] is used (which by default is `false`).
#[inline]
pub fn resizable(mut self, resizable: bool) -> Self {
self.resizable = Some(resizable);
self
@ -103,6 +104,7 @@ impl Column {
/// If you turn on clipping you should also consider calling [`Self::at_least`].
///
/// Default: `false`.
#[inline]
pub fn clip(mut self, clip: bool) -> Self {
self.clip = clip;
self
@ -111,6 +113,7 @@ impl Column {
/// Won't shrink below this width (in points).
///
/// Default: 0.0
#[inline]
pub fn at_least(mut self, minimum: f32) -> Self {
self.width_range.min = minimum;
self
@ -119,12 +122,14 @@ impl Column {
/// Won't grow above this width (in points).
///
/// Default: [`f32::INFINITY`]
#[inline]
pub fn at_most(mut self, maximum: f32) -> Self {
self.width_range.max = maximum;
self
}
/// Allowed range of movement (in points), if in a resizable [`Table`](crate::table::Table).
#[inline]
pub fn range(mut self, range: impl Into<Rangef>) -> Self {
self.width_range = range.into();
self
@ -244,6 +249,7 @@ impl<'a> TableBuilder<'a> {
/// Enable striped row background for improved readability.
///
/// Default is whatever is in [`egui::Visuals::striped`].
#[inline]
pub fn striped(mut self, striped: bool) -> Self {
self.striped = Some(striped);
self
@ -259,12 +265,14 @@ impl<'a> TableBuilder<'a> {
/// (and instead use up the remainder).
///
/// Default is `false`.
#[inline]
pub fn resizable(mut self, resizable: bool) -> Self {
self.resizable = resizable;
self
}
/// Enable vertical scrolling in body (default: `true`)
#[inline]
pub fn vscroll(mut self, vscroll: bool) -> Self {
self.scroll_options.vscroll = vscroll;
self
@ -278,6 +286,7 @@ impl<'a> TableBuilder<'a> {
/// Enables scrolling the table's contents using mouse drag (default: `true`).
///
/// See [`ScrollArea::drag_to_scroll`] for more.
#[inline]
pub fn drag_to_scroll(mut self, drag_to_scroll: bool) -> Self {
self.scroll_options.drag_to_scroll = drag_to_scroll;
self
@ -286,6 +295,7 @@ impl<'a> TableBuilder<'a> {
/// Should the scroll handle stick to the bottom position even as the content size changes
/// dynamically? The scroll handle remains stuck until manually changed, and will become stuck
/// once again when repositioned to the bottom. Default: `false`.
#[inline]
pub fn stick_to_bottom(mut self, stick: bool) -> Self {
self.scroll_options.stick_to_bottom = stick;
self
@ -298,6 +308,7 @@ impl<'a> TableBuilder<'a> {
/// If `align` is `None`, the table will scroll just enough to bring the cursor into view.
///
/// See also: [`Self::vertical_scroll_offset`].
#[inline]
pub fn scroll_to_row(mut self, row: usize, align: Option<Align>) -> Self {
self.scroll_options.scroll_to_row = Some((row, align));
self
@ -306,6 +317,7 @@ impl<'a> TableBuilder<'a> {
/// Set the vertical scroll offset position, in points.
///
/// See also: [`Self::scroll_to_row`].
#[inline]
pub fn vertical_scroll_offset(mut self, offset: f32) -> Self {
self.scroll_options.scroll_offset_y = Some(offset);
self
@ -317,6 +329,7 @@ impl<'a> TableBuilder<'a> {
/// (and so we don't require scroll bars).
///
/// Default: `200.0`.
#[inline]
pub fn min_scrolled_height(mut self, min_scrolled_height: f32) -> Self {
self.scroll_options.min_scrolled_height = min_scrolled_height;
self
@ -326,6 +339,7 @@ impl<'a> TableBuilder<'a> {
///
/// In other words: add scroll-bars when this height is reached.
/// Default: `800.0`.
#[inline]
pub fn max_scroll_height(mut self, max_scroll_height: f32) -> Self {
self.scroll_options.max_scroll_height = max_scroll_height;
self
@ -338,24 +352,28 @@ impl<'a> TableBuilder<'a> {
/// Default: `true`.
///
/// See [`ScrollArea::auto_shrink`] for more.
#[inline]
pub fn auto_shrink(mut self, auto_shrink: impl Into<Vec2b>) -> Self {
self.scroll_options.auto_shrink = auto_shrink.into();
self
}
/// What layout should we use for the individual cells?
#[inline]
pub fn cell_layout(mut self, cell_layout: egui::Layout) -> Self {
self.cell_layout = cell_layout;
self
}
/// Allocate space for one column.
#[inline]
pub fn column(mut self, column: Column) -> Self {
self.columns.push(column);
self
}
/// Allocate space for several columns at once.
#[inline]
pub fn columns(mut self, column: Column, count: usize) -> Self {
for _ in 0..count {
self.columns.push(column);

View File

@ -132,6 +132,7 @@ impl AxisHints {
/// Specify axis label.
///
/// The default is 'x' for x-axes and 'y' for y-axes.
#[inline]
pub fn label(mut self, label: impl Into<WidgetText>) -> Self {
self.label = label.into();
self
@ -140,6 +141,7 @@ impl AxisHints {
/// Specify maximum number of digits for ticks.
///
/// This is considered by the default tick formatter and affects the width of the y-axis
#[inline]
pub fn max_digits(mut self, digits: usize) -> Self {
self.digits = digits;
self
@ -149,6 +151,7 @@ impl AxisHints {
///
/// For X-axis, use [`VPlacement`].
/// For Y-axis, use [`HPlacement`].
#[inline]
pub fn placement(mut self, placement: impl Into<Placement>) -> Self {
self.placement = placement.into();
self

View File

@ -55,18 +55,21 @@ impl Bar {
/// Name of this bar chart element.
#[allow(clippy::needless_pass_by_value)]
#[inline]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
}
/// Add a custom stroke.
#[inline]
pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self {
self.stroke = stroke.into();
self
}
/// Add a custom fill color.
#[inline]
pub fn fill(mut self, color: impl Into<Color32>) -> Self {
self.fill = color.into();
self
@ -75,24 +78,28 @@ impl Bar {
/// Offset the base of the bar.
/// This offset is on the Y axis for a vertical bar
/// and on the X axis for a horizontal bar.
#[inline]
pub fn base_offset(mut self, offset: f64) -> Self {
self.base_offset = Some(offset);
self
}
/// Set the bar width.
#[inline]
pub fn width(mut self, width: f64) -> Self {
self.bar_width = width;
self
}
/// Set orientation of the element as vertical. Argument axis is X.
#[inline]
pub fn vertical(mut self) -> Self {
self.orientation = Orientation::Vertical;
self
}
/// Set orientation of the element as horizontal. Argument axis is Y.
#[inline]
pub fn horizontal(mut self) -> Self {
self.orientation = Orientation::Horizontal;
self

View File

@ -94,42 +94,49 @@ impl BoxElem {
/// Name of this box element.
#[allow(clippy::needless_pass_by_value)]
#[inline]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
}
/// Add a custom stroke.
#[inline]
pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self {
self.stroke = stroke.into();
self
}
/// Add a custom fill color.
#[inline]
pub fn fill(mut self, color: impl Into<Color32>) -> Self {
self.fill = color.into();
self
}
/// Set the box width.
#[inline]
pub fn box_width(mut self, width: f64) -> Self {
self.box_width = width;
self
}
/// Set the whisker width.
#[inline]
pub fn whisker_width(mut self, width: f64) -> Self {
self.whisker_width = width;
self
}
/// Set orientation of the element as vertical. Argument axis is X.
#[inline]
pub fn vertical(mut self) -> Self {
self.orientation = Orientation::Vertical;
self
}
/// Set orientation of the element as horizontal. Argument axis is Y.
#[inline]
pub fn horizontal(mut self) -> Self {
self.orientation = Orientation::Horizontal;
self

View File

@ -134,30 +134,35 @@ impl HLine {
}
/// Highlight this line in the plot by scaling up the line.
#[inline]
pub fn highlight(mut self, highlight: bool) -> Self {
self.highlight = highlight;
self
}
/// Add a stroke.
#[inline]
pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self {
self.stroke = stroke.into();
self
}
/// Stroke width. A high value means the plot thickens.
#[inline]
pub fn width(mut self, width: impl Into<f32>) -> Self {
self.stroke.width = width.into();
self
}
/// Stroke color. Default is `Color32::TRANSPARENT` which means a color will be auto-assigned.
#[inline]
pub fn color(mut self, color: impl Into<Color32>) -> Self {
self.stroke.color = color.into();
self
}
/// Set the line's style. Default is `LineStyle::Solid`.
#[inline]
pub fn style(mut self, style: LineStyle) -> Self {
self.style = style;
self
@ -170,6 +175,7 @@ impl HLine {
/// Multiple plot items may share the same name, in which case they will also share an entry in
/// the legend.
#[allow(clippy::needless_pass_by_value)]
#[inline]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
@ -250,30 +256,35 @@ impl VLine {
}
/// Highlight this line in the plot by scaling up the line.
#[inline]
pub fn highlight(mut self, highlight: bool) -> Self {
self.highlight = highlight;
self
}
/// Add a stroke.
#[inline]
pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self {
self.stroke = stroke.into();
self
}
/// Stroke width. A high value means the plot thickens.
#[inline]
pub fn width(mut self, width: impl Into<f32>) -> Self {
self.stroke.width = width.into();
self
}
/// Stroke color. Default is `Color32::TRANSPARENT` which means a color will be auto-assigned.
#[inline]
pub fn color(mut self, color: impl Into<Color32>) -> Self {
self.stroke.color = color.into();
self
}
/// Set the line's style. Default is `LineStyle::Solid`.
#[inline]
pub fn style(mut self, style: LineStyle) -> Self {
self.style = style;
self
@ -286,6 +297,7 @@ impl VLine {
/// Multiple plot items may share the same name, in which case they will also share an entry in
/// the legend.
#[allow(clippy::needless_pass_by_value)]
#[inline]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
@ -367,36 +379,42 @@ impl Line {
}
/// Highlight this line in the plot by scaling up the line.
#[inline]
pub fn highlight(mut self, highlight: bool) -> Self {
self.highlight = highlight;
self
}
/// Add a stroke.
#[inline]
pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self {
self.stroke = stroke.into();
self
}
/// Stroke width. A high value means the plot thickens.
#[inline]
pub fn width(mut self, width: impl Into<f32>) -> Self {
self.stroke.width = width.into();
self
}
/// Stroke color. Default is `Color32::TRANSPARENT` which means a color will be auto-assigned.
#[inline]
pub fn color(mut self, color: impl Into<Color32>) -> Self {
self.stroke.color = color.into();
self
}
/// Fill the area between this line and a given horizontal reference line.
#[inline]
pub fn fill(mut self, y_reference: impl Into<f32>) -> Self {
self.fill = Some(y_reference.into());
self
}
/// Set the line's style. Default is `LineStyle::Solid`.
#[inline]
pub fn style(mut self, style: LineStyle) -> Self {
self.style = style;
self
@ -409,6 +427,7 @@ impl Line {
/// Multiple plot items may share the same name, in which case they will also share an entry in
/// the legend.
#[allow(clippy::needless_pass_by_value)]
#[inline]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
@ -535,18 +554,21 @@ impl Polygon {
/// Highlight this polygon in the plot by scaling up the stroke and reducing the fill
/// transparency.
#[inline]
pub fn highlight(mut self, highlight: bool) -> Self {
self.highlight = highlight;
self
}
/// Add a custom stroke.
#[inline]
pub fn stroke(mut self, stroke: impl Into<Stroke>) -> Self {
self.stroke = stroke.into();
self
}
/// Set the stroke width.
#[inline]
pub fn width(mut self, width: impl Into<f32>) -> Self {
self.stroke.width = width.into();
self
@ -554,23 +576,27 @@ impl Polygon {
#[deprecated = "Use `fill_color`."]
#[allow(unused, clippy::needless_pass_by_value)]
#[inline]
pub fn color(mut self, color: impl Into<Color32>) -> Self {
self
}
#[deprecated = "Use `fill_color`."]
#[allow(unused, clippy::needless_pass_by_value)]
#[inline]
pub fn fill_alpha(mut self, _alpha: impl Into<f32>) -> Self {
self
}
/// Fill color. Defaults to the stroke color with added transparency.
#[inline]
pub fn fill_color(mut self, color: impl Into<Color32>) -> Self {
self.fill_color = Some(color.into());
self
}
/// Set the outline's style. Default is `LineStyle::Solid`.
#[inline]
pub fn style(mut self, style: LineStyle) -> Self {
self.style = style;
self
@ -583,6 +609,7 @@ impl Polygon {
/// Multiple plot items may share the same name, in which case they will also share an entry in
/// the legend.
#[allow(clippy::needless_pass_by_value)]
#[inline]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
@ -667,18 +694,21 @@ impl Text {
}
/// Highlight this text in the plot by drawing a rectangle around it.
#[inline]
pub fn highlight(mut self, highlight: bool) -> Self {
self.highlight = highlight;
self
}
/// Text color.
#[inline]
pub fn color(mut self, color: impl Into<Color32>) -> Self {
self.color = color.into();
self
}
/// Anchor position of the text. Default is `Align2::CENTER_CENTER`.
#[inline]
pub fn anchor(mut self, anchor: Align2) -> Self {
self.anchor = anchor;
self
@ -691,6 +721,7 @@ impl Text {
/// Multiple plot items may share the same name, in which case they will also share an entry in
/// the legend.
#[allow(clippy::needless_pass_by_value)]
#[inline]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
@ -796,36 +827,42 @@ impl Points {
}
/// Set the shape of the markers.
#[inline]
pub fn shape(mut self, shape: MarkerShape) -> Self {
self.shape = shape;
self
}
/// Highlight these points in the plot by scaling up their markers.
#[inline]
pub fn highlight(mut self, highlight: bool) -> Self {
self.highlight = highlight;
self
}
/// Set the marker's color.
#[inline]
pub fn color(mut self, color: impl Into<Color32>) -> Self {
self.color = color.into();
self
}
/// Whether to fill the marker.
#[inline]
pub fn filled(mut self, filled: bool) -> Self {
self.filled = filled;
self
}
/// Whether to add stems between the markers and a horizontal reference line.
#[inline]
pub fn stems(mut self, y_reference: impl Into<f32>) -> Self {
self.stems = Some(y_reference.into());
self
}
/// Set the maximum extent of the marker around its position.
#[inline]
pub fn radius(mut self, radius: impl Into<f32>) -> Self {
self.radius = radius.into();
self
@ -838,6 +875,7 @@ impl Points {
/// Multiple plot items may share the same name, in which case they will also share an entry in
/// the legend.
#[allow(clippy::needless_pass_by_value)]
#[inline]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
@ -1025,18 +1063,21 @@ impl Arrows {
}
/// Highlight these arrows in the plot.
#[inline]
pub fn highlight(mut self, highlight: bool) -> Self {
self.highlight = highlight;
self
}
/// Set the length of the arrow tips
#[inline]
pub fn tip_length(mut self, tip_length: f32) -> Self {
self.tip_length = Some(tip_length);
self
}
/// Set the arrows' color.
#[inline]
pub fn color(mut self, color: impl Into<Color32>) -> Self {
self.color = color.into();
self
@ -1049,6 +1090,7 @@ impl Arrows {
/// Multiple plot items may share the same name, in which case they will also share an entry in
/// the legend.
#[allow(clippy::needless_pass_by_value)]
#[inline]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
@ -1165,24 +1207,28 @@ impl PlotImage {
}
/// Highlight this image in the plot.
#[inline]
pub fn highlight(mut self, highlight: bool) -> Self {
self.highlight = highlight;
self
}
/// Select UV range. Default is (0,0) in top-left, (1,1) bottom right.
#[inline]
pub fn uv(mut self, uv: impl Into<Rect>) -> Self {
self.uv = uv.into();
self
}
/// A solid color to put behind the image. Useful for transparent images.
#[inline]
pub fn bg_fill(mut self, bg_fill: impl Into<Color32>) -> Self {
self.bg_fill = bg_fill.into();
self
}
/// Multiply image color with this. Default is WHITE (no tint).
#[inline]
pub fn tint(mut self, tint: impl Into<Color32>) -> Self {
self.tint = tint.into();
self
@ -1195,12 +1241,14 @@ impl PlotImage {
/// Multiple plot items may share the same name, in which case they will also share an entry in
/// the legend.
#[allow(clippy::needless_pass_by_value)]
#[inline]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
}
/// Rotate the image counter-clockwise around its center by an angle in radians.
#[inline]
pub fn rotate(mut self, angle: f64) -> Self {
self.rotation = angle;
self
@ -1334,6 +1382,7 @@ impl BarChart {
/// This is the color that shows up in the legend.
/// It can be overridden at the bar level (see [[`Bar`]]).
/// Default is `Color32::TRANSPARENT` which means a color will be auto-assigned.
#[inline]
pub fn color(mut self, color: impl Into<Color32>) -> Self {
let plot_color = color.into();
self.default_color = plot_color;
@ -1351,6 +1400,7 @@ impl BarChart {
/// This name will show up in the plot legend, if legends are turned on. Multiple charts may
/// share the same name, in which case they will also share an entry in the legend.
#[allow(clippy::needless_pass_by_value)]
#[inline]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
@ -1358,6 +1408,7 @@ impl BarChart {
/// Set all elements to be in a vertical orientation.
/// Argument axis will be X and bar values will be on the Y axis.
#[inline]
pub fn vertical(mut self) -> Self {
for b in &mut self.bars {
b.orientation = Orientation::Vertical;
@ -1367,6 +1418,7 @@ impl BarChart {
/// Set all elements to be in a horizontal orientation.
/// Argument axis will be Y and bar values will be on the X axis.
#[inline]
pub fn horizontal(mut self) -> Self {
for b in &mut self.bars {
b.orientation = Orientation::Horizontal;
@ -1375,6 +1427,7 @@ impl BarChart {
}
/// Set the width (thickness) of all its elements.
#[inline]
pub fn width(mut self, width: f64) -> Self {
for b in &mut self.bars {
b.bar_width = width;
@ -1383,6 +1436,7 @@ impl BarChart {
}
/// Highlight all plot elements.
#[inline]
pub fn highlight(mut self, highlight: bool) -> Self {
self.highlight = highlight;
self
@ -1390,6 +1444,7 @@ impl BarChart {
/// Add a custom way to format an element.
/// Can be used to display a set number of decimals or custom labels.
#[inline]
pub fn element_formatter(mut self, formatter: Box<dyn Fn(&Bar, &BarChart) -> String>) -> Self {
self.element_formatter = Some(formatter);
self
@ -1398,6 +1453,7 @@ impl BarChart {
/// Stacks the bars on top of another chart.
/// Positive values are stacked on top of other positive values.
/// Negative values are stacked below other negative values.
#[inline]
pub fn stack_on(mut self, others: &[&BarChart]) -> Self {
for (index, bar) in self.bars.iter_mut().enumerate() {
let new_base_offset = if bar.value.is_sign_positive() {
@ -1506,6 +1562,7 @@ impl BoxPlot {
/// This is the color that shows up in the legend.
/// It can be overridden at the element level (see [`BoxElem`]).
/// Default is `Color32::TRANSPARENT` which means a color will be auto-assigned.
#[inline]
pub fn color(mut self, color: impl Into<Color32>) -> Self {
let plot_color = color.into();
self.default_color = plot_color;
@ -1525,6 +1582,7 @@ impl BoxPlot {
/// This name will show up in the plot legend, if legends are turned on. Multiple series may
/// share the same name, in which case they will also share an entry in the legend.
#[allow(clippy::needless_pass_by_value)]
#[inline]
pub fn name(mut self, name: impl ToString) -> Self {
self.name = name.to_string();
self
@ -1532,6 +1590,7 @@ impl BoxPlot {
/// Set all elements to be in a vertical orientation.
/// Argument axis will be X and values will be on the Y axis.
#[inline]
pub fn vertical(mut self) -> Self {
for box_elem in &mut self.boxes {
box_elem.orientation = Orientation::Vertical;
@ -1541,6 +1600,7 @@ impl BoxPlot {
/// Set all elements to be in a horizontal orientation.
/// Argument axis will be Y and values will be on the X axis.
#[inline]
pub fn horizontal(mut self) -> Self {
for box_elem in &mut self.boxes {
box_elem.orientation = Orientation::Horizontal;
@ -1549,6 +1609,7 @@ impl BoxPlot {
}
/// Highlight all plot elements.
#[inline]
pub fn highlight(mut self, highlight: bool) -> Self {
self.highlight = highlight;
self

View File

@ -46,18 +46,21 @@ impl Default for Legend {
impl Legend {
/// Which text style to use for the legend. Default: `TextStyle::Body`.
#[inline]
pub fn text_style(mut self, style: TextStyle) -> Self {
self.text_style = style;
self
}
/// The alpha of the legend background. Default: `0.75`.
#[inline]
pub fn background_alpha(mut self, alpha: f32) -> Self {
self.background_alpha = alpha;
self
}
/// In which corner to place the legend. Default: `Corner::RightTop`.
#[inline]
pub fn position(mut self, corner: Corner) -> Self {
self.position = corner;
self

View File

@ -260,6 +260,7 @@ impl Plot {
/// For instance, it can be useful to set this to `1.0` for when the two axes show the same
/// unit.
/// By default the plot window's aspect ratio is used.
#[inline]
pub fn data_aspect(mut self, data_aspect: f32) -> Self {
self.data_aspect = Some(data_aspect);
self
@ -267,6 +268,7 @@ impl Plot {
/// width / height ratio of the plot region.
/// By default no fixed aspect ratio is set (and width/height will fill the ui it is in).
#[inline]
pub fn view_aspect(mut self, view_aspect: f32) -> Self {
self.view_aspect = Some(view_aspect);
self
@ -274,6 +276,7 @@ impl Plot {
/// Width of plot. By default a plot will fill the ui it is in.
/// If you set [`Self::view_aspect`], the width can be calculated from the height.
#[inline]
pub fn width(mut self, width: f32) -> Self {
self.min_size.x = width;
self.width = Some(width);
@ -282,6 +285,7 @@ impl Plot {
/// Height of plot. By default a plot will fill the ui it is in.
/// If you set [`Self::view_aspect`], the height can be calculated from the width.
#[inline]
pub fn height(mut self, height: f32) -> Self {
self.min_size.y = height;
self.height = Some(height);
@ -289,30 +293,35 @@ impl Plot {
}
/// Minimum size of the plot view.
#[inline]
pub fn min_size(mut self, min_size: Vec2) -> Self {
self.min_size = min_size;
self
}
/// Show the x-value (e.g. when hovering). Default: `true`.
#[inline]
pub fn show_x(mut self, show_x: bool) -> Self {
self.show_x = show_x;
self
}
/// Show the y-value (e.g. when hovering). Default: `true`.
#[inline]
pub fn show_y(mut self, show_y: bool) -> Self {
self.show_y = show_y;
self
}
/// Always keep the X-axis centered. Default: `false`.
#[inline]
pub fn center_x_axis(mut self, on: bool) -> Self {
self.center_axis.x = on;
self
}
/// Always keep the Y-axis centered. Default: `false`.
#[inline]
pub fn center_y_axis(mut self, on: bool) -> Self {
self.center_axis.y = on;
self
@ -321,6 +330,7 @@ impl Plot {
/// Whether to allow zooming in the plot. Default: `true`.
///
/// Note: Allowing zoom in one axis but not the other may lead to unexpected results if used in combination with `data_aspect`.
#[inline]
pub fn allow_zoom<T>(mut self, on: T) -> Self
where
T: Into<Vec2b>,
@ -330,6 +340,7 @@ impl Plot {
}
/// Whether to allow scrolling in the plot. Default: `true`.
#[inline]
pub fn allow_scroll(mut self, on: bool) -> Self {
self.allow_scroll = on;
self
@ -337,6 +348,7 @@ impl Plot {
/// Whether to allow double clicking to reset the view.
/// Default: `true`.
#[inline]
pub fn allow_double_click_reset(mut self, on: bool) -> Self {
self.allow_double_click_reset = on;
self
@ -345,6 +357,7 @@ impl Plot {
/// Set the side margin as a fraction of the plot size. Only used for auto bounds.
///
/// For instance, a value of `0.1` will add 10% space on both sides.
#[inline]
pub fn set_margin_fraction(mut self, margin_fraction: Vec2) -> Self {
self.margin_fraction = margin_fraction;
self
@ -353,18 +366,21 @@ impl Plot {
/// Whether to allow zooming in the plot by dragging out a box with the secondary mouse button.
///
/// Default: `true`.
#[inline]
pub fn allow_boxed_zoom(mut self, on: bool) -> Self {
self.allow_boxed_zoom = on;
self
}
/// Config the button pointer to use for boxed zooming. Default: [`Secondary`](PointerButton::Secondary)
#[inline]
pub fn boxed_zoom_pointer_button(mut self, boxed_zoom_pointer_button: PointerButton) -> Self {
self.boxed_zoom_pointer_button = boxed_zoom_pointer_button;
self
}
/// Whether to allow dragging in the plot to move the bounds. Default: `true`.
#[inline]
pub fn allow_drag<T>(mut self, on: T) -> Self
where
T: Into<Vec2b>,
@ -442,6 +458,7 @@ impl Plot {
/// ```
///
/// There are helpers for common cases, see [`log_grid_spacer`] and [`uniform_grid_spacer`].
#[inline]
pub fn x_grid_spacer(mut self, spacer: impl Fn(GridInput) -> Vec<GridMark> + 'static) -> Self {
self.grid_spacers[0] = Box::new(spacer);
self
@ -450,6 +467,7 @@ impl Plot {
/// Default is a log-10 grid, i.e. every plot unit is divided into 10 other units.
///
/// See [`Self::x_grid_spacer`] for explanation.
#[inline]
pub fn y_grid_spacer(mut self, spacer: impl Fn(GridInput) -> Vec<GridMark> + 'static) -> Self {
self.grid_spacers[1] = Box::new(spacer);
self
@ -458,6 +476,7 @@ impl Plot {
/// Clamp the grid to only be visible at the range of data where we have values.
///
/// Default: `false`.
#[inline]
pub fn clamp_grid(mut self, clamp_grid: bool) -> Self {
self.clamp_grid = clamp_grid;
self
@ -465,6 +484,7 @@ impl Plot {
/// Expand bounds to include the given x value.
/// For instance, to always show the y axis, call `plot.include_x(0.0)`.
#[inline]
pub fn include_x(mut self, x: impl Into<f64>) -> Self {
self.min_auto_bounds.extend_with_x(x.into());
self
@ -472,24 +492,28 @@ impl Plot {
/// Expand bounds to include the given y value.
/// For instance, to always show the x axis, call `plot.include_y(0.0)`.
#[inline]
pub fn include_y(mut self, y: impl Into<f64>) -> Self {
self.min_auto_bounds.extend_with_y(y.into());
self
}
/// Expand bounds to fit all items across the x axis, including values given by `include_x`.
#[inline]
pub fn auto_bounds_x(mut self) -> Self {
self.auto_bounds.x = true;
self
}
/// Expand bounds to fit all items across the y axis, including values given by `include_y`.
#[inline]
pub fn auto_bounds_y(mut self) -> Self {
self.auto_bounds.y = true;
self
}
/// Show a legend including all named items.
#[inline]
pub fn legend(mut self, legend: Legend) -> Self {
self.legend_config = Some(legend);
self
@ -499,6 +523,7 @@ impl Plot {
///
/// Can be useful to disable if the plot is overlaid over existing content.
/// Default: `true`.
#[inline]
pub fn show_background(mut self, show: bool) -> Self {
self.show_background = show;
self
@ -507,6 +532,7 @@ impl Plot {
/// Show axis labels and grid tick values on the side of the plot.
///
/// Default: `true`.
#[inline]
pub fn show_axes(mut self, show: impl Into<Vec2b>) -> Self {
self.show_axes = show.into();
self
@ -515,6 +541,7 @@ impl Plot {
/// Show a grid overlay on the plot.
///
/// Default: `true`.
#[inline]
pub fn show_grid(mut self, show: impl Into<Vec2b>) -> Self {
self.show_grid = show.into();
self
@ -522,6 +549,7 @@ impl Plot {
/// Add this plot to an axis link group so that this plot will share the bounds with other plots in the
/// same group. A plot cannot belong to more than one axis group.
#[inline]
pub fn link_axis(mut self, group_id: impl Into<Id>, link_x: bool, link_y: bool) -> Self {
self.linked_axes = Some((
group_id.into(),
@ -535,6 +563,7 @@ impl Plot {
/// Add this plot to a cursor link group so that this plot will share the cursor position with other plots
/// in the same group. A plot cannot belong to more than one cursor group.
#[inline]
pub fn link_cursor(mut self, group_id: impl Into<Id>, link_x: bool, link_y: bool) -> Self {
self.linked_cursors = Some((
group_id.into(),
@ -548,12 +577,14 @@ impl Plot {
/// Round grid positions to full pixels to avoid aliasing. Improves plot appearance but might have an
/// undesired effect when shifting the plot bounds. Enabled by default.
#[inline]
pub fn sharp_grid_lines(mut self, enabled: bool) -> Self {
self.sharp_grid_lines = enabled;
self
}
/// Resets the plot.
#[inline]
pub fn reset(mut self) -> Self {
self.reset = true;
self
@ -562,6 +593,7 @@ impl Plot {
/// Set the x axis label of the main X-axis.
///
/// Default: no label.
#[inline]
pub fn x_axis_label(mut self, label: impl Into<WidgetText>) -> Self {
if let Some(main) = self.x_axes.first_mut() {
main.label = label.into();
@ -572,6 +604,7 @@ impl Plot {
/// Set the y axis label of the main Y-axis.
///
/// Default: no label.
#[inline]
pub fn y_axis_label(mut self, label: impl Into<WidgetText>) -> Self {
if let Some(main) = self.y_axes.first_mut() {
main.label = label.into();
@ -580,6 +613,7 @@ impl Plot {
}
/// Set the position of the main X-axis.
#[inline]
pub fn x_axis_position(mut self, placement: axis::VPlacement) -> Self {
if let Some(main) = self.x_axes.first_mut() {
main.placement = placement.into();
@ -588,6 +622,7 @@ impl Plot {
}
/// Set the position of the main Y-axis.
#[inline]
pub fn y_axis_position(mut self, placement: axis::HPlacement) -> Self {
if let Some(main) = self.y_axes.first_mut() {
main.placement = placement.into();
@ -632,6 +667,7 @@ impl Plot {
/// The default is 5 digits.
///
/// > Todo: This is experimental. Changing the font size might break this.
#[inline]
pub fn y_axis_width(mut self, digits: usize) -> Self {
if let Some(main) = self.y_axes.first_mut() {
main.digits = digits;
@ -642,6 +678,7 @@ impl Plot {
/// Set custom configuration for X-axis
///
/// More than one axis may be specified. The first specified axis is considered the main axis.
#[inline]
pub fn custom_x_axes(mut self, hints: Vec<AxisHints>) -> Self {
self.x_axes = hints;
self
@ -650,6 +687,7 @@ impl Plot {
/// Set custom configuration for left Y-axis
///
/// More than one axis may be specified. The first specified axis is considered the main axis.
#[inline]
pub fn custom_y_axes(mut self, hints: Vec<AxisHints>) -> Self {
self.y_axes = hints;
self

View File

@ -150,29 +150,29 @@ impl Rect {
rect
}
#[inline]
#[must_use]
#[inline]
pub fn with_min_x(mut self, min_x: f32) -> Self {
self.min.x = min_x;
self
}
#[inline]
#[must_use]
#[inline]
pub fn with_min_y(mut self, min_y: f32) -> Self {
self.min.y = min_y;
self
}
#[inline]
#[must_use]
#[inline]
pub fn with_max_x(mut self, max_x: f32) -> Self {
self.max.x = max_x;
self
}
#[inline]
#[must_use]
#[inline]
pub fn with_max_y(mut self, max_y: f32) -> Self {
self.max.y = max_y;
self

View File

@ -19,42 +19,56 @@ def lint_file_path(filepath, args) -> int:
print(error)
if args.fix and lines_in != lines_out:
with open(filepath, 'w') as f:
with open(filepath, "w") as f:
f.writelines(lines_out)
print(f'{filepath} fixed.')
print(f"{filepath} fixed.")
return len(errors)
def lint_lines(filepath, lines_in):
last_line_was_empty = True
errors = []
lines_out = []
prev_line = ""
for line_nr, line in enumerate(lines_in):
line_nr = line_nr+1
line_nr = line_nr + 1
# TODO: only # and /// on lines before a keyword
pattern = r'^\s*((///)|((pub(\(\w*\))? )?((impl|fn|struct|enum|union|trait)\b))).*$'
pattern = (
r"^\s*((///)|((pub(\(\w*\))? )?((impl|fn|struct|enum|union|trait)\b))).*$"
)
if re.match(pattern, line):
stripped = prev_line.strip()
last_line_was_empty = (
stripped == ""
or stripped.startswith("#")
or stripped.startswith("//")
or stripped.endswith("{")
or stripped.endswith("(")
or stripped.endswith("\\")
or stripped.endswith('r"')
or stripped.endswith("]")
)
if not last_line_was_empty:
errors.append(
f'{filepath}:{line_nr}: for readability, add newline before `{line.strip()}`')
f"{filepath}:{line_nr}: for readability, add newline before `{line.strip()}`"
)
lines_out.append("\n")
if re.search(r"\(mut self.*-> Self", line):
if prev_line.strip() != "#[inline]":
errors.append(
f"{filepath}:{line_nr}: builder methods should be marked #[inline]"
)
lines_out.append("#[inline]")
lines_out.append(line)
stripped = line.strip()
last_line_was_empty = stripped == '' or \
stripped.startswith('#') or \
stripped.startswith('//') or \
stripped.endswith('{') or \
stripped.endswith('(') or \
stripped.endswith('\\') or \
stripped.endswith('r"') or \
stripped.endswith(']')
prev_line = line
return errors, lines_out
@ -68,7 +82,14 @@ def test_lint():
/// docstring
bar
""",
"""
#[inline]
pub fn with_color(mut self, color: Color32) -> Self {
self.color = color;
self
}
""",
]
should_fail = [
@ -77,29 +98,41 @@ def test_lint():
foo
/// docstring
bar
""",
"""
// not inlined
pub fn with_color(mut self, color: Color32) -> Self {
self.color = color;
self
}
""",
]
for code in should_pass:
errors, _ = lint_lines("test.py", code.split('\n'))
assert len(errors) == 0, f'expected this to pass:\n{code}\ngot: {errors}'
errors, _ = lint_lines("test.py", code.split("\n"))
assert len(errors) == 0, f"expected this to pass:\n{code}\ngot: {errors}"
for code in should_fail:
errors, _ = lint_lines("test.py", code.split('\n'))
assert len(errors) > 0, f'expected this to fail:\n{code}'
errors, _ = lint_lines("test.py", code.split("\n"))
assert len(errors) > 0, f"expected this to fail:\n{code}"
pass
def main():
test_lint() # Make sure we are bug free before we run!
test_lint() # Make sure we are bug free before we run!
parser = argparse.ArgumentParser(
description='Lint Rust code with custom linter.')
parser.add_argument('files', metavar='file', type=str, nargs='*',
help='File paths. Empty = all files, recursively.')
parser.add_argument('--fix', dest='fix', action='store_true',
help='Automatically fix the files')
parser = argparse.ArgumentParser(description="Lint Rust code with custom linter.")
parser.add_argument(
"files",
metavar="file",
type=str,
nargs="*",
help="File paths. Empty = all files, recursively.",
)
parser.add_argument(
"--fix", dest="fix", action="store_true", help="Automatically fix the files"
)
args = parser.parse_args()
@ -110,14 +143,14 @@ def main():
num_errors += lint_file_path(filepath, args)
else:
script_dirpath = os.path.dirname(os.path.realpath(__file__))
root_dirpath = os.path.abspath(f'{script_dirpath}/..')
root_dirpath = os.path.abspath(f"{script_dirpath}/..")
os.chdir(root_dirpath)
exclude = set(['target', 'target_ra'])
for root, dirs, files in os.walk('.', topdown=True):
exclude = set(["target", "target_ra", "target_wasm"])
for root, dirs, files in os.walk(".", topdown=True):
dirs[:] = [d for d in dirs if d not in exclude]
for filename in files:
if filename.endswith('.rs'):
if filename.endswith(".rs"):
filepath = os.path.join(root, filename)
num_errors += lint_file_path(filepath, args)
@ -128,5 +161,6 @@ def main():
print(f"{sys.argv[0]} found {num_errors} errors.")
sys.exit(1)
if __name__ == '__main__':
if __name__ == "__main__":
main()