Skip to content

Commit

Permalink
Merge branch 'master' into emilk/tweak-fonts
Browse files Browse the repository at this point in the history
  • Loading branch information
emilk committed Sep 18, 2024
2 parents 09600d8 + e31b44f commit 861df4f
Show file tree
Hide file tree
Showing 20 changed files with 231 additions and 81 deletions.
18 changes: 12 additions & 6 deletions crates/egui/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2424,12 +2424,18 @@ impl Context {

self.write(|ctx| {
let tessellation_options = ctx.memory.options.tessellation_options;
let texture_atlas = ctx
.fonts
.get(&pixels_per_point.into())
.expect("tessellate called with a different pixels_per_point than the font atlas was created with. \
You should use egui::FullOutput::pixels_per_point when tessellating.")
.texture_atlas();
let texture_atlas = if let Some(fonts) = ctx.fonts.get(&pixels_per_point.into()) {
fonts.texture_atlas()
} else {
#[cfg(feature = "log")]
log::warn!("No font size matching {pixels_per_point} pixels per point found.");
ctx.fonts
.iter()
.next()
.expect("No fonts loaded")
.1
.texture_atlas()
};
let (font_tex_size, prepared_discs) = {
let atlas = texture_atlas.lock();
(atlas.size(), atlas.prepared_discs())
Expand Down
6 changes: 6 additions & 0 deletions crates/egui/src/layers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,12 @@ impl PaintList {
/// and then later setting it using `paint_list.set(idx, cr, frame);`.
#[inline(always)]
pub fn set(&mut self, idx: ShapeIdx, clip_rect: Rect, shape: Shape) {
if self.0.len() <= idx.0 {
#[cfg(feature = "log")]
log::warn!("Index {} is out of bounds for PaintList", idx.0);
return;
}

self.0[idx.0] = ClippedShape { clip_rect, shape };
}

Expand Down
6 changes: 2 additions & 4 deletions crates/egui/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -660,8 +660,6 @@ impl Layout {
let rect = self.align_size_within_rect(size, frame);
debug_assert!(!rect.any_nan());
debug_assert!(!rect.is_negative());
debug_assert!((rect.width() - size.x).abs() < 1.0 || size.x == f32::INFINITY);
debug_assert!((rect.height() - size.y).abs() < 1.0 || size.y == f32::INFINITY);
rect
}

Expand Down Expand Up @@ -767,7 +765,7 @@ impl Layout {

/// Move to the next row in a wrapping layout.
/// Otherwise does nothing.
pub(crate) fn end_row(&mut self, region: &mut Region, spacing: Vec2) {
pub(crate) fn end_row(&self, region: &mut Region, spacing: Vec2) {
if self.main_wrap {
match self.main_dir {
Direction::LeftToRight => {
Expand All @@ -790,7 +788,7 @@ impl Layout {
}

/// Set row height in horizontal wrapping layout.
pub(crate) fn set_row_height(&mut self, region: &mut Region, height: f32) {
pub(crate) fn set_row_height(&self, region: &mut Region, height: f32) {
if self.main_wrap && self.is_horizontal() {
region.cursor.max.y = region.cursor.min.y + height;
}
Expand Down
15 changes: 8 additions & 7 deletions crates/egui/src/memory/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,8 @@ impl Options {
impl Options {
/// Show the options in the ui.
pub fn ui(&mut self, ui: &mut crate::Ui) {
let theme = self.theme();

let Self {
dark_style, // covered above
light_style,
Expand All @@ -383,6 +385,7 @@ impl Options {
reduce_texture_memory,
} = self;

use crate::containers::CollapsingHeader;
use crate::Widget as _;

CollapsingHeader::new("⚙ Options")
Expand All @@ -408,18 +411,16 @@ impl Options {
ui.checkbox(reduce_texture_memory, "Reduce texture memory");
});

use crate::containers::CollapsingHeader;
CollapsingHeader::new("🎑 Style")
.default_open(true)
.show(ui, |ui| {
theme_preference.radio_buttons(ui);

CollapsingHeader::new("Dark")
.default_open(true)
.show(ui, |ui| std::sync::Arc::make_mut(dark_style).ui(ui));
CollapsingHeader::new("Light")
.default_open(true)
.show(ui, |ui| std::sync::Arc::make_mut(light_style).ui(ui));
std::sync::Arc::make_mut(match theme {
Theme::Dark => dark_style,
Theme::Light => light_style,
})
.ui(ui);
});

CollapsingHeader::new("✒ Painting")
Expand Down
4 changes: 2 additions & 2 deletions crates/egui/src/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ impl MenuRoot {
}

pub fn show<R>(
&mut self,
&self,
button: &Response,
add_contents: impl FnOnce(&mut Ui) -> R,
) -> (MenuResponse, Option<InnerResponse<R>>) {
Expand Down Expand Up @@ -759,7 +759,7 @@ impl MenuState {
self.sub_menu.as_ref().map(|(_, sub)| sub)
}

fn submenu(&mut self, id: Id) -> Option<&Arc<RwLock<Self>>> {
fn submenu(&self, id: Id) -> Option<&Arc<RwLock<Self>>> {
self.sub_menu
.as_ref()
.and_then(|(k, sub)| if id == *k { Some(sub) } else { None })
Expand Down
6 changes: 6 additions & 0 deletions crates/egui/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ pub struct Response {
///
/// e.g. the slider was dragged, text was entered in a [`TextEdit`](crate::TextEdit) etc.
/// Always `false` for something like a [`Button`](crate::Button).
///
/// Note that this can be `true` even if the user did not interact with the widget,
/// for instance if an existing slider value was clamped to the given range.
#[doc(hidden)]
pub changed: bool,
}
Expand Down Expand Up @@ -496,6 +499,9 @@ impl Response {
///
/// This is not set if the *view* of the data was changed.
/// For instance, moving the cursor in a [`TextEdit`](crate::TextEdit) does not set this to `true`.
///
/// Note that this can be `true` even if the user did not interact with the widget,
/// for instance if an existing slider value was clamped to the given range.
#[inline(always)]
pub fn changed(&self) -> bool {
self.changed
Expand Down
2 changes: 2 additions & 0 deletions crates/egui/src/text_selection/visuals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ pub fn paint_text_selection(
mesh.indices[glyph_index_start..glyph_index_start + 6]
.clone_from_slice(&selection_triangles);

row.visuals.mesh_bounds = mesh.calc_bounds();

if let Some(new_vertex_indices) = &mut new_vertex_indices {
new_vertex_indices.push(RowVertexIndices {
row: ri,
Expand Down
83 changes: 61 additions & 22 deletions crates/egui/src/widgets/drag_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub struct DragValue<'a> {
prefix: String,
suffix: String,
range: RangeInclusive<f64>,
clamp_to_range: bool,
clamp_existing_to_range: bool,
min_decimals: usize,
max_decimals: Option<usize>,
custom_formatter: Option<NumFormatter<'a>>,
Expand Down Expand Up @@ -72,7 +72,7 @@ impl<'a> DragValue<'a> {
prefix: Default::default(),
suffix: Default::default(),
range: f64::NEG_INFINITY..=f64::INFINITY,
clamp_to_range: true,
clamp_existing_to_range: true,
min_decimals: 0,
max_decimals: None,
custom_formatter: None,
Expand All @@ -93,35 +93,75 @@ impl<'a> DragValue<'a> {
/// Sets valid range for the value.
///
/// By default all values are clamped to this range, even when not interacted with.
/// You can change this behavior by passing `false` to [`crate::Slider::clamp_to_range`].
/// You can change this behavior by passing `false` to [`Self::clamp_existing_to_range`].
#[deprecated = "Use `range` instead"]
#[inline]
pub fn clamp_range<Num: emath::Numeric>(mut self, range: RangeInclusive<Num>) -> Self {
self.range = range.start().to_f64()..=range.end().to_f64();
self
pub fn clamp_range<Num: emath::Numeric>(self, range: RangeInclusive<Num>) -> Self {
self.range(range)
}

/// Sets valid range for dragging the value.
///
/// By default all values are clamped to this range, even when not interacted with.
/// You can change this behavior by passing `false` to [`crate::Slider::clamp_to_range`].
/// You can change this behavior by passing `false` to [`Self::clamp_existing_to_range`].
#[inline]
pub fn range<Num: emath::Numeric>(mut self, range: RangeInclusive<Num>) -> Self {
self.range = range.start().to_f64()..=range.end().to_f64();
self
}

/// If set to `true`, all incoming and outgoing values will be clamped to the sliding [`Self::range`] (if any).
/// If set to `true`, existing values will be clamped to [`Self::range`].
///
/// If set to `false`, a value outside of the range that is set programmatically or by user input will not be changed.
/// Dragging will be restricted to the range regardless of this setting.
/// Default: `true`.
/// If `false`, only values entered by the user (via dragging or text editing)
/// will be clamped to the range.
///
/// ### Without calling `range`
/// ```
/// # egui::__run_test_ui(|ui| {
/// let mut my_value: f32 = 1337.0;
/// ui.add(egui::DragValue::new(&mut my_value));
/// assert_eq!(my_value, 1337.0, "No range, no clamp");
/// # });
/// ```
///
/// ### With `.clamp_existing_to_range(true)` (default)
/// ```
/// # egui::__run_test_ui(|ui| {
/// let mut my_value: f32 = 1337.0;
/// ui.add(egui::DragValue::new(&mut my_value).range(0.0..=1.0));
/// assert!(0.0 <= my_value && my_value <= 1.0, "Existing values should be clamped");
/// # });
/// ```
///
/// ### With `.clamp_existing_to_range(false)`
/// ```
/// # egui::__run_test_ui(|ui| {
/// let mut my_value: f32 = 1337.0;
/// let response = ui.add(
/// egui::DragValue::new(&mut my_value).range(0.0..=1.0)
/// .clamp_existing_to_range(false)
/// );
/// if response.dragged() {
/// // The user edited the value, so it should be clamped to the range
/// assert!(0.0 <= my_value && my_value <= 1.0);
/// } else {
/// // The user didn't edit, so our original value should still be here:
/// assert_eq!(my_value, 1337.0);
/// }
/// # });
/// ```
#[inline]
pub fn clamp_to_range(mut self, clamp_to_range: bool) -> Self {
self.clamp_to_range = clamp_to_range;
pub fn clamp_existing_to_range(mut self, clamp_existing_to_range: bool) -> Self {
self.clamp_existing_to_range = clamp_existing_to_range;
self
}

#[inline]
#[deprecated = "Renamed clamp_existing_to_range"]
pub fn clamp_to_range(self, clamp_to_range: bool) -> Self {
self.clamp_existing_to_range(clamp_to_range)
}

/// Show a prefix before the number, e.g. "x: "
#[inline]
pub fn prefix(mut self, prefix: impl ToString) -> Self {
Expand Down Expand Up @@ -392,7 +432,7 @@ impl<'a> Widget for DragValue<'a> {
mut get_set_value,
speed,
range,
clamp_to_range,
clamp_existing_to_range,
prefix,
suffix,
min_decimals,
Expand Down Expand Up @@ -470,7 +510,7 @@ impl<'a> Widget for DragValue<'a> {
});
}

if clamp_to_range {
if clamp_existing_to_range {
value = clamp_value_to_range(value, range.clone());
}

Expand Down Expand Up @@ -501,9 +541,8 @@ impl<'a> Widget for DragValue<'a> {
// Make sure we applied the last text value:
let parsed_value = parse(&custom_parser, &value_text);
if let Some(mut parsed_value) = parsed_value {
if clamp_to_range {
parsed_value = clamp_value_to_range(parsed_value, range.clone());
}
// User edits always clamps:
parsed_value = clamp_value_to_range(parsed_value, range.clone());
set(&mut get_set_value, parsed_value);
}
}
Expand Down Expand Up @@ -537,9 +576,8 @@ impl<'a> Widget for DragValue<'a> {
if update {
let parsed_value = parse(&custom_parser, &value_text);
if let Some(mut parsed_value) = parsed_value {
if clamp_to_range {
parsed_value = clamp_value_to_range(parsed_value, range.clone());
}
// User edits always clamps:
parsed_value = clamp_value_to_range(parsed_value, range.clone());
set(&mut get_set_value, parsed_value);
}
}
Expand Down Expand Up @@ -699,7 +737,8 @@ fn default_parser(text: &str) -> Option<f64> {
text.parse().ok()
}

fn clamp_value_to_range(x: f64, range: RangeInclusive<f64>) -> f64 {
/// Clamp the given value with careful handling of negative zero, and other corner cases.
pub(crate) fn clamp_value_to_range(x: f64, range: RangeInclusive<f64>) -> f64 {
let (mut min, mut max) = (*range.start(), *range.end());

if min.total_cmp(&max) == Ordering::Greater {
Expand Down
2 changes: 1 addition & 1 deletion crates/egui/src/widgets/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub use self::{
radio_button::RadioButton,
selected_label::SelectableLabel,
separator::Separator,
slider::{Slider, SliderOrientation},
slider::{Slider, SliderClamping, SliderOrientation},
spinner::Spinner,
text_edit::{TextBuffer, TextEdit},
};
Expand Down
Loading

0 comments on commit 861df4f

Please sign in to comment.