From dba88d2102958258e420acc3888e31f61eaea9c4 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 24 Feb 2019 10:33:21 -0800 Subject: [PATCH] clippy --- src/config.rs | 2 ++ src/font/fontconfigandfreetype.rs | 2 +- src/font/ftfont.rs | 27 +++++++------- src/font/ftwrap.rs | 2 +- src/font/mod.rs | 8 ++--- src/gliumwindows.rs | 5 +-- src/guicommon/window.rs | 15 ++++---- src/guiloop/glutinloop.rs | 11 +++--- src/guiloop/mod.rs | 6 ++-- src/guiloop/x11.rs | 11 +++--- src/main.rs | 4 +-- src/opengl/render.rs | 17 +++++---- src/pty/unix.rs | 2 +- src/xwindows/keyboard.rs | 25 ++++++------- term/src/color.rs | 8 ++--- term/src/input.rs | 2 +- term/src/selection.rs | 3 ++ term/src/terminalstate.rs | 59 +++++++++++++++++-------------- termwiz/src/caps/mod.rs | 2 +- termwiz/src/cell.rs | 4 +-- termwiz/src/color.rs | 8 +++-- termwiz/src/escape/csi.rs | 36 ++++++++----------- termwiz/src/escape/esc.rs | 6 ++-- termwiz/src/escape/mod.rs | 3 ++ termwiz/src/escape/osc.rs | 34 ++++++++---------- termwiz/src/escape/parser/mod.rs | 6 ++++ termwiz/src/hyperlink.rs | 4 +-- termwiz/src/input.rs | 53 ++++++++++++++------------- termwiz/src/keymap.rs | 12 +++++-- termwiz/src/render/terminfo.rs | 6 ++-- termwiz/src/surface/line.rs | 13 ++++--- termwiz/src/surface/mod.rs | 35 ++++++++---------- termwiz/src/terminal/unix.rs | 2 +- termwiz/src/widgets/layout.rs | 45 ++++++++++++----------- termwiz/src/widgets/mod.rs | 11 +++--- 35 files changed, 255 insertions(+), 234 deletions(-) diff --git a/src/config.rs b/src/config.rs index 5167080a3..2998d96b3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -211,6 +211,7 @@ impl TextStyle { } } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::let_and_return))] pub fn font_with_fallback(&self) -> Vec { #[allow(unused_mut)] let mut font = self.font.clone(); @@ -238,6 +239,7 @@ impl TextStyle { bold: None, italic: None, }); + font } } diff --git a/src/font/fontconfigandfreetype.rs b/src/font/fontconfigandfreetype.rs index 01412d40a..c2b3ea5fd 100644 --- a/src/font/fontconfigandfreetype.rs +++ b/src/font/fontconfigandfreetype.rs @@ -25,7 +25,7 @@ impl FontSystem for FontConfigAndFreeType { font_scale: f64, ) -> Result, Error> { let fonts = style.font_with_fallback(); - let mut pattern = if fonts.len() >= 1 { + let mut pattern = if !fonts.is_empty() { let mut pattern = FontPattern::new()?; if fonts.len() > 1 { eprintln!( diff --git a/src/font/ftfont.rs b/src/font/ftfont.rs index 52a3d09e2..a6031de24 100644 --- a/src/font/ftfont.rs +++ b/src/font/ftfont.rs @@ -62,7 +62,7 @@ impl FreeTypeFontImpl { } } face.select_size(best)?; - (cell_width as f64, cell_height as f64) + (f64::from(cell_width), f64::from(cell_height)) } }; @@ -96,7 +96,7 @@ impl FreeTypeFontImpl { num_cells: unicode_width::UnicodeWidthChar::width(codepoint).unwrap_or(1) as u8, font_idx: 0, glyph_pos, - x_advance: (metrics.horiAdvance as f64 / 64.0).into(), + x_advance: (metrics.horiAdvance as f64 / 64.0), x_offset: 0.0, //(metrics.horiBearingX as f64 / 64.0).into(), y_advance: 0.0, y_offset: 0.0, @@ -123,7 +123,9 @@ impl Font for FreeTypeFontImpl { } fn has_color(&self) -> bool { let face = self.face.borrow(); - unsafe { (i64::from((*face.face).face_flags) & i64::from(ftwrap::FT_FACE_FLAG_COLOR)) != 0 } + unsafe { + ((*face.face).face_flags & ftwrap::FT_Long::from(ftwrap::FT_FACE_FLAG_COLOR)) != 0 + } } fn metrics(&self) -> FontMetrics { @@ -178,8 +180,7 @@ impl Font for FreeTypeFontImpl { let width = ft_glyph.bitmap.width as usize / 3; let height = ft_glyph.bitmap.rows as usize; let size = (width * height * 4) as usize; - let mut rgba = Vec::with_capacity(size); - rgba.resize(size, 0u8); + let mut rgba = vec![0u8; size]; for y in 0..height { let src_offset = y * pitch as usize; let dest_offset = y * width * 4; @@ -260,8 +261,7 @@ impl Font for FreeTypeFontImpl { let dest_height = 1 + last_line - first_line; let size = (dest_width * dest_height * 4) as usize; - let mut rgba = Vec::with_capacity(size); - rgba.resize(size, 0u8); + let mut rgba = vec![0u8; size]; for y in first_line..=last_line { let src_offset = y * pitch as usize; @@ -284,9 +284,10 @@ impl Font for FreeTypeFontImpl { data: rgba, height: dest_height, width: dest_width, - bearing_x: (ft_glyph.bitmap_left as f64 * (dest_width as f64 / width as f64)) - as i32, - bearing_y: (ft_glyph.bitmap_top as f64 * (dest_height as f64 / height as f64)) + bearing_x: (f64::from(ft_glyph.bitmap_left) + * (dest_width as f64 / width as f64)) as i32, + bearing_y: (f64::from(ft_glyph.bitmap_top) + * (dest_height as f64 / height as f64)) as i32, } } @@ -294,8 +295,7 @@ impl Font for FreeTypeFontImpl { let width = ft_glyph.bitmap.width as usize; let height = ft_glyph.bitmap.rows as usize; let size = (width * height * 4) as usize; - let mut rgba = Vec::with_capacity(size); - rgba.resize(size, 0u8); + let mut rgba = vec![0u8; size]; for y in 0..height { let src_offset = y * pitch; let dest_offset = y * width * 4; @@ -320,8 +320,7 @@ impl Font for FreeTypeFontImpl { let width = ft_glyph.bitmap.width as usize; let height = ft_glyph.bitmap.rows as usize; let size = (width * height * 4) as usize; - let mut rgba = Vec::with_capacity(size); - rgba.resize(size, 0u8); + let mut rgba = vec![0u8; size]; for y in 0..height { let src_offset = y * pitch; let dest_offset = y * width * 4; diff --git a/src/font/ftwrap.rs b/src/font/ftwrap.rs index 6684e6e73..97da83979 100644 --- a/src/font/ftwrap.rs +++ b/src/font/ftwrap.rs @@ -66,7 +66,7 @@ impl Face { codepoint: char, ) -> Result<(FT_UInt, FT_Glyph_Metrics_), Error> { unsafe { - let glyph_pos = FT_Get_Char_Index(self.face, codepoint as u32 as _); + let glyph_pos = FT_Get_Char_Index(self.face, FT_ULong::from(u32::from(codepoint))); let res = FT_Load_Glyph(self.face, glyph_pos, FT_LOAD_COLOR as i32); ensure!( succeeded(res), diff --git a/src/font/mod.rs b/src/font/mod.rs index 7f77d2f41..e198350aa 100644 --- a/src/font/mod.rs +++ b/src/font/mod.rs @@ -69,7 +69,7 @@ impl Default for FontSystemSelection { } impl FontSystemSelection { - fn new_font_system(&self) -> Rc { + fn new_font_system(self) -> Rc { match self { FontSystemSelection::FontConfigAndFreeType => { #[cfg(all(unix, not(target_os = "macos")))] @@ -78,10 +78,10 @@ impl FontSystemSelection { panic!("fontconfig not compiled in"); } FontSystemSelection::FontLoaderAndFreeType => { - return Rc::new(fontloader_and_freetype::FontSystemImpl::new()); + Rc::new(fontloader_and_freetype::FontSystemImpl::new()) } FontSystemSelection::FontLoaderAndRustType => { - return Rc::new(fontloader_and_rusttype::FontSystemImpl::new()); + Rc::new(fontloader_and_rusttype::FontSystemImpl::new()) } FontSystemSelection::CoreText => { #[cfg(target_os = "macos")] @@ -193,7 +193,7 @@ impl FontConfiguration { let font = self.default_font()?; let metrics = font.borrow_mut().get_fallback(0)?.metrics(); - *self.metrics.borrow_mut() = Some(metrics.clone()); + *self.metrics.borrow_mut() = Some(metrics); Ok(metrics) } diff --git a/src/gliumwindows.rs b/src/gliumwindows.rs index 250d9057b..976fe6ede 100644 --- a/src/gliumwindows.rs +++ b/src/gliumwindows.rs @@ -161,7 +161,7 @@ impl TerminalWindow for GliumTerminalWindow { ) -> Result<(), Error> { self.cell_width = cell_width; self.cell_height = cell_height; - self.renderer.scaling_changed(&mut self.host.display) + self.renderer.scaling_changed(&self.host.display) } fn advise_renderer_of_resize(&mut self, width: u16, height: u16) -> Result<(), Error> { self.width = width; @@ -518,6 +518,7 @@ impl GliumTerminalWindow { Some(code) } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::cyclomatic_complexity))] fn normalize_keycode(code: glium::glutin::VirtualKeyCode, shifted: bool) -> Option { use glium::glutin::VirtualKeyCode as V; macro_rules! shifted { @@ -695,7 +696,7 @@ impl GliumTerminalWindow { // think we know, otherwise we will use the wrong font size. let old_dpi_scale = self.fonts.get_dpi_scale(); let dpi_scale = self.host.display.gl_window().get_hidpi_factor(); - if old_dpi_scale != dpi_scale { + if (old_dpi_scale - dpi_scale).abs() < std::f64::EPSILON { let (width, height): (u32, u32) = size.to_physical(dpi_scale).into(); eprintln!( "Synthesize HiDpiFactorChanged {} -> {} current {}x{} -> {}x{}", diff --git a/src/guicommon/window.rs b/src/guicommon/window.rs index fb6d91d79..1a5b363eb 100644 --- a/src/guicommon/window.rs +++ b/src/guicommon/window.rs @@ -203,9 +203,9 @@ pub trait TerminalWindow { "TerminalWindow::scaling_changed dpi_scale={} font_scale={}", dpi_scale, font_scale ); - self.get_tabs() - .get_active() - .map(|tab| tab.terminal().make_all_lines_dirty()); + if let Some(tab) = self.get_tabs().get_active() { + tab.terminal().make_all_lines_dirty(); + } fonts.change_scaling(font_scale, dpi_scale); let metrics = fonts.default_font_metrics()?; @@ -235,12 +235,9 @@ pub trait TerminalWindow { fn tab_did_terminate(&mut self, tab_id: TabId) { self.get_tabs_mut().remove_by_id(tab_id); - match self.get_tabs().get_active() { - Some(tab) => { - tab.terminal().make_all_lines_dirty(); - self.update_title(); - } - None => (), + if let Some(tab) = self.get_tabs().get_active() { + tab.terminal().make_all_lines_dirty(); + self.update_title(); } self.deregister_tab(tab_id).ok(); diff --git a/src/guiloop/glutinloop.rs b/src/guiloop/glutinloop.rs index c1d17f192..1c0c46c5d 100644 --- a/src/guiloop/glutinloop.rs +++ b/src/guiloop/glutinloop.rs @@ -95,7 +95,7 @@ pub struct GlutinGuiSystem { } impl GlutinGuiSystem { - pub fn new() -> Result, Error> { + pub fn try_new() -> Result, Error> { let event_loop = Rc::new(GuiEventLoop::new()?); Ok(Rc::new(Self { event_loop })) } @@ -378,9 +378,12 @@ impl GuiEventLoop { .borrow_mut() .by_id .iter_mut() - .filter_map(|(window_id, window)| match window.test_for_child_exit() { - false => None, - true => Some(*window_id), + .filter_map(|(window_id, window)| { + if window.test_for_child_exit() { + Some(*window_id) + } else { + None + } }) .collect(); diff --git a/src/guiloop/mod.rs b/src/guiloop/mod.rs index 7748aa8b7..a368fb459 100644 --- a/src/guiloop/mod.rs +++ b/src/guiloop/mod.rs @@ -24,12 +24,12 @@ impl Default for GuiSelection { } impl GuiSelection { - pub fn new(&self) -> Result, Error> { + pub fn try_new(self) -> Result, Error> { match self { - GuiSelection::Glutin => glutinloop::GlutinGuiSystem::new(), + GuiSelection::Glutin => glutinloop::GlutinGuiSystem::try_new(), GuiSelection::X11 => { #[cfg(all(unix, not(target_os = "macos")))] - return x11::X11GuiSystem::new(); + return x11::X11GuiSystem::try_new(); #[cfg(not(all(unix, not(target_os = "macos"))))] bail!("X11 not compiled in"); } diff --git a/src/guiloop/x11.rs b/src/guiloop/x11.rs index 03e8a71d4..7a5a4800e 100644 --- a/src/guiloop/x11.rs +++ b/src/guiloop/x11.rs @@ -89,7 +89,7 @@ pub struct X11GuiSystem { event_loop: Rc, } impl X11GuiSystem { - pub fn new() -> Result, Error> { + pub fn try_new() -> Result, Error> { let event_loop = Rc::new(GuiEventLoop::new()?); Ok(Rc::new(Self { event_loop })) } @@ -500,9 +500,12 @@ impl GuiEventLoop { .borrow_mut() .by_id .iter_mut() - .filter_map(|(window_id, window)| match window.test_for_child_exit() { - false => None, - true => Some(*window_id), + .filter_map(|(window_id, window)| { + if window.test_for_child_exit() { + Some(*window_id) + } else { + None + } }) .collect(); diff --git a/src/main.rs b/src/main.rs index ea54ab3cd..f11930b69 100644 --- a/src/main.rs +++ b/src/main.rs @@ -111,14 +111,14 @@ fn main() -> Result<(), Error> { let font_system = opts.font_system.unwrap_or(config.font_system); let fontconfig = Rc::new(FontConfiguration::new(Rc::clone(&config), font_system)); - let cmd = if opts.prog.len() > 0 { + let cmd = if !opts.prog.is_empty() { Some(opts.prog.iter().map(|x| x.as_os_str()).collect()) } else { None }; let gui_system = opts.gui_system.unwrap_or(config.gui_system); - let gui = gui_system.new()?; + let gui = gui_system.try_new()?; spawn_window(&*gui, cmd, &config, &fontconfig)?; gui.run_forever() diff --git a/src/opengl/render.rs b/src/opengl/render.rs index 40056cf1b..deaf162c2 100644 --- a/src/opengl/render.rs +++ b/src/opengl/render.rs @@ -465,8 +465,7 @@ impl Renderer { descender: isize, ) -> Result { let width = 5 * cell_width; - let mut underline_data = Vec::with_capacity(width * cell_height * 4); - underline_data.resize(width * cell_height * 4, 0u8); + let mut underline_data = vec![0u8; width * cell_height * 4]; let descender_row = (cell_height as isize + descender) as usize; let descender_plus_one = (1 + descender_row).min(cell_height - 1); @@ -616,7 +615,7 @@ impl Renderer { } else { 1.0f64 }; - #[cfg_attr(feature = "cargo-clippy", allow(float_cmp))] + #[cfg_attr(feature = "cargo-clippy", allow(clippy::float_cmp))] let (x_offset, y_offset) = if scale != 1.0 { (info.x_offset * scale, info.y_offset * scale) } else { @@ -777,13 +776,13 @@ impl Renderer { }; let style = self.fonts.match_style(attrs); - let bg_color = self.palette.resolve_bg(&attrs.background); + let bg_color = self.palette.resolve_bg(attrs.background); let fg_color = match attrs.foreground { term::color::ColorAttribute::Default => { if let Some(fg) = style.foreground { fg } else { - self.palette.resolve_fg(&attrs.foreground) + self.palette.resolve_fg(attrs.foreground) } } term::color::ColorAttribute::PaletteIndex(idx) if idx < 8 => { @@ -796,9 +795,9 @@ impl Renderer { idx }; self.palette - .resolve_fg(&term::color::ColorAttribute::PaletteIndex(idx)) + .resolve_fg(term::color::ColorAttribute::PaletteIndex(idx)) } - _ => self.palette.resolve_fg(&attrs.foreground), + _ => self.palette.resolve_fg(attrs.foreground), }; let (fg_color, bg_color) = { @@ -834,7 +833,7 @@ impl Renderer { // Figure out what we're going to draw for the underline. // If the current cell is part of the current URL highlight // then we want to show the underline. - #[cfg_attr(feature = "cargo-clippy", allow(match_same_arms))] + #[cfg_attr(feature = "cargo-clippy", allow(clippy::match_same_arms))] let underline: f32 = match ( is_highlited_hyperlink, attrs.strikethrough(), @@ -1033,7 +1032,7 @@ impl Renderer { ) -> Result<(), Error> { let background_color = self .palette - .resolve_bg(&term::color::ColorAttribute::Default); + .resolve_bg(term::color::ColorAttribute::Default); let (r, g, b, a) = background_color.to_tuple_rgba(); target.clear_color(r, g, b, a); diff --git a/src/pty/unix.rs b/src/pty/unix.rs index 7b6f65cd4..ecc052471 100644 --- a/src/pty/unix.rs +++ b/src/pty/unix.rs @@ -138,7 +138,7 @@ pub fn openpty( let result = unsafe { // BSDish systems may require mut pointers to some args - #[cfg_attr(feature = "cargo-clippy", allow(unnecessary_mut_passed))] + #[cfg_attr(feature = "cargo-clippy", allow(clippy::unnecessary_mut_passed))] libc::openpty( &mut master, &mut slave, diff --git a/src/xwindows/keyboard.rs b/src/xwindows/keyboard.rs index 42968478d..d430b4c6d 100644 --- a/src/xwindows/keyboard.rs +++ b/src/xwindows/keyboard.rs @@ -23,7 +23,7 @@ impl Keyboard { let first_ev = connection .get_extension_data(xcb::xkb::id()) .map(|r| r.first_event()) - .ok_or(format_err!("could not get xkb extension data"))?; + .ok_or_else(|| format_err!("could not get xkb extension data"))?; { let cookie = xcb::xkb::use_extension( @@ -92,8 +92,8 @@ impl Keyboard { } let kbd = Keyboard { - context: context, - device_id: device_id, + context, + device_id, keymap: RefCell::new(keymap), state: RefCell::new(state), compose_state: RefCell::new(compose_state), @@ -112,11 +112,11 @@ impl Keyboard { return None; } - let xcode = xcb_ev.detail() as xkb::Keycode; + let xcode = xkb::Keycode::from(xcb_ev.detail()); let xsym = self.state.borrow().key_get_one_sym(xcode); self.compose_state.borrow_mut().feed(xsym); - let cstate = self.compose_state.borrow().status().clone(); + let cstate = self.compose_state.borrow().status(); let ksym = match cstate { ComposeStatus::Composing => { // eat @@ -206,12 +206,12 @@ impl Keyboard { // for convenience, this fn takes &self, not &mut self pub fn update_state(&self, ev: &xcb::xkb::StateNotifyEvent) { self.state.borrow_mut().update_mask( - ev.base_mods() as xkb::ModMask, - ev.latched_mods() as xkb::ModMask, - ev.locked_mods() as xkb::ModMask, + xkb::ModMask::from(ev.base_mods()), + xkb::ModMask::from(ev.latched_mods()), + xkb::ModMask::from(ev.locked_mods()), ev.base_group() as xkb::LayoutIndex, ev.latched_group() as xkb::LayoutIndex, - ev.locked_group() as xkb::LayoutIndex, + xkb::LayoutIndex::from(ev.locked_group()), ); } @@ -223,15 +223,12 @@ impl Keyboard { xkb::KEYMAP_COMPILE_NO_FLAGS, ); ensure!( - new_keymap.get_raw_ptr() != std::ptr::null_mut(), + !new_keymap.get_raw_ptr().is_null(), "problem with new keymap" ); let new_state = xkb::x11::state_new_from_device(&new_keymap, &connection, self.device_id); - ensure!( - new_state.get_raw_ptr() != std::ptr::null_mut(), - "problem with new state" - ); + ensure!(!new_state.get_raw_ptr().is_null(), "problem with new state"); self.state.replace(new_state); self.keymap.replace(new_keymap); diff --git a/term/src/color.rs b/term/src/color.rs index 78e819717..37b9ca85e 100644 --- a/term/src/color.rs +++ b/term/src/color.rs @@ -29,16 +29,16 @@ impl fmt::Debug for Palette256 { } impl ColorPalette { - pub fn resolve_fg(&self, color: &ColorAttribute) -> RgbColor { - match *color { + pub fn resolve_fg(&self, color: ColorAttribute) -> RgbColor { + match color { ColorAttribute::Default => self.foreground, ColorAttribute::PaletteIndex(idx) => self.colors.0[idx as usize], ColorAttribute::TrueColorWithPaletteFallback(color, _) | ColorAttribute::TrueColorWithDefaultFallback(color) => color, } } - pub fn resolve_bg(&self, color: &ColorAttribute) -> RgbColor { - match *color { + pub fn resolve_bg(&self, color: ColorAttribute) -> RgbColor { + match color { ColorAttribute::Default => self.background, ColorAttribute::PaletteIndex(idx) => self.colors.0[idx as usize], ColorAttribute::TrueColorWithPaletteFallback(color, _) diff --git a/term/src/input.rs b/term/src/input.rs index d11a9bebe..aca9bfda1 100644 --- a/term/src/input.rs +++ b/term/src/input.rs @@ -1,5 +1,5 @@ // clippy hates bitflags -#![cfg_attr(feature = "cargo-clippy", allow(suspicious_arithmetic_impl, redundant_field_names))] +#![cfg_attr(feature = "cargo-clippy", allow(clippy::suspicious_arithmetic_impl, clippy::redundant_field_names))] use std::time::{Duration, Instant}; diff --git a/term/src/selection.rs b/term/src/selection.rs index d3f7c5758..bb3bd90a0 100644 --- a/term/src/selection.rs +++ b/term/src/selection.rs @@ -1,3 +1,6 @@ +// The range_plus_one lint can't see when the LHS is not compatible with +// and inclusive range +#![cfg_attr(feature = "cargo-clippy", allow(clippy::range_plus_one))] use super::ScrollbackOrVisibleRowIndex; use std::ops::Range; diff --git a/term/src/terminalstate.rs b/term/src/terminalstate.rs index ec78d2676..60fe42be2 100644 --- a/term/src/terminalstate.rs +++ b/term/src/terminalstate.rs @@ -1,3 +1,6 @@ +// The range_plus_one lint can't see when the LHS is not compatible with +// and inclusive range +#![cfg_attr(feature = "cargo-clippy", allow(clippy::range_plus_one))] use super::*; use image::{self, GenericImage}; use ordered_float::NotNaN; @@ -66,18 +69,20 @@ impl Deref for ScreenOrAlt { type Target = Screen; fn deref(&self) -> &Screen { - match self.alt_screen_is_active { - true => &self.alt_screen, - false => &self.screen, + if self.alt_screen_is_active { + &self.alt_screen + } else { + &self.screen } } } impl DerefMut for ScreenOrAlt { fn deref_mut(&mut self) -> &mut Screen { - match self.alt_screen_is_active { - true => &mut self.alt_screen, - false => &mut self.screen, + if self.alt_screen_is_active { + &mut self.alt_screen + } else { + &mut self.screen } } } @@ -374,7 +379,7 @@ impl TerminalState { self.invalidate_hyperlinks(); } - #[cfg_attr(feature = "cargo-clippy", allow(cyclomatic_complexity))] + #[cfg_attr(feature = "cargo-clippy", allow(clippy::cyclomatic_complexity))] pub fn mouse_event( &mut self, mut event: MouseEvent, @@ -1520,8 +1525,8 @@ impl TerminalState { match cursor { Cursor::SetTopAndBottomMargins { top, bottom } => { let rows = self.screen().physical_rows; - let mut top = (top as i64).saturating_sub(1).min(rows as i64 - 1).max(0); - let mut bottom = (bottom as i64) + let mut top = i64::from(top).saturating_sub(1).min(rows as i64 - 1).max(0); + let mut bottom = i64::from(bottom) .saturating_sub(1) .min(rows as i64 - 1) .max(0); @@ -1541,42 +1546,44 @@ impl TerminalState { Cursor::LineTabulation(_) => {} Cursor::Left(n) => { - self.set_cursor_pos(&Position::Relative(-(n as i64)), &Position::Relative(0)) + self.set_cursor_pos(&Position::Relative(-(i64::from(n))), &Position::Relative(0)) } Cursor::Right(n) => { - self.set_cursor_pos(&Position::Relative(n as i64), &Position::Relative(0)) + self.set_cursor_pos(&Position::Relative(i64::from(n)), &Position::Relative(0)) } Cursor::Up(n) => { - self.set_cursor_pos(&Position::Relative(0), &Position::Relative(-(n as i64))) + self.set_cursor_pos(&Position::Relative(0), &Position::Relative(-(i64::from(n)))) } Cursor::Down(n) => { - self.set_cursor_pos(&Position::Relative(0), &Position::Relative(n as i64)) + self.set_cursor_pos(&Position::Relative(0), &Position::Relative(i64::from(n))) } Cursor::CharacterAndLinePosition { line, col } | Cursor::Position { line, col } => self .set_cursor_pos( - &Position::Absolute((col as i64).saturating_sub(1)), - &Position::Absolute((line as i64).saturating_sub(1)), + &Position::Absolute((i64::from(col)).saturating_sub(1)), + &Position::Absolute((i64::from(line)).saturating_sub(1)), ), Cursor::CharacterAbsolute(col) | Cursor::CharacterPositionAbsolute(col) => self .set_cursor_pos( - &Position::Absolute((col as i64).saturating_sub(1)), + &Position::Absolute((i64::from(col)).saturating_sub(1)), &Position::Relative(0), ), - Cursor::CharacterPositionBackward(col) => { - self.set_cursor_pos(&Position::Relative(-(col as i64)), &Position::Relative(0)) - } + Cursor::CharacterPositionBackward(col) => self.set_cursor_pos( + &Position::Relative(-(i64::from(col))), + &Position::Relative(0), + ), Cursor::CharacterPositionForward(col) => { - self.set_cursor_pos(&Position::Relative(col as i64), &Position::Relative(0)) + self.set_cursor_pos(&Position::Relative(i64::from(col)), &Position::Relative(0)) } Cursor::LinePositionAbsolute(line) => self.set_cursor_pos( &Position::Relative(0), - &Position::Absolute((line as i64).saturating_sub(1)), + &Position::Absolute((i64::from(line)).saturating_sub(1)), + ), + Cursor::LinePositionBackward(line) => self.set_cursor_pos( + &Position::Relative(0), + &Position::Relative(-(i64::from(line))), ), - Cursor::LinePositionBackward(line) => { - self.set_cursor_pos(&Position::Relative(0), &Position::Relative(-(line as i64))) - } Cursor::LinePositionForward(line) => { - self.set_cursor_pos(&Position::Relative(0), &Position::Relative(line as i64)) + self.set_cursor_pos(&Position::Relative(0), &Position::Relative(i64::from(line))) } Cursor::NextLine(n) => { for _ in 0..n { @@ -1584,7 +1591,7 @@ impl TerminalState { } } Cursor::PrecedingLine(n) => { - self.set_cursor_pos(&Position::Absolute(0), &Position::Relative(-(n as i64))) + self.set_cursor_pos(&Position::Absolute(0), &Position::Relative(-(i64::from(n)))) } Cursor::ActivePositionReport { .. } => { // This is really a response from the terminal, and diff --git a/termwiz/src/caps/mod.rs b/termwiz/src/caps/mod.rs index 412c84f9e..9fad9dbbf 100644 --- a/termwiz/src/caps/mod.rs +++ b/termwiz/src/caps/mod.rs @@ -157,7 +157,7 @@ impl Capabilities { hints.term_program(var("TERM_PROGRAM").ok()); hints.term_program_version(var("TERM_PROGRAM_VERSION").ok()); hints.terminfo_db(terminfo::Database::from_env().ok()); - Self::new_with_hints(hints.build().map_err(|e| err_msg(e))?) + Self::new_with_hints(hints.build().map_err(err_msg)?) } /// Build a `Capabilities` object based on the provided `ProbeHints` object. diff --git a/termwiz/src/cell.rs b/termwiz/src/cell.rs index c1fef7b76..bfe3a45e3 100644 --- a/termwiz/src/cell.rs +++ b/termwiz/src/cell.rs @@ -199,12 +199,12 @@ impl Cell { /// to a terminal. All control and movement characters are rewritten /// as a space. fn nerf_control_char(text: &mut SmallVec<[u8; 4]>) { - if text.len() == 0 { + if text.is_empty() { text.push(b' '); return; } - if text.as_slice() == &[b'\r', b'\n'] { + if text.as_slice() == [b'\r', b'\n'] { text.remove(1); text[0] = b' '; return; diff --git a/termwiz/src/color.rs b/termwiz/src/color.rs index 8ea6b47df..c0e28b08b 100644 --- a/termwiz/src/color.rs +++ b/termwiz/src/color.rs @@ -1,4 +1,6 @@ //! Colors for attributes +// for FromPrimitive +#![cfg_attr(feature = "cargo-clippy", allow(clippy::useless_attribute))] use palette; use palette::{LinSrgba, Srgb, Srgba}; @@ -68,19 +70,19 @@ impl RgbColor { Self { red, green, blue } } - pub fn to_linear(&self) -> LinSrgba { + pub fn to_linear(self) -> LinSrgba { Srgba::::new(self.red, self.green, self.blue, 0xff) .into_format() .into_linear() } - pub fn to_tuple_rgba(&self) -> RgbaTuple { + pub fn to_tuple_rgba(self) -> RgbaTuple { Srgba::::new(self.red, self.green, self.blue, 0xff) .into_format() .into_components() } - pub fn to_linear_tuple_rgba(&self) -> RgbaTuple { + pub fn to_linear_tuple_rgba(self) -> RgbaTuple { self.to_linear().into_components() } diff --git a/termwiz/src/escape/csi.rs b/termwiz/src/escape/csi.rs index 707f22542..3ee92a36f 100644 --- a/termwiz/src/escape/csi.rs +++ b/termwiz/src/escape/csi.rs @@ -659,7 +659,7 @@ trait ParseParams: Sized { /// Parse an input parameter into a 1-based unsigned value impl ParseParams for u32 { fn parse_params(params: &[i64]) -> Result { - if params.len() == 0 { + if params.is_empty() { Ok(1) } else if params.len() == 1 { to_1b_u32(params[0]) @@ -674,7 +674,7 @@ impl ParseParams for u32 { /// the pair of values. impl ParseParams for (u32, u32) { fn parse_params(params: &[i64]) -> Result<(u32, u32), ()> { - if params.len() == 0 { + if params.is_empty() { Ok((1, 1)) } else if params.len() == 2 { Ok((to_1b_u32(params[0])?, to_1b_u32(params[1])?)) @@ -695,7 +695,7 @@ trait ParamEnum: num::FromPrimitive { /// implement ParseParams for the enums that also implement ParamEnum. impl ParseParams for T { fn parse_params(params: &[i64]) -> Result { - if params.len() == 0 { + if params.is_empty() { Ok(ParamEnum::default()) } else if params.len() == 1 { num::FromPrimitive::from_i64(params[0]).ok_or(()) @@ -959,7 +959,7 @@ impl CSI { /// A little helper to convert i64 -> u8 if safe fn to_u8(v: i64) -> Result { - if v <= u8::max_value() as i64 { + if v <= i64::from(u8::max_value()) { Ok(v as u8) } else { Err(()) @@ -980,7 +980,7 @@ fn to_u8(v: i64) -> Result { fn to_1b_u32(v: i64) -> Result { if v == 0 { Ok(1) - } else if v > 0 && v <= u32::max_value() as i64 { + } else if v > 0 && v <= i64::from(u32::max_value()) { Ok(v as u32) } else { Err(()) @@ -1047,7 +1047,7 @@ impl<'a> CSIParser<'a> { ('j', &[]) => parse!(Cursor, CharacterPositionBackward, params), ('k', &[]) => parse!(Cursor, LinePositionBackward, params), - ('m', &[]) => self.sgr(params).map(|sgr| CSI::Sgr(sgr)), + ('m', &[]) => self.sgr(params).map(CSI::Sgr), ('n', &[]) => self.dsr(params), ('q', &[b' ']) => self.cursor_style(params), ('r', &[]) => self.decstbm(params), @@ -1069,9 +1069,7 @@ impl<'a> CSIParser<'a> { .dec(params) .map(|mode| CSI::Mode(Mode::SaveDecPrivateMode(mode))), - ('m', &[b'<']) | ('M', &[b'<']) => { - self.mouse_sgr1006(params).map(|mouse| CSI::Mouse(mouse)) - } + ('m', &[b'<']) | ('M', &[b'<']) => self.mouse_sgr1006(params).map(CSI::Mouse), ('c', &[]) => self .req_primary_device_attributes(params) @@ -1123,7 +1121,7 @@ impl<'a> CSIParser<'a> { } fn decstbm(&mut self, params: &'a [i64]) -> Result { - if params.len() == 0 { + if params.is_empty() { Ok(CSI::Cursor(Cursor::SetTopAndBottomMargins { top: 0, bottom: u32::max_value(), @@ -1177,7 +1175,7 @@ impl<'a> CSIParser<'a> { params, Device::DeviceAttributes(DeviceAttributes::Vt100WithAdvancedVideoOption), )) - } else if params.len() >= 1 && params[0] == 62 { + } else if !params.is_empty() && params[0] == 62 { Ok(self.advance_by( params.len(), params, @@ -1185,7 +1183,7 @@ impl<'a> CSIParser<'a> { DeviceAttributeFlags::from_params(¶ms[1..]), )), )) - } else if params.len() >= 1 && params[0] == 63 { + } else if !params.is_empty() && params[0] == 63 { Ok(self.advance_by( params.len(), params, @@ -1193,7 +1191,7 @@ impl<'a> CSIParser<'a> { DeviceAttributeFlags::from_params(¶ms[1..]), )), )) - } else if params.len() >= 1 && params[0] == 64 { + } else if !params.is_empty() && params[0] == 64 { Ok(self.advance_by( params.len(), params, @@ -1213,7 +1211,7 @@ impl<'a> CSIParser<'a> { } // 'M' encodes a press, 'm' a release. - let button = match (self.control, params[0] & 0b1100011) { + let button = match (self.control, params[0] & 0b110_0011) { ('M', 0) => MouseButton::Button1Press, ('m', 0) => MouseButton::Button1Release, ('M', 1) => MouseButton::Button2Press, @@ -1287,7 +1285,7 @@ impl<'a> CSIParser<'a> { } fn sgr(&mut self, params: &'a [i64]) -> Result { - if params.len() == 0 { + if params.is_empty() { // With no parameters, treat as equivalent to Reset. Ok(Sgr::Reset) } else { @@ -1313,9 +1311,7 @@ impl<'a> CSIParser<'a> { SgrCode::BlinkOff => one!(Sgr::Blink(Blink::None)), SgrCode::ItalicOn => one!(Sgr::Italic(true)), SgrCode::ItalicOff => one!(Sgr::Italic(false)), - SgrCode::ForegroundColor => { - self.parse_sgr_color(params).map(|c| Sgr::Foreground(c)) - } + SgrCode::ForegroundColor => self.parse_sgr_color(params).map(Sgr::Foreground), SgrCode::ForegroundBlack => one!(Sgr::Foreground(AnsiColor::Black.into())), SgrCode::ForegroundRed => one!(Sgr::Foreground(AnsiColor::Maroon.into())), SgrCode::ForegroundGreen => one!(Sgr::Foreground(AnsiColor::Green.into())), @@ -1340,9 +1336,7 @@ impl<'a> CSIParser<'a> { one!(Sgr::Foreground(AnsiColor::White.into())) } - SgrCode::BackgroundColor => { - self.parse_sgr_color(params).map(|c| Sgr::Background(c)) - } + SgrCode::BackgroundColor => self.parse_sgr_color(params).map(Sgr::Background), SgrCode::BackgroundBlack => one!(Sgr::Background(AnsiColor::Black.into())), SgrCode::BackgroundRed => one!(Sgr::Background(AnsiColor::Maroon.into())), SgrCode::BackgroundGreen => one!(Sgr::Background(AnsiColor::Green.into())), diff --git a/termwiz/src/escape/esc.rs b/termwiz/src/escape/esc.rs index e3304f370..1c0cc7ce6 100644 --- a/termwiz/src/escape/esc.rs +++ b/termwiz/src/escape/esc.rs @@ -93,8 +93,8 @@ impl Esc { fn internal_parse(intermediate: Option, control: u8) -> Result { let packed = match intermediate { - Some(high) => ((high as u16) << 8) | control as u16, - None => control as u16, + Some(high) => ((u16::from(high)) << 8) | u16::from(control), + None => u16::from(control), }; let code = num::FromPrimitive::from_u16(packed).ok_or(())?; @@ -116,7 +116,7 @@ impl Display for Esc { let packed = code .to_u16() .expect("num-derive failed to implement ToPrimitive"); - if packed > u8::max_value() as u16 { + if packed > u16::from(u8::max_value()) { write!( f, "{}{}", diff --git a/termwiz/src/escape/mod.rs b/termwiz/src/escape/mod.rs index c7cc66010..fb0855135 100644 --- a/termwiz/src/escape/mod.rs +++ b/termwiz/src/escape/mod.rs @@ -1,3 +1,6 @@ +// suppress inscrutable useless_attribute clippy that shows up when +// using derive(FromPrimitive) +#![cfg_attr(feature = "cargo-clippy", allow(clippy::useless_attribute))] //! This module provides the ability to parse escape sequences and attach //! semantic meaning to them. It can also encode the semantic values as //! escape sequences. It provides encoding and decoding functionality diff --git a/termwiz/src/escape/osc.rs b/termwiz/src/escape/osc.rs index 739200279..936a59507 100644 --- a/termwiz/src/escape/osc.rs +++ b/termwiz/src/escape/osc.rs @@ -110,9 +110,9 @@ impl OperatingSystemCommand { fn parse_selection(osc: &[&[u8]]) -> Result { if osc.len() == 2 { - Selection::try_parse(osc[1]).map(|s| OperatingSystemCommand::ClearSelection(s)) + Selection::try_parse(osc[1]).map(OperatingSystemCommand::ClearSelection) } else if osc.len() == 3 && osc[2] == b"?" { - Selection::try_parse(osc[1]).map(|s| OperatingSystemCommand::QuerySelection(s)) + Selection::try_parse(osc[1]).map(OperatingSystemCommand::QuerySelection) } else if osc.len() == 3 { let sel = Selection::try_parse(osc[1])?; let bytes = base64::decode(osc[2])?; @@ -124,7 +124,7 @@ impl OperatingSystemCommand { } fn internal_parse(osc: &[&[u8]]) -> Result { - ensure!(osc.len() > 0, "no params"); + ensure!(!osc.is_empty(), "no params"); let p1str = String::from_utf8_lossy(osc[0]); let code: i64 = p1str.parse()?; let osc_code: OperatingSystemCommandCode = @@ -149,8 +149,9 @@ impl OperatingSystemCommand { SetHyperlink => Ok(OperatingSystemCommand::SetHyperlink(Hyperlink::parse(osc)?)), ManipulateSelectionData => Self::parse_selection(osc), SystemNotification => single_string!(SystemNotification), - ITermProprietary => self::ITermProprietary::parse(osc) - .map(|p| OperatingSystemCommand::ITermProprietary(p)), + ITermProprietary => { + self::ITermProprietary::parse(osc).map(OperatingSystemCommand::ITermProprietary) + } _ => bail!("not impl"), } @@ -348,12 +349,9 @@ impl ITermFileData { .unwrap_or(ITermDimension::Automatic); let preserve_aspect_ratio = params .get("preserveAspectRatio") - .map(|s| if *s == "0" { false } else { true }) + .map(|s| *s != "0") .unwrap_or(true); - let inline = params - .get("inline") - .map(|s| if *s == "0" { false } else { true }) - .unwrap_or(false); + let inline = params.get("inline").map(|s| *s != "0").unwrap_or(false); let data = data.ok_or_else(|| err_msg("didn't set data"))?; Ok(Self { name, @@ -437,7 +435,7 @@ impl ITermDimension { let s = &s[..s.len() - 2]; let num = s.parse()?; Ok(ITermDimension::Pixels(num)) - } else if s.ends_with("%") { + } else if s.ends_with('%') { let s = &s[..s.len() - 1]; let num = s.parse()?; Ok(ITermDimension::Percent(num)) @@ -464,6 +462,7 @@ impl ITermDimension { } impl ITermProprietary { + #[cfg_attr(feature = "cargo-clippy", allow(clippy::cyclomatic_complexity))] fn parse(osc: &[&[u8]]) -> Result { // iTerm has a number of different styles of OSC parameter // encodings, which makes this section of code a bit gnarly. @@ -547,14 +546,11 @@ impl ITermProprietary { let p1 = iter.next(); let p2 = iter.next(); - match (p1, p2) { - (Some(k), Some(v)) => { - return Ok(ITermProprietary::SetUserVar { - name: k.to_string(), - value: String::from_utf8(base64::decode(v)?)?, - }); - } - _ => {} + if let (Some(k), Some(v)) = (p1, p2) { + return Ok(ITermProprietary::SetUserVar { + name: k.to_string(), + value: String::from_utf8(base64::decode(v)?)?, + }); } } } diff --git a/termwiz/src/escape/parser/mod.rs b/termwiz/src/escape/parser/mod.rs index 0f54a5ecb..0d3998b0d 100644 --- a/termwiz/src/escape/parser/mod.rs +++ b/termwiz/src/escape/parser/mod.rs @@ -13,6 +13,12 @@ pub struct Parser { state_machine: vte::Parser, } +impl Default for Parser { + fn default() -> Self { + Self::new() + } +} + impl Parser { pub fn new() -> Self { Self { diff --git a/termwiz/src/hyperlink.rs b/termwiz/src/hyperlink.rs index 6c4fb8de2..0d148a90a 100644 --- a/termwiz/src/hyperlink.rs +++ b/termwiz/src/hyperlink.rs @@ -71,7 +71,7 @@ impl Hyperlink { pub fn parse(osc: &[&[u8]]) -> Result, Error> { ensure!(osc.len() == 3, "wrong param count"); - if osc[1].len() == 0 && osc[2].len() == 0 { + if osc[1].is_empty() && osc[2].is_empty() { // Clearing current hyperlink Ok(None) } else { @@ -79,7 +79,7 @@ impl Hyperlink { let uri = String::from_utf8(osc[2].to_vec())?; let mut params = HashMap::new(); - if param_str.len() > 0 { + if !param_str.is_empty() { for pair in param_str.split(':') { let mut iter = pair.splitn(2, '='); let key = iter.next().ok_or_else(|| err_msg("bad params"))?; diff --git a/termwiz/src/input.rs b/termwiz/src/input.rs index f0b896724..5b56230e3 100644 --- a/termwiz/src/input.rs +++ b/termwiz/src/input.rs @@ -412,6 +412,12 @@ mod windows { } } +impl Default for InputParser { + fn default() -> Self { + Self::new() + } +} + impl InputParser { pub fn new() -> Self { Self { @@ -460,7 +466,7 @@ impl InputParser { map.insert( &app, InputEvent::Key(KeyEvent { - key: keycode.clone(), + key: *keycode, modifiers: Modifiers::NONE, }), ); @@ -470,7 +476,7 @@ impl InputParser { map.insert( &arrow, InputEvent::Key(KeyEvent { - key: keycode.clone(), + key: *keycode, modifiers: Modifiers::NONE, }), ); @@ -489,8 +495,8 @@ impl InputParser { map.insert( key, InputEvent::Key(KeyEvent { - key: keycode.clone(), - modifiers: modifiers.clone(), + key: *keycode, + modifiers: *modifiers, }), ); } @@ -507,7 +513,7 @@ impl InputParser { map.insert( &key, InputEvent::Key(KeyEvent { - key: keycode.clone(), + key: *keycode, modifiers: Modifiers::NONE, }), ); @@ -530,7 +536,7 @@ impl InputParser { key, InputEvent::Key(KeyEvent { key: KeyCode::Function(n), - modifiers: modifiers.clone(), + modifiers: *modifiers, }), ); } @@ -548,7 +554,7 @@ impl InputParser { map.insert( key, InputEvent::Key(KeyEvent { - key: keycode.clone(), + key: *keycode, modifiers: Modifiers::NONE, }), ); @@ -643,7 +649,7 @@ impl InputParser { } Err(err) => { let (valid, _after_valid) = bytes.split_at(err.valid_up_to()); - if valid.len() > 0 { + if !valid.is_empty() { let s = unsafe { std::str::from_utf8_unchecked(valid) }; let (c, len) = Self::first_char_and_len(s); Some((c, len)) @@ -724,28 +730,27 @@ impl InputParser { // parameters out from things like mouse reports. The keymap tree doesn't // know how to grok this. let mut parser = Parser::new(); - match parser.parse_first(self.buf.as_slice()) { - Some((Action::CSI(CSI::Mouse(mouse)), len)) => { - self.buf.advance(len); + if let Some((Action::CSI(CSI::Mouse(mouse)), len)) = + parser.parse_first(self.buf.as_slice()) + { + self.buf.advance(len); - match mouse { - MouseReport::SGR1006 { + match mouse { + MouseReport::SGR1006 { + x, + y, + button, + modifiers, + } => { + callback(InputEvent::Mouse(MouseEvent { x, y, - button, + mouse_buttons: button.into(), modifiers, - } => { - callback(InputEvent::Mouse(MouseEvent { - x, - y, - mouse_buttons: button.into(), - modifiers, - })); - } + })); } - continue; } - _ => {} + continue; } } diff --git a/termwiz/src/keymap.rs b/termwiz/src/keymap.rs index fa5ca9a42..4b77c18c3 100644 --- a/termwiz/src/keymap.rs +++ b/termwiz/src/keymap.rs @@ -18,7 +18,7 @@ impl Node { } fn insert(&mut self, key: &[u8], value: Value) { - if key.len() == 0 { + if key.is_empty() { // We've reached the leaf self.value = Some(value); return; @@ -38,7 +38,7 @@ impl Node { } fn lookup(&self, key: &[u8], depth: usize) -> NodeFind<&Value> { - if key.len() == 0 { + if key.is_empty() { // We've matched the maximum extent of the input key. if self.children.is_empty() { match self.value.as_ref() { @@ -69,7 +69,7 @@ impl Node { None => NodeFind::AmbiguousBackTrack, } } - result @ _ => result, + result => result, } } Err(_) => { @@ -129,6 +129,12 @@ pub struct KeyMap { root: Node, } +impl Default for KeyMap { + fn default() -> Self { + Self::new() + } +} + impl KeyMap { pub fn new() -> Self { Self { root: Node::new(0) } diff --git a/termwiz/src/render/terminfo.rs b/termwiz/src/render/terminfo.rs index 1a154e62b..5e5614fd0 100644 --- a/termwiz/src/render/terminfo.rs +++ b/termwiz/src/render/terminfo.rs @@ -46,6 +46,7 @@ impl TerminfoRenderer { }); } + #[cfg_attr(feature = "cargo-clippy", allow(clippy::cyclomatic_complexity))] fn flush_pending_attr( &mut self, out: &mut W, @@ -277,6 +278,7 @@ impl TerminfoRenderer { } impl TerminfoRenderer { + #[cfg_attr(feature = "cargo-clippy", allow(clippy::cyclomatic_complexity))] pub fn render_to( &mut self, changes: &[Change], @@ -341,7 +343,7 @@ impl TerminfoRenderer { let num_spaces = size.ws_col as usize * size.ws_row as usize; let mut buf = Vec::with_capacity(num_spaces); buf.resize(num_spaces, b' '); - out.write(buf.as_slice())?; + out.write_all(buf.as_slice())?; } } Change::ClearToEndOfLine(color) => { @@ -570,7 +572,7 @@ impl TerminfoRenderer { } if y != image.height - 1 { - write!(out, "\n")?; + writeln!(out)?; self.cursor_left(image.width as u32, out)?; } } diff --git a/termwiz/src/surface/line.rs b/termwiz/src/surface/line.rs index 20679fcdd..69f78897f 100644 --- a/termwiz/src/surface/line.rs +++ b/termwiz/src/surface/line.rs @@ -12,7 +12,7 @@ bitflags! { const NONE = 0; /// The contents of the Line have changed and cached or /// derived data will need to be reassessed. - const DIRTY = 1<<0; + const DIRTY = 1; /// The line contains 1+ cells with explicit hyperlinks set const HAS_HYPERLINK = 1<<1; /// true if we have scanned for implicit hyperlinks @@ -312,7 +312,7 @@ impl Line { text_run.push_str(cell.str()); } else { // flush out the current text run - if text_run.len() > 0 { + if !text_run.is_empty() { result.push(Change::Text(text_run.clone())); text_run.clear(); } @@ -324,7 +324,7 @@ impl Line { } // flush out any remaining text run - if text_run.len() > 0 { + if !text_run.is_empty() { // if this is just spaces then it is likely cheaper // to emit ClearToEndOfLine instead. if attr @@ -336,16 +336,15 @@ impl Line { let num_trailing_spaces = text_run.len() - left.len(); if num_trailing_spaces > 0 { - if left.len() > 0 { + if !left.is_empty() { result.push(Change::Text(left.to_string())); } else if result.len() == 1 { // if the only queued result prior to clearing // to the end of the line is an attribute change, // we can prune it out and return just the line // clearing operation - match result[0] { - Change::AllAttributes(_) => result.clear(), - _ => {} + if let Change::AllAttributes(_) = result[0] { + result.clear() } } diff --git a/termwiz/src/surface/mod.rs b/termwiz/src/surface/mod.rs index f954870de..e517ba016 100644 --- a/termwiz/src/surface/mod.rs +++ b/termwiz/src/surface/mod.rs @@ -175,11 +175,11 @@ impl Surface { Change::Text(text) => self.print_text(text), Change::Attribute(change) => self.change_attribute(change), Change::CursorPosition { x, y } => self.set_cursor_pos(x, y), - Change::ClearScreen(color) => self.clear_screen(color), - Change::ClearToEndOfLine(color) => self.clear_eol(color), - Change::ClearToEndOfScreen(color) => self.clear_eos(color), - Change::CursorColor(color) => self.cursor_color = color.clone(), - Change::CursorShape(shape) => self.cursor_shape = shape.clone(), + Change::ClearScreen(color) => self.clear_screen(*color), + Change::ClearToEndOfLine(color) => self.clear_eol(*color), + Change::ClearToEndOfScreen(color) => self.clear_eos(*color), + Change::CursorColor(color) => self.cursor_color = *color, + Change::CursorShape(shape) => self.cursor_shape = *shape, Change::Image(image) => self.add_image(image), } } @@ -229,10 +229,8 @@ impl Surface { self.xpos += image.width; } - fn clear_screen(&mut self, color: &ColorAttribute) { - self.attributes = CellAttributes::default() - .set_background(color.clone()) - .clone(); + fn clear_screen(&mut self, color: ColorAttribute) { + self.attributes = CellAttributes::default().set_background(color).clone(); let cleared = Cell::new(' ', self.attributes.clone()); for line in &mut self.lines { line.fill_range(0.., &cleared); @@ -241,10 +239,8 @@ impl Surface { self.ypos = 0; } - fn clear_eos(&mut self, color: &ColorAttribute) { - self.attributes = CellAttributes::default() - .set_background(color.clone()) - .clone(); + fn clear_eos(&mut self, color: ColorAttribute) { + self.attributes = CellAttributes::default().set_background(color).clone(); let cleared = Cell::new(' ', self.attributes.clone()); self.lines[self.ypos].fill_range(self.xpos.., &cleared); for line in &mut self.lines.iter_mut().skip(self.ypos + 1) { @@ -252,10 +248,8 @@ impl Surface { } } - fn clear_eol(&mut self, color: &ColorAttribute) { - self.attributes = CellAttributes::default() - .set_background(color.clone()) - .clone(); + fn clear_eol(&mut self, color: ColorAttribute) { + self.attributes = CellAttributes::default().set_background(color).clone(); let cleared = Cell::new(' ', self.attributes.clone()); self.lines[self.ypos].fill_range(self.xpos.., &cleared); } @@ -456,7 +450,7 @@ impl Surface { for (idx, line) in self.lines.iter().rev().enumerate() { let changes = line.changes(&attr); - if changes.len() == 0 { + if changes.is_empty() { // The line recorded no changes; this means that the line // consists of spaces and the default background color match trailing_color { @@ -478,7 +472,7 @@ impl Surface { let last_change = changes.len() - 1; match (&changes[last_change], trailing_color) { (&Change::ClearToEndOfLine(ref color), None) => { - trailing_color = Some(color.clone()); + trailing_color = Some(*color); trailing_idx = Some(idx); } (&Change::ClearToEndOfLine(ref color), Some(other)) => { @@ -519,7 +513,7 @@ impl Surface { let mut changes = line.changes(&attr); let result_len = result.len(); - if changes.len() > 0 && result[result_len - 1].is_text() && changes[0].is_text() { + if !changes.is_empty() && result[result_len - 1].is_text() && changes[0].is_text() { // Assumption: that the output has working automatic margins. // We can skip the cursor position change and just join the // text items together @@ -586,6 +580,7 @@ impl Surface { /// # Panics /// Will panic if the regions of interest are not within the bounds of /// their respective `Surface`. + #[allow(clippy::too_many_arguments)] pub fn diff_region( &self, x: usize, diff --git a/termwiz/src/terminal/unix.rs b/termwiz/src/terminal/unix.rs index f50f66394..081f68d53 100644 --- a/termwiz/src/terminal/unix.rs +++ b/termwiz/src/terminal/unix.rs @@ -132,7 +132,7 @@ impl TtyWriteHandle { } fn flush_local_buffer(&mut self) -> Result<(), IoError> { - if self.write_buffer.len() > 0 { + if !self.write_buffer.is_empty() { do_write(*self.fd, &self.write_buffer)?; self.write_buffer.clear(); } diff --git a/termwiz/src/widgets/layout.rs b/termwiz/src/widgets/layout.rs index 6188439ec..2ed803562 100644 --- a/termwiz/src/widgets/layout.rs +++ b/termwiz/src/widgets/layout.rs @@ -105,10 +105,9 @@ pub struct Constraints { impl Constraints { pub fn with_fixed_width_height(width: u16, height: u16) -> Self { - Self::default() + *Self::default() .set_fixed_width(width) .set_fixed_height(height) - .clone() } pub fn set_fixed_width(&mut self, width: u16) -> &mut Self { @@ -116,7 +115,6 @@ impl Constraints { spec: DimensionSpec::Fixed(width), minimum: Some(width), maximum: Some(width), - ..Default::default() }; self } @@ -134,7 +132,6 @@ impl Constraints { spec: DimensionSpec::Fixed(height), minimum: Some(height), maximum: Some(height), - ..Default::default() }; self } @@ -197,6 +194,12 @@ fn adderr(e: AddConstraintError) -> Error { format_err!("{:?}", e) } +impl Default for LayoutState { + fn default() -> Self { + Self::new() + } +} + impl LayoutState { /// Create a new `LayoutState` pub fn new() -> Self { @@ -229,7 +232,7 @@ impl LayoutState { top: Variable::new(), width: Variable::new(), height: Variable::new(), - constraints: constraints.clone(), + constraints: *constraints, children: children.to_vec(), }; self.widget_states.insert(widget, state); @@ -325,7 +328,7 @@ impl LayoutState { // First, we should fit inside the parent container self.solver .add_constraint( - state.left + state.width | LE(REQUIRED) | parent_left.clone() + parent_width, + (state.left + state.width) | LE(REQUIRED) | (parent_left.clone() + parent_width), ) .map_err(adderr)?; self.solver @@ -334,7 +337,7 @@ impl LayoutState { self.solver .add_constraint( - state.top + state.height | LE(REQUIRED) | parent_top.clone() + parent_height, + (state.top + state.height) | LE(REQUIRED) | (parent_top.clone() + parent_height), ) .map_err(adderr)?; self.solver @@ -351,11 +354,11 @@ impl LayoutState { .map_err(adderr)?, HorizontalAlignment::Right => self .solver - .add_constraint(state.left | EQ(STRONG) | parent_width - state.width) + .add_constraint(state.left | EQ(STRONG) | (parent_width - state.width)) .map_err(adderr)?, HorizontalAlignment::Center => self .solver - .add_constraint(state.left | EQ(STRONG) | (parent_width - state.width) / 2.0) + .add_constraint(state.left | EQ(STRONG) | ((parent_width - state.width) / 2.0)) .map_err(adderr)?, } @@ -366,11 +369,11 @@ impl LayoutState { .map_err(adderr)?, VerticalAlignment::Bottom => self .solver - .add_constraint(state.top | EQ(STRONG) | parent_height - state.height) + .add_constraint(state.top | EQ(STRONG) | (parent_height - state.height)) .map_err(adderr)?, VerticalAlignment::Middle => self .solver - .add_constraint(state.top | EQ(STRONG) | (parent_height - state.height) / 2.0) + .add_constraint(state.top | EQ(STRONG) | ((parent_height - state.height) / 2.0)) .map_err(adderr)?, } } @@ -384,7 +387,7 @@ impl LayoutState { DimensionSpec::Percentage(pct) => { self.solver .add_constraint( - state.width | EQ(STRONG) | f64::from(pct) * parent_width / 100.0, + state.width | EQ(STRONG) | (f64::from(pct) * parent_width / 100.0), ) .map_err(adderr)?; } @@ -411,7 +414,7 @@ impl LayoutState { DimensionSpec::Percentage(pct) => { self.solver .add_constraint( - state.height | EQ(STRONG) | f64::from(pct) * parent_height / 100.0, + state.height | EQ(STRONG) | (f64::from(pct) * parent_height / 100.0), ) .map_err(adderr)?; } @@ -453,9 +456,9 @@ impl LayoutState { HorizontalAlignment::Right => self .solver .add_constraint( - child_state.left + child_state.width + (child_state.left + child_state.width) | EQ(STRONG) - | state.left + state.width, + | (state.left + state.width), ) .map_err(adderr)?, HorizontalAlignment::Center => self @@ -463,7 +466,7 @@ impl LayoutState { .add_constraint( child_state.left | EQ(STRONG) - | state.left + (state.width - child_state.width) / 2.0, + | (state.left + (state.width - child_state.width) / 2.0), ) .map_err(adderr)?, } @@ -476,9 +479,9 @@ impl LayoutState { VerticalAlignment::Bottom => self .solver .add_constraint( - child_state.top + child_state.height + (child_state.top + child_state.height) | EQ(STRONG) - | state.top + state.height, + | (state.top + state.height), ) .map_err(adderr)?, VerticalAlignment::Middle => self @@ -486,7 +489,7 @@ impl LayoutState { .add_constraint( child_state.top | EQ(STRONG) - | state.top + (state.height - child_state.height) / 2.0, + | (state.top + (state.height - child_state.height) / 2.0), ) .map_err(adderr)?, } @@ -506,7 +509,7 @@ impl LayoutState { // This constraint encourages the contents to fill out to the width // of the container, rather than clumping left self.solver - .add_constraint(left_edge | EQ(STRONG) | state.left + state.width) + .add_constraint(left_edge | EQ(STRONG) | (state.left + state.width)) .map_err(adderr)?; self.solver @@ -516,7 +519,7 @@ impl LayoutState { // This constraint encourages the contents to fill out to the height // of the container, rather than clumping top self.solver - .add_constraint(top_edge | EQ(STRONG) | state.top + state.height) + .add_constraint(top_edge | EQ(STRONG) | (state.top + state.height)) .map_err(adderr)?; self.solver diff --git a/termwiz/src/widgets/mod.rs b/termwiz/src/widgets/mod.rs index 8e92c8b7e..ac045478d 100644 --- a/termwiz/src/widgets/mod.rs +++ b/termwiz/src/widgets/mod.rs @@ -1,3 +1,6 @@ +// Ideally this would be scoped to WidgetId, but I can't seem to find the +// right place for it to take effect +#![allow(clippy::new_without_default_derive)] use crate::color::ColorAttribute; use crate::input::InputEvent; use crate::surface::{Change, CursorShape, Position, SequenceNo, Surface}; @@ -159,7 +162,7 @@ impl Graph { id } - fn children<'a>(&'a self, id: WidgetId) -> &[WidgetId] { + fn children(&self, id: WidgetId) -> &[WidgetId] { self.children .get(&id) .map(|v| v.as_slice()) @@ -300,11 +303,7 @@ impl<'widget> Ui<'widget> { } pub fn process_event_queue(&mut self) -> Result<(), Error> { - loop { - let event = match self.input_queue.pop_front() { - Some(event) => event, - None => break, - }; + while let Some(event) = self.input_queue.pop_front() { match event { WidgetEvent::Input(InputEvent::Resized { rows, cols }) => { self.compute_layout(cols, rows)?;