1
0
mirror of https://github.com/emilk/egui.git synced 2026-09-01 06:10:06 -04:00

More newlines for improved readability (#1880)

* Add blank lines above all `fn`, `impl`, `struct`, etc
* Even newlines between docstringed struct and enum fields
* Improve some documentation
This commit is contained in:
Emil Ernerfeldt
2022-08-02 17:26:33 +02:00
committed by GitHub
parent 5d8ef5326b
commit 10788ccc92
56 changed files with 306 additions and 12 deletions

View File

@@ -104,11 +104,13 @@ impl Resize {
self.min_size = min_size.into();
self
}
/// Won't shrink to smaller than this
pub fn min_width(mut self, min_width: f32) -> Self {
self.min_size.x = min_width;
self
}
/// Won't shrink to smaller than this
pub fn min_height(mut self, min_height: f32) -> Self {
self.min_size.y = min_height;

View File

@@ -102,6 +102,7 @@ impl<'open> Window<'open> {
self.resize = self.resize.min_width(min_width);
self
}
/// Set minimum height of the window.
pub fn min_height(mut self, min_height: f32) -> Self {
self.resize = self.resize.min_height(min_height);
@@ -148,6 +149,7 @@ impl<'open> Window<'open> {
self.resize = self.resize.default_width(default_width);
self
}
/// Set initial height of the window.
pub fn default_height(mut self, default_height: f32) -> Self {
self.resize = self.resize.default_height(default_height);
@@ -760,12 +762,15 @@ fn paint_frame_interaction(
struct TitleBar {
/// A title Id used for dragging windows
id: Id,
/// Prepared text in the title
title_galley: WidgetTextGalley,
/// Size of the title bar in a collapsed state (if window is collapsible),
/// which includes all necessary space for showing the expand button, the
/// title and the close button.
min_rect: Rect,
/// Size of the title bar in an expanded state. This size become known only
/// after expanding window and painting its content
rect: Rect,

View File

@@ -138,6 +138,7 @@ impl RawInput {
pub struct HoveredFile {
/// Set by the `egui-winit` backend.
pub path: Option<std::path::PathBuf>,
/// With the `eframe` web backend, this is set to the mime-type of the file (if available).
pub mime: String,
}
@@ -148,10 +149,13 @@ pub struct HoveredFile {
pub struct DroppedFile {
/// Set by the `egui-winit` backend.
pub path: Option<std::path::PathBuf>,
/// Name of the file. Set by the `eframe` web backend.
pub name: String,
/// Set by the `eframe` web backend.
pub last_modified: Option<std::time::SystemTime>,
/// Set by the `eframe` web backend.
pub bytes: Option<std::sync::Arc<[u8]>>,
}
@@ -164,19 +168,25 @@ pub struct DroppedFile {
pub enum Event {
/// The integration detected a "copy" event (e.g. Cmd+C).
Copy,
/// The integration detected a "cut" event (e.g. Cmd+X).
Cut,
/// The integration detected a "paste" event (e.g. Cmd+V).
Paste(String),
/// Text input, e.g. via keyboard.
///
/// When the user presses enter/return, do not send a [`Text`](Event::Text) (just [`Key::Enter`]).
Text(String),
/// A key was pressed or released.
Key {
key: Key,
/// Was it pressed or released?
pressed: bool,
/// The state of the modifier keys at the time of the event.
modifiers: Modifiers,
},
@@ -188,13 +198,17 @@ pub enum Event {
PointerButton {
/// Where is the pointer?
pos: Pos2,
/// What mouse button? For touches, use [`PointerButton::Primary`].
button: PointerButton,
/// Was it the button/touch pressed this frame, or released?
pressed: bool,
/// The state of the modifier keys at the time of the event.
modifiers: Modifiers,
},
/// The mouse left the screen, or the last/primary touch input disappeared.
///
/// This means there is no longer a cursor on the screen for hovering etc.
@@ -225,8 +239,10 @@ pub enum Event {
/// IME composition start.
CompositionStart,
/// A new IME candidate is being suggested.
CompositionUpdate(String),
/// IME composition ended with this final result.
CompositionEnd(String),
@@ -236,13 +252,17 @@ pub enum Event {
/// Hashed device identifier (if available; may be zero).
/// Can be used to separate touches from different devices.
device_id: TouchDeviceId,
/// Unique identifier of a finger/pen. Value is stable from touch down
/// to lift-up
id: TouchId,
/// One of: start move end cancel.
phase: TouchPhase,
/// Position of the touch (or where the touch was last detected)
pos: Pos2,
/// Describes how hard the touch device was pressed. May always be `0` if the platform does
/// not support pressure sensitivity.
/// The value is in the range from 0.0 (no pressure) to 1.0 (maximum pressure).
@@ -256,13 +276,17 @@ pub enum Event {
pub enum PointerButton {
/// The primary mouse button is usually the left one.
Primary = 0,
/// The secondary mouse button is usually the right one,
/// and most often used for context menus or other optional things.
Secondary = 1,
/// The tertiary mouse button is usually the middle mouse button (e.g. clicking the scroll wheel).
Middle = 2,
/// The first extra mouse button on some mice. In web typically corresponds to the Browser back button.
Extra1 = 3,
/// The second extra mouse button on some mice. In web typically corresponds to the Browser forward button.
Extra2 = 4,
}
@@ -337,6 +361,7 @@ impl Modifiers {
mac_cmd: false,
command: false,
};
/// The Mac ⌘ Command key
pub const MAC_CMD: Self = Self {
alt: false,
@@ -345,6 +370,7 @@ impl Modifiers {
mac_cmd: true,
command: false,
};
/// On Mac: ⌘ Command key, elsewhere: Ctrl key
pub const COMMAND: Self = Self {
alt: false,
@@ -426,6 +452,7 @@ impl Modifiers {
impl std::ops::BitOr for Modifiers {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self {
alt: self.alt | rhs.alt,
@@ -593,12 +620,15 @@ pub struct TouchId(pub u64);
pub enum TouchPhase {
/// User just placed a touch point on the touch surface
Start,
/// User moves a touch point along the surface. This event is also sent when
/// any attributes (position, force, …) of the touch point change.
Move,
/// User lifted the finger or pen from the surface, or slid off the edge of
/// the surface
End,
/// Touch operation has been disrupted by something (various reasons are possible,
/// maybe a pop-up alert or any other kind of interruption which may not have
/// been intended by the user)

View File

@@ -143,10 +143,12 @@ impl PlatformOutput {
}
}
/// What URL to open, and how.
#[derive(Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct OpenUrl {
pub url: String,
/// If `true`, open the url in a new tab.
/// If `false` open it in the same tab.
/// Only matters when in a web browser.
@@ -247,10 +249,13 @@ pub enum CursorIcon {
// Resizing in two directions:
/// Horizontal resize `-` to make something wider or more narrow (left to/from right)
ResizeHorizontal,
/// Diagonal resize `/` (right-up to/from left-down)
ResizeNeSw,
/// Diagonal resize `\` (left-up to/from right-down)
ResizeNwSe,
/// Vertical resize `|` (up-down or down-up)
ResizeVertical,
@@ -258,24 +263,32 @@ pub enum CursorIcon {
// Resizing in one direction:
/// Resize something rightwards (e.g. when dragging the right-most edge of something)
ResizeEast,
/// Resize something down and right (e.g. when dragging the bottom-right corner of something)
ResizeSouthEast,
/// Resize something downwards (e.g. when dragging the bottom edge of something)
ResizeSouth,
/// Resize something down and left (e.g. when dragging the bottom-left corner of something)
ResizeSouthWest,
/// Resize something leftwards (e.g. when dragging the left edge of something)
ResizeWest,
/// Resize something up and left (e.g. when dragging the top-left corner of something)
ResizeNorthWest,
/// Resize something up (e.g. when dragging the top edge of something)
ResizeNorth,
/// Resize something up and right (e.g. when dragging the top-right corner of something)
ResizeNorthEast,
// ------------------------------------
/// Resize a column
ResizeColumn,
/// Resize a row
ResizeRow,
@@ -283,6 +296,7 @@ pub enum CursorIcon {
// Zooming:
/// Enhance!
ZoomIn,
/// Let's get a better overview
ZoomOut,
}
@@ -339,17 +353,22 @@ impl Default for CursorIcon {
#[derive(Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum OutputEvent {
// A widget was clicked.
/// A widget was clicked.
Clicked(WidgetInfo),
// A widget was double-clicked.
/// A widget was double-clicked.
DoubleClicked(WidgetInfo),
// A widget was triple-clicked.
/// A widget was triple-clicked.
TripleClicked(WidgetInfo),
/// A widget gained keyboard focus (by tab key).
FocusGained(WidgetInfo),
// Text selection was updated.
/// Text selection was updated.
TextSelectionChanged(WidgetInfo),
// A widget's value changed.
/// A widget's value changed.
ValueChanged(WidgetInfo),
}
@@ -372,19 +391,26 @@ impl std::fmt::Debug for OutputEvent {
pub struct WidgetInfo {
/// The type of widget this is.
pub typ: WidgetType,
// Whether the widget is enabled.
/// Whether the widget is enabled.
pub enabled: bool,
/// The text on labels, buttons, checkboxes etc.
pub label: Option<String>,
/// The contents of some editable text (for [`TextEdit`](crate::TextEdit) fields).
pub current_text_value: Option<String>,
// The previous text value.
/// The previous text value.
pub prev_text_value: Option<String>,
/// The current value of checkboxes and radio buttons.
pub selected: Option<bool>,
/// The current value of sliders etc.
pub value: Option<f64>,
// Selected range of characters in [`Self::current_text_value`].
/// Selected range of characters in [`Self::current_text_value`].
pub text_selection: Option<std::ops::RangeInclusive<usize>>,
}

View File

@@ -110,6 +110,7 @@ impl GridLayout {
.col_width(col)
.unwrap_or(self.min_cell_size.x)
}
fn prev_row_height(&self, row: usize) -> f32 {
self.prev_state
.row_height(row)

View File

@@ -91,9 +91,11 @@ impl std::hash::Hasher for IdHasher {
fn write_u8(&mut self, _n: u8) {
unreachable!("Invalid use of IdHasher");
}
fn write_u16(&mut self, _n: u16) {
unreachable!("Invalid use of IdHasher");
}
fn write_u32(&mut self, _n: u32) {
unreachable!("Invalid use of IdHasher");
}
@@ -110,15 +112,19 @@ impl std::hash::Hasher for IdHasher {
fn write_i8(&mut self, _n: i8) {
unreachable!("Invalid use of IdHasher");
}
fn write_i16(&mut self, _n: i16) {
unreachable!("Invalid use of IdHasher");
}
fn write_i32(&mut self, _n: i32) {
unreachable!("Invalid use of IdHasher");
}
fn write_i64(&mut self, _n: i64) {
unreachable!("Invalid use of IdHasher");
}
fn write_isize(&mut self, _n: isize) {
unreachable!("Invalid use of IdHasher");
}

View File

@@ -399,6 +399,7 @@ impl Click {
pub fn is_double(&self) -> bool {
self.count == 2
}
pub fn is_triple(&self) -> bool {
self.count == 3
}
@@ -418,9 +419,11 @@ impl PointerEvent {
pub fn is_press(&self) -> bool {
matches!(self, PointerEvent::Pressed { .. })
}
pub fn is_release(&self) -> bool {
matches!(self, PointerEvent::Released(_))
}
pub fn is_click(&self) -> bool {
matches!(self, PointerEvent::Released(Some(_click)))
}

View File

@@ -68,6 +68,7 @@ pub(crate) struct TouchState {
/// Technical identifier of the touch device. This is used to identify relevant touch events
/// for this [`TouchState`] instance.
device_id: TouchDeviceId,
/// Active touches, if any.
///
/// TouchId is the unique identifier of the touch. It is valid as long as the finger/pen touches the surface. The
@@ -75,6 +76,7 @@ pub(crate) struct TouchState {
///
/// Refer to [`ActiveTouch`].
active_touches: BTreeMap<TouchId, ActiveTouch>,
/// If a gesture has been recognized (i.e. when exactly two fingers touch the surface), this
/// holds state information
gesture_state: Option<GestureState>,
@@ -107,6 +109,7 @@ struct DynGestureState {
struct ActiveTouch {
/// Current position of this touch, in device coordinates (not necessarily screen position)
pos: Pos2,
/// Current force of the touch. A value in the interval [0.0 .. 1.0]
///
/// Note that a value of 0.0 either indicates a very light touch, or it means that the device

View File

@@ -10,16 +10,21 @@ use epaint::{ClippedShape, Shape};
pub enum Order {
/// Painted behind all floating windows
Background,
/// Special layer between panels and windows
PanelResizeLine,
/// Normal moveable windows that you reorder by click
Middle,
/// Popups, menus etc that should always be painted on top of windows
/// Foreground objects can also have tooltips
Foreground,
/// Things floating on top of everything else, like tooltips.
/// You cannot interact with these.
Tooltip,
/// Debug layer, always painted last / on top
Debug,
}

View File

@@ -479,15 +479,19 @@ macro_rules! egui_assert {
pub mod special_emojis {
/// Tux, the Linux penguin.
pub const OS_LINUX: char = '🐧';
/// The Windows logo.
pub const OS_WINDOWS: char = '';
/// The Android logo.
pub const OS_ANDROID: char = '';
/// The Apple logo.
pub const OS_APPLE: char = '';
/// The Github logo.
pub const GITHUB: char = '';
/// The Twitter bird.
pub const TWITTER: char = '';

View File

@@ -49,12 +49,15 @@ impl BarState {
self.open_menu.show(response, add_contents)
}
}
impl std::ops::Deref for BarState {
type Target = MenuRootManager;
fn deref(&self) -> &Self::Target {
&self.open_menu
}
}
impl std::ops::DerefMut for BarState {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.open_menu
@@ -194,6 +197,7 @@ pub(crate) fn context_menu(
pub(crate) struct MenuRootManager {
inner: Option<MenuRoot>,
}
impl MenuRootManager {
/// Show a menu at pointer if right-clicked response.
/// Should be called from [`Context`] on a [`Response`]
@@ -212,16 +216,20 @@ impl MenuRootManager {
None
}
}
fn is_menu_open(&self, id: Id) -> bool {
self.inner.as_ref().map(|m| m.id) == Some(id)
}
}
impl std::ops::Deref for MenuRootManager {
type Target = Option<MenuRoot>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl std::ops::DerefMut for MenuRootManager {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
@@ -242,6 +250,7 @@ impl MenuRoot {
id,
}
}
pub fn show<R>(
&mut self,
response: &Response,
@@ -349,22 +358,26 @@ impl MenuRoot {
Self::handle_menu_response(root, menu_response);
}
}
#[derive(Copy, Clone, PartialEq)]
pub(crate) enum MenuResponse {
Close,
Stay,
Create(Pos2, Id),
}
impl MenuResponse {
pub fn is_close(&self) -> bool {
*self == Self::Close
}
}
pub struct SubMenuButton {
text: WidgetText,
icon: WidgetText,
index: usize,
}
impl SubMenuButton {
/// The `icon` can be an emoji (e.g. `⏵` right arrow), shown right of the label
fn new(text: impl Into<WidgetText>, icon: impl Into<WidgetText>, index: usize) -> Self {
@@ -442,10 +455,12 @@ impl SubMenuButton {
response
}
}
pub struct SubMenu {
button: SubMenuButton,
parent_state: Arc<RwLock<MenuState>>,
}
impl SubMenu {
fn new(parent_state: Arc<RwLock<MenuState>>, text: impl Into<WidgetText>) -> Self {
let index = parent_state.write().next_entry_index();
@@ -472,16 +487,21 @@ impl SubMenu {
InnerResponse::new(inner, button)
}
}
pub(crate) struct MenuState {
/// The opened sub-menu and its [`Id`]
sub_menu: Option<(Id, Arc<RwLock<MenuState>>)>,
/// Bounding box of this menu (without the sub-menu)
pub rect: Rect,
/// Used to check if any menu in the tree wants to close
pub response: MenuResponse,
/// Used to hash different [`Id`]s for sub-menus
entry_count: usize,
}
impl MenuState {
pub fn new(position: Pos2) -> Self {
Self {
@@ -491,10 +511,12 @@ impl MenuState {
entry_count: 0,
}
}
/// Close menu hierarchy.
pub fn close(&mut self) {
self.response = MenuResponse::Close;
}
pub fn show<R>(
ctx: &Context,
menu_state: &Arc<RwLock<Self>>,
@@ -503,6 +525,7 @@ impl MenuState {
) -> InnerResponse<R> {
crate::menu::menu_ui(ctx, id, menu_state, add_contents)
}
fn show_submenu<R>(
&mut self,
ctx: &Context,
@@ -516,6 +539,7 @@ impl MenuState {
self.cascade_close_response(sub_response);
Some(response)
}
/// Check if position is in the menu hierarchy's area.
pub fn area_contains(&self, pos: Pos2) -> bool {
self.rect.contains(pos)
@@ -524,10 +548,12 @@ impl MenuState {
.as_ref()
.map_or(false, |(_, sub)| sub.read().area_contains(pos))
}
fn next_entry_index(&mut self) -> usize {
self.entry_count += 1;
self.entry_count - 1
}
/// Sense button interaction opening and closing submenu.
fn submenu_button_interaction(&mut self, ui: &mut Ui, sub_id: Id, button: &Response) {
let pointer = &ui.input().pointer.clone();
@@ -542,6 +568,7 @@ impl MenuState {
self.close_submenu();
}
}
/// Check if `dir` points from `pos` towards left side of `rect`.
fn points_at_left_of_rect(pos: Pos2, dir: Vec2, rect: Rect) -> bool {
let vel_a = dir.angle();
@@ -549,6 +576,7 @@ impl MenuState {
let bottom_a = (rect.left_bottom() - pos).angle();
bottom_a - vel_a >= 0.0 && top_a - vel_a <= 0.0
}
/// Check if pointer is moving towards current submenu.
fn moving_towards_current_submenu(&self, pointer: &PointerState) -> bool {
if pointer.is_still() {
@@ -561,6 +589,7 @@ impl MenuState {
}
false
}
/// Check if pointer is hovering current submenu.
fn hovering_current_submenu(&self, pointer: &PointerState) -> bool {
if let Some(sub_menu) = self.get_current_submenu() {
@@ -570,32 +599,39 @@ impl MenuState {
}
false
}
/// Cascade close response to menu root.
fn cascade_close_response(&mut self, response: MenuResponse) {
if response.is_close() {
self.response = response;
}
}
fn is_open(&self, id: Id) -> bool {
self.get_sub_id() == Some(id)
}
fn get_sub_id(&self) -> Option<Id> {
self.sub_menu.as_ref().map(|(id, _)| *id)
}
fn get_current_submenu(&self) -> Option<&Arc<RwLock<MenuState>>> {
self.sub_menu.as_ref().map(|(_, sub)| sub)
}
fn get_submenu(&mut self, id: Id) -> Option<&Arc<RwLock<MenuState>>> {
self.sub_menu
.as_ref()
.and_then(|(k, sub)| if id == *k { Some(sub) } else { None })
}
/// Open submenu at position, if not already open.
fn open_submenu(&mut self, id: Id, pos: Pos2) {
if !self.is_open(id) {
self.sub_menu = Some((id, Arc::new(RwLock::new(MenuState::new(pos)))));
}
}
fn close_submenu(&mut self) {
self.sub_menu = None;
}

View File

@@ -603,6 +603,7 @@ impl Response {
/// Now `draw_vec2(ui, foo).hovered` is true if either [`DragValue`](crate::DragValue) were hovered.
impl std::ops::BitOr for Response {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
self.union(rhs)
}
@@ -644,6 +645,7 @@ impl std::ops::BitOrAssign for Response {
pub struct InnerResponse<R> {
/// What the user closure returned.
pub inner: R,
/// The response of the area.
pub response: Response,
}

View File

@@ -367,6 +367,7 @@ impl From<Vec2> for Margin {
impl std::ops::Add for Margin {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
left: self.left + other.left,
@@ -524,12 +525,16 @@ pub struct Widgets {
/// * `noninteractive.bg_fill` is the background color of windows.
/// * `noninteractive.fg_stroke` is the normal text color.
pub noninteractive: WidgetVisuals,
/// The style of an interactive widget, such as a button, at rest.
pub inactive: WidgetVisuals,
/// The style of an interactive widget while you hover it.
pub hovered: WidgetVisuals,
/// The style of an interactive widget as you are clicking or dragging it.
pub active: WidgetVisuals,
/// The style of a button that has an open menu beneath it (e.g. a combo-box)
pub open: WidgetVisuals,
}
@@ -721,6 +726,7 @@ impl Selection {
stroke: Stroke::new(1.0, Color32::from_rgb(192, 222, 255)),
}
}
fn light() -> Self {
Self {
bg_fill: Color32::from_rgb(144, 209, 255),

View File

@@ -78,10 +78,12 @@ enum Element {
#[cfg(feature = "persistence")]
serialize_fn: Option<Serializer>,
},
/// A serialized value
Serialized {
/// The type of value we are storing.
type_id: TypeId,
/// The ron data we can deserialize.
ron: Arc<str>,
},
@@ -512,6 +514,7 @@ impl PersistedMap {
.collect(),
)
}
fn into_map(self) -> IdTypeMap {
IdTypeMap(
self.0

View File

@@ -94,6 +94,7 @@ pub trait WidgetWithState {
pub fn reset_button<T: Default + PartialEq>(ui: &mut Ui, value: &mut T) {
reset_button_with(ui, value, T::default());
}
/// Show a button to reset a value to its default.
/// The button is only enabled if the value does not already have its original value.
pub fn reset_button_with<T: PartialEq>(ui: &mut Ui, value: &mut T, reset_value: T) {

View File

@@ -33,12 +33,19 @@ pub(super) struct PlotConfig<'a> {
/// Trait shared by things that can be drawn in the plot.
pub(super) trait PlotItem {
fn get_shapes(&self, ui: &mut Ui, transform: &ScreenTransform, shapes: &mut Vec<Shape>);
fn initialize(&mut self, x_range: RangeInclusive<f64>);
fn name(&self) -> &str;
fn color(&self) -> Color32;
fn highlight(&mut self);
fn highlighted(&self) -> bool;
fn geometry(&self) -> PlotGeometry<'_>;
fn get_bounds(&self) -> PlotBounds;
fn find_closest(&self, point: Pos2, transform: &ScreenTransform) -> Option<ClosestElem> {

View File

@@ -6,7 +6,9 @@ use epaint::{Color32, Rgba, Stroke};
/// Trait that abstracts from rectangular 'Value'-like elements, such as bars or boxes
pub(super) trait RectElement {
fn name(&self) -> &str;
fn bounds_min(&self) -> PlotPoint;
fn bounds_max(&self) -> PlotPoint;
fn bounds(&self) -> PlotBounds {

View File

@@ -12,6 +12,7 @@ pub struct PlotPoint {
/// This is often something monotonically increasing, such as time, but doesn't have to be.
/// Goes from left to right.
pub x: f64,
/// Goes from bottom to top (inverse of everything else in egui!).
pub y: f64,
}

View File

@@ -167,10 +167,13 @@ impl PlotBounds {
pub(crate) struct ScreenTransform {
/// The screen rectangle.
frame: Rect,
/// The plot bounds.
bounds: PlotBounds,
/// Whether to always center the x-range of the bounds.
x_centered: bool,
/// Whether to always center the y-range of the bounds.
y_centered: bool,
}

View File

@@ -27,9 +27,11 @@ fn set(get_set_value: &mut GetSetValue<'_>, value: f64) {
#[derive(Clone)]
struct SliderSpec {
logarithmic: bool,
/// For logarithmic sliders, the smallest positive value we are interested in.
/// 1 for integer sliders, maybe 1e-6 for others.
smallest_positive: f64,
/// 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.