chore(rustfmt): use nightly (#2325)

Stable rustfmt lacks a lot of features resulting in worse formatted
code, thus use nightly formatter.
This commit is contained in:
Kirill Chibisov 2024-04-26 19:11:44 +04:00 committed by GitHub
parent 7006c7ceca
commit 7b0c7b6cb2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
154 changed files with 3439 additions and 5891 deletions

View file

@ -1,7 +1,4 @@
#[cfg(all(
feature = "rwh_06",
any(x11_platform, macos_platform, windows_platform)
))]
#[cfg(all(feature = "rwh_06", any(x11_platform, macos_platform, windows_platform)))]
#[allow(deprecated)]
fn main() -> Result<(), impl std::error::Error> {
use std::collections::HashMap;
@ -46,25 +43,22 @@ fn main() -> Result<(), impl std::error::Error> {
println!("Parent window id: {parent_window_id:?})");
windows.insert(window.id(), window);
}
},
Event::WindowEvent { window_id, event } => match event {
WindowEvent::CloseRequested => {
windows.clear();
event_loop.exit();
}
},
WindowEvent::CursorEntered { device_id: _ } => {
// On x11, println when the cursor entered in a window even if the child window is created
// by some key inputs.
// the child windows are always placed at (0, 0) with size (200, 200) in the parent window,
// so we also can see this log when we move the cursor around (200, 200) in parent window.
// On x11, println when the cursor entered in a window even if the child window
// is created by some key inputs.
// the child windows are always placed at (0, 0) with size (200, 200) in the
// parent window, so we also can see this log when we move
// the cursor around (200, 200) in parent window.
println!("cursor entered in the window {window_id:?}");
}
},
WindowEvent::KeyboardInput {
event:
KeyEvent {
state: ElementState::Pressed,
..
},
event: KeyEvent { state: ElementState::Pressed, .. },
..
} => {
let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
@ -72,12 +66,12 @@ fn main() -> Result<(), impl std::error::Error> {
let child_id = child_window.id();
println!("Child window created with id: {child_id:?}");
windows.insert(child_id, child_window);
}
},
WindowEvent::RedrawRequested => {
if let Some(window) = windows.get(&window_id) {
fill::fill_window(window);
}
}
},
_ => (),
},
_ => (),
@ -85,10 +79,10 @@ fn main() -> Result<(), impl std::error::Error> {
})
}
#[cfg(all(
feature = "rwh_06",
not(any(x11_platform, macos_platform, windows_platform))
))]
#[cfg(all(feature = "rwh_06", not(any(x11_platform, macos_platform, windows_platform))))]
fn main() {
panic!("This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature enabled.");
panic!(
"This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature \
enabled."
);
}

View file

@ -85,14 +85,9 @@ impl ApplicationHandler for ControlFlowDemo {
match event {
WindowEvent::CloseRequested => {
self.close_requested = true;
}
},
WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: key,
state: ElementState::Pressed,
..
},
event: KeyEvent { logical_key: key, state: ElementState::Pressed, .. },
..
} => match key.as_ref() {
// WARNING: Consider using `key_without_modifiers()` if available on your platform.
@ -100,29 +95,29 @@ impl ApplicationHandler for ControlFlowDemo {
Key::Character("1") => {
self.mode = Mode::Wait;
warn!("mode: {:?}", self.mode);
}
},
Key::Character("2") => {
self.mode = Mode::WaitUntil;
warn!("mode: {:?}", self.mode);
}
},
Key::Character("3") => {
self.mode = Mode::Poll;
warn!("mode: {:?}", self.mode);
}
},
Key::Character("r") => {
self.request_redraw = !self.request_redraw;
warn!("request_redraw: {}", self.request_redraw);
}
},
Key::Named(NamedKey::Escape) => {
self.close_requested = true;
}
},
_ => (),
},
WindowEvent::RedrawRequested => {
let window = self.window.as_ref().unwrap();
window.pre_present_notify();
fill::fill_window(window);
}
},
_ => (),
}
}
@ -139,11 +134,11 @@ impl ApplicationHandler for ControlFlowDemo {
event_loop
.set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
}
}
},
Mode::Poll => {
thread::sleep(POLL_SLEEP_TIME);
event_loop.set_control_flow(ControlFlow::Poll);
}
},
};
if self.close_requested {

View file

@ -1,15 +1,11 @@
#![allow(clippy::single_match)]
// Limit this example to only compatible platforms.
#[cfg(any(
windows_platform,
macos_platform,
x11_platform,
wayland_platform,
android_platform,
))]
#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform, android_platform,))]
fn main() -> std::process::ExitCode {
use std::{process::ExitCode, thread::sleep, time::Duration};
use std::process::ExitCode;
use std::thread::sleep;
use std::time::Duration;
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
@ -49,7 +45,7 @@ fn main() -> std::process::ExitCode {
WindowEvent::RedrawRequested => {
fill::fill_window(window);
window.request_redraw();
}
},
_ => (),
}
}

View file

@ -60,13 +60,17 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
match event {
WindowEvent::CloseRequested => {
println!("--------------------------------------------------------- Window {} CloseRequested", self.idx);
println!(
"--------------------------------------------------------- Window {} \
CloseRequested",
self.idx
);
fill::cleanup_window(window);
self.window = None;
}
},
WindowEvent::RedrawRequested => {
fill::fill_window(window);
}
},
_ => (),
}
}
@ -76,10 +80,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut event_loop = EventLoop::new().unwrap();
let mut app = App {
idx: 1,
..Default::default()
};
let mut app = App { idx: 1, ..Default::default() };
event_loop.run_app_on_demand(&mut app)?;
println!("--------------------------------------------------------- Finished first loop");

View file

@ -20,8 +20,7 @@ mod platform {
use std::num::NonZeroU32;
use softbuffer::{Context, Surface};
use winit::window::Window;
use winit::window::WindowId;
use winit::window::{Window, WindowId};
thread_local! {
// NOTE: You should never do things like that, create context and drop it before
@ -80,24 +79,17 @@ mod platform {
// Either get the last context used or create a new one.
let mut gc = gc.borrow_mut();
let surface = gc
.get_or_insert_with(|| GraphicsContext::new(window))
.create_surface(window);
let surface =
gc.get_or_insert_with(|| GraphicsContext::new(window)).create_surface(window);
// Fill a buffer with a solid color.
const DARK_GRAY: u32 = 0xFF181818;
const DARK_GRAY: u32 = 0xff181818;
surface
.resize(width, height)
.expect("Failed to resize the softbuffer surface");
surface.resize(width, height).expect("Failed to resize the softbuffer surface");
let mut buffer = surface
.buffer_mut()
.expect("Failed to get the softbuffer buffer");
let mut buffer = surface.buffer_mut().expect("Failed to get the softbuffer buffer");
buffer.fill(DARK_GRAY);
buffer
.present()
.expect("Failed to present the softbuffer buffer");
buffer.present().expect("Failed to present the softbuffer buffer");
})
}

View file

@ -4,9 +4,7 @@ pub fn init() {
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
EnvFilter::builder().with_default_directive(LevelFilter::INFO.into()).from_env_lossy(),
)
.init();
}

View file

@ -2,12 +2,11 @@
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::fmt::Debug;
use std::mem;
#[cfg(not(any(android_platform, ios_platform)))]
use std::num::NonZeroU32;
use std::sync::Arc;
use std::{fmt, mem};
use ::tracing::{error, info};
use cursor_icon::CursorIcon;
@ -18,15 +17,13 @@ use softbuffer::{Context, Surface};
use winit::application::ApplicationHandler;
use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
use winit::event::{DeviceEvent, DeviceId, Ime, WindowEvent};
use winit::event::{MouseButton, MouseScrollDelta};
use winit::event::{DeviceEvent, DeviceId, Ime, MouseButton, MouseScrollDelta, WindowEvent};
use winit::event_loop::{ActiveEventLoop, EventLoop};
use winit::keyboard::{Key, ModifiersState};
use winit::window::{
Cursor, CursorGrabMode, CustomCursor, CustomCursorSource, Fullscreen, Icon, ResizeDirection,
Theme,
Theme, Window, WindowId,
};
use winit::window::{Window, WindowId};
#[cfg(macos_platform)]
use winit::platform::macos::{OptionAsAlt, WindowAttributesExtMacOS, WindowExtMacOS};
@ -100,10 +97,11 @@ impl Application {
.unwrap(),
);
// You'll have to choose an icon size at your own discretion. On X11, the desired size varies
// by WM, and on Windows, you still have to account for screen scaling. Here we use 32px,
// since it seems to work well enough in most cases. Be careful about going too high, or
// you'll be bitten by the low-quality downscaling built into the WM.
// You'll have to choose an icon size at your own discretion. On X11, the desired size
// varies by WM, and on Windows, you still have to account for screen scaling. Here
// we use 32px, since it seems to work well enough in most cases. Be careful about
// going too high, or you'll be bitten by the low-quality downscaling built into the
// WM.
let icon = load_icon(include_bytes!("data/icon.png"));
info!("Loading cursor assets");
@ -177,7 +175,7 @@ impl Application {
match action {
Action::CloseWindow => {
let _ = self.windows.remove(&window_id);
}
},
Action::CreateNewWindow => {
#[cfg(any(x11_platform, wayland_platform))]
if let Err(err) = window.window.request_activation_token() {
@ -189,7 +187,7 @@ impl Application {
if let Err(err) = self.create_window(event_loop, None) {
error!("Error creating new window: {err}");
}
}
},
Action::ToggleResizeIncrements => window.toggle_resize_increments(),
Action::ToggleCursorVisibility => window.toggle_cursor_visibility(),
Action::ToggleResizable => window.toggle_resizable(),
@ -205,7 +203,7 @@ impl Application {
#[cfg(web_platform)]
Action::AnimationCustomCursor => {
window.animation_custom_cursor(event_loop, &self.custom_cursors)
}
},
Action::CycleCursorGrab => window.cycle_cursor_grab(),
Action::DragWindow => window.drag_window(),
Action::DragResizeWindow => window.drag_resize_window(),
@ -219,7 +217,7 @@ impl Application {
if let Err(err) = self.create_window(event_loop, Some(tab_id)) {
error!("Error creating new window: {err}");
}
}
},
Action::RequestResize => window.swap_dimensions(),
}
}
@ -260,31 +258,23 @@ impl Application {
let PhysicalSize { width, height } = mode.size();
let bits = mode.bit_depth();
let m_hz = mode.refresh_rate_millihertz();
info!(
" {width}x{height}x{bits} @ {}.{} Hz",
m_hz / 1000,
m_hz % 1000
);
info!(" {width}x{height}x{bits} @ {}.{} Hz", m_hz / 1000, m_hz % 1000);
}
}
}
/// Process the key binding.
fn process_key_binding(key: &str, mods: &ModifiersState) -> Option<Action> {
KEY_BINDINGS.iter().find_map(|binding| {
binding
.is_triggered_by(&key, mods)
.then_some(binding.action)
})
KEY_BINDINGS
.iter()
.find_map(|binding| binding.is_triggered_by(&key, mods).then_some(binding.action))
}
/// Process mouse binding.
fn process_mouse_binding(button: MouseButton, mods: &ModifiersState) -> Option<Action> {
MOUSE_BINDINGS.iter().find_map(|binding| {
binding
.is_triggered_by(&button, mods)
.then_some(binding.action)
})
MOUSE_BINDINGS
.iter()
.find_map(|binding| binding.is_triggered_by(&button, mods).then_some(binding.action))
}
fn print_help(&self) {
@ -330,50 +320,46 @@ impl ApplicationHandler<UserEvent> for Application {
match event {
WindowEvent::Resized(size) => {
window.resize(size);
}
},
WindowEvent::Focused(focused) => {
if focused {
info!("Window={window_id:?} focused");
} else {
info!("Window={window_id:?} unfocused");
}
}
},
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
info!("Window={window_id:?} changed scale to {scale_factor}");
}
},
WindowEvent::ThemeChanged(theme) => {
info!("Theme changed to {theme:?}");
window.set_theme(theme);
}
},
WindowEvent::RedrawRequested => {
if let Err(err) = window.draw() {
error!("Error drawing window: {err}");
}
}
},
WindowEvent::Occluded(occluded) => {
window.set_occluded(occluded);
}
},
WindowEvent::CloseRequested => {
info!("Closing Window={window_id:?}");
self.windows.remove(&window_id);
}
},
WindowEvent::ModifiersChanged(modifiers) => {
window.modifiers = modifiers.state();
info!("Modifiers changed to {:?}", window.modifiers);
}
},
WindowEvent::MouseWheel { delta, .. } => match delta {
MouseScrollDelta::LineDelta(x, y) => {
info!("Mouse wheel Line Delta: ({x},{y})");
}
},
MouseScrollDelta::PixelDelta(px) => {
info!("Mouse wheel Pixel Delta: ({},{})", px.x, px.y);
}
},
},
WindowEvent::KeyboardInput {
event,
is_synthetic: false,
..
} => {
WindowEvent::KeyboardInput { event, is_synthetic: false, .. } => {
let mods = window.modifiers;
// Dispatch actions only on press.
@ -388,25 +374,23 @@ impl ApplicationHandler<UserEvent> for Application {
self.handle_action(event_loop, window_id, action);
}
}
}
},
WindowEvent::MouseInput { button, state, .. } => {
let mods = window.modifiers;
if let Some(action) = state
.is_pressed()
.then(|| Self::process_mouse_binding(button, &mods))
.flatten()
if let Some(action) =
state.is_pressed().then(|| Self::process_mouse_binding(button, &mods)).flatten()
{
self.handle_action(event_loop, window_id, action);
}
}
},
WindowEvent::CursorLeft { .. } => {
info!("Cursor left Window={window_id:?}");
window.cursor_left();
}
},
WindowEvent::CursorMoved { position, .. } => {
info!("Moved cursor to {position:?}");
window.cursor_moved(position);
}
},
WindowEvent::ActivationTokenDone { token: _token, .. } => {
#[cfg(any(x11_platform, wayland_platform))]
{
@ -415,15 +399,15 @@ impl ApplicationHandler<UserEvent> for Application {
error!("Error creating new window: {err}");
}
}
}
},
WindowEvent::Ime(event) => match event {
Ime::Enabled => info!("IME enabled for Window={window_id:?}"),
Ime::Preedit(text, caret_pos) => {
info!("Preedit: {}, with caret at {:?}", text, caret_pos);
}
},
Ime::Commit(text) => {
info!("Committed: {}", text);
}
},
Ime::Disabled => info!("IME disabled for Window={window_id:?}"),
},
WindowEvent::PinchGesture { delta, .. } => {
@ -434,7 +418,7 @@ impl ApplicationHandler<UserEvent> for Application {
} else {
info!("Zoomed out {delta:.5} (now: {zoom:.5})");
}
}
},
WindowEvent::RotationGesture { delta, .. } => {
window.rotated += delta;
let rotated = window.rotated;
@ -443,10 +427,10 @@ impl ApplicationHandler<UserEvent> for Application {
} else {
info!("Rotated clockwise {delta:.5} (now: {rotated:.5})");
}
}
},
WindowEvent::DoubleTapGesture { .. } => {
info!("Smart zoom");
}
},
WindowEvent::TouchpadPressure { .. }
| WindowEvent::HoveredFileCancelled
| WindowEvent::KeyboardInput { .. }
@ -474,8 +458,7 @@ impl ApplicationHandler<UserEvent> for Application {
self.dump_monitors(event_loop);
// Create initial window.
self.create_window(event_loop, None)
.expect("failed to create initial window");
self.create_window(event_loop, None).expect("failed to create initial window");
self.print_help();
}
@ -575,8 +558,7 @@ impl WindowState {
self.ime = !self.ime;
self.window.set_ime_allowed(self.ime);
if let Some(position) = self.ime.then_some(self.cursor_position).flatten() {
self.window
.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
}
}
@ -587,8 +569,7 @@ impl WindowState {
pub fn cursor_moved(&mut self, position: PhysicalPosition<f64>) {
self.cursor_position = Some(position);
if self.ime {
self.window
.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
}
}
@ -689,8 +670,7 @@ impl WindowState {
fn next_cursor(&mut self) {
self.named_idx = (self.named_idx + 1) % CURSORS.len();
info!("Setting cursor to \"{:?}\"", CURSORS[self.named_idx]);
self.window
.set_cursor(Cursor::Icon(CURSORS[self.named_idx]));
self.window.set_cursor(Cursor::Icon(CURSORS[self.named_idx]));
}
/// Pick the next custom cursor.
@ -739,9 +719,7 @@ impl WindowState {
(Some(width), Some(height)) => (width, height),
_ => return,
};
self.surface
.resize(width, height)
.expect("failed to resize inner buffer");
self.surface.resize(width, height).expect("failed to resize inner buffer");
}
self.window.request_redraw();
}
@ -775,7 +753,7 @@ impl WindowState {
None => {
info!("Drag-resize requires cursor to be inside the window");
return;
}
},
};
let win_size = self.window.inner_size();
@ -834,8 +812,8 @@ impl WindowState {
return Ok(());
}
const WHITE: u32 = 0xFFFFFFFF;
const DARK_GRAY: u32 = 0xFF181818;
const WHITE: u32 = 0xffffffff;
const DARK_GRAY: u32 = 0xff181818;
let color = match self.theme {
Theme::Light => WHITE,
@ -864,11 +842,7 @@ struct Binding<T: Eq> {
impl<T: Eq> Binding<T> {
const fn new(trigger: T, mods: ModifiersState, action: Action) -> Self {
Self {
trigger,
mods,
action,
}
Self { trigger, mods, action }
}
fn is_triggered_by(&self, trigger: &T, mods: &ModifiersState) -> bool {
@ -962,10 +936,7 @@ fn url_custom_cursor() -> CustomCursorSource {
static URL_COUNTER: AtomicU64 = AtomicU64::new(0);
CustomCursor::from_url(
format!(
"https://picsum.photos/128?random={}",
URL_COUNTER.fetch_add(1, Ordering::Relaxed)
),
format!("https://picsum.photos/128?random={}", URL_COUNTER.fetch_add(1, Ordering::Relaxed)),
64,
64,
)
@ -1086,19 +1057,7 @@ const KEY_BINDINGS: &[Binding<&'static str>] = &[
];
const MOUSE_BINDINGS: &[Binding<MouseButton>] = &[
Binding::new(
MouseButton::Left,
ModifiersState::ALT,
Action::DragResizeWindow,
),
Binding::new(
MouseButton::Left,
ModifiersState::CONTROL,
Action::DragWindow,
),
Binding::new(
MouseButton::Right,
ModifiersState::CONTROL,
Action::ShowWindowMenu,
),
Binding::new(MouseButton::Left, ModifiersState::ALT, Action::DragResizeWindow),
Binding::new(MouseButton::Left, ModifiersState::CONTROL, Action::DragWindow),
Binding::new(MouseButton::Right, ModifiersState::CONTROL, Action::ShowWindowMenu),
];

View file

@ -39,7 +39,7 @@ fn main() -> Result<(), Box<dyn Error>> {
WindowEvent::RedrawRequested => {
window.pre_present_notify();
fill::fill_window(window);
}
},
_ => (),
}
}
@ -58,10 +58,7 @@ fn main() -> Result<(), Box<dyn Error>> {
tracing_subscriber::fmt::init();
let event_loop = EventLoop::new()?;
let mut app = XEmbedDemo {
parent_window_id,
window: None,
};
let mut app = XEmbedDemo { parent_window_id, window: None };
event_loop.run_app(&mut app).map_err(Into::into)
}