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

Enable the clippy::std_instead_of_core lint (#8394)

Prefer `core::` over `std::` where either work

* Part of https://github.com/emilk/egui/issues/5735
This commit is contained in:
Emil Ernerfeldt
2026-08-06 04:19:13 -07:00
committed by GitHub
parent 2a5f3d99b5
commit 6aea7eff94
176 changed files with 633 additions and 615 deletions

View File

@@ -1,7 +1,7 @@
use crate::{AtomLayout, FontSelection, Image, ImageSource, SizedAtomKind, Ui, WidgetText};
use core::fmt::Debug;
use emath::Vec2;
use epaint::text::TextWrapMode;
use std::fmt::Debug;
/// Args passed when sizing an [`super::Atom`]
pub struct IntoSizedArgs {
@@ -90,7 +90,7 @@ impl Clone for AtomKind<'_> {
}
impl Debug for AtomKind<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
AtomKind::Empty => write!(f, "AtomKind::Empty"),
AtomKind::Text(text) => write!(f, "AtomKind::Text({text:?})"),

View File

@@ -2,11 +2,11 @@ use crate::{
AtomKind, Atoms, Direction, FontSelection, Frame, Id, Image, IntoAtoms, Response, Sense,
SizedAtom, SizedAtomKind, Stroke, Ui, Widget, text_selection::LabelSelectionState,
};
use core::ops::{Deref, DerefMut};
use emath::{Align2, GuiRounding as _, NumExt as _, Rect, Vec2};
use epaint::text::TextWrapMode;
use epaint::{Color32, Galley};
use smallvec::SmallVec;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
/// The `(main, cross)` axis indices for `direction`, for indexing a [`Vec2`] (0 = x, 1 = y).
@@ -557,7 +557,7 @@ impl<'atom> SizedAtomLayout<'atom> {
F: FnMut(SizedAtomKind<'atom>) -> SizedAtomKind<'atom>,
{
for kind in self.iter_kinds_mut() {
*kind = f(std::mem::take(kind));
*kind = f(core::mem::take(kind));
}
}

View File

@@ -1,6 +1,6 @@
use crate::{Atom, AtomKind, Image, WidgetText};
use core::ops::{Deref, DerefMut};
use std::borrow::Cow;
use std::ops::{Deref, DerefMut};
/// A list of [`Atom`]s.
///
@@ -41,7 +41,7 @@ impl<'a> Atoms<'a> {
///
/// If you have weird lifetime issues with this, use [`Self::push_left`] in a loop instead.
pub fn extend_left(&mut self, mut atoms: Self) {
std::mem::swap(&mut atoms.0, &mut self.0);
core::mem::swap(&mut atoms.0, &mut self.0);
self.0.extend(atoms.0);
}
@@ -128,7 +128,7 @@ impl<'a> Atoms<'a> {
pub fn map_atoms(&mut self, mut f: impl FnMut(Atom<'a>) -> Atom<'a>) {
self.iter_mut()
.for_each(|atom| *atom = f(std::mem::take(atom)));
.for_each(|atom| *atom = f(core::mem::take(atom)));
}
pub fn map_kind<F>(&mut self, mut f: F)
@@ -136,7 +136,7 @@ impl<'a> Atoms<'a> {
F: FnMut(AtomKind<'a>) -> AtomKind<'a>,
{
for kind in self.iter_kinds_mut() {
*kind = f(std::mem::take(kind));
*kind = f(core::mem::take(kind));
}
}

View File

@@ -23,18 +23,18 @@ use super::CacheTrait;
/// ```
#[derive(Default)]
pub struct CacheStorage {
caches: ahash::HashMap<std::any::TypeId, Box<dyn CacheTrait>>,
caches: ahash::HashMap<core::any::TypeId, Box<dyn CacheTrait>>,
}
impl CacheStorage {
pub fn cache<Cache: CacheTrait + Default>(&mut self) -> &mut Cache {
let cache = self
.caches
.entry(std::any::TypeId::of::<Cache>())
.entry(core::any::TypeId::of::<Cache>())
.or_insert_with(|| Box::<Cache>::default());
#[expect(clippy::unwrap_used)]
(cache.as_mut() as &mut dyn std::any::Any)
(cache.as_mut() as &mut dyn core::any::Any)
.downcast_mut::<Cache>()
.unwrap()
}
@@ -60,8 +60,8 @@ impl Clone for CacheStorage {
}
}
impl std::fmt::Debug for CacheStorage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for CacheStorage {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"FrameCacheStorage[{} caches with {} elements]",

View File

@@ -1,6 +1,6 @@
/// A cache, storing some value for some length of time.
#[expect(clippy::len_without_is_empty)]
pub trait CacheTrait: 'static + Send + Sync + std::any::Any {
pub trait CacheTrait: 'static + Send + Sync + core::any::Any {
/// Call once per frame to evict cache.
fn update(&mut self);

View File

@@ -48,7 +48,7 @@ impl<Value, Computer> FrameCache<Value, Computer> {
/// or recompute and store in the cache.
pub fn get<Key>(&mut self, key: Key) -> &Value
where
Key: Copy + std::hash::Hash,
Key: Copy + core::hash::Hash,
Computer: ComputerMut<Key, Value>,
{
let hash = crate::util::hash(key);

View File

@@ -1,4 +1,4 @@
use std::hash::Hash;
use core::hash::Hash;
use super::CacheTrait;

View File

@@ -1,4 +1,4 @@
use std::fmt::Write as _;
use core::fmt::Write as _;
#[derive(Clone)]
struct Frame {
@@ -239,7 +239,7 @@ fn test_shorten_path() {
),
("/weird/path/file.rs", "/weird/path/file.rs"),
] {
use std::str::FromStr as _;
use core::str::FromStr as _;
let before = std::path::PathBuf::from_str(before).unwrap();
assert_eq!(shorten_source_file_path(&before), after);
}

View File

@@ -1,6 +1,6 @@
#[expect(unused_imports)]
use crate::{Ui, UiBuilder};
use std::sync::atomic::AtomicBool;
use core::sync::atomic::AtomicBool;
/// A tag to mark a container as closable.
///
@@ -18,11 +18,12 @@ impl ClosableTag {
/// Set close to `true`
pub fn set_close(&self) {
self.close.store(true, std::sync::atomic::Ordering::Relaxed);
self.close
.store(true, core::sync::atomic::Ordering::Relaxed);
}
/// Returns `true` if [`ClosableTag::set_close`] has been called.
pub fn should_close(&self) -> bool {
self.close.load(std::sync::atomic::Ordering::Relaxed)
self.close.load(core::sync::atomic::Ordering::Relaxed)
}
}

View File

@@ -342,7 +342,7 @@ pub fn paint_default_icon(ui: &mut Ui, openness: f32, response: &Response) {
let rect = Rect::from_center_size(rect.center(), vec2(rect.width(), rect.height()) * 0.75);
let rect = rect.expand(visuals.expansion);
let mut points = vec![rect.left_top(), rect.right_top(), rect.center_bottom()];
use std::f32::consts::TAU;
use core::f32::consts::TAU;
let rotation = emath::Rot2::from_angle(remap(openness, 0.0..=1.0, -TAU / 4.0..=0.0));
for p in &mut points {
*p = rect.center() + rotation * (*p - rect.center());

View File

@@ -143,12 +143,12 @@ pub struct Frame {
#[test]
fn frame_size() {
assert_eq!(
std::mem::size_of::<Frame>(),
core::mem::size_of::<Frame>(),
32,
"Frame changed size! If it shrank - good! Update this test. If it grew - bad! Try to find a way to avoid it."
);
assert!(
std::mem::size_of::<Frame>() <= 64,
core::mem::size_of::<Frame>() <= 64,
"Frame is getting way too big!"
);
}

View File

@@ -1,4 +1,4 @@
use std::iter::once;
use core::iter::once;
use emath::{Align, Pos2, Rect, RectAlign, Vec2, vec2};
@@ -483,12 +483,12 @@ impl<'a> Popup<'a> {
RectAlign::find_best_align(
#[expect(clippy::iter_on_empty_collections)]
#[expect(clippy::or_fun_call)]
std::iter::chain(
core::iter::chain(
once(self.rect_align),
self.alternative_aligns
// Need the empty slice so the iters have the same type so we can unwrap_or
.map(|a| std::iter::chain(a.iter().copied(), [].iter().copied()))
.unwrap_or(std::iter::chain(
.map(|a| core::iter::chain(a.iter().copied(), [].iter().copied()))
.unwrap_or(core::iter::chain(
self.rect_align.symmetries().iter().copied(),
RectAlign::MENU_ALIGNS.iter().copied(),
)),

View File

@@ -2,7 +2,7 @@
#![expect(clippy::needless_range_loop)]
use std::ops::{Add, AddAssign, BitOr, BitOrAssign};
use core::ops::{Add, AddAssign, BitOr, BitOrAssign};
use emath::GuiRounding as _;
use epaint::{Color32, Direction, Margin, Shape};
@@ -930,7 +930,7 @@ impl ScrollArea {
let saved_scroll_target = content_ui
.ctx()
.pass_state_mut(|state| std::mem::take(&mut state.scroll_target));
.pass_state_mut(|state| core::mem::take(&mut state.scroll_target));
Prepared {
id,
@@ -985,7 +985,7 @@ impl ScrollArea {
ui: &mut Ui,
row_height_sans_spacing: f32,
total_rows: usize,
add_contents: impl FnOnce(&mut Ui, std::ops::Range<usize>) -> R,
add_contents: impl FnOnce(&mut Ui, core::ops::Range<usize>) -> R,
) -> ScrollAreaOutput<R> {
let spacing = ui.spacing().item_spacing;
let row_height_with_spacing = row_height_sans_spacing + spacing.y;
@@ -1093,7 +1093,7 @@ impl Prepared {
if direction_enabled[d] {
let (scroll_delta, scroll_animation) = content_ui.ctx().pass_state_mut(|state| {
(
std::mem::take(&mut state.scroll_delta.0[d]),
core::mem::take(&mut state.scroll_delta.0[d]),
state.scroll_delta.1,
)
});

View File

@@ -921,7 +921,7 @@ impl SideResponse {
}
}
impl std::ops::BitAnd for SideResponse {
impl core::ops::BitAnd for SideResponse {
type Output = Self;
fn bitand(self, rhs: Self) -> Self::Output {
@@ -932,7 +932,7 @@ impl std::ops::BitAnd for SideResponse {
}
}
impl std::ops::BitOrAssign for SideResponse {
impl core::ops::BitOrAssign for SideResponse {
fn bitor_assign(&mut self, rhs: Self) {
*self = Self {
hover: self.hover || rhs.hover,

View File

@@ -1,6 +1,7 @@
#![warn(missing_docs)] // Let's keep `Context` well-documented.
use std::{borrow::Cow, cell::RefCell, panic::Location, sync::Arc, time::Duration};
use core::{cell::RefCell, panic::Location, time::Duration};
use std::{borrow::Cow, sync::Arc};
use emath::GuiRounding as _;
use epaint::{
@@ -98,7 +99,7 @@ impl ContextImpl {
fn begin_pass_repaint_logic(&mut self, viewport_id: ViewportId) {
let viewport = self.viewports.entry(viewport_id).or_default();
std::mem::swap(
core::mem::swap(
&mut viewport.repaint.prev_causes,
&mut viewport.repaint.causes,
);
@@ -264,14 +265,14 @@ pub struct RepaintCause {
pub reason: Cow<'static, str>,
}
impl std::fmt::Debug for RepaintCause {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for RepaintCause {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}:{} {}", self.file, self.line, self.reason)
}
}
impl std::fmt::Display for RepaintCause {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Display for RepaintCause {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}:{} {}", self.file, self.line, self.reason)
}
}
@@ -459,7 +460,7 @@ impl ContextImpl {
self.memory.begin_pass(&new_raw_input, &all_viewport_ids);
viewport.input = std::mem::take(&mut viewport.input).begin_pass(
viewport.input = core::mem::take(&mut viewport.input).begin_pass(
new_raw_input,
viewport.repaint.requested_immediate_repaint_prev_pass(),
pixels_per_point,
@@ -653,7 +654,7 @@ impl ContextImpl {
}
fn all_viewport_ids(&self) -> ViewportIdSet {
std::iter::chain(self.viewports.keys().copied(), [ViewportId::ROOT]).collect()
core::iter::chain(self.viewports.keys().copied(), [ViewportId::ROOT]).collect()
}
/// The current active viewport
@@ -721,13 +722,13 @@ impl ContextImpl {
#[derive(Clone)]
pub struct Context(Arc<RwLock<ContextImpl>>);
impl std::fmt::Debug for Context {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for Context {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Context").finish_non_exhaustive()
}
}
impl std::cmp::PartialEq for Context {
impl core::cmp::PartialEq for Context {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
@@ -737,7 +738,7 @@ impl Default for Context {
fn default() -> Self {
let ctx_impl = ContextImpl {
embed_viewports: true,
viewports: std::iter::once((ViewportId::ROOT, ViewportState::default())).collect(),
viewports: core::iter::once((ViewportId::ROOT, ViewportState::default())).collect(),
..Default::default()
};
let ctx = Self(Arc::new(RwLock::new(ctx_impl)));
@@ -847,7 +848,7 @@ impl Context {
self.write(|ctx| {
let viewport = ctx.viewport_for(viewport_id);
viewport.output.num_completed_passes =
std::mem::take(&mut output.platform_output.num_completed_passes);
core::mem::take(&mut output.platform_output.num_completed_passes);
output.platform_output.request_discard_reasons.clear();
});
@@ -929,12 +930,12 @@ impl Context {
logic(self);
self.write(|ctx| LogicOutput {
platform_output: std::mem::take(&mut ctx.viewport_for(viewport_id).output),
platform_output: core::mem::take(&mut ctx.viewport_for(viewport_id).output),
viewport_commands: ctx
.viewports
.iter_mut()
.filter(|(_, viewport)| !viewport.commands.is_empty())
.map(|(&id, viewport)| (id, std::mem::take(&mut viewport.commands)))
.map(|(&id, viewport)| (id, core::mem::take(&mut viewport.commands)))
.collect(),
})
}
@@ -1875,7 +1876,7 @@ impl Context {
/// See [`Self::request_repaint_after`] for details.
#[track_caller]
pub fn request_repaint_after_secs(&self, seconds: f32) {
if let Ok(duration) = std::time::Duration::try_from_secs_f32(seconds) {
if let Ok(duration) = core::time::Duration::try_from_secs_f32(seconds) {
self.request_repaint_after(duration);
}
}
@@ -2058,7 +2059,7 @@ impl Context {
&self,
f: impl FnOnce(&mut T) -> R,
) -> Option<R> {
let plugin = self.read(|ctx| ctx.plugins.get(std::any::TypeId::of::<T>()));
let plugin = self.read(|ctx| ctx.plugins.get(core::any::TypeId::of::<T>()));
plugin.map(|plugin| f(plugin.lock().typed_plugin_mut()))
}
@@ -2070,13 +2071,13 @@ impl Context {
if let Some(plugin) = self.plugin_opt() {
plugin
} else {
panic!("Plugin of type {:?} not found", std::any::type_name::<T>());
panic!("Plugin of type {:?} not found", core::any::type_name::<T>());
}
}
/// Get a handle to the plugin of type `T`, if it was registered.
pub fn plugin_opt<T: plugin::Plugin>(&self) -> Option<TypedPluginHandle<T>> {
let plugin = self.read(|ctx| ctx.plugins.get(std::any::TypeId::of::<T>()));
let plugin = self.read(|ctx| ctx.plugins.get(core::any::TypeId::of::<T>()));
plugin.map(TypedPluginHandle::new)
}
@@ -2499,7 +2500,7 @@ impl Context {
#[cfg(debug_assertions)]
fn debug_painting(&self) {
#![expect(clippy::iter_over_hash_type)] // ok to be sloppy in debug painting
use std::fmt::Write as _;
use core::fmt::Write as _;
let paint_widget = |widget: &WidgetRect, text: &str, color: Color32| {
let rect = widget.interact_rect;
@@ -2680,7 +2681,7 @@ impl ContextImpl {
// Inform the backend of all textures that have been updated (including font atlas).
let textures_delta = self.tex_manager.0.write().take_delta();
let mut platform_output: PlatformOutput = std::mem::take(&mut viewport.output);
let mut platform_output: PlatformOutput = core::mem::take(&mut viewport.output);
if self.memory.should_interrupt_ime()
&& let Some(ime) = &mut platform_output.ime
@@ -2740,7 +2741,7 @@ impl ContextImpl {
shapes
};
std::mem::swap(&mut viewport.prev_pass, &mut viewport.this_pass);
core::mem::swap(&mut viewport.prev_pass, &mut viewport.this_pass);
if repaint_needed {
self.request_repaint(ended_viewport_id, RepaintCause::new());
@@ -2802,7 +2803,7 @@ impl ContextImpl {
// Let the primary immediate viewport handle the commands of its children too.
// This can make things easier for the backend, as otherwise we may get commands
// that affect a viewport while its egui logic is running.
std::mem::take(&mut viewport.commands)
core::mem::take(&mut viewport.commands)
} else {
vec![]
};
@@ -4287,13 +4288,13 @@ fn warn_if_rect_changes_id(
struct OrderedRect(Rect);
impl PartialOrd for OrderedRect {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for OrderedRect {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
let lhs = self.0;
let rhs = other.0;
lhs.min

View File

@@ -1,13 +1,13 @@
use std::{path::Path, sync::Arc};
#[cfg(target_arch = "wasm32")]
use std::{future::Future, pin::Pin};
use core::{future::Future, pin::Pin};
/// A file dropped into egui.
///
/// The integration owns the concrete file handle, letting egui remain independent of windowing
/// backends and file APIs.
pub trait DroppedFile: std::fmt::Debug {
pub trait DroppedFile: core::fmt::Debug {
/// The path of the dropped file.
///
/// This is an absolute path on native platforms. On the web, it is a relative path containing

View File

@@ -14,7 +14,7 @@ pub enum ImeEvent {
/// a non-empty preedit string indicates that the IME is active.
Preedit {
text: String,
active_range_chars: Option<std::ops::Range<usize>>,
active_range_chars: Option<core::ops::Range<usize>>,
},
/// IME composition ended with this final result.

View File

@@ -37,8 +37,8 @@ pub struct Modifiers {
pub command: bool,
}
impl std::fmt::Debug for Modifiers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for Modifiers {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if self.is_none() {
return write!(f, "Modifiers::NONE");
}
@@ -387,7 +387,7 @@ impl Modifiers {
}
}
impl std::ops::BitOr for Modifiers {
impl core::ops::BitOr for Modifiers {
type Output = Self;
#[inline]
@@ -396,7 +396,7 @@ impl std::ops::BitOr for Modifiers {
}
}
impl std::ops::BitOrAssign for Modifiers {
impl core::ops::BitOrAssign for Modifiers {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = *self | rhs;

View File

@@ -95,7 +95,7 @@ impl Default for RawInput {
fn default() -> Self {
Self {
viewport_id: ViewportId::ROOT,
viewports: std::iter::once((ViewportId::ROOT, Default::default())).collect(),
viewports: core::iter::once((ViewportId::ROOT, Default::default())).collect(),
screen_rect: None,
max_texture_side: None,
time: None,
@@ -134,9 +134,9 @@ impl RawInput {
max_texture_side: self.max_texture_side.take(),
time: self.time,
predicted_dt: self.predicted_dt,
events: std::mem::take(&mut self.events),
events: core::mem::take(&mut self.events),
hovered_files: self.hovered_files.clone(),
dropped_files: std::mem::take(&mut self.dropped_files),
dropped_files: core::mem::take(&mut self.dropped_files),
focused: self.focused,
system_theme: self.system_theme,
}

View File

@@ -10,7 +10,7 @@ use crate::emath::Rect;
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct SafeAreaInsets(pub MarginF32);
impl std::ops::Sub<SafeAreaInsets> for Rect {
impl core::ops::Sub<SafeAreaInsets> for Rect {
type Output = Self;
fn sub(self, rhs: SafeAreaInsets) -> Self::Output {

View File

@@ -117,7 +117,7 @@ impl ViewportInfo {
Self {
parent: self.parent,
title: self.title.clone(),
events: std::mem::take(&mut self.events),
events: core::mem::take(&mut self.events),
native_pixels_per_point: self.native_pixels_per_point,
monitor_size: self.monitor_size,
inner_rect: self.inner_rect,
@@ -209,7 +209,7 @@ impl ViewportInfo {
}
#[expect(clippy::ref_option)]
fn opt_as_str<T: std::fmt::Debug>(v: &Option<T>) -> String {
fn opt_as_str<T: core::fmt::Debug>(v: &Option<T>) -> String {
v.as_ref().map_or(String::new(), |v| format!("{v:?}"))
}
});

View File

@@ -1,6 +1,6 @@
//! All the data egui returns to the backend at the end of each frame.
use std::ops::Range;
use core::ops::Range;
use epaint::text::CharIndex;
@@ -242,7 +242,7 @@ impl PlatformOutput {
/// Take everything ephemeral (everything except `cursor_icon` and
/// `cursor_image` currently)
pub fn take(&mut self) -> Self {
let taken = std::mem::take(self);
let taken = core::mem::take(self);
self.cursor_icon = taken.cursor_icon; // sticky between frames
self.cursor_image = taken.cursor_image.clone(); // sticky between frames
taken
@@ -327,8 +327,8 @@ pub struct CustomCursorImage {
pub hotspot: [u16; 2],
}
impl std::fmt::Debug for CustomCursorImage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for CustomCursorImage {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("CustomCursorImage")
.field("size", &self.size)
.field("hotspot", &self.hotspot)
@@ -544,8 +544,8 @@ impl OutputEvent {
}
}
impl std::fmt::Debug for OutputEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for OutputEvent {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Clicked(wi) => write!(f, "Clicked({wi:?})"),
Self::DoubleClicked(wi) => write!(f, "DoubleClicked({wi:?})"),
@@ -591,8 +591,8 @@ pub struct WidgetInfo {
pub hint_text: Option<String>,
}
impl std::fmt::Debug for WidgetInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for WidgetInfo {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let Self {
typ,
enabled,

View File

@@ -1,4 +1,5 @@
use std::{any::Any, sync::Arc};
use core::any::Any;
use std::sync::Arc;
/// A wrapper around `dyn Any`, used for passing custom user data
/// to [`crate::ViewportCommand::Screenshot`].
@@ -30,8 +31,8 @@ impl PartialEq for UserData {
impl Eq for UserData {}
impl std::hash::Hash for UserData {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
impl core::hash::Hash for UserData {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.data.as_ref().map(Arc::as_ptr).hash(state);
}
}
@@ -57,7 +58,7 @@ impl<'de> serde::Deserialize<'de> for UserData {
impl serde::de::Visitor<'_> for UserDataVisitor {
type Value = UserData;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str("a None value")
}

View File

@@ -26,7 +26,7 @@ pub fn print(ctx: &Context, text: impl Into<WidgetText>) {
return;
}
let location = std::panic::Location::caller();
let location = core::panic::Location::caller();
let location = format!("{}:{}", location.file(), location.line());
let plugin = ctx.plugin::<DebugTextPlugin>();
@@ -58,7 +58,7 @@ impl Plugin for DebugTextPlugin {
}
fn on_end_pass(&mut self, ui: &mut Ui) {
let entries = std::mem::take(&mut self.entries);
let entries = core::mem::take(&mut self.entries);
Self::paint_entries(ui, entries);
}
}

View File

@@ -1,4 +1,5 @@
use std::{any::Any, sync::Arc};
use core::any::Any;
use std::sync::Arc;
use crate::{Context, CursorIcon, Plugin, Ui};

View File

@@ -1,6 +1,6 @@
// TODO(emilk): have separate types `PositionId` and `UniqueId`. ?
use std::num::NonZeroU64;
use core::num::NonZeroU64;
use crate::{AsIdSalt, IdSalt};
@@ -8,9 +8,9 @@ use crate::{AsIdSalt, IdSalt};
///
/// This is all types implementing `Hash` and `Debug`,
/// which includes things like string, integers, tuples of those, etc.
pub trait AsId: std::hash::Hash + std::fmt::Debug {}
pub trait AsId: core::hash::Hash + core::fmt::Debug {}
impl<T: std::hash::Hash + std::fmt::Debug> AsId for T {}
impl<T: core::hash::Hash + core::fmt::Debug> AsId for T {}
/// egui tracks widgets frame-to-frame using [`Id`]s.
///
@@ -75,7 +75,7 @@ impl Id {
/// Generate a child [`Id`] by salting the parent [`Id`] with the given argument.
pub fn with(self, salt: impl AsIdSalt) -> Self {
use std::hash::{BuildHasher as _, Hasher as _};
use core::hash::{BuildHasher as _, Hasher as _};
let mut hasher = ahash::RandomState::with_seeds(1, 2, 3, 4).build_hasher();
hasher.write_u64(self.value());
hasher.write_u64(IdSalt::new(&salt).value());
@@ -124,8 +124,8 @@ impl Id {
}
}
impl std::fmt::Debug for Id {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for Id {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if *self == Self::NULL {
return write!(f, "Id::NULL");
}
@@ -204,8 +204,8 @@ mod id_source {
#[test]
fn id_size() {
assert_eq!(std::mem::size_of::<Id>(), 8);
assert_eq!(std::mem::size_of::<Option<Id>>(), 8);
assert_eq!(core::mem::size_of::<Id>(), 8);
assert_eq!(core::mem::size_of::<Option<Id>>(), 8);
}
#[cfg(test)]

View File

@@ -1,12 +1,12 @@
use std::num::NonZeroU64;
use core::num::NonZeroU64;
/// Types that can be converted to an [`IdSalt`].
///
/// This is all types implementing `Hash` and `Debug`,
/// which includes things like string, integers, tuples of those, etc.
pub trait AsIdSalt: std::hash::Hash + std::fmt::Debug {}
pub trait AsIdSalt: core::hash::Hash + core::fmt::Debug {}
impl<T: std::hash::Hash + std::fmt::Debug> AsIdSalt for T {}
impl<T: core::hash::Hash + core::fmt::Debug> AsIdSalt for T {}
/// Uniquely identifies a child widget within a parent widget.
///
@@ -57,8 +57,8 @@ impl IdSalt {
}
}
impl std::fmt::Debug for IdSalt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for IdSalt {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
#[cfg(debug_assertions)]
if let Some(source) = id_salt_source::get(*self) {
return write!(f, "IdSalt::new({source})");

View File

@@ -13,10 +13,8 @@ use crate::{
},
input_state::wheel_state::WheelState,
};
use std::{
collections::{BTreeMap, HashSet},
time::Duration,
};
use core::time::Duration;
use std::collections::{BTreeMap, HashSet};
pub use crate::Key;
pub use touch_state::MultiTouchInfo;

View File

@@ -1,4 +1,5 @@
use std::{collections::BTreeMap, fmt::Debug};
use core::fmt::Debug;
use std::collections::BTreeMap;
use crate::{
Event, RawInput, TouchId, TouchPhase,
@@ -305,7 +306,7 @@ impl TouchState {
impl Debug for TouchState {
// This outputs less clutter than `#[derive(Debug)]`:
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
for (id, touch) in &self.active_touches {
f.write_fmt(format_args!("#{id:?}: {touch:#?}\n"))?;
}

View File

@@ -274,7 +274,7 @@ pub(crate) fn interact(
let drag_order = hits.drag.and_then(|w| order(w.id)).unwrap_or(0);
let top_interactive_order = click_order.max(drag_order);
let mut hovered: IdSet = std::iter::chain(&hits.click, &hits.drag)
let mut hovered: IdSet = core::iter::chain(&hits.click, &hits.drag)
.map(|w| w.id)
.collect();

View File

@@ -96,8 +96,8 @@ impl LayerId {
}
}
impl std::fmt::Debug for LayerId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for LayerId {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let Self { order, id } = self;
write!(f, "LayerId {{ {order:?} {id:?} }}")
}

View File

@@ -55,12 +55,11 @@
mod bytes_loader;
mod texture_loader;
use std::{
borrow::Cow,
use core::{
fmt::{Debug, Display},
ops::Deref,
sync::Arc,
};
use std::{borrow::Cow, sync::Arc};
use ahash::HashMap;
@@ -108,13 +107,13 @@ impl LoadError {
detected_format.as_ref().map_or(0, |s| s.len())
}
Self::Loading(message) => message.len(),
_ => std::mem::size_of::<Self>(),
_ => core::mem::size_of::<Self>(),
}
}
}
impl Display for LoadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::NoImageLoaders => f.write_str(
"No image loaders are installed. If you're trying to load some images \
@@ -136,9 +135,9 @@ impl Display for LoadError {
}
}
impl std::error::Error for LoadError {}
impl core::error::Error for LoadError {}
pub type Result<T, E = LoadError> = std::result::Result<T, E>;
pub type Result<T, E = LoadError> = core::result::Result<T, E>;
/// Given as a hint for image loading requests.
///
@@ -209,7 +208,7 @@ pub enum Bytes {
}
impl Debug for Bytes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Static(arg0) => f.debug_tuple("Static").field(&arg0.len()).finish(),
Self::Shared(arg0) => f.debug_tuple("Shared").field(&arg0.len()).finish(),
@@ -387,7 +386,7 @@ pub type ImageLoadResult = Result<ImagePoll>;
/// An `ImageLoader` decodes raw bytes into a [`ColorImage`].
///
/// Implementations are expected to cache at least each `URI`.
pub trait ImageLoader: std::any::Any {
pub trait ImageLoader: core::any::Any {
/// Unique ID of this loader.
///
/// To reduce the chance of collisions, include `module_path!()` as part of this ID.

View File

@@ -1,6 +1,6 @@
#![warn(missing_docs)] // Let's keep this file well-documented.` to memory.rs
use std::num::NonZeroUsize;
use core::num::NonZeroUsize;
use ahash::{HashMap, HashSet};
use epaint::emath::TSTransform;
@@ -942,7 +942,7 @@ impl Memory {
if let Some(modal_layer) = self.focus().and_then(|f| f.top_modal_layer) {
matches!(
self.areas().compare_order(layer_id, modal_layer),
std::cmp::Ordering::Equal | std::cmp::Ordering::Greater
core::cmp::Ordering::Equal | core::cmp::Ordering::Greater
)
} else {
true
@@ -982,7 +982,7 @@ impl Memory {
if let Some(current) = self.focus().and_then(|f| f.top_modal_layer_current_frame)
&& matches!(
self.areas().compare_order(layer_id, current),
std::cmp::Ordering::Less
core::cmp::Ordering::Less
)
{
return;
@@ -1223,12 +1223,12 @@ impl Areas {
/// Compare the order of two layers, based on the order list from last frame.
///
/// May return [`std::cmp::Ordering::Equal`] if the layers are not in the order list.
pub(crate) fn compare_order(&self, a: LayerId, b: LayerId) -> std::cmp::Ordering {
pub(crate) fn compare_order(&self, a: LayerId, b: LayerId) -> core::cmp::Ordering {
// Sort by layer `order` first and use `order_map` to resolve disputes.
// If `order_map` only contains one layer ID, then the other one will be
// lower because `None < Some(x)`.
match a.order.cmp(&b.order) {
std::cmp::Ordering::Equal => self.order_map.get(&a).cmp(&self.order_map.get(&b)),
core::cmp::Ordering::Equal => self.order_map.get(&a).cmp(&self.order_map.get(&b)),
cmp => cmp,
}
}
@@ -1276,7 +1276,7 @@ impl Areas {
}
pub fn visible_layer_ids(&self) -> ahash::HashSet<LayerId> {
std::iter::chain(
core::iter::chain(
&self.visible_areas_last_frame,
&self.visible_areas_current_frame,
)
@@ -1365,7 +1365,7 @@ impl Areas {
..
} = self;
std::mem::swap(visible_areas_last_frame, visible_areas_current_frame);
core::mem::swap(visible_areas_last_frame, visible_areas_current_frame);
visible_areas_current_frame.clear();
order.sort_by_key(|layer| (layer.order, wants_to_be_on_top.contains(layer)));
@@ -1374,7 +1374,7 @@ impl Areas {
// For all layers with sublayers, put the sublayers directly after the parent layer:
// (it doesn't matter in which order we replace parents with their children)
#[expect(clippy::iter_over_hash_type)]
for (parent, children) in std::mem::take(sublayers) {
for (parent, children) in core::mem::take(sublayers) {
let mut moved_layers = vec![parent]; // parent first…
order.retain(|l| {
@@ -1483,14 +1483,14 @@ fn order_map_total_ordering() {
let mut i = 0;
for &[a, b] in layers.array_windows() {
assert!(a.order <= b.order, "does not follow LayerId.order");
if areas.compare_order(a, b) != std::cmp::Ordering::Equal {
if areas.compare_order(a, b) != core::cmp::Ordering::Equal {
i += 1;
}
equivalence_classes.push(i);
}
assert_eq!(layers.len(), equivalence_classes.len());
for (&l1, c1) in std::iter::zip(&layers, &equivalence_classes) {
for (&l2, c2) in std::iter::zip(&layers, &equivalence_classes) {
for (&l1, c1) in core::iter::zip(&layers, &equivalence_classes) {
for (&l2, c2) in core::iter::zip(&layers, &equivalence_classes) {
assert_eq!(
c1.cmp(c2),
areas.compare_order(l1, l2),

View File

@@ -280,7 +280,7 @@ impl Painter {
);
}
pub fn error(&self, pos: Pos2, text: impl std::fmt::Display) -> Rect {
pub fn error(&self, pos: Pos2, text: impl core::fmt::Display) -> Rect {
let color = self.ctx.global_style().visuals.error_fg_color;
self.debug_text(pos, Align2::LEFT_TOP, color, format!("🔥 {text}"))
}
@@ -416,7 +416,7 @@ impl Painter {
/// Show an arrow starting at `origin` and going in the direction of `vec`, with the length `vec.length()`.
pub fn arrow(&self, origin: Pos2, vec: Vec2, stroke: impl Into<Stroke>) {
use crate::emath::Rot2;
let rot = Rot2::from_angle(std::f32::consts::TAU / 10.0);
let rot = Rot2::from_angle(core::f32::consts::TAU / 10.0);
let tip_length = vec.length() / 4.0;
let tip = origin + vec;
let dir = vec.normalized();

View File

@@ -10,7 +10,7 @@ use std::sync::Arc;
/// Plugins should not hold a reference to the [`Context`], since this would create a cycle
/// (which would prevent the [`Context`] from being dropped).
#[expect(unused_variables)]
pub trait Plugin: Send + Sync + std::any::Any + 'static {
pub trait Plugin: Send + Sync + core::any::Any + 'static {
/// Plugin name.
///
/// Used when profiling.
@@ -60,14 +60,14 @@ pub(crate) struct PluginHandle {
/// Use [`Self::lock`] to access the plugin.
pub struct TypedPluginHandle<P: Plugin> {
handle: Arc<Mutex<PluginHandle>>,
_type: std::marker::PhantomData<P>,
_type: core::marker::PhantomData<P>,
}
impl<P: Plugin> TypedPluginHandle<P> {
pub(crate) fn new(handle: Arc<Mutex<PluginHandle>>) -> Self {
Self {
handle,
_type: std::marker::PhantomData,
_type: core::marker::PhantomData,
}
}
@@ -77,7 +77,7 @@ impl<P: Plugin> TypedPluginHandle<P> {
pub fn lock(&self) -> TypedPluginGuard<'_, P> {
TypedPluginGuard {
guard: self.handle.lock(),
_type: std::marker::PhantomData,
_type: core::marker::PhantomData,
}
}
}
@@ -85,12 +85,12 @@ impl<P: Plugin> TypedPluginHandle<P> {
/// A guard that provides access to a [`Plugin`].
pub struct TypedPluginGuard<'a, P: Plugin> {
guard: MutexGuard<'a, PluginHandle>,
_type: std::marker::PhantomData<P>,
_type: core::marker::PhantomData<P>,
}
impl<P: Plugin> TypedPluginGuard<'_, P> {}
impl<P: Plugin> std::ops::Deref for TypedPluginGuard<'_, P> {
impl<P: Plugin> core::ops::Deref for TypedPluginGuard<'_, P> {
type Target = P;
fn deref(&self) -> &Self::Target {
@@ -98,7 +98,7 @@ impl<P: Plugin> std::ops::Deref for TypedPluginGuard<'_, P> {
}
}
impl<P: Plugin> std::ops::DerefMut for TypedPluginGuard<'_, P> {
impl<P: Plugin> core::ops::DerefMut for TypedPluginGuard<'_, P> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.guard.typed_plugin_mut()
}
@@ -111,7 +111,7 @@ impl PluginHandle {
}))
}
fn plugin_type_id(&self) -> std::any::TypeId {
fn plugin_type_id(&self) -> core::any::TypeId {
(*self.plugin).type_id()
}
@@ -120,13 +120,13 @@ impl PluginHandle {
}
fn typed_plugin<P: Plugin + 'static>(&self) -> &P {
(self.plugin.as_ref() as &dyn std::any::Any)
(self.plugin.as_ref() as &dyn core::any::Any)
.downcast_ref::<P>()
.expect("PluginHandle: plugin is not of the expected type")
}
pub fn typed_plugin_mut<P: Plugin + 'static>(&mut self) -> &mut P {
(self.plugin.as_mut() as &mut dyn std::any::Any)
(self.plugin.as_mut() as &mut dyn core::any::Any)
.downcast_mut::<P>()
.expect("PluginHandle: plugin is not of the expected type")
}
@@ -135,7 +135,7 @@ impl PluginHandle {
/// User-registered plugins.
#[derive(Clone, Default)]
pub(crate) struct Plugins {
plugins: HashMap<std::any::TypeId, Arc<Mutex<PluginHandle>>>,
plugins: HashMap<core::any::TypeId, Arc<Mutex<PluginHandle>>>,
plugins_ordered: PluginsOrdered,
}
@@ -215,7 +215,7 @@ impl Plugins {
true
}
pub fn get(&self, type_id: std::any::TypeId) -> Option<Arc<Mutex<PluginHandle>>> {
pub fn get(&self, type_id: core::any::TypeId) -> Option<Arc<Mutex<PluginHandle>>> {
self.plugins.get(&type_id).cloned()
}
}

View File

@@ -1,4 +1,5 @@
use std::{any::Any, sync::Arc};
use core::any::Any;
use std::sync::Arc;
use crate::{
Context, CursorIcon, Id, LayerId, PointerButton, Popup, PopupKind, Sense, Tooltip, Ui,
@@ -77,7 +78,7 @@ pub struct Response {
#[test]
fn test_response_size() {
assert_eq!(
std::mem::size_of::<Response>(),
core::mem::size_of::<Response>(),
88,
"Keep Response small, because we create them often, and we want to keep it lean and fast"
);
@@ -1112,7 +1113,7 @@ impl Response {
/// ```
///
/// Now `draw_vec2(ui, foo).hovered` is true if either [`DragValue`](crate::DragValue) were hovered.
impl std::ops::BitOr for Response {
impl core::ops::BitOr for Response {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
@@ -1133,7 +1134,7 @@ impl std::ops::BitOr for Response {
/// if response.hovered() { ui.label("You hovered at least one of the widgets"); }
/// # });
/// ```
impl std::ops::BitOrAssign for Response {
impl core::ops::BitOrAssign for Response {
fn bitor_assign(&mut self, rhs: Self) {
*self = self.union(rhs);
}

View File

@@ -22,8 +22,8 @@ bitflags::bitflags! {
}
}
impl std::fmt::Debug for Sense {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for Sense {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Sense {{")?;
if self.senses_click() {
write!(f, " click")?;

View File

@@ -1,11 +1,12 @@
//! egui theme (spacing, colors, etc).
use core::ops::RangeInclusive;
use emath::Align;
use epaint::{
CornerRadius, FontColorTransferFunction, Shadow, Stroke, TextOptions,
text::{FontTweak, FontVariationAxis, HintingTarget, SmoothHinting},
};
use std::{collections::BTreeMap, ops::RangeInclusive, sync::Arc};
use std::{collections::BTreeMap, sync::Arc};
use crate::{
ComboBox, CursorIcon, FontFamily, FontId, Grid, Margin, Response, RichText, TextWrapMode,
@@ -47,8 +48,8 @@ impl NumberFormatter {
}
}
impl std::fmt::Debug for NumberFormatter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for NumberFormatter {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("NumberFormatter")
}
}
@@ -93,8 +94,8 @@ pub enum TextStyle {
Name(std::sync::Arc<str>),
}
impl std::fmt::Display for TextStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Display for TextStyle {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Small => "Small".fmt(f),
Self::Body => "Body".fmt(f),
@@ -192,8 +193,8 @@ impl From<TextStyle> for FontSelection {
#[derive(Clone, Default)]
pub struct StyleModifier(Option<Arc<dyn Fn(&mut Style) + Send + Sync>>);
impl std::fmt::Debug for StyleModifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for StyleModifier {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("StyleModifier")
}
}
@@ -2695,7 +2696,7 @@ impl DebugOptions {
}
// TODO(emilk): improve and standardize
fn two_drag_values(value: &mut Vec2, range: std::ops::RangeInclusive<f32>) -> impl Widget + '_ {
fn two_drag_values(value: &mut Vec2, range: core::ops::RangeInclusive<f32>) -> impl Widget + '_ {
move |ui: &mut crate::Ui| {
ui.horizontal(|ui| {
ui.add(
@@ -2764,8 +2765,8 @@ impl NumericColorSpace {
}
}
impl std::fmt::Display for NumericColorSpace {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Display for NumericColorSpace {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::GammaByte => write!(f, "U8"),
Self::Linear => write!(f, "F"),

View File

@@ -49,9 +49,9 @@ impl CCursorRange {
}
/// The range of selected character indices.
pub fn as_sorted_char_range(&self) -> std::ops::Range<CharIndex> {
pub fn as_sorted_char_range(&self) -> core::ops::Range<CharIndex> {
let [start, end] = self.sorted_cursors();
std::ops::Range {
core::ops::Range {
start: start.index,
end: end.index,
}

View File

@@ -47,8 +47,8 @@ fn pos_in_galley(galley: &Galley, ccursor: CCursor) -> Pos2 {
galley.pos_from_cursor(ccursor).center()
}
impl std::fmt::Debug for WidgetTextCursor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for WidgetTextCursor {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let Self {
widget_id,
ccursor,
@@ -271,7 +271,7 @@ impl ViewportLabelSelectionState {
self.is_dragging = false;
}
let text_to_copy = std::mem::take(&mut self.text_to_copy);
let text_to_copy = core::mem::take(&mut self.text_to_copy);
if !text_to_copy.is_empty() {
ui.copy_text(text_to_copy);
}

View File

@@ -294,7 +294,7 @@ pub fn char_index_from_byte_index(input: &str, byte_index: ByteIndex) -> CharInd
CharIndex(input.chars().count())
}
pub fn slice_char_range(s: &str, char_range: std::ops::Range<CharIndex>) -> &str {
pub fn slice_char_range(s: &str, char_range: core::ops::Range<CharIndex>) -> &str {
assert!(
char_range.start <= char_range.end,
"Invalid range, start must be less than end, but start = {}, end = {}",

View File

@@ -139,8 +139,8 @@ pub(crate) fn paint_ime_preedit_text_visuals(
painter: &Painter,
galley: &Arc<Galley>,
row_height: f32,
preedit_range: std::ops::Range<CCursor>,
mut relative_active_range: Option<std::ops::Range<CCursor>>,
preedit_range: core::ops::Range<CCursor>,
mut relative_active_range: Option<core::ops::Range<CCursor>>,
time_since_last_interaction: f64,
) {
/// Instead of implementing [`PartialOrd`] and [`Ord`] for [`CCursor`] to
@@ -150,7 +150,7 @@ pub(crate) fn paint_ime_preedit_text_visuals(
/// These traits are intentionally not implemented because
/// [`CCursor::prefer_next_row`] makes it difficult to define a clear
/// ordering between two [`CCursor`]s.
fn is_cursor_range_empty(range: &std::ops::Range<CCursor>) -> bool {
fn is_cursor_range_empty(range: &core::ops::Range<CCursor>) -> bool {
range.start.index == range.end.index
}

View File

@@ -1,7 +1,8 @@
#![warn(missing_docs)] // Let's keep `Ui` well-documented.
#![expect(clippy::use_self)]
use std::{any::Any, ops::Deref, sync::Arc};
use core::{any::Any, ops::Deref};
use std::sync::Arc;
use crate::containers::menu;
use crate::widget_style::{HasClasses as _, ROOT_CLASS};
@@ -1984,7 +1985,7 @@ impl Ui {
/// but is shown to the user in fractions of one Tau (i.e. fractions of one turn).
/// The angle is NOT wrapped, so the user may select, for instance 2𝞃 (720°)
pub fn drag_angle_tau(&mut self, radians: &mut f32) -> Response {
use std::f32::consts::TAU;
use core::f32::consts::TAU;
let mut taus = *radians / TAU;
let mut response = self.add(DragValue::new(&mut taus).speed(0.01).suffix("τ"));
@@ -2599,7 +2600,7 @@ impl Ui {
let column_width = (self.available_width() - total_spacing) / (NUM_COL as f32);
let top_left = self.cursor().min;
let mut columns = std::array::from_fn(|col_idx| {
let mut columns = core::array::from_fn(|col_idx| {
let pos = top_left + vec2((col_idx as f32) * (column_width + spacing), 0.0);
let child_rect = Rect::from_min_max(
pos,

View File

@@ -1,5 +1,5 @@
use core::{any::Any, iter::FusedIterator};
use std::sync::Arc;
use std::{any::Any, iter::FusedIterator};
use crate::widget_style::Classes;
use epaint::Color32;

View File

@@ -16,15 +16,15 @@ where
}
}
impl<K, V> std::fmt::Debug for FixedCache<K, V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl<K, V> core::fmt::Debug for FixedCache<K, V> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Cache")
}
}
impl<K, V> FixedCache<K, V>
where
K: std::hash::Hash + PartialEq,
K: core::hash::Hash + PartialEq,
{
pub fn get(&self, key: &K) -> Option<&V> {
let bucket = (hash(key) % (FIXED_CACHE_SIZE as u64)) as usize;

View File

@@ -3,7 +3,8 @@
// For non-serializable types, these simply return `None`.
// This will also allow users to pick their own serialization format per type.
use std::{any::Any, sync::Arc};
use core::any::Any;
use std::sync::Arc;
// -----------------------------------------------------------------------------------------------
/// Like [`std::any::TypeId`], but can be serialized and deserialized.
@@ -14,7 +15,7 @@ pub struct TypeId(u64);
impl TypeId {
#[inline]
pub fn of<T: Any + 'static>() -> Self {
std::any::TypeId::of::<T>().into()
core::any::TypeId::of::<T>().into()
}
#[inline(always)]
@@ -23,9 +24,9 @@ impl TypeId {
}
}
impl From<std::any::TypeId> for TypeId {
impl From<core::any::TypeId> for TypeId {
#[inline]
fn from(id: std::any::TypeId) -> Self {
fn from(id: core::any::TypeId) -> Self {
Self(epaint::util::hash(id))
}
}
@@ -113,8 +114,8 @@ impl Clone for Element {
}
}
impl std::fmt::Debug for Element {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for Element {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match &self {
Self::Value { value, .. } => f
.debug_struct("Element::Value")
@@ -314,7 +315,7 @@ fn from_ron_str<T: serde::de::DeserializeOwned>(ron: &str) -> Option<T> {
Err(_err) => {
log::warn!(
"egui: Failed to deserialize {} from memory: {}, ron error: {:?}",
std::any::type_name::<T>(),
core::any::type_name::<T>(),
_err,
ron
);
@@ -578,7 +579,7 @@ impl IdTypeMap {
pub fn remove_temp<T: 'static + Default>(&mut self, id: Id) -> Option<T> {
let key = RawKey::new::<T>(id);
let mut element = self.map.remove(&key)?;
Some(std::mem::take(element.get_mut_temp()?))
Some(core::mem::take(element.get_mut_temp()?))
}
/// Remove a temporary value given a raw key.

View File

@@ -67,8 +67,8 @@ pub struct Undoer<State> {
flux: Option<Flux<State>>,
}
impl<State> std::fmt::Debug for Undoer<State> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl<State> core::fmt::Debug for Undoer<State> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let Self { undos, redos, .. } = self;
f.debug_struct("Undoer")
.field("undo count", &undos.len())

View File

@@ -120,13 +120,13 @@ pub struct ViewportId(pub Id);
// We implement `PartialOrd` and `Ord` so we can use `ViewportId` in a `BTreeMap`,
// which allows predicatable iteration order, frame-to-frame.
impl PartialOrd for ViewportId {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for ViewportId {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.0.value().cmp(&other.0.value())
}
}
@@ -138,8 +138,8 @@ impl Default for ViewportId {
}
}
impl std::fmt::Debug for ViewportId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for ViewportId {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.0.short_debug_format().fmt(f)
}
}
@@ -198,8 +198,8 @@ impl IconData {
}
}
impl std::fmt::Debug for IconData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for IconData {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("IconData")
.field("width", &self.width)
.field("height", &self.height)
@@ -1275,7 +1275,7 @@ pub struct ViewportOutput {
/// but if you haven't, you can use this instead.
///
/// If the duration is zero, schedule a repaint immediately.
pub repaint_delay: std::time::Duration,
pub repaint_delay: core::time::Duration,
}
impl ViewportOutput {

View File

@@ -256,7 +256,7 @@ impl HasClasses for Classes {
}
}
impl std::fmt::Display for Classes {
impl core::fmt::Display for Classes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.classes.iter().for_each(|class| {
let _ = f.write_str(class.as_str());

View File

@@ -1,5 +1,5 @@
use core::fmt::Formatter;
use epaint::text::{IntoTag, TextFormat, VariationCoords};
use std::fmt::Formatter;
use std::{borrow::Cow, sync::Arc};
use crate::{
@@ -539,8 +539,8 @@ pub enum WidgetText {
Galley(Arc<Galley>),
}
impl std::fmt::Debug for WidgetText {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for WidgetText {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
let text = self.text();
match self {
Self::Text(_) => write!(f, "Text({text:?})"),

View File

@@ -3,8 +3,8 @@ use crate::{
Modifiers, NumExt as _, Response, RichText, Sense, TextEdit, TextWrapMode, Ui, Widget,
WidgetInfo, emath, text,
};
use core::{cmp::Ordering, ops::RangeInclusive};
use emath::Vec2;
use std::{cmp::Ordering, ops::RangeInclusive};
// ----------------------------------------------------------------------------
@@ -780,7 +780,7 @@ mod tests {
macro_rules! total_assert_eq {
($a:expr, $b:expr) => {
assert!(
matches!($a.total_cmp(&$b), std::cmp::Ordering::Equal),
matches!($a.total_cmp(&$b), core::cmp::Ordering::Equal),
"{} != {}",
$a,
$b

View File

@@ -1,4 +1,5 @@
use std::{borrow::Cow, slice::Iter, sync::Arc, time::Duration};
use core::{slice::Iter, time::Duration};
use std::{borrow::Cow, sync::Arc};
use emath::{Align, Float as _, GuiRounding as _, NumExt as _, Rot2};
use epaint::{
@@ -607,8 +608,8 @@ pub enum ImageSource<'a> {
},
}
impl std::fmt::Debug for ImageSource<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for ImageSource<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
ImageSource::Bytes { uri, .. } | ImageSource::Uri(uri) => uri.as_ref().fmt(f),
ImageSource::Texture(st) => st.id.fmt(f),

View File

@@ -163,7 +163,7 @@ impl Widget for ProgressBar {
if animate && !has_custom_cr {
let n_points = 20;
let time = ui.input(|i| i.time);
let start_angle = time * std::f64::consts::TAU;
let start_angle = time * core::f64::consts::TAU;
let end_angle = start_angle + 240f64.to_radians() * time.sin();
let circle_radius = half_height - 2.0;
let points: Vec<Pos2> = (0..n_points)

View File

@@ -1,6 +1,6 @@
#![expect(clippy::needless_pass_by_value)] // False positives with `impl ToString`
use std::ops::RangeInclusive;
use core::ops::RangeInclusive;
use crate::{
Color32, DragValue, EventFilter, Key, Label, MINUS_CHAR_STR, NumExt as _, Pos2, Rangef, Rect,

View File

@@ -45,7 +45,7 @@ impl Spinner {
let radius = (rect.height().min(rect.width()) / 2.0) - 2.0;
let n_points = (radius.round() as u32).clamp(8, 128);
let time = ui.input(|i| i.time);
let start_angle = time * std::f64::consts::TAU;
let start_angle = time * core::f64::consts::TAU;
let end_angle = start_angle + 240f64.to_radians() * time.sin();
let points: Vec<Pos2> = (0..n_points)
.map(|i| {

View File

@@ -1008,7 +1008,7 @@ impl TextEdit<'_> {
fn mask_if_password(is_password: bool, text: &str) -> String {
fn mask_password(text: &str) -> String {
std::iter::repeat_n(
core::iter::repeat_n(
epaint::text::PASSWORD_REPLACEMENT_CHAR,
text.chars().count(),
)
@@ -1084,7 +1084,7 @@ fn events(
Selection(CCursorRange),
ImeComposition {
cursor_range: CCursorRange,
active_range: Option<std::ops::Range<CCursor>>,
active_range: Option<core::ops::Range<CCursor>>,
},
ImeCompositionCursorRange(CCursorRange),
}

View File

@@ -95,7 +95,7 @@ pub(crate) enum TextEditCursorPurpose {
/// irrelevant.
///
/// When `None`, no active range is displayed.
active_range: Option<std::ops::Range<CCursor>>,
active_range: Option<core::ops::Range<CCursor>>,
},
}

View File

@@ -1,4 +1,5 @@
use std::{borrow::Cow, ops::Range};
use core::ops::Range;
use std::borrow::Cow;
use epaint::{
Galley,
@@ -237,7 +238,7 @@ pub trait TextBuffer {
/// }
/// }
/// ```
fn type_id(&self) -> std::any::TypeId;
fn type_id(&self) -> core::any::TypeId;
}
impl TextBuffer for String {
@@ -282,11 +283,11 @@ impl TextBuffer for String {
}
fn take(&mut self) -> String {
std::mem::take(self)
core::mem::take(self)
}
fn type_id(&self) -> std::any::TypeId {
std::any::TypeId::of::<Self>()
fn type_id(&self) -> core::any::TypeId {
core::any::TypeId::of::<Self>()
}
}
@@ -316,11 +317,11 @@ impl TextBuffer for Cow<'_, str> {
}
fn take(&mut self) -> String {
std::mem::take(self).into_owned()
core::mem::take(self).into_owned()
}
fn type_id(&self) -> std::any::TypeId {
std::any::TypeId::of::<Cow<'_, str>>()
fn type_id(&self) -> core::any::TypeId {
core::any::TypeId::of::<Cow<'_, str>>()
}
}
@@ -340,8 +341,8 @@ impl TextBuffer for &str {
fn delete_char_range(&mut self, _ch_range: Range<CharIndex>) {}
fn type_id(&self) -> std::any::TypeId {
std::any::TypeId::of::<&str>()
fn type_id(&self) -> core::any::TypeId {
core::any::TypeId::of::<&str>()
}
}