1
0
mirror of https://github.com/emilk/egui.git synced 2026-08-29 04:40:03 -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

@@ -7,7 +7,7 @@
#![warn(missing_docs)] // Let's keep `epi` well-documented.
#[cfg(target_arch = "wasm32")]
use std::any::Any;
use core::any::Any;
#[cfg(not(target_arch = "wasm32"))]
#[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
@@ -41,7 +41,7 @@ pub type EventLoopBuilderHook = Box<dyn FnOnce(&mut EventLoopBuilder<UserEvent>)
#[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
pub type WindowBuilderHook = Box<dyn FnOnce(egui::ViewportBuilder) -> egui::ViewportBuilder>;
type DynError = Box<dyn std::error::Error + Send + Sync>;
type DynError = Box<dyn core::error::Error + Send + Sync>;
/// This is how your app is created.
///
@@ -73,7 +73,7 @@ pub struct CreationContext<'s> {
/// The `get_proc_address` wrapper of underlying GL context
#[cfg(feature = "glow")]
pub get_proc_address:
Option<std::sync::Arc<dyn Fn(&std::ffi::CStr) -> *const std::ffi::c_void + Send + Sync>>,
Option<std::sync::Arc<dyn Fn(&core::ffi::CStr) -> *const core::ffi::c_void + Send + Sync>>,
/// The underlying WGPU render state.
///
@@ -231,8 +231,8 @@ pub trait App {
// Settings:
/// Time between automatic calls to [`Self::save`]
fn auto_save_interval(&self) -> std::time::Duration {
std::time::Duration::from_secs(30)
fn auto_save_interval(&self) -> core::time::Duration {
core::time::Duration::from_secs(30)
}
/// Background color values for the app, e.g. what is sent to `gl.clearColor`.
@@ -621,8 +621,8 @@ impl Default for Renderer {
}
#[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
impl std::fmt::Display for Renderer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Display for Renderer {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
#[cfg(feature = "glow")]
Self::Glow => "glow".fmt(f),
@@ -634,7 +634,7 @@ impl std::fmt::Display for Renderer {
}
#[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
impl std::str::FromStr for Renderer {
impl core::str::FromStr for Renderer {
type Err = String;
fn from_str(name: &str) -> Result<Self, String> {

View File

@@ -503,7 +503,7 @@ pub fn run_ui_native(
#[derive(Debug)]
pub enum Error {
/// Something went wrong in user code when creating the app.
AppCreation(Box<dyn std::error::Error + Send + Sync>),
AppCreation(Box<dyn core::error::Error + Send + Sync>),
/// An error from [`winit`].
#[cfg(not(target_arch = "wasm32"))]
@@ -519,7 +519,7 @@ pub enum Error {
/// An error from [`glutin`] when using [`glow`].
#[cfg(all(feature = "glow", not(target_arch = "wasm32")))]
NoGlutinConfigs(glutin::config::ConfigTemplate, Box<dyn std::error::Error>),
NoGlutinConfigs(glutin::config::ConfigTemplate, Box<dyn core::error::Error>),
/// An error from [`glutin`] when using [`glow`].
#[cfg(feature = "glow")]
@@ -530,7 +530,7 @@ pub enum Error {
Wgpu(egui_wgpu::WgpuError),
}
impl std::error::Error for Error {}
impl core::error::Error for Error {}
#[cfg(not(target_arch = "wasm32"))]
impl From<winit::error::OsError> for Error {
@@ -572,8 +572,8 @@ impl From<egui_wgpu::WgpuError> for Error {
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::AppCreation(err) => write!(f, "app creation error: {err}"),
@@ -614,4 +614,4 @@ impl std::fmt::Display for Error {
}
/// Short for `Result<T, eframe::Error>`.
pub type Result<T = (), E = Error> = std::result::Result<T, E>;
pub type Result<T = (), E = Error> = core::result::Result<T, E>;

View File

@@ -123,7 +123,7 @@ fn set_app_icon_windows(icon_data: &IconData) -> AppIconStatus {
)
.is_err()
{
return std::ptr::null_mut();
return core::ptr::null_mut();
}
// SAFETY: Creating an HICON which should be readonly on our data.

View File

@@ -83,7 +83,7 @@ pub fn viewport_builder(
}
}
match std::mem::take(&mut native_options.window_builder) {
match core::mem::take(&mut native_options.window_builder) {
Some(hook) => hook(viewport_builder),
None => viewport_builder,
}
@@ -310,7 +310,7 @@ impl EpiIntegration {
}
self.pending_full_output.append(full_output);
std::mem::take(&mut self.pending_full_output)
core::mem::take(&mut self.pending_full_output)
}
/// Let the app tick its logic without showing any ui,
@@ -354,7 +354,7 @@ impl EpiIntegration {
app: &mut dyn epi::App,
new_input: egui::RawInput,
) -> egui::RawInput {
let mut raw_input = std::mem::take(&mut self.pending_raw_input);
let mut raw_input = core::mem::take(&mut self.pending_raw_input);
raw_input.append(new_input); // The new input wins where they overlap
raw_input.time = Some(self.beginning.elapsed().as_secs_f64());
@@ -379,7 +379,7 @@ impl EpiIntegration {
pub fn post_rendering(&mut self, window: &winit::window::Window) {
profiling::function_scope!();
if std::mem::take(&mut self.is_first_frame) {
if core::mem::take(&mut self.is_first_frame) {
// We keep hidden until we've painted something. See https://github.com/emilk/egui/pull/2279
window.set_visible(true);
}

View File

@@ -1,4 +1,4 @@
use std::cell::Cell;
use core::cell::Cell;
use winit::event_loop::ActiveEventLoop;
thread_local! {
@@ -14,7 +14,7 @@ impl EventLoopGuard {
cell.get().is_none(),
"Attempted to set a new event loop while one is already set"
);
cell.set(Some(std::ptr::from_ref::<ActiveEventLoop>(event_loop)));
cell.set(Some(core::ptr::from_ref::<ActiveEventLoop>(event_loop)));
});
Self
}

View File

@@ -44,10 +44,10 @@ pub fn storage_dir(app_id: &str) -> Option<PathBuf> {
#[cfg(all(windows, not(target_vendor = "uwp")))]
#[expect(unsafe_code)]
fn roaming_appdata() -> Option<PathBuf> {
use core::ptr;
use core::slice;
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt as _;
use std::ptr;
use std::slice;
use windows_sys::Win32::Foundation::S_OK;
use windows_sys::Win32::System::Com::CoTaskMemFree;
@@ -66,7 +66,7 @@ fn roaming_appdata() -> Option<PathBuf> {
SHGetKnownFolderPath(
&FOLDERID_RoamingAppData,
KF_FLAG_DONT_VERIFY as u32,
std::ptr::null_mut(),
core::ptr::null_mut(),
&mut path_raw,
)
};

View File

@@ -8,7 +8,8 @@
#![expect(clippy::undocumented_unsafe_blocks)]
#![expect(clippy::unwrap_used)]
use std::{cell::RefCell, num::NonZeroU32, rc::Rc, sync::Arc, time::Instant};
use core::{cell::RefCell, num::NonZeroU32};
use std::{rc::Rc, sync::Arc, time::Instant};
use egui_winit::ActionRequested;
use glutin::{
@@ -152,7 +153,7 @@ impl Viewport {
egui_winit::process_viewport_commands(
egui_ctx,
&mut self.info,
std::mem::take(&mut self.deferred_commands),
core::mem::take(&mut self.deferred_commands),
window,
&mut self.actions_requested,
);
@@ -338,7 +339,7 @@ impl<'app> GlowWinitApp<'app> {
log::warn!("set_cursor_hittest(false) failed: {err}");
}
let app_creator = std::mem::take(&mut self.app_creator)
let app_creator = core::mem::take(&mut self.app_creator)
.expect("Single-use AppCreator has unexpectedly already been taken");
crate::maybe_attach_inspection_plugin(&integration.egui_ctx, Some(self.app_name.clone()));
@@ -1408,7 +1409,7 @@ impl GlutinWindowContext {
}
}
fn get_proc_address(&self, addr: &std::ffi::CStr) -> *const std::ffi::c_void {
fn get_proc_address(&self, addr: &core::ffi::CStr) -> *const core::ffi::c_void {
self.gl_config.display().get_proc_address(addr)
}

View File

@@ -1,4 +1,5 @@
use std::time::{Duration, Instant};
use core::time::Duration;
use std::time::Instant;
use winit::{
application::ApplicationHandler,
@@ -41,7 +42,7 @@ fn create_event_loop(native_options: &mut epi::NativeOptions) -> Result<EventLoo
))
})?);
if let Some(hook) = std::mem::take(&mut native_options.event_loop_builder) {
if let Some(hook) = core::mem::take(&mut native_options.event_loop_builder) {
hook(&mut builder);
}
@@ -58,7 +59,7 @@ fn with_event_loop<R>(
mut native_options: epi::NativeOptions,
f: impl FnOnce(&mut EventLoop<UserEvent>, epi::NativeOptions) -> R,
) -> Result<R> {
thread_local!(static EVENT_LOOP: std::cell::RefCell<Option<EventLoop<UserEvent>>> = const { std::cell::RefCell::new(None) });
thread_local!(static EVENT_LOOP: core::cell::RefCell<Option<EventLoop<UserEvent>>> = const { core::cell::RefCell::new(None) });
EVENT_LOOP.with(|event_loop| {
// Since we want to reference NativeOptions when creating the EventLoop we can't
@@ -550,7 +551,7 @@ impl<'a> EframeWinitApplication<'a> {
pub fn pump_eframe_app(
&mut self,
event_loop: &mut EventLoop<UserEvent>,
timeout: Option<std::time::Duration>,
timeout: Option<core::time::Duration>,
) -> EframePumpStatus {
use winit::platform::pump_events::{EventLoopExtPumpEvents as _, PumpStatus};

View File

@@ -5,7 +5,8 @@
//! There is a bunch of improvements we could do,
//! like removing a bunch of `unwraps`.
use std::{cell::RefCell, num::NonZeroU32, rc::Rc, sync::Arc, time::Instant};
use core::{cell::RefCell, num::NonZeroU32};
use std::{rc::Rc, sync::Arc, time::Instant};
use egui_winit::ActionRequested;
use parking_lot::Mutex;
@@ -309,7 +310,7 @@ impl<'app> WgpuWinitApp<'app> {
egui_winit.init_accesskit(event_loop, &window, event_loop_proxy);
}
let app_creator = std::mem::take(&mut self.app_creator)
let app_creator = core::mem::take(&mut self.app_creator)
.expect("Single-use AppCreator has unexpectedly already been taken");
crate::maybe_attach_inspection_plugin(&egui_ctx, Some(self.app_name.clone()));
@@ -1040,7 +1041,7 @@ impl Viewport {
egui_winit::process_viewport_commands(
egui_ctx,
&mut self.info,
std::mem::take(&mut self.deferred_commands),
core::mem::take(&mut self.deferred_commands),
window,
&mut self.actions_requested,
);

View File

@@ -25,7 +25,7 @@ pub fn is_invisible_or_minimized(window: &Window) -> bool {
pub fn sleep_if_invisible_or_minimized(window: Option<&Window>) {
if window.is_some_and(is_invisible_or_minimized) {
profiling::scope!("minimized_sleep");
std::thread::sleep(std::time::Duration::from_millis(10));
std::thread::sleep(core::time::Duration::from_millis(10));
}
}

View File

@@ -344,7 +344,7 @@ impl AppRunner {
/// Paint the results of the last call to [`Self::logic`].
pub fn paint(&mut self) {
let clipped_primitives = std::mem::take(&mut self.clipped_primitives);
let clipped_primitives = core::mem::take(&mut self.clipped_primitives);
if let Some(clipped_primitives) = clipped_primitives {
let mut screenshot_commands = vec![];

View File

@@ -1,8 +1,5 @@
use std::{
future::Future,
path::{Path, PathBuf},
pin::Pin,
};
use core::{future::Future, pin::Pin};
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub(crate) struct WebFile {

View File

@@ -32,7 +32,7 @@ pub fn primary_touch_pos(
event: &web_sys::TouchEvent,
) -> Option<(egui::Pos2, web_sys::Touch)> {
// On touchend we don't get anything in `touches`, but we still get `changed_touches`, so include those:
let all_touches: Vec<_> = std::iter::chain(
let all_touches: Vec<_> = core::iter::chain(
(0..event.touches().length()).filter_map(|i| event.touches().get(i)),
(0..event.changed_touches().length()).filter_map(|i| event.changed_touches().get(i)),
)

View File

@@ -1,7 +1,8 @@
//! The text agent is a hidden `<input>` element used to capture
//! IME and mobile keyboard input events.
use std::{cell::RefCell, rc::Rc};
use core::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
@@ -366,7 +367,7 @@ impl InputState {
&self,
text: &str,
prefix_len_chars: usize,
) -> Option<std::ops::Range<usize>> {
) -> Option<core::ops::Range<usize>> {
let selection_start = self.input.selection_start().unwrap_or(None)? as usize;
let selection_end = self.input.selection_end().unwrap_or(None)? as usize;
@@ -444,7 +445,7 @@ impl InputState {
}
fn longest_common_prefix_length(a: &str, b: &str) -> usize {
std::iter::zip(a.chars(), b.chars())
core::iter::zip(a.chars(), b.chars())
.take_while(|(a, b)| a == b)
.count()
}

View File

@@ -368,7 +368,7 @@ impl WebPainter for WebPainterWgpu {
// Submit the commands: both the main buffer and user-defined ones.
render_state
.queue
.submit(std::iter::chain(user_cmd_bufs, [encoder.finish()]));
.submit(core::iter::chain(user_cmd_bufs, [encoder.finish()]));
if let Some((frame, capture_buffer)) = frame_and_capture_buffer {
if let Some(capture_buffer) = capture_buffer

View File

@@ -1,4 +1,5 @@
use std::{cell::RefCell, rc::Rc};
use core::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
@@ -107,7 +108,7 @@ impl WebRunner {
fn unsubscribe_from_all_events(&self) {
let events_to_unsubscribe: Vec<_> =
std::mem::take(&mut *self.events_to_unsubscribe.borrow_mut());
core::mem::take(&mut *self.events_to_unsubscribe.borrow_mut());
if !events_to_unsubscribe.is_empty() {
log::debug!("Unsubscribing from {} events", events_to_unsubscribe.len());
@@ -139,7 +140,7 @@ impl WebRunner {
/// Returns `None` if there has been a panic, or if we have been destroyed.
/// In that case, just return to JS.
pub(crate) fn try_lock(&self) -> Option<std::cell::RefMut<'_, AppRunner>> {
pub(crate) fn try_lock(&self) -> Option<core::cell::RefMut<'_, AppRunner>> {
if self.panic_handler.has_panicked() {
// Unsubscribe from all events so that we don't get any more callbacks
// that will try to access the poisoned runner.
@@ -147,7 +148,7 @@ impl WebRunner {
None
} else {
let lock = self.app_runner.try_borrow_mut().ok()?;
std::cell::RefMut::filter_map(lock, |lock| -> Option<&mut AppRunner> { lock.as_mut() })
core::cell::RefMut::filter_map(lock, |lock| -> Option<&mut AppRunner> { lock.as_mut() })
.ok()
}
}
@@ -158,9 +159,9 @@ impl WebRunner {
/// and return `None` if this runner has panicked.
pub fn app_mut<ConcreteApp: 'static + App>(
&self,
) -> Option<std::cell::RefMut<'_, ConcreteApp>> {
) -> Option<core::cell::RefMut<'_, ConcreteApp>> {
self.try_lock()
.map(|lock| std::cell::RefMut::map(lock, |runner| runner.app_mut::<ConcreteApp>()))
.map(|lock| core::cell::RefMut::map(lock, |runner| runner.app_mut::<ConcreteApp>()))
}
/// Convenience function to reduce boilerplate and ensure that all event handlers