file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
src/platform_impl/windows/util.rs
Rust
use std::{ ffi::{c_void, OsStr, OsString}, io, iter::once, mem, ops::BitAnd, os::windows::prelude::{OsStrExt, OsStringExt}, ptr, sync::atomic::{AtomicBool, Ordering}, }; use once_cell::sync::Lazy; use windows_sys::{ core::{HRESULT, PCWSTR}, Win32::{ Foundation::{BOOL, HINSTANCE, HWND, RECT}, Graphics::Gdi::{ClientToScreen, HMONITOR}, System::{ LibraryLoader::{GetProcAddress, LoadLibraryA}, SystemServices::IMAGE_DOS_HEADER, }, UI::{ HiDpi::{DPI_AWARENESS_CONTEXT, MONITOR_DPI_TYPE, PROCESS_DPI_AWARENESS}, Input::KeyboardAndMouse::GetActiveWindow, WindowsAndMessaging::{ ClipCursor, GetClientRect, GetClipCursor, GetSystemMetrics, GetWindowPlacement, GetWindowRect, IsIconic, ShowCursor, IDC_APPSTARTING, IDC_ARROW, IDC_CROSS, IDC_HAND, IDC_HELP, IDC_IBEAM, IDC_NO, IDC_SIZEALL, IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZEWE, IDC_WAIT, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_MAXIMIZE, WINDOWPLACEMENT, }, }, }, }; use crate::window::CursorIcon; pub fn encode_wide(string: impl AsRef<OsStr>) -> Vec<u16> { string.as_ref().encode_wide().chain(once(0)).collect() } pub fn decode_wide(mut wide_c_string: &[u16]) -> OsString { if let Some(null_pos) = wide_c_string.iter().position(|c| *c == 0) { wide_c_string = &wide_c_string[..null_pos]; } OsString::from_wide(wide_c_string) } pub fn has_flag<T>(bitset: T, flag: T) -> bool where T: Copy + PartialEq + BitAnd<T, Output = T>, { bitset & flag == flag } pub(crate) fn win_to_err(result: BOOL) -> Result<(), io::Error> { if result != false.into() { Ok(()) } else { Err(io::Error::last_os_error()) } } pub enum WindowArea { Outer, Inner, } impl WindowArea { pub fn get_rect(self, hwnd: HWND) -> Result<RECT, io::Error> { let mut rect = unsafe { mem::zeroed() }; match self { WindowArea::Outer => { win_to_err(unsafe { GetWindowRect(hwnd, &mut rect) })?; } WindowArea::Inner => unsafe { let mut top_left = mem::zeroed(); win_to_err(ClientToScreen(hwnd, &mut top_left))?; win_to_err(GetClientRect(hwnd, &mut rect))?; rect.left += top_left.x; rect.top += top_left.y; rect.right += top_left.x; rect.bottom += top_left.y; }, } Ok(rect) } } pub fn is_maximized(window: HWND) -> bool { unsafe { let mut placement: WINDOWPLACEMENT = mem::zeroed(); placement.length = mem::size_of::<WINDOWPLACEMENT>() as u32; GetWindowPlacement(window, &mut placement); placement.showCmd == SW_MAXIMIZE } } pub fn set_cursor_hidden(hidden: bool) { static HIDDEN: AtomicBool = AtomicBool::new(false); let changed = HIDDEN.swap(hidden, Ordering::SeqCst) ^ hidden; if changed { unsafe { ShowCursor(BOOL::from(!hidden)) }; } } pub fn get_cursor_clip() -> Result<RECT, io::Error> { unsafe { let mut rect: RECT = mem::zeroed(); win_to_err(GetClipCursor(&mut rect)).map(|_| rect) } } /// Sets the cursor's clip rect. /// /// Note that calling this will automatically dispatch a `WM_MOUSEMOVE` event. pub fn set_cursor_clip(rect: Option<RECT>) -> Result<(), io::Error> { unsafe { let rect_ptr = rect .as_ref() .map(|r| r as *const RECT) .unwrap_or(ptr::null()); win_to_err(ClipCursor(rect_ptr)) } } pub fn get_desktop_rect() -> RECT { unsafe { let left = GetSystemMetrics(SM_XVIRTUALSCREEN); let top = GetSystemMetrics(SM_YVIRTUALSCREEN); RECT { left, top, right: left + GetSystemMetrics(SM_CXVIRTUALSCREEN), bottom: top + GetSystemMetrics(SM_CYVIRTUALSCREEN), } } } pub fn is_focused(window: HWND) -> bool { window == unsafe { GetActiveWindow() } } pub fn is_minimized(window: HWND) -> bool { unsafe { IsIconic(window) != false.into() } } pub fn get_instance_handle() -> HINSTANCE { // Gets the instance handle by taking the address of the // pseudo-variable created by the microsoft linker: // https://devblogs.microsoft.com/oldnewthing/20041025-00/?p=37483 // This is preferred over GetModuleHandle(NULL) because it also works in DLLs: // https://stackoverflow.com/questions/21718027/getmodulehandlenull-vs-hinstance extern "C" { static __ImageBase: IMAGE_DOS_HEADER; } unsafe { &__ImageBase as *const _ as _ } } impl CursorIcon { pub(crate) fn to_windows_cursor(self) -> PCWSTR { match self { CursorIcon::Arrow | CursorIcon::Default => IDC_ARROW, CursorIcon::Hand => IDC_HAND, CursorIcon::Crosshair => IDC_CROSS, CursorIcon::Text | CursorIcon::VerticalText => IDC_IBEAM, CursorIcon::NotAllowed | CursorIcon::NoDrop => IDC_NO, CursorIcon::Grab | CursorIcon::Grabbing | CursorIcon::Move | CursorIcon::AllScroll => { IDC_SIZEALL } CursorIcon::EResize | CursorIcon::WResize | CursorIcon::EwResize | CursorIcon::ColResize => IDC_SIZEWE, CursorIcon::NResize | CursorIcon::SResize | CursorIcon::NsResize | CursorIcon::RowResize => IDC_SIZENS, CursorIcon::NeResize | CursorIcon::SwResize | CursorIcon::NeswResize => IDC_SIZENESW, CursorIcon::NwResize | CursorIcon::SeResize | CursorIcon::NwseResize => IDC_SIZENWSE, CursorIcon::Wait => IDC_WAIT, CursorIcon::Progress => IDC_APPSTARTING, CursorIcon::Help => IDC_HELP, _ => IDC_ARROW, // use arrow for the missing cases. } } } // Helper function to dynamically load function pointer. // `library` and `function` must be zero-terminated. pub(super) fn get_function_impl(library: &str, function: &str) -> Option<*const c_void> { assert_eq!(library.chars().last(), Some('\0')); assert_eq!(function.chars().last(), Some('\0')); // Library names we will use are ASCII so we can use the A version to avoid string conversion. let module = unsafe { LoadLibraryA(library.as_ptr()) }; if module == 0 { return None; } unsafe { GetProcAddress(module, function.as_ptr()) }.map(|function_ptr| function_ptr as _) } macro_rules! get_function { ($lib:expr, $func:ident) => { crate::platform_impl::platform::util::get_function_impl( concat!($lib, '\0'), concat!(stringify!($func), '\0'), ) .map(|f| unsafe { std::mem::transmute::<*const _, $func>(f) }) }; } pub type SetProcessDPIAware = unsafe extern "system" fn() -> BOOL; pub type SetProcessDpiAwareness = unsafe extern "system" fn(value: PROCESS_DPI_AWARENESS) -> HRESULT; pub type SetProcessDpiAwarenessContext = unsafe extern "system" fn(value: DPI_AWARENESS_CONTEXT) -> BOOL; pub type GetDpiForWindow = unsafe extern "system" fn(hwnd: HWND) -> u32; pub type GetDpiForMonitor = unsafe extern "system" fn( hmonitor: HMONITOR, dpi_type: MONITOR_DPI_TYPE, dpi_x: *mut u32, dpi_y: *mut u32, ) -> HRESULT; pub type EnableNonClientDpiScaling = unsafe extern "system" fn(hwnd: HWND) -> BOOL; pub type AdjustWindowRectExForDpi = unsafe extern "system" fn( rect: *mut RECT, dwStyle: u32, bMenu: BOOL, dwExStyle: u32, dpi: u32, ) -> BOOL; pub static GET_DPI_FOR_WINDOW: Lazy<Option<GetDpiForWindow>> = Lazy::new(|| get_function!("user32.dll", GetDpiForWindow)); pub static ADJUST_WINDOW_RECT_EX_FOR_DPI: Lazy<Option<AdjustWindowRectExForDpi>> = Lazy::new(|| get_function!("user32.dll", AdjustWindowRectExForDpi)); pub static GET_DPI_FOR_MONITOR: Lazy<Option<GetDpiForMonitor>> = Lazy::new(|| get_function!("shcore.dll", GetDpiForMonitor)); pub static ENABLE_NON_CLIENT_DPI_SCALING: Lazy<Option<EnableNonClientDpiScaling>> = Lazy::new(|| get_function!("user32.dll", EnableNonClientDpiScaling)); pub static SET_PROCESS_DPI_AWARENESS_CONTEXT: Lazy<Option<SetProcessDpiAwarenessContext>> = Lazy::new(|| get_function!("user32.dll", SetProcessDpiAwarenessContext)); pub static SET_PROCESS_DPI_AWARENESS: Lazy<Option<SetProcessDpiAwareness>> = Lazy::new(|| get_function!("shcore.dll", SetProcessDpiAwareness)); pub static SET_PROCESS_DPI_AWARE: Lazy<Option<SetProcessDPIAware>> = Lazy::new(|| get_function!("user32.dll", SetProcessDPIAware));
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/window.rs
Rust
#![cfg(windows_platform)] use raw_window_handle::{ RawDisplayHandle, RawWindowHandle, Win32WindowHandle, WindowsDisplayHandle, }; use std::{ cell::Cell, ffi::c_void, io, mem, panic, ptr, sync::{mpsc::channel, Arc, Mutex, MutexGuard}, }; use windows_sys::Win32::{ Foundation::{ HINSTANCE, HWND, LPARAM, OLE_E_WRONGCOMPOBJ, POINT, POINTS, RECT, RPC_E_CHANGED_MODE, S_OK, WPARAM, }, Graphics::{ Dwm::{DwmEnableBlurBehindWindow, DWM_BB_BLURREGION, DWM_BB_ENABLE, DWM_BLURBEHIND}, Gdi::{ ChangeDisplaySettingsExW, ClientToScreen, CreateRectRgn, DeleteObject, InvalidateRgn, RedrawWindow, CDS_FULLSCREEN, DISP_CHANGE_BADFLAGS, DISP_CHANGE_BADMODE, DISP_CHANGE_BADPARAM, DISP_CHANGE_FAILED, DISP_CHANGE_SUCCESSFUL, RDW_INTERNALPAINT, }, }, System::{ Com::{ CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_APARTMENTTHREADED, }, Ole::{OleInitialize, RegisterDragDrop}, }, UI::{ Input::{ KeyboardAndMouse::{ EnableWindow, GetActiveWindow, MapVirtualKeyW, ReleaseCapture, SendInput, INPUT, INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_EXTENDEDKEY, KEYEVENTF_KEYUP, MAPVK_VK_TO_VSC, VK_LMENU, VK_MENU, }, Touch::{RegisterTouchWindow, TWF_WANTPALM}, }, WindowsAndMessaging::{ CreateWindowExW, FlashWindowEx, GetClientRect, GetCursorPos, GetForegroundWindow, GetSystemMetrics, GetWindowPlacement, GetWindowTextLengthW, GetWindowTextW, IsWindowVisible, LoadCursorW, PeekMessageW, PostMessageW, RegisterClassExW, SetCursor, SetCursorPos, SetForegroundWindow, SetWindowDisplayAffinity, SetWindowPlacement, SetWindowPos, SetWindowTextW, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, FLASHWINFO, FLASHW_ALL, FLASHW_STOP, FLASHW_TIMERNOFG, FLASHW_TRAY, GWLP_HINSTANCE, HTCAPTION, NID_READY, PM_NOREMOVE, SM_DIGITIZER, SWP_ASYNCWINDOWPOS, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER, WDA_EXCLUDEFROMCAPTURE, WDA_NONE, WM_NCLBUTTONDOWN, WNDCLASSEXW, }, }, }; use crate::{ dpi::{PhysicalPosition, PhysicalSize, Position, Size}, error::{ExternalError, NotSupportedError, OsError as RootOsError}, icon::Icon, platform_impl::platform::{ dark_mode::try_theme, definitions::{ CLSID_TaskbarList, IID_ITaskbarList, IID_ITaskbarList2, ITaskbarList, ITaskbarList2, }, dpi::{dpi_to_scale_factor, enable_non_client_dpi_scaling, hwnd_dpi}, drop_handler::FileDropHandler, event_loop::{self, EventLoopWindowTarget, DESTROY_MSG_ID}, icon::{self, IconType}, ime::ImeContext, monitor::{self, MonitorHandle}, util, window_state::{CursorFlags, SavedWindow, WindowFlags, WindowState}, Fullscreen, PlatformSpecificWindowBuilderAttributes, WindowId, }, window::{ CursorGrabMode, CursorIcon, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, WindowButtons, WindowLevel, }, }; /// The Win32 implementation of the main `Window` object. pub(crate) struct Window { /// Main handle for the window. window: WindowWrapper, /// The current window state. window_state: Arc<Mutex<WindowState>>, // The events loop proxy. thread_executor: event_loop::EventLoopThreadExecutor, } impl Window { pub(crate) fn new<T: 'static>( event_loop: &EventLoopWindowTarget<T>, w_attr: WindowAttributes, pl_attr: PlatformSpecificWindowBuilderAttributes, ) -> Result<Window, RootOsError> { // We dispatch an `init` function because of code style. // First person to remove the need for cloning here gets a cookie! // // done. you owe me -- ossi unsafe { init(w_attr, pl_attr, event_loop) } } fn window_state_lock(&self) -> MutexGuard<'_, WindowState> { self.window_state.lock().unwrap() } pub fn set_title(&self, text: &str) { let wide_text = util::encode_wide(text); unsafe { SetWindowTextW(self.hwnd(), wide_text.as_ptr()); } } pub fn set_transparent(&self, _transparent: bool) {} #[inline] pub fn set_visible(&self, visible: bool) { let window = self.window.clone(); let window_state = Arc::clone(&self.window_state); self.thread_executor.execute_in_thread(move || { let _ = &window; WindowState::set_window_flags(window_state.lock().unwrap(), window.0, |f| { f.set(WindowFlags::VISIBLE, visible) }); }); } #[inline] pub fn is_visible(&self) -> Option<bool> { Some(unsafe { IsWindowVisible(self.window.0) == 1 }) } #[inline] pub fn request_redraw(&self) { unsafe { RedrawWindow(self.hwnd(), ptr::null(), 0, RDW_INTERNALPAINT); } } #[inline] pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { util::WindowArea::Outer.get_rect(self.hwnd()) .map(|rect| Ok(PhysicalPosition::new(rect.left, rect.top))) .expect("Unexpected GetWindowRect failure; please report this error to https://github.com/rust-windowing/winit") } #[inline] pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { let mut position: POINT = unsafe { mem::zeroed() }; if unsafe { ClientToScreen(self.hwnd(), &mut position) } == false.into() { panic!("Unexpected ClientToScreen failure: please report this error to https://github.com/rust-windowing/winit") } Ok(PhysicalPosition::new(position.x, position.y)) } #[inline] pub fn set_outer_position(&self, position: Position) { let (x, y): (i32, i32) = position.to_physical::<i32>(self.scale_factor()).into(); let window_state = Arc::clone(&self.window_state); let window = self.window.clone(); self.thread_executor.execute_in_thread(move || { let _ = &window; WindowState::set_window_flags(window_state.lock().unwrap(), window.0, |f| { f.set(WindowFlags::MAXIMIZED, false) }); }); unsafe { SetWindowPos( self.hwnd(), 0, x, y, 0, 0, SWP_ASYNCWINDOWPOS | SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE, ); InvalidateRgn(self.hwnd(), 0, false.into()); } } #[inline] pub fn inner_size(&self) -> PhysicalSize<u32> { let mut rect: RECT = unsafe { mem::zeroed() }; if unsafe { GetClientRect(self.hwnd(), &mut rect) } == false.into() { panic!("Unexpected GetClientRect failure: please report this error to https://github.com/rust-windowing/winit") } PhysicalSize::new( (rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32, ) } #[inline] pub fn outer_size(&self) -> PhysicalSize<u32> { util::WindowArea::Outer .get_rect(self.hwnd()) .map(|rect| { PhysicalSize::new( (rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32, ) }) .unwrap() } #[inline] pub fn set_inner_size(&self, size: Size) { let scale_factor = self.scale_factor(); let physical_size = size.to_physical::<u32>(scale_factor); let window_state = Arc::clone(&self.window_state); let window = self.window.clone(); self.thread_executor.execute_in_thread(move || { let _ = &window; WindowState::set_window_flags(window_state.lock().unwrap(), window.0, |f| { f.set(WindowFlags::MAXIMIZED, false) }); }); let window_flags = self.window_state_lock().window_flags; window_flags.set_size(self.hwnd(), physical_size); } #[inline] pub fn set_min_inner_size(&self, size: Option<Size>) { self.window_state_lock().min_size = size; // Make windows re-check the window size bounds. let size = self.inner_size(); self.set_inner_size(size.into()); } #[inline] pub fn set_max_inner_size(&self, size: Option<Size>) { self.window_state_lock().max_size = size; // Make windows re-check the window size bounds. let size = self.inner_size(); self.set_inner_size(size.into()); } #[inline] pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { None } #[inline] pub fn set_resize_increments(&self, _increments: Option<Size>) {} #[inline] pub fn set_resizable(&self, resizable: bool) { let window = self.window.clone(); let window_state = Arc::clone(&self.window_state); self.thread_executor.execute_in_thread(move || { let _ = &window; WindowState::set_window_flags(window_state.lock().unwrap(), window.0, |f| { f.set(WindowFlags::RESIZABLE, resizable) }); }); } #[inline] pub fn is_resizable(&self) -> bool { let window_state = self.window_state_lock(); window_state.window_flags.contains(WindowFlags::RESIZABLE) } #[inline] pub fn set_enabled_buttons(&self, buttons: WindowButtons) { let window = self.window.clone(); let window_state = Arc::clone(&self.window_state); self.thread_executor.execute_in_thread(move || { let _ = &window; WindowState::set_window_flags(window_state.lock().unwrap(), window.0, |f| { f.set( WindowFlags::MINIMIZABLE, buttons.contains(WindowButtons::MINIMIZE), ); f.set( WindowFlags::MAXIMIZABLE, buttons.contains(WindowButtons::MAXIMIZE), ); f.set( WindowFlags::CLOSABLE, buttons.contains(WindowButtons::CLOSE), ) }); }); } pub fn enabled_buttons(&self) -> WindowButtons { let mut buttons = WindowButtons::empty(); let window_state = self.window_state_lock(); if window_state.window_flags.contains(WindowFlags::MINIMIZABLE) { buttons |= WindowButtons::MINIMIZE; } if window_state.window_flags.contains(WindowFlags::MAXIMIZABLE) { buttons |= WindowButtons::MAXIMIZE; } if window_state.window_flags.contains(WindowFlags::CLOSABLE) { buttons |= WindowButtons::CLOSE; } buttons } /// Returns the `hwnd` of this window. #[inline] pub fn hwnd(&self) -> HWND { self.window.0 } #[inline] pub fn hinstance(&self) -> HINSTANCE { unsafe { super::get_window_long(self.hwnd(), GWLP_HINSTANCE) } } #[inline] pub fn raw_window_handle(&self) -> RawWindowHandle { let mut window_handle = Win32WindowHandle::empty(); window_handle.hwnd = self.window.0 as *mut _; window_handle.hinstance = self.hinstance() as *mut _; RawWindowHandle::Win32(window_handle) } #[inline] pub fn raw_display_handle(&self) -> RawDisplayHandle { RawDisplayHandle::Windows(WindowsDisplayHandle::empty()) } #[inline] pub fn set_cursor_icon(&self, cursor: CursorIcon) { self.window_state_lock().mouse.cursor = cursor; self.thread_executor.execute_in_thread(move || unsafe { let cursor = LoadCursorW(0, cursor.to_windows_cursor()); SetCursor(cursor); }); } #[inline] pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> { let confine = match mode { CursorGrabMode::None => false, CursorGrabMode::Confined => true, CursorGrabMode::Locked => { return Err(ExternalError::NotSupported(NotSupportedError::new())) } }; let window = self.window.clone(); let window_state = Arc::clone(&self.window_state); let (tx, rx) = channel(); self.thread_executor.execute_in_thread(move || { let _ = &window; let result = window_state .lock() .unwrap() .mouse .set_cursor_flags(window.0, |f| f.set(CursorFlags::GRABBED, confine)) .map_err(|e| ExternalError::Os(os_error!(e))); let _ = tx.send(result); }); rx.recv().unwrap() } #[inline] pub fn set_cursor_visible(&self, visible: bool) { let window = self.window.clone(); let window_state = Arc::clone(&self.window_state); let (tx, rx) = channel(); self.thread_executor.execute_in_thread(move || { let _ = &window; let result = window_state .lock() .unwrap() .mouse .set_cursor_flags(window.0, |f| f.set(CursorFlags::HIDDEN, !visible)) .map_err(|e| e.to_string()); let _ = tx.send(result); }); rx.recv().unwrap().ok(); } #[inline] pub fn scale_factor(&self) -> f64 { self.window_state_lock().scale_factor } #[inline] pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> { let scale_factor = self.scale_factor(); let (x, y) = position.to_physical::<i32>(scale_factor).into(); let mut point = POINT { x, y }; unsafe { if ClientToScreen(self.hwnd(), &mut point) == false.into() { return Err(ExternalError::Os(os_error!(io::Error::last_os_error()))); } if SetCursorPos(point.x, point.y) == false.into() { return Err(ExternalError::Os(os_error!(io::Error::last_os_error()))); } } Ok(()) } #[inline] pub fn drag_window(&self) -> Result<(), ExternalError> { unsafe { let points = { let mut pos = mem::zeroed(); GetCursorPos(&mut pos); pos }; let points = POINTS { x: points.x as i16, y: points.y as i16, }; ReleaseCapture(); self.window_state_lock().dragging = true; PostMessageW( self.hwnd(), WM_NCLBUTTONDOWN, HTCAPTION as WPARAM, &points as *const _ as LPARAM, ); } Ok(()) } #[inline] pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), ExternalError> { Err(ExternalError::NotSupported(NotSupportedError::new())) } #[inline] pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> { let window = self.window.clone(); let window_state = Arc::clone(&self.window_state); self.thread_executor.execute_in_thread(move || { WindowState::set_window_flags(window_state.lock().unwrap(), window.0, |f| { f.set(WindowFlags::IGNORE_CURSOR_EVENT, !hittest) }); }); Ok(()) } #[inline] pub fn id(&self) -> WindowId { WindowId(self.hwnd()) } #[inline] pub fn set_minimized(&self, minimized: bool) { let window = self.window.clone(); let window_state = Arc::clone(&self.window_state); let is_minimized = util::is_minimized(self.hwnd()); self.thread_executor.execute_in_thread(move || { let _ = &window; WindowState::set_window_flags_in_place(&mut window_state.lock().unwrap(), |f| { f.set(WindowFlags::MINIMIZED, is_minimized) }); WindowState::set_window_flags(window_state.lock().unwrap(), window.0, |f| { f.set(WindowFlags::MINIMIZED, minimized) }); }); } #[inline] pub fn is_minimized(&self) -> Option<bool> { Some(util::is_minimized(self.hwnd())) } #[inline] pub fn set_maximized(&self, maximized: bool) { let window = self.window.clone(); let window_state = Arc::clone(&self.window_state); self.thread_executor.execute_in_thread(move || { let _ = &window; WindowState::set_window_flags(window_state.lock().unwrap(), window.0, |f| { f.set(WindowFlags::MAXIMIZED, maximized) }); }); } #[inline] pub fn is_maximized(&self) -> bool { let window_state = self.window_state_lock(); window_state.window_flags.contains(WindowFlags::MAXIMIZED) } #[inline] pub fn fullscreen(&self) -> Option<Fullscreen> { let window_state = self.window_state_lock(); window_state.fullscreen.clone() } #[inline] pub fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) { let window = self.window.clone(); let window_state = Arc::clone(&self.window_state); let mut window_state_lock = window_state.lock().unwrap(); let old_fullscreen = window_state_lock.fullscreen.clone(); if window_state_lock.fullscreen == fullscreen { return; } window_state_lock.fullscreen = fullscreen.clone(); drop(window_state_lock); self.thread_executor.execute_in_thread(move || { let _ = &window; // Change video mode if we're transitioning to or from exclusive // fullscreen match (&old_fullscreen, &fullscreen) { (_, Some(Fullscreen::Exclusive(video_mode))) => { let monitor = video_mode.monitor(); let monitor_info = monitor::get_monitor_info(monitor.hmonitor()).unwrap(); let res = unsafe { ChangeDisplaySettingsExW( monitor_info.szDevice.as_ptr(), &*video_mode.native_video_mode, 0, CDS_FULLSCREEN, ptr::null(), ) }; debug_assert!(res != DISP_CHANGE_BADFLAGS); debug_assert!(res != DISP_CHANGE_BADMODE); debug_assert!(res != DISP_CHANGE_BADPARAM); debug_assert!(res != DISP_CHANGE_FAILED); assert_eq!(res, DISP_CHANGE_SUCCESSFUL); } (Some(Fullscreen::Exclusive(_)), _) => { let res = unsafe { ChangeDisplaySettingsExW( ptr::null(), ptr::null(), 0, CDS_FULLSCREEN, ptr::null(), ) }; debug_assert!(res != DISP_CHANGE_BADFLAGS); debug_assert!(res != DISP_CHANGE_BADMODE); debug_assert!(res != DISP_CHANGE_BADPARAM); debug_assert!(res != DISP_CHANGE_FAILED); assert_eq!(res, DISP_CHANGE_SUCCESSFUL); } _ => (), } unsafe { // There are some scenarios where calling `ChangeDisplaySettingsExW` takes long // enough to execute that the DWM thinks our program has frozen and takes over // our program's window. When that happens, the `SetWindowPos` call below gets // eaten and the window doesn't get set to the proper fullscreen position. // // Calling `PeekMessageW` here notifies Windows that our process is still running // fine, taking control back from the DWM and ensuring that the `SetWindowPos` call // below goes through. let mut msg = mem::zeroed(); PeekMessageW(&mut msg, 0, 0, 0, PM_NOREMOVE); } // Update window style WindowState::set_window_flags(window_state.lock().unwrap(), window.0, |f| { f.set( WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN, matches!(fullscreen, Some(Fullscreen::Exclusive(_))), ); f.set( WindowFlags::MARKER_BORDERLESS_FULLSCREEN, matches!(fullscreen, Some(Fullscreen::Borderless(_))), ); }); // Mark as fullscreen window wrt to z-order // // this needs to be called before the below fullscreen SetWindowPos as this itself // will generate WM_SIZE messages of the old window size that can race with what we set below unsafe { taskbar_mark_fullscreen(window.0, fullscreen.is_some()); } // Update window bounds match &fullscreen { Some(fullscreen) => { // Save window bounds before entering fullscreen let placement = unsafe { let mut placement = mem::zeroed(); GetWindowPlacement(window.0, &mut placement); placement }; window_state.lock().unwrap().saved_window = Some(SavedWindow { placement }); let monitor = match &fullscreen { Fullscreen::Exclusive(video_mode) => video_mode.monitor(), Fullscreen::Borderless(Some(monitor)) => monitor.clone(), Fullscreen::Borderless(None) => monitor::current_monitor(window.0), }; let position: (i32, i32) = monitor.position().into(); let size: (u32, u32) = monitor.size().into(); unsafe { SetWindowPos( window.0, 0, position.0, position.1, size.0 as i32, size.1 as i32, SWP_ASYNCWINDOWPOS | SWP_NOZORDER, ); InvalidateRgn(window.0, 0, false.into()); } } None => { let mut window_state_lock = window_state.lock().unwrap(); if let Some(SavedWindow { placement }) = window_state_lock.saved_window.take() { drop(window_state_lock); unsafe { SetWindowPlacement(window.0, &placement); InvalidateRgn(window.0, 0, false.into()); } } } } }); } #[inline] pub fn set_decorations(&self, decorations: bool) { let window = self.window.clone(); let window_state = Arc::clone(&self.window_state); self.thread_executor.execute_in_thread(move || { let _ = &window; WindowState::set_window_flags(window_state.lock().unwrap(), window.0, |f| { f.set(WindowFlags::MARKER_DECORATIONS, decorations) }); }); } #[inline] pub fn is_decorated(&self) -> bool { let window_state = self.window_state_lock(); window_state .window_flags .contains(WindowFlags::MARKER_DECORATIONS) } #[inline] pub fn set_window_level(&self, level: WindowLevel) { let window = self.window.clone(); let window_state = Arc::clone(&self.window_state); self.thread_executor.execute_in_thread(move || { let _ = &window; WindowState::set_window_flags(window_state.lock().unwrap(), window.0, |f| { f.set( WindowFlags::ALWAYS_ON_TOP, level == WindowLevel::AlwaysOnTop, ); f.set( WindowFlags::ALWAYS_ON_BOTTOM, level == WindowLevel::AlwaysOnBottom, ); }); }); } #[inline] pub fn current_monitor(&self) -> Option<MonitorHandle> { Some(monitor::current_monitor(self.hwnd())) } #[inline] pub fn set_window_icon(&self, window_icon: Option<Icon>) { if let Some(ref window_icon) = window_icon { window_icon .inner .set_for_window(self.hwnd(), IconType::Small); } else { icon::unset_for_window(self.hwnd(), IconType::Small); } self.window_state_lock().window_icon = window_icon; } #[inline] pub fn set_enable(&self, enabled: bool) { unsafe { EnableWindow(self.hwnd(), enabled.into()) }; } #[inline] pub fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>) { if let Some(ref taskbar_icon) = taskbar_icon { taskbar_icon .inner .set_for_window(self.hwnd(), IconType::Big); } else { icon::unset_for_window(self.hwnd(), IconType::Big); } self.window_state_lock().taskbar_icon = taskbar_icon; } #[inline] pub fn set_ime_position(&self, spot: Position) { unsafe { ImeContext::current(self.hwnd()).set_ime_position(spot, self.scale_factor()); } } #[inline] pub fn set_ime_allowed(&self, allowed: bool) { self.window_state_lock().ime_allowed = allowed; unsafe { ImeContext::set_ime_allowed(self.hwnd(), allowed); } } #[inline] pub fn set_ime_purpose(&self, _purpose: ImePurpose) {} #[inline] pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) { let window = self.window.clone(); let active_window_handle = unsafe { GetActiveWindow() }; if window.0 == active_window_handle { return; } self.thread_executor.execute_in_thread(move || unsafe { let _ = &window; let (flags, count) = request_type .map(|ty| match ty { UserAttentionType::Critical => (FLASHW_ALL | FLASHW_TIMERNOFG, u32::MAX), UserAttentionType::Informational => (FLASHW_TRAY | FLASHW_TIMERNOFG, 0), }) .unwrap_or((FLASHW_STOP, 0)); let flash_info = FLASHWINFO { cbSize: mem::size_of::<FLASHWINFO>() as u32, hwnd: window.0, dwFlags: flags, uCount: count, dwTimeout: 0, }; FlashWindowEx(&flash_info); }); } #[inline] pub fn set_theme(&self, theme: Option<Theme>) { try_theme(self.window.0, theme); } #[inline] pub fn theme(&self) -> Option<Theme> { Some(self.window_state_lock().current_theme) } #[inline] pub fn has_focus(&self) -> bool { let window_state = self.window_state.lock().unwrap(); window_state.has_active_focus() } pub fn title(&self) -> String { let len = unsafe { GetWindowTextLengthW(self.window.0) } + 1; let mut buf = vec![0; len as usize]; unsafe { GetWindowTextW(self.window.0, buf.as_mut_ptr(), len) }; util::decode_wide(&buf).to_string_lossy().to_string() } #[inline] pub fn set_skip_taskbar(&self, skip: bool) { self.window_state_lock().skip_taskbar = skip; unsafe { set_skip_taskbar(self.hwnd(), skip) }; } #[inline] pub fn set_undecorated_shadow(&self, shadow: bool) { let window = self.window.clone(); let window_state = Arc::clone(&self.window_state); self.thread_executor.execute_in_thread(move || { let _ = &window; WindowState::set_window_flags(window_state.lock().unwrap(), window.0, |f| { f.set(WindowFlags::MARKER_UNDECORATED_SHADOW, shadow) }); }); } #[inline] pub fn focus_window(&self) { let window = self.window.clone(); let window_flags = self.window_state_lock().window_flags(); let is_visible = window_flags.contains(WindowFlags::VISIBLE); let is_minimized = util::is_minimized(self.hwnd()); let is_foreground = window.0 == unsafe { GetForegroundWindow() }; if is_visible && !is_minimized && !is_foreground { unsafe { force_window_active(window.0) }; } } #[inline] pub fn set_content_protected(&self, protected: bool) { unsafe { SetWindowDisplayAffinity( self.hwnd(), if protected { WDA_EXCLUDEFROMCAPTURE } else { WDA_NONE }, ) }; } } impl Drop for Window { #[inline] fn drop(&mut self) { unsafe { // The window must be destroyed from the same thread that created it, so we send a // custom message to be handled by our callback to do the actual work. PostMessageW(self.hwnd(), DESTROY_MSG_ID.get(), 0, 0); } } } /// A simple non-owning wrapper around a window. #[doc(hidden)] #[derive(Clone)] pub struct WindowWrapper(HWND); // Send and Sync are not implemented for HWND and HDC, we have to wrap it and implement them manually. // For more info see: // https://github.com/retep998/winapi-rs/issues/360 // https://github.com/retep998/winapi-rs/issues/396 unsafe impl Sync for WindowWrapper {} unsafe impl Send for WindowWrapper {} pub(super) struct InitData<'a, T: 'static> { // inputs pub event_loop: &'a EventLoopWindowTarget<T>, pub attributes: WindowAttributes, pub pl_attribs: PlatformSpecificWindowBuilderAttributes, pub window_flags: WindowFlags, // outputs pub window: Option<Window>, } impl<'a, T: 'static> InitData<'a, T> { unsafe fn create_window(&self, window: HWND) -> Window { // Register for touch events if applicable { let digitizer = GetSystemMetrics(SM_DIGITIZER) as u32; if digitizer & NID_READY != 0 { RegisterTouchWindow(window, TWF_WANTPALM); } } let dpi = hwnd_dpi(window); let scale_factor = dpi_to_scale_factor(dpi); // If the system theme is dark, we need to set the window theme now // before we update the window flags (and possibly show the // window for the first time). let current_theme = try_theme(window, self.attributes.preferred_theme); let window_state = { let window_state = WindowState::new( &self.attributes, scale_factor, current_theme, self.attributes.preferred_theme, ); let window_state = Arc::new(Mutex::new(window_state)); WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { *f = self.window_flags }); window_state }; enable_non_client_dpi_scaling(window); ImeContext::set_ime_allowed(window, false); Window { window: WindowWrapper(window), window_state, thread_executor: self.event_loop.create_thread_executor(), } } unsafe fn create_window_data(&self, win: &Window) -> event_loop::WindowData<T> { let file_drop_handler = if self.pl_attribs.drag_and_drop { let ole_init_result = OleInitialize(ptr::null_mut()); // It is ok if the initialize result is `S_FALSE` because it might happen that // multiple windows are created on the same thread. if ole_init_result == OLE_E_WRONGCOMPOBJ { panic!("OleInitialize failed! Result was: `OLE_E_WRONGCOMPOBJ`"); } else if ole_init_result == RPC_E_CHANGED_MODE { panic!( "OleInitialize failed! Result was: `RPC_E_CHANGED_MODE`. \ Make sure other crates are not using multithreaded COM library \ on the same thread or disable drag and drop support." ); } let file_drop_runner = self.event_loop.runner_shared.clone(); let file_drop_handler = FileDropHandler::new( win.window.0, Box::new(move |event| { if let Ok(e) = event.map_nonuser_event() { file_drop_runner.send_event(e) } }), ); let handler_interface_ptr = &mut (*file_drop_handler.data).interface as *mut _ as *mut c_void; assert_eq!(RegisterDragDrop(win.window.0, handler_interface_ptr), S_OK); Some(file_drop_handler) } else { None }; self.event_loop.runner_shared.register_window(win.window.0); event_loop::WindowData { window_state: win.window_state.clone(), event_loop_runner: self.event_loop.runner_shared.clone(), _file_drop_handler: file_drop_handler, userdata_removed: Cell::new(false), recurse_depth: Cell::new(0), } } // Returns a pointer to window user data on success. // The user data will be registered for the window and can be accessed within the window event callback. pub unsafe fn on_nccreate(&mut self, window: HWND) -> Option<isize> { let runner = self.event_loop.runner_shared.clone(); let result = runner.catch_unwind(|| { let window = self.create_window(window); let window_data = self.create_window_data(&window); (window, window_data) }); result.map(|(win, userdata)| { self.window = Some(win); let userdata = Box::into_raw(Box::new(userdata)); userdata as _ }) } pub unsafe fn on_create(&mut self) { let win = self.window.as_mut().expect("failed window creation"); // making the window transparent if self.attributes.transparent && !self.pl_attribs.no_redirection_bitmap { // Empty region for the blur effect, so the window is fully transparent let region = CreateRectRgn(0, 0, -1, -1); let bb = DWM_BLURBEHIND { dwFlags: DWM_BB_ENABLE | DWM_BB_BLURREGION, fEnable: true.into(), hRgnBlur: region, fTransitionOnMaximized: false.into(), }; let hr = DwmEnableBlurBehindWindow(win.hwnd(), &bb); if hr < 0 { warn!( "Setting transparent window is failed. HRESULT Code: 0x{:X}", hr ); } DeleteObject(region); } win.set_skip_taskbar(self.pl_attribs.skip_taskbar); win.set_window_icon(self.attributes.window_icon.clone()); win.set_taskbar_icon(self.pl_attribs.taskbar_icon.clone()); let attributes = self.attributes.clone(); if attributes.content_protected { win.set_content_protected(true); } // Set visible before setting the size to ensure the // attribute is correctly applied. win.set_visible(attributes.visible); win.set_enabled_buttons(attributes.enabled_buttons); if attributes.fullscreen.is_some() { win.set_fullscreen(attributes.fullscreen.map(Into::into)); force_window_active(win.window.0); } else { let size = attributes .inner_size .unwrap_or_else(|| PhysicalSize::new(800, 600).into()); let max_size = attributes .max_inner_size .unwrap_or_else(|| PhysicalSize::new(f64::MAX, f64::MAX).into()); let min_size = attributes .min_inner_size .unwrap_or_else(|| PhysicalSize::new(0, 0).into()); let clamped_size = Size::clamp(size, min_size, max_size, win.scale_factor()); win.set_inner_size(clamped_size); if attributes.maximized { // Need to set MAXIMIZED after setting `inner_size` as // `Window::set_inner_size` changes MAXIMIZED to false. win.set_maximized(true); } } // let margins = MARGINS { // cxLeftWidth: 1, // cxRightWidth: 1, // cyTopHeight: 1, // cyBottomHeight: 1, // }; // dbg!(DwmExtendFrameIntoClientArea(win.hwnd(), &margins as *const _)); if let Some(position) = attributes.position { win.set_outer_position(position); } } } unsafe fn init<T>( attributes: WindowAttributes, pl_attribs: PlatformSpecificWindowBuilderAttributes, event_loop: &EventLoopWindowTarget<T>, ) -> Result<Window, RootOsError> where T: 'static, { let title = util::encode_wide(&attributes.title); let class_name = register_window_class::<T>(); let mut window_flags = WindowFlags::empty(); window_flags.set(WindowFlags::MARKER_DECORATIONS, attributes.decorations); window_flags.set( WindowFlags::MARKER_UNDECORATED_SHADOW, pl_attribs.decoration_shadow, ); window_flags.set( WindowFlags::ALWAYS_ON_TOP, attributes.window_level == WindowLevel::AlwaysOnTop, ); window_flags.set( WindowFlags::ALWAYS_ON_BOTTOM, attributes.window_level == WindowLevel::AlwaysOnBottom, ); window_flags.set( WindowFlags::NO_BACK_BUFFER, pl_attribs.no_redirection_bitmap, ); window_flags.set(WindowFlags::MARKER_ACTIVATE, attributes.active); window_flags.set(WindowFlags::TRANSPARENT, attributes.transparent); // WindowFlags::VISIBLE and MAXIMIZED are set down below after the window has been configured. window_flags.set(WindowFlags::RESIZABLE, attributes.resizable); // Will be changed later using `window.set_enabled_buttons` but we need to set a default here // so the diffing later can work. window_flags.set(WindowFlags::CLOSABLE, true); let parent = match attributes.parent_window { Some(RawWindowHandle::Win32(handle)) => { window_flags.set(WindowFlags::CHILD, true); if pl_attribs.menu.is_some() { warn!("Setting a menu on a child window is unsupported"); } Some(handle.hwnd as HWND) } Some(raw) => unreachable!("Invalid raw window handle {raw:?} on Windows"), None => match pl_attribs.owner { Some(parent) => { window_flags.set(WindowFlags::POPUP, true); Some(parent) } None => { window_flags.set(WindowFlags::ON_TASKBAR, true); None } }, }; let mut initdata = InitData { event_loop, attributes, pl_attribs: pl_attribs.clone(), window_flags, window: None, }; let (style, ex_style) = window_flags.to_window_styles(); let handle = CreateWindowExW( ex_style, class_name.as_ptr(), title.as_ptr(), style, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, parent.unwrap_or(0), pl_attribs.menu.unwrap_or(0), util::get_instance_handle(), &mut initdata as *mut _ as *mut _, ); // If the window creation in `InitData` panicked, then should resume panicking here if let Err(panic_error) = event_loop.runner_shared.take_panic_error() { panic::resume_unwind(panic_error) } if handle == 0 { return Err(os_error!(io::Error::last_os_error())); } // If the handle is non-null, then window creation must have succeeded, which means // that we *must* have populated the `InitData.window` field. Ok(initdata.window.unwrap()) } unsafe fn register_window_class<T: 'static>() -> Vec<u16> { let class_name = util::encode_wide("Window Class"); let class = WNDCLASSEXW { cbSize: mem::size_of::<WNDCLASSEXW>() as u32, style: CS_HREDRAW | CS_VREDRAW, lpfnWndProc: Some(super::event_loop::public_window_callback::<T>), cbClsExtra: 0, cbWndExtra: 0, hInstance: util::get_instance_handle(), hIcon: 0, hCursor: 0, // must be null in order for cursor state to work properly hbrBackground: 0, lpszMenuName: ptr::null(), lpszClassName: class_name.as_ptr(), hIconSm: 0, }; // We ignore errors because registering the same window class twice would trigger // an error, and because errors here are detected during CreateWindowEx anyway. // Also since there is no weird element in the struct, there is no reason for this // call to fail. RegisterClassExW(&class); class_name } struct ComInitialized(*mut ()); impl Drop for ComInitialized { fn drop(&mut self) { unsafe { CoUninitialize() }; } } thread_local! { static COM_INITIALIZED: ComInitialized = { unsafe { CoInitializeEx(ptr::null(), COINIT_APARTMENTTHREADED); ComInitialized(ptr::null_mut()) } }; static TASKBAR_LIST: Cell<*mut ITaskbarList> = Cell::new(ptr::null_mut()); static TASKBAR_LIST2: Cell<*mut ITaskbarList2> = Cell::new(ptr::null_mut()); } pub fn com_initialized() { COM_INITIALIZED.with(|_| {}); } // Reference Implementation: // https://github.com/chromium/chromium/blob/f18e79d901f56154f80eea1e2218544285e62623/ui/views/win/fullscreen_handler.cc // // As per MSDN marking the window as fullscreen should ensure that the // taskbar is moved to the bottom of the Z-order when the fullscreen window // is activated. If the window is not fullscreen, the Shell falls back to // heuristics to determine how the window should be treated, which means // that it could still consider the window as fullscreen. :( unsafe fn taskbar_mark_fullscreen(handle: HWND, fullscreen: bool) { com_initialized(); TASKBAR_LIST2.with(|task_bar_list2_ptr| { let mut task_bar_list2 = task_bar_list2_ptr.get(); if task_bar_list2.is_null() { let hr = CoCreateInstance( &CLSID_TaskbarList, ptr::null_mut(), CLSCTX_ALL, &IID_ITaskbarList2, &mut task_bar_list2 as *mut _ as *mut _, ); if hr != S_OK { // In visual studio retrieving the taskbar list fails return; } let hr_init = (*(*task_bar_list2).lpVtbl).parent.HrInit; if hr_init(task_bar_list2.cast()) != S_OK { // In some old windows, the taskbar object could not be created, we just ignore it return; } task_bar_list2_ptr.set(task_bar_list2) } task_bar_list2 = task_bar_list2_ptr.get(); let mark_fullscreen_window = (*(*task_bar_list2).lpVtbl).MarkFullscreenWindow; mark_fullscreen_window(task_bar_list2, handle, fullscreen.into()); }) } pub(crate) unsafe fn set_skip_taskbar(hwnd: HWND, skip: bool) { com_initialized(); TASKBAR_LIST.with(|task_bar_list_ptr| { let mut task_bar_list = task_bar_list_ptr.get(); if task_bar_list.is_null() { let hr = CoCreateInstance( &CLSID_TaskbarList, ptr::null_mut(), CLSCTX_ALL, &IID_ITaskbarList, &mut task_bar_list as *mut _ as *mut _, ); if hr != S_OK { // In visual studio retrieving the taskbar list fails return; } let hr_init = (*(*task_bar_list).lpVtbl).HrInit; if hr_init(task_bar_list.cast()) != S_OK { // In some old windows, the taskbar object could not be created, we just ignore it return; } task_bar_list_ptr.set(task_bar_list) } task_bar_list = task_bar_list_ptr.get(); if skip { let delete_tab = (*(*task_bar_list).lpVtbl).DeleteTab; delete_tab(task_bar_list, hwnd); } else { let add_tab = (*(*task_bar_list).lpVtbl).AddTab; add_tab(task_bar_list, hwnd); } }); } unsafe fn force_window_active(handle: HWND) { // In some situation, calling SetForegroundWindow could not bring up the window, // This is a little hack which can "steal" the foreground window permission // We only call this function in the window creation, so it should be fine. // See : https://stackoverflow.com/questions/10740346/setforegroundwindow-only-working-while-visual-studio-is-open let alt_sc = MapVirtualKeyW(VK_MENU as u32, MAPVK_VK_TO_VSC); let inputs = [ INPUT { r#type: INPUT_KEYBOARD, Anonymous: INPUT_0 { ki: KEYBDINPUT { wVk: VK_LMENU, wScan: alt_sc as u16, dwFlags: KEYEVENTF_EXTENDEDKEY, dwExtraInfo: 0, time: 0, }, }, }, INPUT { r#type: INPUT_KEYBOARD, Anonymous: INPUT_0 { ki: KEYBDINPUT { wVk: VK_LMENU, wScan: alt_sc as u16, dwFlags: KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, dwExtraInfo: 0, time: 0, }, }, }, ]; // Simulate a key press and release SendInput( inputs.len() as u32, inputs.as_ptr(), mem::size_of::<INPUT>() as i32, ); SetForegroundWindow(handle); }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/platform_impl/windows/window_state.rs
Rust
use crate::{ dpi::{PhysicalPosition, PhysicalSize, Size}, event::ModifiersState, icon::Icon, platform_impl::platform::{event_loop, util, Fullscreen}, window::{CursorIcon, Theme, WindowAttributes}, }; use std::io; use std::sync::MutexGuard; use windows_sys::Win32::{ Foundation::{HWND, RECT}, Graphics::Gdi::InvalidateRgn, UI::WindowsAndMessaging::{ AdjustWindowRectEx, EnableMenuItem, GetMenu, GetSystemMenu, GetWindowLongW, SendMessageW, SetWindowLongW, SetWindowPos, ShowWindow, GWL_EXSTYLE, GWL_STYLE, HWND_BOTTOM, HWND_NOTOPMOST, HWND_TOPMOST, MF_BYCOMMAND, MF_DISABLED, MF_ENABLED, SC_CLOSE, SWP_ASYNCWINDOWPOS, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOREPOSITION, SWP_NOSIZE, SWP_NOZORDER, SW_HIDE, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE, SW_SHOW, SW_SHOWNOACTIVATE, WINDOWPLACEMENT, WINDOW_EX_STYLE, WINDOW_STYLE, WS_BORDER, WS_CAPTION, WS_CHILD, WS_CLIPCHILDREN, WS_CLIPSIBLINGS, WS_EX_ACCEPTFILES, WS_EX_APPWINDOW, WS_EX_LAYERED, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_EX_WINDOWEDGE, WS_MAXIMIZE, WS_MAXIMIZEBOX, WS_MINIMIZE, WS_MINIMIZEBOX, WS_OVERLAPPEDWINDOW, WS_POPUP, WS_SIZEBOX, WS_SYSMENU, WS_VISIBLE, }, }; /// Contains information about states and the window that the callback is going to use. pub(crate) struct WindowState { pub mouse: MouseProperties, /// Used by `WM_GETMINMAXINFO`. pub min_size: Option<Size>, pub max_size: Option<Size>, pub window_icon: Option<Icon>, pub taskbar_icon: Option<Icon>, pub saved_window: Option<SavedWindow>, pub scale_factor: f64, pub modifiers_state: ModifiersState, pub fullscreen: Option<Fullscreen>, pub current_theme: Theme, pub preferred_theme: Option<Theme>, pub high_surrogate: Option<u16>, pub window_flags: WindowFlags, pub ime_state: ImeState, pub ime_allowed: bool, // Used by WM_NCACTIVATE, WM_SETFOCUS and WM_KILLFOCUS pub is_active: bool, pub is_focused: bool, pub dragging: bool, pub skip_taskbar: bool, } #[derive(Clone)] pub struct SavedWindow { pub placement: WINDOWPLACEMENT, } #[derive(Clone)] pub struct MouseProperties { pub cursor: CursorIcon, pub capture_count: u32, cursor_flags: CursorFlags, pub last_position: Option<PhysicalPosition<f64>>, } bitflags! { pub struct CursorFlags: u8 { const GRABBED = 1 << 0; const HIDDEN = 1 << 1; const IN_WINDOW = 1 << 2; } } bitflags! { pub struct WindowFlags: u32 { const RESIZABLE = 1 << 0; const MINIMIZABLE = 1 << 1; const MAXIMIZABLE = 1 << 2; const CLOSABLE = 1 << 3; const VISIBLE = 1 << 4; const ON_TASKBAR = 1 << 5; const ALWAYS_ON_TOP = 1 << 6; const ALWAYS_ON_BOTTOM = 1 << 7; const NO_BACK_BUFFER = 1 << 8; const TRANSPARENT = 1 << 9; const CHILD = 1 << 10; const MAXIMIZED = 1 << 11; const POPUP = 1 << 12; /// Marker flag for fullscreen. Should always match `WindowState::fullscreen`, but is /// included here to make masking easier. const MARKER_EXCLUSIVE_FULLSCREEN = 1 << 13; const MARKER_BORDERLESS_FULLSCREEN = 1 << 14; /// The `WM_SIZE` event contains some parameters that can effect the state of `WindowFlags`. /// In most cases, it's okay to let those parameters change the state. However, when we're /// running the `WindowFlags::apply_diff` function, we *don't* want those parameters to /// effect our stored state, because the purpose of `apply_diff` is to update the actual /// window's state to match our stored state. This controls whether to accept those changes. const MARKER_RETAIN_STATE_ON_SIZE = 1 << 15; const MARKER_IN_SIZE_MOVE = 1 << 16; const MINIMIZED = 1 << 17; const IGNORE_CURSOR_EVENT = 1 << 18; /// Fully decorated window (incl. caption, border and drop shadow). const MARKER_DECORATIONS = 1 << 19; /// Drop shadow for undecorated windows. const MARKER_UNDECORATED_SHADOW = 1 << 20; const MARKER_ACTIVATE = 1 << 21; const EXCLUSIVE_FULLSCREEN_OR_MASK = WindowFlags::ALWAYS_ON_TOP.bits; } } #[derive(Eq, PartialEq)] pub enum ImeState { Disabled, Enabled, Preedit, } impl WindowState { pub(crate) fn new( attributes: &WindowAttributes, scale_factor: f64, current_theme: Theme, preferred_theme: Option<Theme>, ) -> WindowState { WindowState { mouse: MouseProperties { cursor: CursorIcon::default(), capture_count: 0, cursor_flags: CursorFlags::empty(), last_position: None, }, min_size: attributes.min_inner_size, max_size: attributes.max_inner_size, window_icon: attributes.window_icon.clone(), taskbar_icon: None, saved_window: None, scale_factor, modifiers_state: ModifiersState::default(), fullscreen: None, current_theme, preferred_theme, high_surrogate: None, window_flags: WindowFlags::empty(), ime_state: ImeState::Disabled, ime_allowed: false, is_active: false, is_focused: false, dragging: false, skip_taskbar: false, } } pub fn window_flags(&self) -> WindowFlags { self.window_flags } pub fn set_window_flags<F>(mut this: MutexGuard<'_, Self>, window: HWND, f: F) where F: FnOnce(&mut WindowFlags), { let old_flags = this.window_flags; f(&mut this.window_flags); let new_flags = this.window_flags; drop(this); old_flags.apply_diff(window, new_flags); } pub fn set_window_flags_in_place<F>(&mut self, f: F) where F: FnOnce(&mut WindowFlags), { f(&mut self.window_flags); } pub fn has_active_focus(&self) -> bool { self.is_active && self.is_focused } // Updates is_active and returns whether active-focus state has changed pub fn set_active(&mut self, is_active: bool) -> bool { let old = self.has_active_focus(); self.is_active = is_active; old != self.has_active_focus() } // Updates is_focused and returns whether active-focus state has changed pub fn set_focused(&mut self, is_focused: bool) -> bool { let old = self.has_active_focus(); self.is_focused = is_focused; old != self.has_active_focus() } } impl MouseProperties { pub fn cursor_flags(&self) -> CursorFlags { self.cursor_flags } pub fn set_cursor_flags<F>(&mut self, window: HWND, f: F) -> Result<(), io::Error> where F: FnOnce(&mut CursorFlags), { let old_flags = self.cursor_flags; f(&mut self.cursor_flags); match self.cursor_flags.refresh_os_cursor(window) { Ok(()) => (), Err(e) => { self.cursor_flags = old_flags; return Err(e); } } Ok(()) } } impl WindowFlags { fn mask(mut self) -> WindowFlags { if self.contains(WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN) { self |= WindowFlags::EXCLUSIVE_FULLSCREEN_OR_MASK; } self } pub fn to_window_styles(self) -> (WINDOW_STYLE, WINDOW_EX_STYLE) { // Required styles to properly support common window functionality like aero snap. let mut style = WS_CAPTION | WS_BORDER | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_SYSMENU; let mut style_ex = WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES; if self.contains(WindowFlags::RESIZABLE) { style |= WS_SIZEBOX; } if self.contains(WindowFlags::MAXIMIZABLE) { style |= WS_MAXIMIZEBOX; } if self.contains(WindowFlags::MINIMIZABLE) { style |= WS_MINIMIZEBOX; } if self.contains(WindowFlags::VISIBLE) { style |= WS_VISIBLE; } if self.contains(WindowFlags::ON_TASKBAR) { style_ex |= WS_EX_APPWINDOW; } if self.contains(WindowFlags::ALWAYS_ON_TOP) { style_ex |= WS_EX_TOPMOST; } if self.contains(WindowFlags::NO_BACK_BUFFER) { style_ex |= WS_EX_NOREDIRECTIONBITMAP; } if self.contains(WindowFlags::CHILD) { style |= WS_CHILD; // This is incompatible with WS_POPUP if that gets added eventually. } if self.contains(WindowFlags::POPUP) { style |= WS_POPUP; } if self.contains(WindowFlags::MINIMIZED) { style |= WS_MINIMIZE; } if self.contains(WindowFlags::MAXIMIZED) { style |= WS_MAXIMIZE; } if self.contains(WindowFlags::IGNORE_CURSOR_EVENT) { style_ex |= WS_EX_TRANSPARENT | WS_EX_LAYERED; } if self.intersects( WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN | WindowFlags::MARKER_BORDERLESS_FULLSCREEN, ) { style &= !WS_OVERLAPPEDWINDOW; } (style, style_ex) } /// Adjust the window client rectangle to the return value, if present. fn apply_diff(mut self, window: HWND, mut new: WindowFlags) { self = self.mask(); new = new.mask(); let mut diff = self ^ new; if diff == WindowFlags::empty() { return; } if new.contains(WindowFlags::VISIBLE) { let flag = if !self.contains(WindowFlags::MARKER_ACTIVATE) { self.set(WindowFlags::MARKER_ACTIVATE, true); SW_SHOWNOACTIVATE } else { SW_SHOW }; unsafe { ShowWindow(window, flag); } } if diff.intersects(WindowFlags::ALWAYS_ON_TOP | WindowFlags::ALWAYS_ON_BOTTOM) { unsafe { SetWindowPos( window, match ( new.contains(WindowFlags::ALWAYS_ON_TOP), new.contains(WindowFlags::ALWAYS_ON_BOTTOM), ) { (true, false) => HWND_TOPMOST, (false, false) => HWND_NOTOPMOST, (false, true) => HWND_BOTTOM, (true, true) => unreachable!(), }, 0, 0, 0, 0, SWP_ASYNCWINDOWPOS | SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE, ); InvalidateRgn(window, 0, false.into()); } } if diff.contains(WindowFlags::MAXIMIZED) || new.contains(WindowFlags::MAXIMIZED) { unsafe { ShowWindow( window, match new.contains(WindowFlags::MAXIMIZED) { true => SW_MAXIMIZE, false => SW_RESTORE, }, ); } } // Minimize operations should execute after maximize for proper window animations if diff.contains(WindowFlags::MINIMIZED) { unsafe { ShowWindow( window, match new.contains(WindowFlags::MINIMIZED) { true => SW_MINIMIZE, false => SW_RESTORE, }, ); } diff.remove(WindowFlags::MINIMIZED); } if diff.contains(WindowFlags::CLOSABLE) || new.contains(WindowFlags::CLOSABLE) { let flags = MF_BYCOMMAND | new .contains(WindowFlags::CLOSABLE) .then(|| MF_ENABLED) .unwrap_or(MF_DISABLED); unsafe { EnableMenuItem(GetSystemMenu(window, 0), SC_CLOSE, flags); } } if !new.contains(WindowFlags::VISIBLE) { unsafe { ShowWindow(window, SW_HIDE); } } if diff != WindowFlags::empty() { let (style, style_ex) = new.to_window_styles(); unsafe { SendMessageW( window, event_loop::SET_RETAIN_STATE_ON_SIZE_MSG_ID.get(), 1, 0, ); // This condition is necessary to avoid having an unrestorable window if !new.contains(WindowFlags::MINIMIZED) { SetWindowLongW(window, GWL_STYLE, style as i32); SetWindowLongW(window, GWL_EXSTYLE, style_ex as i32); } let mut flags = SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED; // We generally don't want style changes here to affect window // focus, but for fullscreen windows they must be activated // (i.e. focused) so that they appear on top of the taskbar if !new.contains(WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN) && !new.contains(WindowFlags::MARKER_BORDERLESS_FULLSCREEN) { flags |= SWP_NOACTIVATE; } // Refresh the window frame SetWindowPos(window, 0, 0, 0, 0, 0, flags); SendMessageW( window, event_loop::SET_RETAIN_STATE_ON_SIZE_MSG_ID.get(), 0, 0, ); } } } pub fn adjust_rect(self, hwnd: HWND, mut rect: RECT) -> Result<RECT, io::Error> { unsafe { let mut style = GetWindowLongW(hwnd, GWL_STYLE) as u32; let style_ex = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32; // Frameless style implemented by manually overriding the non-client area in `WM_NCCALCSIZE`. if !self.contains(WindowFlags::MARKER_DECORATIONS) { style &= !(WS_CAPTION | WS_SIZEBOX); } util::win_to_err({ let b_menu = GetMenu(hwnd) != 0; if let (Some(get_dpi_for_window), Some(adjust_window_rect_ex_for_dpi)) = ( *util::GET_DPI_FOR_WINDOW, *util::ADJUST_WINDOW_RECT_EX_FOR_DPI, ) { let dpi = get_dpi_for_window(hwnd); adjust_window_rect_ex_for_dpi(&mut rect, style, b_menu.into(), style_ex, dpi) } else { AdjustWindowRectEx(&mut rect, style, b_menu.into(), style_ex) } })?; Ok(rect) } } pub fn adjust_size(self, hwnd: HWND, size: PhysicalSize<u32>) -> PhysicalSize<u32> { let (width, height): (u32, u32) = size.into(); let rect = RECT { left: 0, right: width as i32, top: 0, bottom: height as i32, }; let rect = self.adjust_rect(hwnd, rect).unwrap_or(rect); let outer_x = (rect.right - rect.left).abs(); let outer_y = (rect.top - rect.bottom).abs(); PhysicalSize::new(outer_x as _, outer_y as _) } pub fn set_size(self, hwnd: HWND, size: PhysicalSize<u32>) { unsafe { let (width, height): (u32, u32) = self.adjust_size(hwnd, size).into(); SetWindowPos( hwnd, 0, 0, 0, width as _, height as _, SWP_ASYNCWINDOWPOS | SWP_NOZORDER | SWP_NOREPOSITION | SWP_NOMOVE | SWP_NOACTIVATE, ); InvalidateRgn(hwnd, 0, false.into()); } } } impl CursorFlags { fn refresh_os_cursor(self, window: HWND) -> Result<(), io::Error> { let client_rect = util::WindowArea::Inner.get_rect(window)?; if util::is_focused(window) { let cursor_clip = match self.contains(CursorFlags::GRABBED) { true => Some(client_rect), false => None, }; let rect_to_tuple = |rect: RECT| (rect.left, rect.top, rect.right, rect.bottom); let active_cursor_clip = rect_to_tuple(util::get_cursor_clip()?); let desktop_rect = rect_to_tuple(util::get_desktop_rect()); let active_cursor_clip = match desktop_rect == active_cursor_clip { true => None, false => Some(active_cursor_clip), }; // We do this check because calling `set_cursor_clip` incessantly will flood the event // loop with `WM_MOUSEMOVE` events, and `refresh_os_cursor` is called by `set_cursor_flags` // which at times gets called once every iteration of the eventloop. if active_cursor_clip != cursor_clip.map(rect_to_tuple) { util::set_cursor_clip(cursor_clip)?; } } let cursor_in_client = self.contains(CursorFlags::IN_WINDOW); if cursor_in_client { util::set_cursor_hidden(self.contains(CursorFlags::HIDDEN)); } else { util::set_cursor_hidden(false); } Ok(()) } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
src/window.rs
Rust
//! The [`Window`] struct and associated types. use std::fmt; use raw_window_handle::{ HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle, }; use crate::{ dpi::{PhysicalPosition, PhysicalSize, Position, Size}, error::{ExternalError, NotSupportedError, OsError}, event_loop::EventLoopWindowTarget, monitor::{MonitorHandle, VideoMode}, platform_impl, }; pub use crate::icon::{BadIcon, Icon}; /// Represents a window. /// /// # Example /// /// ```no_run /// use winit::{ /// event::{Event, WindowEvent}, /// event_loop::EventLoop, /// window::Window, /// }; /// /// let mut event_loop = EventLoop::new(); /// let window = Window::new(&event_loop).unwrap(); /// /// event_loop.run(move |event, _, control_flow| { /// control_flow.set_wait(); /// /// match event { /// Event::WindowEvent { /// event: WindowEvent::CloseRequested, /// .. /// } => control_flow.set_exit(), /// _ => (), /// } /// }); /// ``` pub struct Window { pub(crate) window: platform_impl::Window, } impl fmt::Debug for Window { fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result { fmtr.pad("Window { .. }") } } impl Drop for Window { fn drop(&mut self) { // If the window is in exclusive fullscreen, we must restore the desktop // video mode (generally this would be done on application exit, but // closing the window doesn't necessarily always mean application exit, // such as when there are multiple windows) if let Some(Fullscreen::Exclusive(_)) = self.fullscreen() { self.set_fullscreen(None); } } } /// Identifier of a window. Unique for each window. /// /// Can be obtained with [`window.id()`](`Window::id`). /// /// Whenever you receive an event specific to a window, this event contains a `WindowId` which you /// can then compare to the ids of your windows. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct WindowId(pub(crate) platform_impl::WindowId); impl WindowId { /// Returns a dummy id, useful for unit testing. /// /// # Safety /// /// The only guarantee made about the return value of this function is that /// it will always be equal to itself and to future values returned by this function. /// No other guarantees are made. This may be equal to a real [`WindowId`]. /// /// **Passing this into a winit function will result in undefined behavior.** pub const unsafe fn dummy() -> Self { WindowId(platform_impl::WindowId::dummy()) } } impl From<WindowId> for u64 { fn from(window_id: WindowId) -> Self { window_id.0.into() } } impl From<u64> for WindowId { fn from(raw_id: u64) -> Self { Self(raw_id.into()) } } /// Object that allows building windows. #[derive(Clone, Default)] #[must_use] pub struct WindowBuilder { /// The attributes to use to create the window. pub(crate) window: WindowAttributes, // Platform-specific configuration. pub(crate) platform_specific: platform_impl::PlatformSpecificWindowBuilderAttributes, } impl fmt::Debug for WindowBuilder { fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result { fmtr.debug_struct("WindowBuilder") .field("window", &self.window) .finish() } } /// Attributes to use when creating a window. #[derive(Debug, Clone)] pub struct WindowAttributes { pub inner_size: Option<Size>, pub min_inner_size: Option<Size>, pub max_inner_size: Option<Size>, pub position: Option<Position>, pub resizable: bool, pub enabled_buttons: WindowButtons, pub title: String, pub fullscreen: Option<Fullscreen>, pub maximized: bool, pub visible: bool, pub transparent: bool, pub decorations: bool, pub window_icon: Option<Icon>, pub preferred_theme: Option<Theme>, pub resize_increments: Option<Size>, pub content_protected: bool, pub window_level: WindowLevel, pub parent_window: Option<RawWindowHandle>, pub active: bool, } impl Default for WindowAttributes { #[inline] fn default() -> WindowAttributes { WindowAttributes { inner_size: None, min_inner_size: None, max_inner_size: None, position: None, resizable: true, enabled_buttons: WindowButtons::all(), title: "winit window".to_owned(), maximized: false, fullscreen: None, visible: true, transparent: false, decorations: true, window_level: Default::default(), window_icon: None, preferred_theme: None, resize_increments: None, content_protected: false, parent_window: None, active: true, } } } impl WindowBuilder { /// Initializes a new builder with default values. #[inline] pub fn new() -> Self { Default::default() } /// Get the current window attributes. pub fn window_attributes(&self) -> &WindowAttributes { &self.window } /// Requests the window to be of specific dimensions. /// /// If this is not set, some platform-specific dimensions will be used. /// /// See [`Window::set_inner_size`] for details. #[inline] pub fn with_inner_size<S: Into<Size>>(mut self, size: S) -> Self { self.window.inner_size = Some(size.into()); self } /// Sets the minimum dimensions a window can have. /// /// If this is not set, the window will have no minimum dimensions (aside /// from reserved). /// /// See [`Window::set_min_inner_size`] for details. #[inline] pub fn with_min_inner_size<S: Into<Size>>(mut self, min_size: S) -> Self { self.window.min_inner_size = Some(min_size.into()); self } /// Sets the maximum dimensions a window can have. /// /// If this is not set, the window will have no maximum or will be set to /// the primary monitor's dimensions by the platform. /// /// See [`Window::set_max_inner_size`] for details. #[inline] pub fn with_max_inner_size<S: Into<Size>>(mut self, max_size: S) -> Self { self.window.max_inner_size = Some(max_size.into()); self } /// Sets a desired initial position for the window. /// /// If this is not set, some platform-specific position will be chosen. /// /// See [`Window::set_outer_position`] for details. /// /// ## Platform-specific /// /// - **macOS:** The top left corner position of the window content, the /// window's "inner" position. The window title bar will be placed above /// it. The window will be positioned such that it fits on screen, /// maintaining set `inner_size` if any. /// If you need to precisely position the top left corner of the whole /// window you have to use [`Window::set_outer_position`] after creating /// the window. /// - **Windows:** The top left corner position of the window title bar, /// the window's "outer" position. /// There may be a small gap between this position and the window due to /// the specifics of the Window Manager. /// - **X11:** The top left corner of the window, the window's "outer" /// position. /// - **Others:** Ignored. #[inline] pub fn with_position<P: Into<Position>>(mut self, position: P) -> Self { self.window.position = Some(position.into()); self } /// Sets whether the window is resizable or not. /// /// The default is `true`. /// /// See [`Window::set_resizable`] for details. #[inline] pub fn with_resizable(mut self, resizable: bool) -> Self { self.window.resizable = resizable; self } /// Sets the enabled window buttons. /// /// The default is [`WindowButtons::all`] /// /// See [`Window::set_enabled_buttons`] for details. #[inline] pub fn with_enabled_buttons(mut self, buttons: WindowButtons) -> Self { self.window.enabled_buttons = buttons; self } /// Sets the initial title of the window in the title bar. /// /// The default is `"winit window"`. /// /// See [`Window::set_title`] for details. #[inline] pub fn with_title<T: Into<String>>(mut self, title: T) -> Self { self.window.title = title.into(); self } /// Sets whether the window should be put into fullscreen upon creation. /// /// The default is `None`. /// /// See [`Window::set_fullscreen`] for details. #[inline] pub fn with_fullscreen(mut self, fullscreen: Option<Fullscreen>) -> Self { self.window.fullscreen = fullscreen; self } /// Request that the window is maximized upon creation. /// /// The default is `false`. /// /// See [`Window::set_maximized`] for details. #[inline] pub fn with_maximized(mut self, maximized: bool) -> Self { self.window.maximized = maximized; self } /// Sets whether the window will be initially visible or hidden. /// /// The default is to show the window. /// /// See [`Window::set_visible`] for details. #[inline] pub fn with_visible(mut self, visible: bool) -> Self { self.window.visible = visible; self } /// Sets whether the background of the window should be transparent. /// /// If this is `true`, writing colors with alpha values different than /// `1.0` will produce a transparent window. On some platforms this /// is more of a hint for the system and you'd still have the alpha /// buffer. To control it see [`Window::set_transparent`]. /// /// The default is `false`. #[inline] pub fn with_transparent(mut self, transparent: bool) -> Self { self.window.transparent = transparent; self } /// Get whether the window will support transparency. #[inline] pub fn transparent(&self) -> bool { self.window.transparent } /// Sets whether the window should have a border, a title bar, etc. /// /// The default is `true`. /// /// See [`Window::set_decorations`] for details. #[inline] pub fn with_decorations(mut self, decorations: bool) -> Self { self.window.decorations = decorations; self } /// Sets the window level. /// /// This is just a hint to the OS, and the system could ignore it. /// /// The default is [`WindowLevel::Normal`]. /// /// See [`WindowLevel`] for details. #[inline] pub fn with_window_level(mut self, level: WindowLevel) -> Self { self.window.window_level = level; self } /// Sets the window icon. /// /// The default is `None`. /// /// See [`Window::set_window_icon`] for details. #[inline] pub fn with_window_icon(mut self, window_icon: Option<Icon>) -> Self { self.window.window_icon = window_icon; self } /// Sets a specific theme for the window. /// /// If `None` is provided, the window will use the system theme. /// /// The default is `None`. /// /// ## Platform-specific /// /// - **macOS:** This is an app-wide setting. /// - **Wayland:** This control only CSD. You can also use `WINIT_WAYLAND_CSD_THEME` env variable to set the theme. /// Possible values for env variable are: "dark" and light". /// - **x11:** Build window with `_GTK_THEME_VARIANT` hint set to `dark` or `light`. /// - **iOS / Android / Web / x11 / Orbital:** Ignored. #[inline] pub fn with_theme(mut self, theme: Option<Theme>) -> Self { self.window.preferred_theme = theme; self } /// Build window with resize increments hint. /// /// The default is `None`. /// /// See [`Window::set_resize_increments`] for details. #[inline] pub fn with_resize_increments<S: Into<Size>>(mut self, resize_increments: S) -> Self { self.window.resize_increments = Some(resize_increments.into()); self } /// Prevents the window contents from being captured by other apps. /// /// The default is `false`. /// /// ## Platform-specific /// /// - **macOS**: if `false`, [`NSWindowSharingNone`] is used but doesn't completely /// prevent all apps from reading the window content, for instance, QuickTime. /// - **iOS / Android / Web / x11 / Orbital:** Ignored. /// /// [`NSWindowSharingNone`]: https://developer.apple.com/documentation/appkit/nswindowsharingtype/nswindowsharingnone #[inline] pub fn with_content_protected(mut self, protected: bool) -> Self { self.window.content_protected = protected; self } /// Whether the window will be initially focused or not. /// /// The window should be assumed as not focused by default /// following by the [`WindowEvent::Focused`]. /// /// ## Platform-specific: /// /// **Android / iOS / X11 / Wayland / Orbital:** Unsupported. /// /// [`WindowEvent::Focused`]: crate::event::WindowEvent::Focused. #[inline] pub fn with_active(mut self, active: bool) -> WindowBuilder { self.window.active = active; self } /// Build window with parent window. /// /// The default is `None`. /// /// ## Safety /// /// `parent_window` must be a valid window handle. /// /// ## Platform-specific /// /// - **Windows** : A child window has the WS_CHILD style and is confined /// to the client area of its parent window. For more information, see /// <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows> /// - **X11**: A child window is confined to the client area of its parent window. /// - **Android / iOS / Wayland:** Unsupported. #[inline] pub unsafe fn with_parent_window(mut self, parent_window: Option<RawWindowHandle>) -> Self { self.window.parent_window = parent_window; self } /// Builds the window. /// /// Possible causes of error include denied permission, incompatible system, and lack of memory. /// /// ## Platform-specific /// /// - **Web:** The window is created but not inserted into the web page automatically. Please /// see the web platform module for more information. #[inline] pub fn build<T: 'static>( self, window_target: &EventLoopWindowTarget<T>, ) -> Result<Window, OsError> { platform_impl::Window::new(&window_target.p, self.window, self.platform_specific).map( |window| { window.request_redraw(); Window { window } }, ) } } /// Base Window functions. impl Window { /// Creates a new Window for platforms where this is appropriate. /// /// This function is equivalent to [`WindowBuilder::new().build(event_loop)`]. /// /// Error should be very rare and only occur in case of permission denied, incompatible system, /// out of memory, etc. /// /// ## Platform-specific /// /// - **Web:** The window is created but not inserted into the web page automatically. Please /// see the web platform module for more information. /// /// [`WindowBuilder::new().build(event_loop)`]: WindowBuilder::build #[inline] pub fn new<T: 'static>(event_loop: &EventLoopWindowTarget<T>) -> Result<Window, OsError> { let builder = WindowBuilder::new(); builder.build(event_loop) } /// Returns an identifier unique to the window. #[inline] pub fn id(&self) -> WindowId { WindowId(self.window.id()) } /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa. /// /// See the [`dpi`](crate::dpi) module for more information. /// /// Note that this value can change depending on user action (for example if the window is /// moved to another screen); as such, tracking [`WindowEvent::ScaleFactorChanged`] events is /// the most robust way to track the DPI you need to use to draw. /// /// ## Platform-specific /// /// - **X11:** This respects Xft.dpi, and can be overridden using the `WINIT_X11_SCALE_FACTOR` environment variable. /// - **Wayland:** Uses the wp-fractional-scale protocol if available. Falls back to integer-scale factors otherwise. /// - **Android:** Always returns 1.0. /// - **iOS:** Can only be called on the main thread. Returns the underlying `UIView`'s /// [`contentScaleFactor`]. /// /// [`WindowEvent::ScaleFactorChanged`]: crate::event::WindowEvent::ScaleFactorChanged /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc #[inline] pub fn scale_factor(&self) -> f64 { self.window.scale_factor() } /// Emits a [`Event::RedrawRequested`] event in the associated event loop after all OS /// events have been processed by the event loop. /// /// This is the **strongly encouraged** method of redrawing windows, as it can integrate with /// OS-requested redraws (e.g. when a window gets resized). /// /// This function can cause `RedrawRequested` events to be emitted after [`Event::MainEventsCleared`] /// but before `Event::NewEvents` if called in the following circumstances: /// * While processing `MainEventsCleared`. /// * While processing a `RedrawRequested` event that was sent during `MainEventsCleared` or any /// directly subsequent `RedrawRequested` event. /// /// ## Platform-specific /// /// - **iOS:** Can only be called on the main thread. /// - **Android:** Subsequent calls after `MainEventsCleared` are not handled. /// /// [`Event::RedrawRequested`]: crate::event::Event::RedrawRequested /// [`Event::MainEventsCleared`]: crate::event::Event::MainEventsCleared #[inline] pub fn request_redraw(&self) { self.window.request_redraw() } } /// Position and size functions. impl Window { /// Returns the position of the top-left hand corner of the window's client area relative to the /// top-left hand corner of the desktop. /// /// The same conditions that apply to [`Window::outer_position`] apply to this method. /// /// ## Platform-specific /// /// - **iOS:** Can only be called on the main thread. Returns the top left coordinates of the /// window's [safe area] in the screen space coordinate system. /// - **Web:** Returns the top-left coordinates relative to the viewport. _Note: this returns the /// same value as [`Window::outer_position`]._ /// - **Android / Wayland:** Always returns [`NotSupportedError`]. /// /// [safe area]: https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc #[inline] pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { self.window.inner_position() } /// Returns the position of the top-left hand corner of the window relative to the /// top-left hand corner of the desktop. /// /// Note that the top-left hand corner of the desktop is not necessarily the same as /// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner /// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop. /// /// The coordinates can be negative if the top-left hand corner of the window is outside /// of the visible screen region. /// /// ## Platform-specific /// /// - **iOS:** Can only be called on the main thread. Returns the top left coordinates of the /// window in the screen space coordinate system. /// - **Web:** Returns the top-left coordinates relative to the viewport. /// - **Android / Wayland:** Always returns [`NotSupportedError`]. #[inline] pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { self.window.outer_position() } /// Modifies the position of the window. /// /// See [`Window::outer_position`] for more information about the coordinates. /// This automatically un-maximizes the window if it's maximized. /// /// ```no_run /// # use winit::dpi::{LogicalPosition, PhysicalPosition}; /// # use winit::event_loop::EventLoop; /// # use winit::window::Window; /// # let mut event_loop = EventLoop::new(); /// # let window = Window::new(&event_loop).unwrap(); /// // Specify the position in logical dimensions like this: /// window.set_outer_position(LogicalPosition::new(400.0, 200.0)); /// /// // Or specify the position in physical dimensions like this: /// window.set_outer_position(PhysicalPosition::new(400, 200)); /// ``` /// /// ## Platform-specific /// /// - **iOS:** Can only be called on the main thread. Sets the top left coordinates of the /// window in the screen space coordinate system. /// - **Web:** Sets the top-left coordinates relative to the viewport. /// - **Android / Wayland:** Unsupported. #[inline] pub fn set_outer_position<P: Into<Position>>(&self, position: P) { self.window.set_outer_position(position.into()) } /// Returns the physical size of the window's client area. /// /// The client area is the content of the window, excluding the title bar and borders. /// /// ## Platform-specific /// /// - **iOS:** Can only be called on the main thread. Returns the `PhysicalSize` of the window's /// [safe area] in screen space coordinates. /// - **Web:** Returns the size of the canvas element. /// /// [safe area]: https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc #[inline] pub fn inner_size(&self) -> PhysicalSize<u32> { self.window.inner_size() } /// Modifies the inner size of the window. /// /// See [`Window::inner_size`] for more information about the values. /// This automatically un-maximizes the window if it's maximized. /// /// ```no_run /// # use winit::dpi::{LogicalSize, PhysicalSize}; /// # use winit::event_loop::EventLoop; /// # use winit::window::Window; /// # let mut event_loop = EventLoop::new(); /// # let window = Window::new(&event_loop).unwrap(); /// // Specify the size in logical dimensions like this: /// window.set_inner_size(LogicalSize::new(400.0, 200.0)); /// /// // Or specify the size in physical dimensions like this: /// window.set_inner_size(PhysicalSize::new(400, 200)); /// ``` /// /// ## Platform-specific /// /// - **iOS / Android:** Unsupported. /// - **Web:** Sets the size of the canvas element. #[inline] pub fn set_inner_size<S: Into<Size>>(&self, size: S) { self.window.set_inner_size(size.into()) } /// Returns the physical size of the entire window. /// /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), /// use [`Window::inner_size`] instead. /// /// ## Platform-specific /// /// - **iOS:** Can only be called on the main thread. Returns the [`PhysicalSize`] of the window in /// screen space coordinates. /// - **Web:** Returns the size of the canvas element. _Note: this returns the same value as /// [`Window::inner_size`]._ #[inline] pub fn outer_size(&self) -> PhysicalSize<u32> { self.window.outer_size() } /// Sets a minimum dimension size for the window. /// /// ```no_run /// # use winit::dpi::{LogicalSize, PhysicalSize}; /// # use winit::event_loop::EventLoop; /// # use winit::window::Window; /// # let mut event_loop = EventLoop::new(); /// # let window = Window::new(&event_loop).unwrap(); /// // Specify the size in logical dimensions like this: /// window.set_min_inner_size(Some(LogicalSize::new(400.0, 200.0))); /// /// // Or specify the size in physical dimensions like this: /// window.set_min_inner_size(Some(PhysicalSize::new(400, 200))); /// ``` /// /// ## Platform-specific /// /// - **iOS / Android / Web / Orbital:** Unsupported. #[inline] pub fn set_min_inner_size<S: Into<Size>>(&self, min_size: Option<S>) { self.window.set_min_inner_size(min_size.map(|s| s.into())) } /// Sets a maximum dimension size for the window. /// /// ```no_run /// # use winit::dpi::{LogicalSize, PhysicalSize}; /// # use winit::event_loop::EventLoop; /// # use winit::window::Window; /// # let mut event_loop = EventLoop::new(); /// # let window = Window::new(&event_loop).unwrap(); /// // Specify the size in logical dimensions like this: /// window.set_max_inner_size(Some(LogicalSize::new(400.0, 200.0))); /// /// // Or specify the size in physical dimensions like this: /// window.set_max_inner_size(Some(PhysicalSize::new(400, 200))); /// ``` /// /// ## Platform-specific /// /// - **iOS / Android / Web / Orbital:** Unsupported. #[inline] pub fn set_max_inner_size<S: Into<Size>>(&self, max_size: Option<S>) { self.window.set_max_inner_size(max_size.map(|s| s.into())) } /// Returns window resize increments if any were set. /// /// ## Platform-specific /// /// - **iOS / Android / Web / Wayland / Windows / Orbital:** Always returns [`None`]. #[inline] pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { self.window.resize_increments() } /// Sets window resize increments. /// /// This is a niche constraint hint usually employed by terminal emulators /// and other apps that need "blocky" resizes. /// /// ## Platform-specific /// /// - **macOS:** Increments are converted to logical size and then macOS rounds them to whole numbers. /// - **Wayland / Windows:** Not implemented. /// - **iOS / Android / Web / Orbital:** Unsupported. #[inline] pub fn set_resize_increments<S: Into<Size>>(&self, increments: Option<S>) { self.window .set_resize_increments(increments.map(Into::into)) } } /// Misc. attribute functions. impl Window { /// Modifies the title of the window. /// /// ## Platform-specific /// /// - **iOS / Android:** Unsupported. #[inline] pub fn set_title(&self, title: &str) { self.window.set_title(title) } /// Change the window transparency state. /// /// This is just a hint that may not change anything about /// the window transparency, however doing a missmatch between /// the content of your window and this hint may result in /// visual artifacts. /// /// The default value follows the [`WindowBuilder::with_transparent`]. /// /// ## Platform-specific /// /// - **Windows / X11 / Web / iOS / Android / Orbital:** Unsupported. #[inline] pub fn set_transparent(&self, transparent: bool) { self.window.set_transparent(transparent) } /// Modifies the window's visibility. /// /// If `false`, this will hide the window. If `true`, this will show the window. /// /// ## Platform-specific /// /// - **Android / Wayland / Web:** Unsupported. /// - **iOS:** Can only be called on the main thread. #[inline] pub fn set_visible(&self, visible: bool) { self.window.set_visible(visible) } /// Gets the window's current visibility state. /// /// `None` means it couldn't be determined, so it is not recommended to use this to drive your rendering backend. /// /// ## Platform-specific /// /// - **X11:** Not implemented. /// - **Wayland / iOS / Android / Web:** Unsupported. #[inline] pub fn is_visible(&self) -> Option<bool> { self.window.is_visible() } /// Sets whether the window is resizable or not. /// /// Note that making the window unresizable doesn't exempt you from handling [`WindowEvent::Resized`], as that /// event can still be triggered by DPI scaling, entering fullscreen mode, etc. Also, the /// window could still be resized by calling [`Window::set_inner_size`]. /// /// ## Platform-specific /// /// This only has an effect on desktop platforms. /// /// - **X11:** Due to a bug in XFCE, this has no effect on Xfwm. /// - **iOS / Android / Web:** Unsupported. /// /// [`WindowEvent::Resized`]: crate::event::WindowEvent::Resized #[inline] pub fn set_resizable(&self, resizable: bool) { self.window.set_resizable(resizable) } /// Gets the window's current resizable state. /// /// ## Platform-specific /// /// - **X11:** Not implemented. /// - **iOS / Android / Web:** Unsupported. #[inline] pub fn is_resizable(&self) -> bool { self.window.is_resizable() } /// Sets the enabled window buttons. /// /// ## Platform-specific /// /// - **Wayland / X11 / Orbital:** Not implemented. /// - **Web / iOS / Android:** Unsupported. pub fn set_enabled_buttons(&self, buttons: WindowButtons) { self.window.set_enabled_buttons(buttons) } /// Gets the enabled window buttons. /// /// ## Platform-specific /// /// - **Wayland / X11 / Orbital:** Not implemented. Always returns [`WindowButtons::all`]. /// - **Web / iOS / Android:** Unsupported. Always returns [`WindowButtons::all`]. pub fn enabled_buttons(&self) -> WindowButtons { self.window.enabled_buttons() } /// Sets the window to minimized or back /// /// ## Platform-specific /// /// - **iOS / Android / Web / Orbital:** Unsupported. /// - **Wayland:** Un-minimize is unsupported. #[inline] pub fn set_minimized(&self, minimized: bool) { self.window.set_minimized(minimized); } /// Gets the window's current minimized state. /// /// `None` will be returned, if the minimized state couldn't be determined. /// /// ## Note /// /// - You shouldn't stop rendering for minimized windows, however you could lower the fps. /// /// ## Platform-specific /// /// - **Wayland**: always `None`. /// - **iOS / Android / Web / Orbital:** Unsupported. #[inline] pub fn is_minimized(&self) -> Option<bool> { self.window.is_minimized() } /// Sets the window to maximized or back. /// /// ## Platform-specific /// /// - **iOS / Android / Web / Orbital:** Unsupported. #[inline] pub fn set_maximized(&self, maximized: bool) { self.window.set_maximized(maximized) } /// Gets the window's current maximized state. /// /// ## Platform-specific /// /// - **iOS / Android / Web / Orbital:** Unsupported. #[inline] pub fn is_maximized(&self) -> bool { self.window.is_maximized() } /// Sets the window to fullscreen or back. /// /// ## Platform-specific /// /// - **macOS:** [`Fullscreen::Exclusive`] provides true exclusive mode with a /// video mode change. *Caveat!* macOS doesn't provide task switching (or /// spaces!) while in exclusive fullscreen mode. This mode should be used /// when a video mode change is desired, but for a better user experience, /// borderless fullscreen might be preferred. /// /// [`Fullscreen::Borderless`] provides a borderless fullscreen window on a /// separate space. This is the idiomatic way for fullscreen games to work /// on macOS. See `WindowExtMacOs::set_simple_fullscreen` if /// separate spaces are not preferred. /// /// The dock and the menu bar are disabled in exclusive fullscreen mode. /// - **iOS:** Can only be called on the main thread. /// - **Wayland:** Does not support exclusive fullscreen mode and will no-op a request. /// - **Windows:** Screen saver is disabled in fullscreen mode. /// - **Android / Orbital:** Unsupported. #[inline] pub fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) { self.window.set_fullscreen(fullscreen.map(|f| f.into())) } /// Gets the window's current fullscreen state. /// /// ## Platform-specific /// /// - **iOS:** Can only be called on the main thread. /// - **Android / Orbital:** Will always return `None`. /// - **Wayland:** Can return `Borderless(None)` when there are no monitors. #[inline] pub fn fullscreen(&self) -> Option<Fullscreen> { self.window.fullscreen().map(|f| f.into()) } /// Turn window decorations on or off. /// /// Enable/disable window decorations provided by the server or Winit. /// By default this is enabled. Note that fullscreen windows and windows on /// mobile and web platforms naturally do not have decorations. /// /// ## Platform-specific /// /// - **iOS / Android / Web:** No effect. #[inline] pub fn set_decorations(&self, decorations: bool) { self.window.set_decorations(decorations) } /// Gets the window's current decorations state. /// /// Returns `true` when windows are decorated (server-side or by Winit). /// Also returns `true` when no decorations are required (mobile, web). /// /// ## Platform-specific /// /// - **iOS / Android / Web:** Always returns `true`. #[inline] pub fn is_decorated(&self) -> bool { self.window.is_decorated() } /// Change the window level. /// /// This is just a hint to the OS, and the system could ignore it. /// /// See [`WindowLevel`] for details. pub fn set_window_level(&self, level: WindowLevel) { self.window.set_window_level(level) } /// Sets the window icon. /// /// On Windows and X11, this is typically the small icon in the top-left /// corner of the titlebar. /// /// ## Platform-specific /// /// - **iOS / Android / Web / Wayland / macOS / Orbital:** Unsupported. /// /// - **Windows:** Sets `ICON_SMALL`. The base size for a window icon is 16x16, but it's /// recommended to account for screen scaling and pick a multiple of that, i.e. 32x32. /// /// - **X11:** Has no universal guidelines for icon sizes, so you're at the whims of the WM. That /// said, it's usually in the same ballpark as on Windows. #[inline] pub fn set_window_icon(&self, window_icon: Option<Icon>) { self.window.set_window_icon(window_icon) } /// Sets location of IME candidate box in client area coordinates relative to the top left. /// /// This is the window / popup / overlay that allows you to select the desired characters. /// The look of this box may differ between input devices, even on the same platform. /// /// (Apple's official term is "candidate window", see their [chinese] and [japanese] guides). /// /// ## Example /// /// ```no_run /// # use winit::dpi::{LogicalPosition, PhysicalPosition}; /// # use winit::event_loop::EventLoop; /// # use winit::window::Window; /// # let mut event_loop = EventLoop::new(); /// # let window = Window::new(&event_loop).unwrap(); /// // Specify the position in logical dimensions like this: /// window.set_ime_position(LogicalPosition::new(400.0, 200.0)); /// /// // Or specify the position in physical dimensions like this: /// window.set_ime_position(PhysicalPosition::new(400, 200)); /// ``` /// /// ## Platform-specific /// /// - **iOS / Android / Web / Orbital:** Unsupported. /// /// [chinese]: https://support.apple.com/guide/chinese-input-method/use-the-candidate-window-cim12992/104/mac/12.0 /// [japanese]: https://support.apple.com/guide/japanese-input-method/use-the-candidate-window-jpim10262/6.3/mac/12.0 #[inline] pub fn set_ime_position<P: Into<Position>>(&self, position: P) { self.window.set_ime_position(position.into()) } /// Sets whether the window should get IME events /// /// When IME is allowed, the window will receive [`Ime`] events, and during the /// preedit phase the window will NOT get [`KeyboardInput`] or /// [`ReceivedCharacter`] events. The window should allow IME while it is /// expecting text input. /// /// When IME is not allowed, the window won't receive [`Ime`] events, and will /// receive [`KeyboardInput`] events for every keypress instead. Without /// allowing IME, the window will also get [`ReceivedCharacter`] events for /// certain keyboard input. Not allowing IME is useful for games for example. /// /// IME is **not** allowed by default. /// /// ## Platform-specific /// /// - **macOS:** IME must be enabled to receive text-input where dead-key sequences are combined. /// - **iOS / Android / Web / Orbital:** Unsupported. /// /// [`Ime`]: crate::event::WindowEvent::Ime /// [`KeyboardInput`]: crate::event::WindowEvent::KeyboardInput /// [`ReceivedCharacter`]: crate::event::WindowEvent::ReceivedCharacter #[inline] pub fn set_ime_allowed(&self, allowed: bool) { self.window.set_ime_allowed(allowed); } /// Sets the IME purpose for the window using [`ImePurpose`]. /// /// ## Platform-specific /// /// - **iOS / Android / Web / Windows / X11 / macOS / Orbital:** Unsupported. #[inline] pub fn set_ime_purpose(&self, purpose: ImePurpose) { self.window.set_ime_purpose(purpose); } /// Brings the window to the front and sets input focus. Has no effect if the window is /// already in focus, minimized, or not visible. /// /// This method steals input focus from other applications. Do not use this method unless /// you are certain that's what the user wants. Focus stealing can cause an extremely disruptive /// user experience. /// /// ## Platform-specific /// /// - **iOS / Android / Web / Wayland / Orbital:** Unsupported. #[inline] pub fn focus_window(&self) { self.window.focus_window() } /// Gets whether the window has keyboard focus. /// /// This queries the same state information as [`WindowEvent::Focused`]. /// /// [`WindowEvent::Focused`]: crate::event::WindowEvent::Focused #[inline] pub fn has_focus(&self) -> bool { self.window.has_focus() } /// Requests user attention to the window, this has no effect if the application /// is already focused. How requesting for user attention manifests is platform dependent, /// see [`UserAttentionType`] for details. /// /// Providing `None` will unset the request for user attention. Unsetting the request for /// user attention might not be done automatically by the WM when the window receives input. /// /// ## Platform-specific /// /// - **iOS / Android / Web / Orbital:** Unsupported. /// - **macOS:** `None` has no effect. /// - **X11:** Requests for user attention must be manually cleared. /// - **Wayland:** Requires `xdg_activation_v1` protocol, `None` has no effect. #[inline] pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) { self.window.request_user_attention(request_type) } /// Sets the current window theme. Use `None` to fallback to system default. /// /// ## Platform-specific /// /// - **macOS:** This is an app-wide setting. /// - **Wayland:** You can also use `WINIT_WAYLAND_CSD_THEME` env variable to set the theme. /// Possible values for env variable are: "dark" and light". When unspecified, a theme is automatically selected. /// -**x11:** Sets `_GTK_THEME_VARIANT` hint to `dark` or `light` and if `None` is used, it will default to [`Theme::Dark`]. /// - **iOS / Android / Web / x11 / Orbital:** Unsupported. #[inline] pub fn set_theme(&self, theme: Option<Theme>) { self.window.set_theme(theme) } /// Returns the current window theme. /// /// ## Platform-specific /// /// - **macOS:** This is an app-wide setting. /// - **iOS / Android / Wayland / x11 / Orbital:** Unsupported. #[inline] pub fn theme(&self) -> Option<Theme> { self.window.theme() } /// Prevents the window contents from being captured by other apps. /// /// ## Platform-specific /// /// - **macOS**: if `false`, [`NSWindowSharingNone`] is used but doesn't completely /// prevent all apps from reading the window content, for instance, QuickTime. /// - **iOS / Android / x11 / Wayland / Web / Orbital:** Unsupported. /// /// [`NSWindowSharingNone`]: https://developer.apple.com/documentation/appkit/nswindowsharingtype/nswindowsharingnone pub fn set_content_protected(&self, _protected: bool) { #[cfg(any(macos_platform, windows_platform))] self.window.set_content_protected(_protected); } /// Gets the current title of the window. /// /// ## Platform-specific /// /// - **iOS / Android / x11 / Wayland / Web:** Unsupported. Always returns an empty string. #[inline] pub fn title(&self) -> String { self.window.title() } } /// Cursor functions. impl Window { /// Modifies the cursor icon of the window. /// /// ## Platform-specific /// /// - **iOS / Android / Orbital:** Unsupported. #[inline] pub fn set_cursor_icon(&self, cursor: CursorIcon) { self.window.set_cursor_icon(cursor); } /// Changes the position of the cursor in window coordinates. /// /// ```no_run /// # use winit::dpi::{LogicalPosition, PhysicalPosition}; /// # use winit::event_loop::EventLoop; /// # use winit::window::Window; /// # let mut event_loop = EventLoop::new(); /// # let window = Window::new(&event_loop).unwrap(); /// // Specify the position in logical dimensions like this: /// window.set_cursor_position(LogicalPosition::new(400.0, 200.0)); /// /// // Or specify the position in physical dimensions like this: /// window.set_cursor_position(PhysicalPosition::new(400, 200)); /// ``` /// /// ## Platform-specific /// /// - **iOS / Android / Web / Wayland / Orbital:** Always returns an [`ExternalError::NotSupported`]. #[inline] pub fn set_cursor_position<P: Into<Position>>(&self, position: P) -> Result<(), ExternalError> { self.window.set_cursor_position(position.into()) } /// Set grabbing [mode]([`CursorGrabMode`]) on the cursor preventing it from leaving the window. /// /// # Example /// /// First try confining the cursor, and if that fails, try locking it instead. /// /// ```no_run /// # use winit::event_loop::EventLoop; /// # use winit::window::{CursorGrabMode, Window}; /// # let mut event_loop = EventLoop::new(); /// # let window = Window::new(&event_loop).unwrap(); /// window.set_cursor_grab(CursorGrabMode::Confined) /// .or_else(|_e| window.set_cursor_grab(CursorGrabMode::Locked)) /// .unwrap(); /// ``` #[inline] pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> { self.window.set_cursor_grab(mode) } /// Modifies the cursor's visibility. /// /// If `false`, this will hide the cursor. If `true`, this will show the cursor. /// /// ## Platform-specific /// /// - **Windows:** The cursor is only hidden within the confines of the window. /// - **X11:** The cursor is only hidden within the confines of the window. /// - **Wayland:** The cursor is only hidden within the confines of the window. /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is /// outside of the window. /// - **iOS / Android / Orbital:** Unsupported. #[inline] pub fn set_cursor_visible(&self, visible: bool) { self.window.set_cursor_visible(visible) } /// Moves the window with the left mouse button until the button is released. /// /// There's no guarantee that this will work unless the left mouse button was pressed /// immediately before this function is called. /// /// ## Platform-specific /// /// - **X11:** Un-grabs the cursor. /// - **Wayland:** Requires the cursor to be inside the window to be dragged. /// - **macOS:** May prevent the button release event to be triggered. /// - **iOS / Android / Web / Orbital:** Always returns an [`ExternalError::NotSupported`]. #[inline] pub fn drag_window(&self) -> Result<(), ExternalError> { self.window.drag_window() } /// Resizes the window with the left mouse button until the button is released. /// /// There's no guarantee that this will work unless the left mouse button was pressed /// immediately before this function is called. /// /// ## Platform-specific /// /// Only X11 is supported at this time. #[inline] pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> { self.window.drag_resize_window(direction) } /// Modifies whether the window catches cursor events. /// /// If `true`, the window will catch the cursor events. If `false`, events are passed through /// the window such that any other window behind it receives them. By default hittest is enabled. /// /// ## Platform-specific /// /// - **iOS / Android / Web / X11 / Orbital:** Always returns an [`ExternalError::NotSupported`]. #[inline] pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> { self.window.set_cursor_hittest(hittest) } } /// Monitor info functions. impl Window { /// Returns the monitor on which the window currently resides. /// /// Returns `None` if current monitor can't be detected. /// /// ## Platform-specific /// /// **iOS:** Can only be called on the main thread. #[inline] pub fn current_monitor(&self) -> Option<MonitorHandle> { self.window .current_monitor() .map(|inner| MonitorHandle { inner }) } /// Returns the list of all the monitors available on the system. /// /// This is the same as [`EventLoopWindowTarget::available_monitors`], and is provided for convenience. /// /// ## Platform-specific /// /// **iOS:** Can only be called on the main thread. /// /// [`EventLoopWindowTarget::available_monitors`]: crate::event_loop::EventLoopWindowTarget::available_monitors #[inline] pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> { self.window .available_monitors() .into_iter() .map(|inner| MonitorHandle { inner }) } /// Returns the primary monitor of the system. /// /// Returns `None` if it can't identify any monitor as a primary one. /// /// This is the same as [`EventLoopWindowTarget::primary_monitor`], and is provided for convenience. /// /// ## Platform-specific /// /// **iOS:** Can only be called on the main thread. /// **Wayland:** Always returns `None`. /// /// [`EventLoopWindowTarget::primary_monitor`]: crate::event_loop::EventLoopWindowTarget::primary_monitor #[inline] pub fn primary_monitor(&self) -> Option<MonitorHandle> { self.window .primary_monitor() .map(|inner| MonitorHandle { inner }) } } unsafe impl HasRawWindowHandle for Window { /// Returns a [`raw_window_handle::RawWindowHandle`] for the Window /// /// ## Platform-specific /// /// ### Android /// /// Only available after receiving [`Event::Resumed`] and before [`Event::Suspended`]. *If you /// try to get the handle outside of that period, this function will panic*! /// /// Make sure to release or destroy any resources created from this `RawWindowHandle` (ie. Vulkan /// or OpenGL surfaces) before returning from [`Event::Suspended`], at which point Android will /// release the underlying window/surface: any subsequent interaction is undefined behavior. /// /// [`Event::Resumed`]: crate::event::Event::Resumed /// [`Event::Suspended`]: crate::event::Event::Suspended fn raw_window_handle(&self) -> RawWindowHandle { self.window.raw_window_handle() } } unsafe impl HasRawDisplayHandle for Window { /// Returns a [`raw_window_handle::RawDisplayHandle`] used by the [`EventLoop`] that /// created a window. /// /// [`EventLoop`]: crate::event_loop::EventLoop fn raw_display_handle(&self) -> RawDisplayHandle { self.window.raw_display_handle() } } /// The behavior of cursor grabbing. /// /// Use this enum with [`Window::set_cursor_grab`] to grab the cursor. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum CursorGrabMode { /// No grabbing of the cursor is performed. None, /// The cursor is confined to the window area. /// /// There's no guarantee that the cursor will be hidden. You should hide it by yourself if you /// want to do so. /// /// ## Platform-specific /// /// - **macOS:** Not implemented. Always returns [`ExternalError::NotSupported`] for now. /// - **iOS / Android / Web / Orbital:** Always returns an [`ExternalError::NotSupported`]. Confined, /// The cursor is locked inside the window area to the certain position. /// /// There's no guarantee that the cursor will be hidden. You should hide it by yourself if you /// want to do so. /// /// ## Platform-specific /// /// - **X11 / Windows:** Not implemented. Always returns [`ExternalError::NotSupported`] for now. /// - **iOS / Android / Orbital:** Always returns an [`ExternalError::NotSupported`]. Locked, } /// Describes the appearance of the mouse cursor. #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum CursorIcon { /// The platform-dependent default cursor. #[default] Default, /// A simple crosshair. Crosshair, /// A hand (often used to indicate links in web browsers). Hand, /// Self explanatory. Arrow, /// Indicates something is to be moved. Move, /// Indicates text that may be selected or edited. Text, /// Program busy indicator. Wait, /// Help indicator (often rendered as a "?") Help, /// Progress indicator. Shows that processing is being done. But in contrast /// with "Wait" the user may still interact with the program. Often rendered /// as a spinning beach ball, or an arrow with a watch or hourglass. Progress, /// Cursor showing that something cannot be done. NotAllowed, ContextMenu, Cell, VerticalText, Alias, Copy, NoDrop, /// Indicates something can be grabbed. Grab, /// Indicates something is grabbed. Grabbing, AllScroll, ZoomIn, ZoomOut, /// Indicate that some edge is to be moved. For example, the 'SeResize' cursor /// is used when the movement starts from the south-east corner of the box. EResize, NResize, NeResize, NwResize, SResize, SeResize, SwResize, WResize, EwResize, NsResize, NeswResize, NwseResize, ColResize, RowResize, } /// Defines the orientation that a window resize will be performed. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum ResizeDirection { East, North, NorthEast, NorthWest, South, SouthEast, SouthWest, West, } impl From<ResizeDirection> for CursorIcon { fn from(direction: ResizeDirection) -> Self { use ResizeDirection::*; match direction { East => CursorIcon::EResize, North => CursorIcon::NResize, NorthEast => CursorIcon::NeResize, NorthWest => CursorIcon::NwResize, South => CursorIcon::SResize, SouthEast => CursorIcon::SeResize, SouthWest => CursorIcon::SwResize, West => CursorIcon::WResize, } } } /// Fullscreen modes. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Fullscreen { Exclusive(VideoMode), /// Providing `None` to `Borderless` will fullscreen on the current monitor. Borderless(Option<MonitorHandle>), } /// The theme variant to use. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum Theme { /// Use the light variant. Light, /// Use the dark variant. Dark, } /// ## Platform-specific /// /// - **X11:** Sets the WM's `XUrgencyHint`. No distinction between [`Critical`] and [`Informational`]. /// /// [`Critical`]: Self::Critical /// [`Informational`]: Self::Informational #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub enum UserAttentionType { /// ## Platform-specific /// /// - **macOS:** Bounces the dock icon until the application is in focus. /// - **Windows:** Flashes both the window and the taskbar button until the application is in focus. Critical, /// ## Platform-specific /// /// - **macOS:** Bounces the dock icon once. /// - **Windows:** Flashes the taskbar button until the application is in focus. #[default] Informational, } bitflags! { pub struct WindowButtons: u32 { const CLOSE = 1 << 0; const MINIMIZE = 1 << 1; const MAXIMIZE = 1 << 2; } } /// A window level groups windows with respect to their z-position. /// /// The relative ordering between windows in different window levels is fixed. /// The z-order of a window within the same window level may change dynamically on user interaction. /// /// ## Platform-specific /// /// - **iOS / Android / Web / Wayland:** Unsupported. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum WindowLevel { /// The window will always be below normal windows. /// /// This is useful for a widget-based app. AlwaysOnBottom, /// The default. Normal, /// The window will always be on top of normal windows. AlwaysOnTop, } impl Default for WindowLevel { fn default() -> Self { Self::Normal } } /// Generic IME purposes for use in [`Window::set_ime_purpose`]. /// /// The purpose may improve UX by optimizing the IME for the specific use case, /// if winit can express the purpose to the platform and the platform reacts accordingly. /// /// ## Platform-specific /// /// - **iOS / Android / Web / Windows / X11 / macOS / Orbital:** Unsupported. #[derive(Debug, PartialEq, Eq, Clone, Copy)] #[non_exhaustive] pub enum ImePurpose { /// No special hints for the IME (default). Normal, /// The IME is used for password input. Password, /// The IME is used to input into a terminal. /// /// For example, that could alter OSK on Wayland to show extra buttons. Terminal, } impl Default for ImePurpose { fn default() -> Self { Self::Normal } }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
tests/send_objects.rs
Rust
#[allow(dead_code)] fn needs_send<T: Send>() {} #[test] fn event_loop_proxy_send() { #[allow(dead_code)] fn is_send<T: 'static + Send>() { // ensures that `winit::EventLoopProxy` implements `Send` needs_send::<winit::event_loop::EventLoopProxy<T>>(); } } #[test] fn window_send() { // ensures that `winit::Window` implements `Send` needs_send::<winit::window::Window>(); } #[test] fn ids_send() { // ensures that the various `..Id` types implement `Send` needs_send::<winit::window::WindowId>(); needs_send::<winit::event::DeviceId>(); needs_send::<winit::monitor::MonitorHandle>(); }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
tests/serde_objects.rs
Rust
#![cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use winit::{ dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}, event::{ ElementState, KeyboardInput, ModifiersState, MouseButton, MouseScrollDelta, TouchPhase, VirtualKeyCode, }, window::CursorIcon, }; #[allow(dead_code)] fn needs_serde<S: Serialize + Deserialize<'static>>() {} #[test] fn window_serde() { needs_serde::<CursorIcon>(); } #[test] fn events_serde() { needs_serde::<KeyboardInput>(); needs_serde::<TouchPhase>(); needs_serde::<ElementState>(); needs_serde::<MouseButton>(); needs_serde::<MouseScrollDelta>(); needs_serde::<VirtualKeyCode>(); needs_serde::<ModifiersState>(); } #[test] fn dpi_serde() { needs_serde::<LogicalPosition<f64>>(); needs_serde::<PhysicalPosition<i32>>(); needs_serde::<PhysicalPosition<f64>>(); needs_serde::<LogicalSize<f64>>(); needs_serde::<PhysicalSize<u32>>(); }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
tests/sync_object.rs
Rust
#[allow(dead_code)] fn needs_sync<T: Sync>() {} #[test] fn window_sync() { // ensures that `winit::Window` implements `Sync` needs_sync::<winit::window::Window>(); }
wusyong/winit-gtk
3
Rust
wusyong
Wu Yuwei
commitlint.config.mjs
JavaScript
export default { extends: ["@commitlint/config-conventional"], rules: { "body-max-line-length": [2, "always", 300], }, };
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/__init__.py
Python
"""Init for Midea LAN. integration load process: 1. component setup: `async_setup` 1.1 use `hass.services.async_register` to register service 2. config entry setup: `async_setup_entry` 2.1 forward the Config Entry to the platform `async_forward_entry_setups` 2.2 register listener `update_listener` 3. unloading a config entry: `async_unload_entry` """ import logging from typing import Any, cast import homeassistant.helpers.config_validation as cv import homeassistant.helpers.device_registry as dr import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_CUSTOMIZE, CONF_DEVICE_ID, CONF_IP_ADDRESS, CONF_NAME, CONF_PORT, CONF_PROTOCOL, CONF_TOKEN, CONF_TYPE, MAJOR_VERSION, MINOR_VERSION, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.typing import ConfigType from midealocal.device import DeviceType, MideaDevice, ProtocolVersion from midealocal.devices import device_selector from .const import ( ALL_PLATFORM, CONF_ACCOUNT, CONF_KEY, CONF_MODEL, CONF_REFRESH_INTERVAL, CONF_SUBTYPE, DEVICES, DOMAIN, EXTRA_SWITCH, ) from .midea_devices import MIDEA_DEVICES _LOGGER = logging.getLogger(__name__) async def update_listener(hass: HomeAssistant, config_entry: ConfigEntry) -> None: """Option flow signal update. register update listener for config entry that will be called when entry is updated. A listener is registered by adding the following to the `async_setup_entry`: `config_entry.async_on_unload(config_entry.add_update_listener(update_listener))` means the Listener is attached when the entry is loaded and detached at unload """ # Forward the unloading of an entry to platforms. await hass.config_entries.async_unload_platforms(config_entry, ALL_PLATFORM) # forward the Config Entry to the platforms hass.async_create_task( hass.config_entries.async_forward_entry_setups(config_entry, ALL_PLATFORM), ) device_id: int = cast("int", config_entry.data.get(CONF_DEVICE_ID)) customize = config_entry.options.get(CONF_CUSTOMIZE, "") ip_address = config_entry.options.get(CONF_IP_ADDRESS, None) refresh_interval = config_entry.options.get(CONF_REFRESH_INTERVAL, None) dev: MideaDevice = hass.data[DOMAIN][DEVICES].get(device_id) if dev: dev.set_customize(customize) if ip_address is not None: dev.set_ip_address(ip_address) if refresh_interval is not None: dev.set_refresh_interval(refresh_interval) async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: # noqa: ARG001 """Set up midea_lan component when load this integration. Returns ------- True if entry is configured. """ hass.data.setdefault(DOMAIN, {}) attributes = [] for device_entities in MIDEA_DEVICES.values(): for attribute_name, attribute in cast( "dict", device_entities["entities"], ).items(): if ( attribute.get("type") in EXTRA_SWITCH and attribute_name.value not in attributes ): attributes.append(attribute_name.value) def service_set_attribute(service: Any) -> None: # noqa: ANN401 """Set service attribute func.""" device_id: int = service.data["device_id"] attr = service.data["attribute"] value = service.data["value"] dev: MideaDevice = hass.data[DOMAIN][DEVICES].get(device_id) if dev: if attr == "fan_speed" and value == "auto": value = 102 item = None if dev_ := MIDEA_DEVICES.get(dev.device_type): item = cast("dict", dev_["entities"]).get(attr) if ( item and (item.get("type") in EXTRA_SWITCH) or ( dev.device_type == DeviceType.AC and attr == "fan_speed" and value in range(103) ) ): dev.set_attribute(attr=attr, value=value) else: _LOGGER.error( "Appliance [%s] has no attribute %s or value is invalid", device_id, attr, ) def service_send_command(service: Any) -> None: # noqa: ANN401 """Send command to service func.""" device_id = service.data.get("device_id") cmd_type = service.data.get("cmd_type") cmd_body = service.data.get("cmd_body") try: cmd_body = bytearray.fromhex(cmd_body) except ValueError: _LOGGER.exception( "Appliance [%s] invalid cmd_body, a hexadecimal string required", device_id, ) return dev = hass.data[DOMAIN][DEVICES].get(device_id) if dev: dev.send_command(cmd_type, cmd_body) # register service func calls: # `service_set_attribute`, service.yaml key: `set_attribute` hass.services.async_register( DOMAIN, "set_attribute", service_set_attribute, schema=vol.Schema( { vol.Required("device_id"): vol.Coerce(int), vol.Required("attribute"): vol.In(attributes), vol.Required("value"): vol.Any(int, cv.boolean, str), }, ), ) # register service func calls: # `service_send_command`, service.yaml key: `send_command` hass.services.async_register( DOMAIN, "send_command", service_send_command, schema=vol.Schema( { vol.Required("device_id"): vol.Coerce(int), vol.Required("cmd_type"): vol.In([2, 3]), vol.Required("cmd_body"): str, }, ), ) return True async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Set up platform for current integration. Returns ------- True if entry is configured. """ device_type = config_entry.data.get(CONF_TYPE) if device_type == CONF_ACCOUNT: return True name = config_entry.data.get(CONF_NAME) device_id: int = config_entry.data[CONF_DEVICE_ID] if name is None: name = f"{device_id}" if device_type is None: device_type = 0xAC token: str = config_entry.data.get(CONF_TOKEN) or "" key: str = config_entry.data.get(CONF_KEY) or "" ip_address = config_entry.options.get(CONF_IP_ADDRESS, None) if ip_address is None: ip_address = config_entry.data.get(CONF_IP_ADDRESS) refresh_interval = config_entry.options.get(CONF_REFRESH_INTERVAL) port: int = config_entry.data[CONF_PORT] model: str = config_entry.data[CONF_MODEL] subtype = config_entry.data.get(CONF_SUBTYPE, 0) protocol: ProtocolVersion = ProtocolVersion(config_entry.data[CONF_PROTOCOL]) customize: str = config_entry.options.get(CONF_CUSTOMIZE, "") if protocol == ProtocolVersion.V3 and (key == "" or token == ""): _LOGGER.error("For V3 devices, the key and the token is required") return False # device_selector in `midealocal/devices/__init__.py` # hass core version >= 2024.3 if (MAJOR_VERSION, MINOR_VERSION) >= (2024, 3): device = await hass.async_add_import_executor_job( device_selector, name, device_id, device_type, ip_address, port, token, key, protocol, model, subtype, customize, ) # hass core version < 2024.3 else: device = device_selector( name=name, device_id=device_id, device_type=device_type, ip_address=ip_address, port=port, token=token, key=key, device_protocol=protocol, model=model, subtype=subtype, customize=customize, ) if device: if refresh_interval is not None: device.set_refresh_interval(refresh_interval) device.open() if DOMAIN not in hass.data: hass.data[DOMAIN] = {} if DEVICES not in hass.data[DOMAIN]: hass.data[DOMAIN][DEVICES] = {} hass.data[DOMAIN][DEVICES][device_id] = device # Forward the setup of an entry to all platforms await hass.config_entries.async_forward_entry_setups(config_entry, ALL_PLATFORM) # Listener `update_listener` is # attached when the entry is loaded # and detached when it's unloaded config_entry.async_on_unload(config_entry.add_update_listener(update_listener)) return True return False async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Clean up entities, unsubscribe event listener and close all connections. Returns ------- True if entry is unloaded. """ device_type = config_entry.data.get(CONF_TYPE) if device_type == CONF_ACCOUNT: return True device_id = config_entry.data.get(CONF_DEVICE_ID) if device_id is not None: dm = hass.data[DOMAIN][DEVICES].get(device_id) if dm is not None: try: dm.close() except (OSError, ConnectionError, AttributeError) as e: _LOGGER.warning("Failed to close Midea socket cleanly: %s", e) hass.data[DOMAIN][DEVICES].pop(device_id) # Forward the unloading of an entry to platforms await hass.config_entries.async_unload_platforms(config_entry, ALL_PLATFORM) return True async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Migrate old entry. Returns ------- True if entry is migrated. """ # 1 -> 2: convert device identifiers from int to str if config_entry.version == 1: _LOGGER.debug("Migrating configuration from version 1") if (MAJOR_VERSION, MINOR_VERSION) >= (2024, 3): hass.config_entries.async_update_entry(config_entry, version=2) else: config_entry.version = 2 hass.config_entries.async_update_entry(config_entry) # Migrate device. await _async_migrate_device_identifiers(hass, config_entry) _LOGGER.debug("Migration to configuration version 2 successful") return True async def _async_migrate_device_identifiers( hass: HomeAssistant, config_entry: ConfigEntry, ) -> None: """Migrate the device identifiers to the new format.""" device_registry = dr.async_get(hass) device_entry_found = False for device_entry in dr.async_entries_for_config_entry( device_registry, config_entry.entry_id, ): for identifier in device_entry.identifiers: # Device found in registry. Update identifiers. new_identifiers = { ( DOMAIN, str(identifier[1]), ), } _LOGGER.debug( "Migrating device identifiers from %s to %s", device_entry.identifiers, new_identifiers, ) device_registry.async_update_device( device_id=device_entry.id, new_identifiers=new_identifiers, ) # Device entry found. Leave inner for loop. device_entry_found = True break # Leave outer for loop if device entry is already found. if device_entry_found: break
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/binary_sensor.py
Python
"""Binary sensor for Midea Lan.""" from typing import cast from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DEVICE_ID, CONF_SENSORS, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DEVICES, DOMAIN from .midea_devices import MIDEA_DEVICES from .midea_entity import MideaEntity async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up sensors for device.""" device_id = config_entry.data.get(CONF_DEVICE_ID) device = hass.data[DOMAIN][DEVICES].get(device_id) extra_sensors = config_entry.options.get(CONF_SENSORS, []) binary_sensors = [] for entity_key, config in cast( "dict", MIDEA_DEVICES[device.device_type]["entities"], ).items(): if config["type"] == Platform.BINARY_SENSOR and entity_key in extra_sensors: sensor = MideaBinarySensor(device, entity_key) binary_sensors.append(sensor) async_add_entities(binary_sensors) class MideaBinarySensor(MideaEntity, BinarySensorEntity): """Represent a Midea binary sensor.""" @property def device_class(self) -> BinarySensorDeviceClass | None: """Return device class.""" return cast("BinarySensorDeviceClass", self._config.get("device_class")) @property def is_on(self) -> bool: """Return true if sensor state is on.""" return cast("bool", self._device.get_attribute(self._entity_key))
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/climate.py
Python
"""Midea Climate entries.""" import logging from typing import Any, ClassVar, TypeAlias, cast from homeassistant.components.climate import ( ATTR_HVAC_MODE, FAN_AUTO, FAN_HIGH, FAN_LOW, FAN_MEDIUM, PRESET_AWAY, PRESET_BOOST, PRESET_COMFORT, PRESET_ECO, PRESET_NONE, PRESET_SLEEP, SWING_BOTH, SWING_HORIZONTAL, SWING_OFF, SWING_ON, SWING_VERTICAL, ClimateEntity, ClimateEntityFeature, HVACMode, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_TEMPERATURE, CONF_DEVICE_ID, CONF_SWITCHES, MAJOR_VERSION, MINOR_VERSION, PRECISION_HALVES, PRECISION_WHOLE, Platform, UnitOfTemperature, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from midealocal.device import DeviceType from midealocal.devices.ac import DeviceAttributes as ACAttributes from midealocal.devices.ac import MideaACDevice from midealocal.devices.c3 import DeviceAttributes as C3Attributes from midealocal.devices.c3 import MideaC3Device from midealocal.devices.cc import DeviceAttributes as CCAttributes from midealocal.devices.cc import MideaCCDevice from midealocal.devices.cf import DeviceAttributes as CFAttributes from midealocal.devices.cf import MideaCFDevice from midealocal.devices.fb import DeviceAttributes as FBAttributes from midealocal.devices.fb import MideaFBDevice from .const import DEVICES, DOMAIN, FanSpeed from .midea_devices import MIDEA_DEVICES from .midea_entity import MideaEntity _LOGGER = logging.getLogger(__name__) TEMPERATURE_MAX = 30 TEMPERATURE_MIN = 16 FAN_SILENT = "silent" FAN_FULL_SPEED = "full" async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up climate entries.""" device_id = config_entry.data.get(CONF_DEVICE_ID) device = hass.data[DOMAIN][DEVICES].get(device_id) extra_switches = config_entry.options.get(CONF_SWITCHES, []) devs: list[ MideaACClimate | MideaCCClimate | MideaCFClimate | MideaC3Climate | MideaFBClimate ] = [] for entity_key, config in cast( "dict", MIDEA_DEVICES[device.device_type]["entities"], ).items(): if config["type"] == Platform.CLIMATE and ( config.get("default") or entity_key in extra_switches ): if device.device_type == DeviceType.AC: # add config_entry args to fix indoor_humidity error bug devs.append(MideaACClimate(device, entity_key, config_entry)) elif device.device_type == DeviceType.CC: devs.append(MideaCCClimate(device, entity_key)) elif device.device_type == DeviceType.CF: devs.append(MideaCFClimate(device, entity_key)) elif device.device_type == DeviceType.C3: devs.append(MideaC3Climate(device, entity_key, config["zone"])) elif device.device_type == DeviceType.FB: devs.append(MideaFBClimate(device, entity_key)) async_add_entities(devs) MideaClimateDevice: TypeAlias = ( MideaACDevice | MideaCCDevice | MideaCFDevice | MideaC3Device | MideaFBDevice ) class MideaClimate(MideaEntity, ClimateEntity): """Midea Climate Entries Base Class.""" # https://developers.home-assistant.io/blog/2024/01/24/climate-climateentityfeatures-expanded _enable_turn_on_off_backwards_compatibility: bool = ( False # maybe remove after 2025.1 ) _device: MideaClimateDevice _attr_max_temp: float = TEMPERATURE_MAX _attr_min_temp: float = TEMPERATURE_MIN _attr_target_temperature_high: float | None = TEMPERATURE_MAX _attr_target_temperature_low: float | None = TEMPERATURE_MIN _attr_temperature_unit: str = UnitOfTemperature.CELSIUS def __init__(self, device: MideaClimateDevice, entity_key: str) -> None: """Midea Climate entity init.""" super().__init__(device, entity_key) @property def supported_features(self) -> ClimateEntityFeature: """Midea Climate supported features.""" features = ( ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.FAN_MODE | ClimateEntityFeature.PRESET_MODE | ClimateEntityFeature.SWING_MODE ) if (MAJOR_VERSION, MINOR_VERSION) >= (2024, 2): features |= ClimateEntityFeature.TURN_OFF | ClimateEntityFeature.TURN_ON return features @property def hvac_mode(self) -> HVACMode: """Midea Climate hvac mode.""" if self._device.get_attribute("power"): mode = cast("int", self._device.get_attribute("mode")) return self.hvac_modes[mode] return HVACMode.OFF @property def target_temperature(self) -> float: """Midea Climate target temperature.""" return cast("float", self._device.get_attribute("target_temperature")) @property def current_temperature(self) -> float | None: """Midea Climate current temperature.""" return cast("float | None", self._device.get_attribute("indoor_temperature")) @property def preset_mode(self) -> str: """Midea Climate preset mode.""" if self._device.get_attribute("comfort_mode"): mode = PRESET_COMFORT elif self._device.get_attribute("eco_mode"): mode = PRESET_ECO elif self._device.get_attribute("boost_mode"): mode = PRESET_BOOST elif self._device.get_attribute("sleep_mode"): mode = PRESET_SLEEP elif self._device.get_attribute("frost_protect"): mode = PRESET_AWAY else: mode = PRESET_NONE return str(mode) @property def extra_state_attributes(self) -> dict: """Midea Climate extra state attributes.""" return cast("dict", self._device.attributes) def turn_on(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea Climate turn on.""" self._device.set_attribute(attr="power", value=True) def turn_off(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea Climate turn off.""" self._device.set_attribute(attr="power", value=False) def set_temperature(self, **kwargs: Any) -> None: # noqa: ANN401 """Midea Climate set temperature.""" if ATTR_TEMPERATURE not in kwargs: return temperature = float(int((float(kwargs[ATTR_TEMPERATURE]) * 2) + 0.5)) / 2 hvac_mode = kwargs.get(ATTR_HVAC_MODE) if hvac_mode == HVACMode.OFF: self.turn_off() else: try: mode = self.hvac_modes.index(hvac_mode.lower()) if hvac_mode else None self._device.set_target_temperature( target_temperature=temperature, mode=mode, zone=None, ) except ValueError: _LOGGER.exception("Error setting temperature with: %s", kwargs) def set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Midea Climate set hvac mode.""" if hvac_mode == HVACMode.OFF: self.turn_off() else: self._device.set_attribute( attr="mode", value=self.hvac_modes.index(hvac_mode), ) def set_preset_mode(self, preset_mode: str) -> None: """Midea Climate set preset mode.""" old_mode = self.preset_mode preset_mode = preset_mode.lower() if preset_mode == PRESET_AWAY: self._device.set_attribute(attr="frost_protect", value=True) elif preset_mode == PRESET_COMFORT: self._device.set_attribute(attr="comfort_mode", value=True) elif preset_mode == PRESET_SLEEP: self._device.set_attribute(attr="sleep_mode", value=True) elif preset_mode == PRESET_ECO: self._device.set_attribute(attr="eco_mode", value=True) elif preset_mode == PRESET_BOOST: self._device.set_attribute(attr="boost_mode", value=True) elif old_mode == PRESET_AWAY: self._device.set_attribute(attr="frost_protect", value=False) elif old_mode == PRESET_COMFORT: self._device.set_attribute(attr="comfort_mode", value=False) elif old_mode == PRESET_SLEEP: self._device.set_attribute(attr="sleep_mode", value=False) elif old_mode == PRESET_ECO: self._device.set_attribute(attr="eco_mode", value=False) elif old_mode == PRESET_BOOST: self._device.set_attribute(attr="boost_mode", value=False) def update_state(self, status: Any) -> None: # noqa: ANN401, ARG002 """Midea Climate update state.""" if not self.hass: _LOGGER.warning( "Climate update_state skipped for %s [%s]: HASS is None", self.name, type(self), ) return self.schedule_update_ha_state() class MideaACClimate(MideaClimate): """Midea AC Climate Entries.""" _device: MideaACDevice def __init__( self, device: MideaACDevice, entity_key: str, config_entry: ConfigEntry, ) -> None: """Midea AC Climate entity init.""" super().__init__(device, entity_key) self._attr_hvac_modes = [ HVACMode.OFF, HVACMode.AUTO, HVACMode.COOL, HVACMode.DRY, HVACMode.HEAT, HVACMode.FAN_ONLY, ] self._fan_speeds: dict[str, int] = { FAN_SILENT: 20, FAN_LOW: 40, FAN_MEDIUM: 60, FAN_HIGH: 80, FAN_FULL_SPEED: 100, FAN_AUTO: 102, } self._attr_swing_modes: list[str] = [ SWING_OFF, SWING_VERTICAL, SWING_HORIZONTAL, SWING_BOTH, ] self._attr_preset_modes = [ PRESET_NONE, PRESET_COMFORT, PRESET_ECO, PRESET_BOOST, PRESET_SLEEP, PRESET_AWAY, ] self._attr_fan_modes = list(self._fan_speeds.keys()) # fix error humidity value, disable indoor_humidity # add config_entry args to fix indoor_humidity error bug self._indoor_humidity_enabled = ( "sensors" in config_entry.options and "indoor_humidity" in config_entry.options["sensors"] ) @property def fan_mode(self) -> str: """Midea AC Climate fan mode.""" fan_speed = cast("int", self._device.get_attribute(ACAttributes.fan_speed)) if fan_speed > FanSpeed.AUTO: return str(FAN_AUTO) if fan_speed > FanSpeed.FULL_SPEED: return str(FAN_FULL_SPEED) if fan_speed > FanSpeed.HIGH: return str(FAN_HIGH) if fan_speed > FanSpeed.MEDIUM: return str(FAN_MEDIUM) if fan_speed > FanSpeed.LOW: return str(FAN_LOW) return str(FAN_SILENT) @property def target_temperature_step(self) -> float: """Midea AC Climate target temperature step.""" return float( PRECISION_WHOLE if self._device.temperature_step == 1 else PRECISION_HALVES, ) @property def swing_mode(self) -> str: """Midea AC Climate swing mode.""" swing_mode = ( 1 if self._device.get_attribute(ACAttributes.swing_vertical) else 0 ) + (2 if self._device.get_attribute(ACAttributes.swing_horizontal) else 0) return self._attr_swing_modes[swing_mode] @property def current_humidity(self) -> float | None: """Return the current indoor humidity, or None if unavailable.""" # fix error humidity, disable indoor_humidity in web UI # https://github.com/wuwentao/midea_ac_lan/pull/641 if not self._indoor_humidity_enabled: return None raw = self._device.get_attribute("indoor_humidity") if isinstance(raw, (int, float)) and raw not in {0, 0xFF}: return float(raw) # indoor_humidity is 0 or 255, return None # https://github.com/wuwentao/midea_ac_lan/pull/614 return None @property def outdoor_temperature(self) -> float: """Midea AC Climate outdoor temperature.""" return cast( "float", self._device.get_attribute(ACAttributes.outdoor_temperature), ) def set_fan_mode(self, fan_mode: str) -> None: """Midea AC Climate set fan mode.""" fan_speed = self._fan_speeds.get(fan_mode) if fan_speed: self._device.set_attribute(attr=ACAttributes.fan_speed, value=fan_speed) def set_swing_mode(self, swing_mode: str) -> None: """Midea AC Climate set swing mode.""" swing = self._attr_swing_modes.index(swing_mode) swing_vertical = swing & 1 > 0 swing_horizontal = swing & 2 > 0 self._device.set_swing( swing_vertical=swing_vertical, swing_horizontal=swing_horizontal, ) class MideaCCClimate(MideaClimate): """Midea CC Climate Entries Base Class.""" _device: MideaCCDevice def __init__(self, device: MideaCCDevice, entity_key: str) -> None: """Midea CC Climate entity init.""" super().__init__(device, entity_key) self._attr_hvac_modes = [ HVACMode.OFF, HVACMode.FAN_ONLY, HVACMode.DRY, HVACMode.HEAT, HVACMode.COOL, HVACMode.AUTO, ] self._attr_swing_modes = [SWING_OFF, SWING_ON] self._attr_preset_modes = [PRESET_NONE, PRESET_SLEEP, PRESET_ECO] @property def fan_modes(self) -> list[str] | None: """Midea CC Climate fan modes.""" return cast("list", self._device.fan_modes) @property def fan_mode(self) -> str: """Midea CC Climate fan mode.""" return cast("str", self._device.get_attribute(CCAttributes.fan_speed)) @property def target_temperature_step(self) -> float: """Midea CC Climate target temperature step.""" return cast( "float", self._device.get_attribute(CCAttributes.temperature_precision), ) @property def swing_mode(self) -> str: """Midea CC Climate swing mode.""" return str( SWING_ON if self._device.get_attribute(CCAttributes.swing) else SWING_OFF, ) def set_fan_mode(self, fan_mode: str) -> None: """Midea CC Climate set fan mode.""" self._device.set_attribute(attr=CCAttributes.fan_speed, value=fan_mode) def set_swing_mode(self, swing_mode: str) -> None: """Midea CC Climate set swing mode.""" self._device.set_attribute( attr=CCAttributes.swing, value=swing_mode == SWING_ON, ) class MideaCFClimate(MideaClimate): """Midea CF Climate Entries.""" _device: MideaCFDevice _attr_target_temperature_step: float | None = PRECISION_WHOLE def __init__(self, device: MideaCFDevice, entity_key: str) -> None: """Midea CF Climate entity init.""" super().__init__(device, entity_key) self._attr_hvac_modes = [ HVACMode.OFF, HVACMode.AUTO, HVACMode.COOL, HVACMode.HEAT, ] @property def supported_features(self) -> ClimateEntityFeature: """Midea CF Climate supported features.""" features = ClimateEntityFeature.TARGET_TEMPERATURE if (MAJOR_VERSION, MINOR_VERSION) >= (2024, 2): features |= ClimateEntityFeature.TURN_OFF | ClimateEntityFeature.TURN_ON return features @property def min_temp(self) -> float: """Midea CF Climate min temperature.""" return cast("float", self._device.get_attribute(CFAttributes.min_temperature)) @property def max_temp(self) -> float: """Midea CF Climate max temperature.""" return cast("float", self._device.get_attribute(CFAttributes.max_temperature)) @property def target_temperature_low(self) -> float: """Midea CF Climate target temperature.""" return cast("float", self._device.get_attribute(CFAttributes.min_temperature)) @property def target_temperature_high(self) -> float: """Midea CF Climate target temperature high.""" return cast("float", self._device.get_attribute(CFAttributes.max_temperature)) @property def current_temperature(self) -> float: """Midea CF Climate current temperature.""" return cast( "float", self._device.get_attribute(CFAttributes.current_temperature), ) class MideaC3Climate(MideaClimate): """Midea C3 Climate Entries.""" _device: MideaC3Device _powers: ClassVar[list[C3Attributes]] = [ C3Attributes.zone1_power, C3Attributes.zone2_power, ] def __init__(self, device: MideaC3Device, entity_key: str, zone: int) -> None: """Midea C3 Climate entity init.""" super().__init__(device, entity_key) self._zone = zone self._attr_hvac_modes = [ HVACMode.OFF, HVACMode.AUTO, HVACMode.COOL, HVACMode.HEAT, ] self._power_attr = MideaC3Climate._powers[zone] def _temperature(self, minimum: bool) -> list[str]: """Midea C3 Climate temperature. Returns ------- List of temperatures """ # fmt: off value = (C3Attributes.temperature_min if minimum else C3Attributes.temperature_max) # fmt: on return cast("list[str]", self._device.get_attribute(value)) @property def supported_features(self) -> ClimateEntityFeature: """Midea C3 Climate supported features.""" features = ClimateEntityFeature.TARGET_TEMPERATURE if (MAJOR_VERSION, MINOR_VERSION) >= (2024, 2): features |= ClimateEntityFeature.TURN_OFF | ClimateEntityFeature.TURN_ON return features @property def target_temperature_step(self) -> float: """Midea C3 Climate target temperature step.""" zone_temp_type = cast( "list[str]", self._device.get_attribute(C3Attributes.zone_temp_type), ) return float( PRECISION_WHOLE if zone_temp_type[self._zone] else PRECISION_HALVES, ) @property def min_temp(self) -> float: """Midea C3 Climate min temperature.""" return cast( "float", self._temperature(True)[self._zone], ) @property def max_temp(self) -> float: """Midea C3 Climate max temperature.""" return cast( "float", self._temperature(False)[self._zone], ) @property def target_temperature_low(self) -> float: """Midea C3 Climate target temperature low.""" return cast( "float", self._temperature(True)[self._zone], ) @property def target_temperature_high(self) -> float: """Midea C3 Climate target temperature high.""" return cast( "float", self._temperature(False)[self._zone], ) def turn_on(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea C3 Climate turn on.""" self._device.set_attribute(attr=self._power_attr, value=True) def turn_off(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea C3 Climate turn off.""" self._device.set_attribute(attr=self._power_attr, value=False) @property def hvac_mode(self) -> HVACMode: """Midea C3 Climate hvac mode.""" mode = self._device.get_attribute(C3Attributes.mode) if self._device.get_attribute(self._power_attr) and isinstance(mode, int): return self.hvac_modes[mode] return HVACMode.OFF @property def target_temperature(self) -> float: """Midea C3 Climate target temperature.""" target_temperature = cast( "list[str]", self._device.get_attribute(C3Attributes.target_temperature), ) return cast( "float", target_temperature[self._zone], ) @property def current_temperature(self) -> float | None: """Midea C3 Climate current temperature.""" return None def set_temperature(self, **kwargs: Any) -> None: # noqa: ANN401 """Midea C3 Climate set temperature.""" if ATTR_TEMPERATURE not in kwargs: return temperature = float(int((float(kwargs[ATTR_TEMPERATURE]) * 2) + 0.5)) / 2 hvac_mode = kwargs.get(ATTR_HVAC_MODE) if hvac_mode == HVACMode.OFF: self.turn_off() else: try: mode = self.hvac_modes.index(hvac_mode.lower()) if hvac_mode else None self._device.set_target_temperature( target_temperature=temperature, mode=mode, zone=self._zone, ) except ValueError: _LOGGER.exception("Error setting temperature with: %s", kwargs) def set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Midea C3 Climate set hvac mode.""" if hvac_mode == HVACMode.OFF: self.turn_off() else: self._device.set_mode(self._zone, self.hvac_modes.index(hvac_mode)) class MideaFBClimate(MideaClimate): """Midea FB Climate Entries.""" _device: MideaFBDevice _attr_max_temp: float = 35 _attr_min_temp: float = 5 _attr_target_temperature_high: float | None = 35 _attr_target_temperature_low: float | None = 5 _attr_target_temperature_step: float | None = PRECISION_WHOLE def __init__(self, device: MideaFBDevice, entity_key: str) -> None: """Midea FB Climate entity init.""" super().__init__(device, entity_key) self._attr_hvac_modes = [HVACMode.OFF, HVACMode.HEAT] self._attr_preset_modes: list[str] = self._device.modes @property def supported_features(self) -> ClimateEntityFeature: """Midea FB Climate supported features.""" features = ( ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.PRESET_MODE ) if (MAJOR_VERSION, MINOR_VERSION) >= (2024, 2): features |= ClimateEntityFeature.TURN_OFF | ClimateEntityFeature.TURN_ON return features @property def preset_mode(self) -> str: """Midea FB Climate preset mode.""" return cast("str", self._device.get_attribute(attr=FBAttributes.mode)) @property def hvac_mode(self) -> HVACMode: """Midea FB Climate hvac mode.""" return ( HVACMode.HEAT if self._device.get_attribute(attr=FBAttributes.power) else HVACMode.OFF ) @property def current_temperature(self) -> float: """Midea FB Climate current temperature.""" return cast( "float", self._device.get_attribute(FBAttributes.current_temperature), ) def set_temperature(self, **kwargs: Any) -> None: # noqa: ANN401 """Midea FB Climate set temperature.""" if ATTR_TEMPERATURE not in kwargs: return temperature = float(int((float(kwargs[ATTR_TEMPERATURE]) * 2) + 0.5)) / 2 hvac_mode = kwargs.get(ATTR_HVAC_MODE) if hvac_mode == HVACMode.OFF: self.turn_off() else: self._device.set_target_temperature( target_temperature=temperature, mode=None, ) def set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Midea FB Climate set hvac mode.""" if hvac_mode == HVACMode.OFF: self.turn_off() else: self.turn_on() def set_preset_mode(self, preset_mode: str) -> None: """Midea FB Climate set preset mode.""" self._device.set_attribute(attr=FBAttributes.mode, value=preset_mode)
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/config_flow.py
Python
"""Config flow for Midea LAN. Setup current integration and add device entry via the web UI enable by adding `config_flow: true` in `manifest.json` `MideaLanConfigFlow`: add device entry `MideaLanOptionsFlowHandler`: update the options of a config entry job process: 1. run `async_step_user` when select `Add Device` from web UI 2. default auto discovery action run `async_step_discovery` 3. device available, run `async_step_auto` to show available device list in web UI 3.1 check local device json with `_load_device_config` 3.1.1 device exist with `_check_storage_device`, send json data to `async_step_manually` 3.1.2 device NOT exist, get device data from cloud, send to `async_step_manually` - check login with `async_step_login` 4. add selected device detail with `async_step_manually` 5. run `_save_device_config` and `async_create_entry` """ import logging from pathlib import Path from typing import TYPE_CHECKING, Any, cast import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.config_entries import ConfigEntry, ConfigFlow, OptionsFlow from homeassistant.const import ( CONF_CUSTOMIZE, CONF_DEVICE, CONF_DEVICE_ID, CONF_IP_ADDRESS, CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_PROTOCOL, CONF_SENSORS, CONF_SWITCHES, CONF_TOKEN, CONF_TYPE, MAJOR_VERSION, MINOR_VERSION, ) from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_create_clientsession from homeassistant.helpers.json import save_json from homeassistant.util.json import load_json from midealocal.cloud import ( PRESET_ACCOUNT_DATA, SUPPORTED_CLOUDS, MideaCloud, get_midea_cloud, ) from midealocal.device import AuthException, MideaDevice, ProtocolVersion from midealocal.discover import discover from midealocal.exceptions import SocketException if TYPE_CHECKING: from aiohttp import ClientSession if (MAJOR_VERSION, MINOR_VERSION) >= (2024, 4): from homeassistant.config_entries import ConfigFlowResult # pylint: disable=E0611 else: from homeassistant.data_entry_flow import ( # type: ignore[assignment] FlowResult as ConfigFlowResult, ) from .const import ( CONF_ACCOUNT, CONF_KEY, CONF_MODEL, CONF_REFRESH_INTERVAL, CONF_SERVER, CONF_SUBTYPE, DOMAIN, EXTRA_CONTROL, EXTRA_SENSOR, ) from .midea_devices import MIDEA_DEVICES _LOGGER = logging.getLogger(__name__) ADD_WAY = { "discovery": "Discover automatically", "manually": "Configure manually", "list": "List all appliances only", "cache": "Remove login cache", } # Select DEFAULT_CLOUD from the list of supported cloud DEFAULT_CLOUD: str = list(SUPPORTED_CLOUDS)[3] STORAGE_PATH = f".storage/{DOMAIN}" SKIP_LOGIN = "Skip Login (input any user/password)" class MideaLanConfigFlow(ConfigFlow, domain=DOMAIN): # type: ignore[call-arg] """Define current integration setup steps. Use ConfigFlow handle to support config entries ConfigFlow will manage the creation of entries from user input, discovery """ VERSION = 2 MINOR_VERSION = 1 def __init__(self) -> None: """MideaLanConfigFlow class.""" self.available_device: dict = {} self.devices: dict = {} self.found_device: dict[str, Any] = {} self.supports: dict = {} self.unsorted: dict[int, Any] = {} self.account: dict = {} self.cloud: MideaCloud | None = None self.session: ClientSession | None = None for device_type, device_info in MIDEA_DEVICES.items(): self.unsorted[device_type] = device_info["name"] sorted_device_names = sorted(self.unsorted.items(), key=lambda x: x[1]) for item in sorted_device_names: self.supports[item[0]] = item[1] # preset account self.preset_account: str = bytes.fromhex( format((PRESET_ACCOUNT_DATA[0] ^ PRESET_ACCOUNT_DATA[1]), "X"), ).decode("utf-8", errors="ignore") # preset password self.preset_password: str = bytes.fromhex( format((PRESET_ACCOUNT_DATA[0] ^ PRESET_ACCOUNT_DATA[2]), "X"), ).decode("utf-8", errors="ignore") self.preset_cloud_name: str = DEFAULT_CLOUD def _save_device_config(self, data: dict[str, Any]) -> None: """Save device config to json file with device id.""" storage_path = Path(self.hass.config.path(STORAGE_PATH)) storage_path.mkdir(parents=True, exist_ok=True) record_file = storage_path.joinpath(f"{data[CONF_DEVICE_ID]!s}.json") save_json(str(record_file), data) def _load_device_config(self, device_id: str) -> Any: # noqa: ANN401 """Load device config from json file with device id. Returns ------- Device configuration (json) """ record_file = Path( self.hass.config.path(f"{STORAGE_PATH}", f"{device_id}.json"), ) if record_file.exists(): with record_file.open(encoding="utf-8") as f: return load_json(f.name, default={}) return {} @staticmethod def _check_storage_device(device: dict, storage_device: dict) -> bool: """Check input device with storage_device. Returns ------- True if storage device exist """ if storage_device.get(CONF_SUBTYPE) is None: return False return not ( device.get(CONF_PROTOCOL) == ProtocolVersion.V3 and ( storage_device.get(CONF_TOKEN) is None or storage_device.get(CONF_KEY) is None ) ) def _already_configured(self, device_id: str, ip_address: str) -> bool: """Check device from json with device_id or ip address. Returns ------- True if device is already configured """ for entry in self._async_current_entries(): if device_id == entry.data.get( CONF_DEVICE_ID, ) or ip_address == entry.data.get(CONF_IP_ADDRESS): return True return False async def async_step_user( self, user_input: dict[str, Any] | None = None, error: str | None = None, ) -> ConfigFlowResult: """Define config flow steps. Using `async_step_<step_id>` and `async_step_user` will be the first step, then select discovery mode Returns ------- Config flow result """ # user select a device discovery mode if user_input is not None: # default is auto discovery mode if user_input["action"] == "discovery": return await self.async_step_discovery() # manual input device detail if user_input["action"] == "manually": self.found_device = {} return await self.async_step_manually() # remove cached login data and input new one if user_input["action"] == "cache": return await self.async_step_cache() # only list all devices return await self.async_step_list() # user not input, show device discovery select form in UI return self.async_show_form( step_id="user", data_schema=vol.Schema( {vol.Required("action", default="discovery"): vol.In(ADD_WAY)}, ), errors={"base": error} if error else None, ) async def async_step_cache( self, user_input: dict[str, Any] | None = None, error: str | None = None, ) -> ConfigFlowResult: """Remove cached login data and can input a new one. Returns ------- Config flow result """ # user input data exist if user_input is not None: # key is not None if self.hass.data.get(DOMAIN): self.hass.data[DOMAIN].pop("login_data", None) self.hass.data[DOMAIN].pop("login_mode", None) return await self.async_step_user() # show cache info form in UI return self.async_show_form( step_id="cache", data_schema=vol.Schema( { vol.Required("action", default="remove"): vol.In( {"action": "remove"}, ), }, ), errors={"base": error} if error else None, ) async def async_step_login( self, user_input: dict[str, Any] | None = None, error: str | None = None, ) -> ConfigFlowResult: """User login steps. Returns ------- Config flow result """ # get cloud servers configs cloud_servers = await MideaCloud.get_cloud_servers() default_keys = await MideaCloud.get_default_keys() # add skip login option to web UI with key 99 cloud_servers[next(iter(default_keys))] = SKIP_LOGIN # user input data exist if user_input is not None: if not self.hass.data.get(DOMAIN): self.hass.data[DOMAIN] = {} # check skip login option if user_input[CONF_SERVER] == next(iter(default_keys)): # use preset account and DEFAULT_CLOUD cloud _LOGGER.debug("skip login matched, cloud_servers: %s", cloud_servers) # get DEFAULT_CLOUD key from dict key = next( key for key, value in cloud_servers.items() if value == DEFAULT_CLOUD ) cloud_server = cloud_servers[key] account = self.preset_account password = self.preset_password # set a login_mode flag self.hass.data[DOMAIN]["login_mode"] = "preset" # use input data else: _LOGGER.debug("user input login matched") cloud_server = cloud_servers[user_input[CONF_SERVER]] account = user_input[CONF_ACCOUNT] password = user_input[CONF_PASSWORD] # set a login_mode flag self.hass.data[DOMAIN]["login_mode"] = "input" # cloud login MUST pass with user input or perset account if await self._check_cloud_login( cloud_name=cloud_server, account=account, password=password, force_login=True, ): # save passed account to cache, available before HA reboot self.hass.data[DOMAIN]["login_data"] = { CONF_ACCOUNT: account, CONF_PASSWORD: password, CONF_SERVER: cloud_server, } # return to next step after login pass return await self.async_step_auto() # return error with login failed _LOGGER.debug( "ERROR: Failed to login with %s account in %s server", self.hass.data[DOMAIN]["login_mode"], cloud_server, ) return await self.async_step_login(error="login_failed") # user not login, show login form in UI return self.async_show_form( step_id="login", data_schema=vol.Schema( { vol.Required(CONF_ACCOUNT): str, vol.Required(CONF_PASSWORD): str, vol.Required(CONF_SERVER, default=1): vol.In(cloud_servers), }, ), errors={"base": error} if error else None, ) async def async_step_list( self, error: str | None = None, ) -> ConfigFlowResult: """List all devices and show device info in web UI. Returns ------- Config flow result """ # get all devices list all_devices = discover() # available devices exist if len(all_devices) > 0: table = ( "Appliance code|Type|IP address|SN|Supported\n:--:|:--:|:--:|:--:|:--:" ) green = "<font color=gree>YES</font>" red = "<font color=red>NO</font>" for device_id, device in all_devices.items(): supported = device.get(CONF_TYPE) in self.supports table += ( f"\n{device_id}|{f'{device.get(CONF_TYPE):02X}'}|" f"{device.get(CONF_IP_ADDRESS)}|" f"{device.get('sn')}|" f"{green if supported else red}" ) # no available device else: table = "Not found" # show devices list result in UI return self.async_show_form( step_id="list", description_placeholders={"table": table}, errors={"base": error} if error else None, ) async def async_step_discovery( self, discovery_info: dict[str, Any] | None = None, error: str | None = None, ) -> ConfigFlowResult: """Discovery device with auto mode or ip address. Returns ------- Config flow result """ # input is not None, using ip_address to discovery device if discovery_info is not None: # auto mode, ip_address is None if discovery_info[CONF_IP_ADDRESS].lower() == "auto": ip_address = None # ip exist else: ip_address = discovery_info[CONF_IP_ADDRESS] # use midea-local discover() to get devices list with ip_address self.devices = discover(list(self.supports.keys()), ip_address=ip_address) self.available_device = {} for device_id, device in self.devices.items(): # remove exist devices and only return new devices if not self._already_configured( str(device_id), device[CONF_IP_ADDRESS], ): # fmt: off self.available_device[device_id] = ( f"{device_id} ({self.supports.get(device.get(CONF_TYPE))})" ) # fmt: on if len(self.available_device) > 0: return await self.async_step_auto() return await self.async_step_discovery(error="no_devices") # show discovery device input form with auto or ip address in web UI return self.async_show_form( step_id="discovery", data_schema=vol.Schema( {vol.Required(CONF_IP_ADDRESS, default="auto"): str}, ), errors={"base": error} if error else None, ) async def _check_cloud_login( self, cloud_name: str | None = None, account: str | None = None, password: str | None = None, force_login: bool = False, ) -> bool: """Check cloud login. Returns ------- True if cloud login succeeded """ # set default args with perset account if cloud_name is None or account is None or password is None: cloud_name = self.preset_cloud_name account = self.preset_account password = self.preset_password if self.session is None: self.session = async_create_clientsession(self.hass) # init cloud object or force reinit with new one if self.cloud is None or force_login: self.cloud = get_midea_cloud( cloud_name, self.session, account, password, ) # check cloud login after self.cloud exist if await self.cloud.login(): _LOGGER.debug( "Using account %s login to %s cloud pass", account, cloud_name, ) return True _LOGGER.debug( "ERROR: unable to use account %s login to %s cloud", account, cloud_name, ) return False async def _check_key_from_cloud( self, appliance_id: int, default_key: bool = True, ) -> dict[str, Any]: """Use perset DEFAULT_CLOUD account to get v3 device token and key. Returns ------- Dictionary of keys """ device = self.devices[appliance_id] if self.cloud is None: return {"error": "cloud_none"} # get device token/key from cloud keys = await self.cloud.get_cloud_keys(appliance_id) default_keys = await MideaCloud.get_default_keys() # use token/key to connect device and confirm token result for k, value in keys.items(): # skip default_key if not default_key and k == next(iter(default_keys)): continue dm = MideaDevice( name="", device_id=appliance_id, device_type=device.get(CONF_TYPE), ip_address=device.get(CONF_IP_ADDRESS), port=device.get(CONF_PORT), token=value["token"], key=value["key"], device_protocol=ProtocolVersion.V3, model=device.get(CONF_MODEL), subtype=0, attributes={}, ) if dm.connect(): try: dm.authenticate() except AuthException: _LOGGER.debug("Unable to authenticate.") dm.close_socket() except SocketException: _LOGGER.debug("Socket closed.") else: dm.close_socket() return value # return debug log with failed key _LOGGER.debug( "connect device using method %s token/key failed", k, ) _LOGGER.debug( "Unable to connect device with all the token/key", ) return {"error": "connect_error"} async def async_step_auto( self, user_input: dict[str, Any] | None = None, error: str | None = None, ) -> ConfigFlowResult: """Discovery device detail info. Returns ------- Config flow result """ # input device exist if user_input is not None: device_id = user_input[CONF_DEVICE] device = self.devices[device_id] # set device args with protocol decode data # then get subtype from cloud, get v3 device token/key from cloud self.found_device = { CONF_DEVICE_ID: device_id, CONF_TYPE: device.get(CONF_TYPE), CONF_PROTOCOL: device.get(CONF_PROTOCOL), CONF_IP_ADDRESS: device.get(CONF_IP_ADDRESS), CONF_PORT: device.get(CONF_PORT), CONF_MODEL: device.get(CONF_MODEL), } storage_device = self._load_device_config(device_id) # device config already exist, load from local json without cloud if self._check_storage_device(device, storage_device): self.found_device = { CONF_DEVICE_ID: device_id, CONF_TYPE: device.get(CONF_TYPE), CONF_PROTOCOL: device.get(CONF_PROTOCOL), CONF_IP_ADDRESS: device.get(CONF_IP_ADDRESS), CONF_PORT: device.get(CONF_PORT), CONF_MODEL: device.get(CONF_MODEL), CONF_NAME: storage_device.get(CONF_NAME), CONF_SUBTYPE: storage_device.get(CONF_SUBTYPE), CONF_TOKEN: storage_device.get(CONF_TOKEN), CONF_KEY: storage_device.get(CONF_KEY), } _LOGGER.debug( "Loaded configuration for device %s from storage", device_id, ) return await self.async_step_manually() # device config not exist in local # check login cache, show login web if no cache if not self.hass.data.get(DOMAIN) or not self.hass.data[DOMAIN].get( "login_data", ): return await self.async_step_login() # login cached exist, cloud is None, reinit and login if self.cloud is None and not await self._check_cloud_login( cloud_name=self.hass.data[DOMAIN]["login_data"][CONF_SERVER], account=self.hass.data[DOMAIN]["login_data"][CONF_ACCOUNT], password=self.hass.data[DOMAIN]["login_data"][CONF_PASSWORD], ): # print error in debug log and show login web _LOGGER.debug( "Login with cached %s account %s failed in %s server", self.hass.data[DOMAIN].get("login_mode"), self.hass.data[DOMAIN]["login_data"][CONF_ACCOUNT], self.hass.data[DOMAIN]["login_data"][CONF_SERVER], ) # remove error cache and relogin self.hass.data[DOMAIN].pop("login_data", None) self.hass.data[DOMAIN].pop("login_mode", None) return await self.async_step_login() # get subtype from cloud if self.cloud is not None and ( device_info := await self.cloud.get_device_info(device_id) ): # set subtype with model_number self.found_device[CONF_NAME] = device_info.get("name") self.found_device[CONF_SUBTYPE] = device_info.get("model_number") # MUST get a auth passed token/key for v3 device, disable add before pass if device.get(CONF_PROTOCOL) == ProtocolVersion.V3: # phase 1, try with user input login data keys = await self._check_key_from_cloud(device_id) # no available key, continue the phase 2 if not keys.get("token") or not keys.get("key"): _LOGGER.debug( "Can't get valid token with %s account in %s server", self.hass.data[DOMAIN]["login_mode"], self.hass.data[DOMAIN]["login_data"][CONF_SERVER], ) # exclude: user selected not login and phase 1 is preset account if self.hass.data[DOMAIN]["login_mode"] == "preset": return await self.async_step_auto( error="can't get valid token from Midea server", ) # get key phase 2: reinit cloud with preset account if not await self._check_cloud_login(force_login=True): return await self.async_step_auto( error="Perset account login failed!", ) # try to get a passed key, without default_key keys = await self._check_key_from_cloud( device_id, default_key=False, ) # phase 2 got no available token/key, disable device add if not keys.get("token") or not keys.get("key"): _LOGGER.debug( "Can't get available token from Midea server for device %s", device_id, ) return await self.async_step_auto( error=( f"Can't get available token from Midea server" f" for device {device_id}" ), ) # get key pass self.found_device[CONF_TOKEN] = keys["token"] self.found_device[CONF_KEY] = keys["key"] return await self.async_step_manually() # v1/v2 device add without token/key return await self.async_step_manually() # show available device list in UI return self.async_show_form( step_id="auto", data_schema=vol.Schema( { vol.Required( CONF_DEVICE, default=next(iter(self.available_device.keys())), ): vol.In(self.available_device), }, ), errors={"base": error} if error else None, ) async def async_step_manually( self, user_input: dict[str, Any] | None = None, error: str | None = None, ) -> ConfigFlowResult: """Add device with device detail info. Returns ------- Config flow result """ if user_input is not None: try: bytearray.fromhex(user_input[CONF_TOKEN]) bytearray.fromhex(user_input[CONF_KEY]) except ValueError: return await self.async_step_manually(error="invalid_token") device_id = user_input[CONF_DEVICE_ID] # check device, discover already done or only manual add if len(self.devices) < 1: ip = user_input[CONF_IP_ADDRESS] # discover device self.devices = discover( list(self.supports.keys()), ip_address=ip, ) # discover result MUST exist if len(self.devices) != 1: return await self.async_step_manually(error="invalid_device_ip") # check all the input, disable error add device_id = next(iter(self.devices.keys())) # check if device_id is correctly set for that IP if user_input[CONF_DEVICE_ID] != device_id: return await self.async_step_manually( error=f"For ip {ip} the device_id MUST be {device_id}", ) device = self.devices[device_id] if user_input[CONF_IP_ADDRESS] != device.get(CONF_IP_ADDRESS): return await self.async_step_manually( error=f"ip_address MUST be {device.get(CONF_IP_ADDRESS)}", ) if user_input[CONF_PROTOCOL] != device.get(CONF_PROTOCOL): return await self.async_step_manually( error=f"protocol MUST be {device.get(CONF_PROTOCOL)}", ) # try to get token/key with preset account if user_input[CONF_PROTOCOL] == ProtocolVersion.V3 and ( len(user_input[CONF_TOKEN]) == 0 or len(user_input[CONF_KEY]) == 0 ): # init cloud with preset account result = await self._check_cloud_login() if not result: return await self.async_step_manually( error="Perset account login failed!", ) # try to get a passed key keys = await self._check_key_from_cloud(int(user_input[CONF_DEVICE_ID])) # no available token/key, disable device add if not keys.get("token") or not keys.get("key"): _LOGGER.debug( "Can't get a valid token from Midea server for device %s", user_input[CONF_DEVICE_ID], ) return await self.async_step_manually( error=( f"Can't get a valid token from Midea server" f" for device {user_input[CONF_DEVICE_ID]}" ), ) # set token/key from preset account user_input[CONF_KEY] = keys["key"] user_input[CONF_TOKEN] = keys["token"] self.found_device = { CONF_DEVICE_ID: user_input[CONF_DEVICE_ID], CONF_TYPE: user_input[CONF_TYPE], CONF_PROTOCOL: user_input[CONF_PROTOCOL], CONF_IP_ADDRESS: user_input[CONF_IP_ADDRESS], CONF_PORT: user_input[CONF_PORT], CONF_MODEL: user_input[CONF_MODEL], CONF_TOKEN: user_input[CONF_TOKEN], CONF_KEY: user_input[CONF_KEY], } # check device connection with all the input dm = MideaDevice( name="", device_id=user_input[CONF_DEVICE_ID], device_type=user_input[CONF_TYPE], ip_address=user_input[CONF_IP_ADDRESS], port=user_input[CONF_PORT], token=user_input[CONF_TOKEN], key=user_input[CONF_KEY], device_protocol=user_input[CONF_PROTOCOL], model=user_input[CONF_MODEL], subtype=0, attributes={}, ) if dm.connect(): try: if user_input[CONF_PROTOCOL] == ProtocolVersion.V3: dm.authenticate() except SocketException: _LOGGER.exception("Socket closed.") except AuthException: _LOGGER.exception( "Unable to authenticate with provided key and token.", ) dm.close_socket() else: dm.close_socket() data = { CONF_NAME: user_input[CONF_NAME], CONF_DEVICE_ID: user_input[CONF_DEVICE_ID], CONF_TYPE: user_input[CONF_TYPE], CONF_PROTOCOL: user_input[CONF_PROTOCOL], CONF_IP_ADDRESS: user_input[CONF_IP_ADDRESS], CONF_PORT: user_input[CONF_PORT], CONF_MODEL: user_input[CONF_MODEL], CONF_SUBTYPE: user_input[CONF_SUBTYPE], CONF_TOKEN: user_input[CONF_TOKEN], CONF_KEY: user_input[CONF_KEY], } # save device json config when adding new device self._save_device_config(data) # finish add device entry return self.async_create_entry( title=f"{user_input[CONF_NAME]}", data=data, ) return await self.async_step_manually( error="Device auth failed with input config", ) protocol = self.found_device.get(CONF_PROTOCOL) return self.async_show_form( step_id="manually", data_schema=vol.Schema( { vol.Required( CONF_NAME, default=( self.found_device.get(CONF_NAME) if self.found_device.get(CONF_NAME) else self.supports.get(self.found_device.get(CONF_TYPE)) ), ): str, vol.Required( CONF_DEVICE_ID, default=self.found_device.get(CONF_DEVICE_ID), ): int, vol.Required( CONF_TYPE, default=( self.found_device.get(CONF_TYPE) if self.found_device.get(CONF_TYPE) else 0xAC ), ): vol.In(self.supports), vol.Required( CONF_IP_ADDRESS, default=self.found_device.get(CONF_IP_ADDRESS), ): str, vol.Required( CONF_PORT, default=( self.found_device.get(CONF_PORT) if self.found_device.get(CONF_PORT) else 6444 ), ): int, vol.Required( CONF_PROTOCOL, default=protocol or ProtocolVersion.V3, ): vol.In( [protocol] if protocol else ProtocolVersion, ), vol.Required( CONF_MODEL, default=( self.found_device.get(CONF_MODEL) if self.found_device.get(CONF_MODEL) else "Unknown" ), ): str, vol.Required( CONF_SUBTYPE, default=( self.found_device.get(CONF_SUBTYPE) if self.found_device.get(CONF_SUBTYPE) else 0 ), ): int, vol.Optional( CONF_TOKEN, default=( self.found_device.get(CONF_TOKEN) if self.found_device.get(CONF_TOKEN) else "" ), ): str, vol.Optional( CONF_KEY, default=( self.found_device.get(CONF_KEY) if self.found_device.get(CONF_KEY) else "" ), ): str, }, ), errors={"base": error} if error else None, ) @staticmethod @callback def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlow: """Create the options flow with MideaLanOptionsFlowHandler. Returns ------- Config flow options handler """ return MideaLanOptionsFlowHandler(config_entry) class MideaLanOptionsFlowHandler(OptionsFlow): """define an Options Flow Handler to update the options of a config entry.""" def __init__(self, config_entry: ConfigEntry) -> None: """Initialize options flow.""" self._config_entry = config_entry self._device_type = config_entry.data.get(CONF_TYPE) if self._device_type is None: self._device_type = 0xAC if CONF_SENSORS in self._config_entry.options: for key in self._config_entry.options[CONF_SENSORS]: if key not in MIDEA_DEVICES[self._device_type]["entities"]: self._config_entry.options[CONF_SENSORS].remove(key) if CONF_SWITCHES in self._config_entry.options: for key in self._config_entry.options[CONF_SWITCHES]: if key not in MIDEA_DEVICES[self._device_type]["entities"]: self._config_entry.options[CONF_SWITCHES].remove(key) async def async_step_init( self, user_input: dict[str, Any] | None = None, ) -> ConfigFlowResult: """Manage the options. Returns ------- Config flow result """ if self._device_type == CONF_ACCOUNT: return self.async_abort(reason="account_option") if user_input is not None: return self.async_create_entry(title="", data=user_input) sensors = {} switches = {} for attribute, attribute_config in cast( "dict", MIDEA_DEVICES[cast("int", self._device_type)]["entities"], ).items(): attribute_name = ( attribute if isinstance(attribute, str) else attribute.value ) if attribute_config.get("type") in EXTRA_SENSOR: sensors[attribute_name] = attribute_config.get("name") elif attribute_config.get( "type", ) in EXTRA_CONTROL and not attribute_config.get("default"): switches[attribute_name] = attribute_config.get("name") ip_address = self._config_entry.options.get(CONF_IP_ADDRESS, None) if ip_address is None: ip_address = self._config_entry.data.get(CONF_IP_ADDRESS, None) refresh_interval = self._config_entry.options.get(CONF_REFRESH_INTERVAL, 30) extra_sensors = list( set(sensors.keys()) & set(self._config_entry.options.get(CONF_SENSORS, [])), ) extra_switches = list( set(switches.keys()) & set(self._config_entry.options.get(CONF_SWITCHES, [])), ) customize = self._config_entry.options.get(CONF_CUSTOMIZE, "") data_schema = vol.Schema( { vol.Required(CONF_IP_ADDRESS, default=ip_address): str, vol.Required(CONF_REFRESH_INTERVAL, default=refresh_interval): int, }, ) if len(sensors) > 0: data_schema = data_schema.extend( { vol.Required( CONF_SENSORS, default=extra_sensors, ): cv.multi_select(sensors), }, ) if len(switches) > 0: data_schema = data_schema.extend( { vol.Required( CONF_SWITCHES, default=extra_switches, ): cv.multi_select(switches), }, ) data_schema = data_schema.extend( { vol.Optional( CONF_CUSTOMIZE, default=customize, ): str, }, ) return self.async_show_form(step_id="init", data_schema=data_schema)
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/const.py
Python
"""Const for Midea Lan.""" from enum import IntEnum from homeassistant.const import Platform DOMAIN = "midea_ac_lan" COMPONENT = "component" DEVICES = "devices" CONF_KEY = "key" CONF_MODEL = "model" CONF_SUBTYPE = "subtype" CONF_ACCOUNT = "account" CONF_SERVER = "server" CONF_REFRESH_INTERVAL = "refresh_interval" EXTRA_SENSOR = [Platform.SENSOR, Platform.BINARY_SENSOR] EXTRA_SWITCH = [Platform.SWITCH, Platform.LOCK, Platform.SELECT, Platform.NUMBER] EXTRA_CONTROL = [ Platform.CLIMATE, Platform.WATER_HEATER, Platform.FAN, Platform.HUMIDIFIER, Platform.LIGHT, *EXTRA_SWITCH, ] ALL_PLATFORM = EXTRA_SENSOR + EXTRA_CONTROL class FanSpeed(IntEnum): """FanSpeed reference values.""" LOW = 20 MEDIUM = 40 HIGH = 60 FULL_SPEED = 80 AUTO = 100
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/diagnostics.py
Python
"""Diagnostics support for Midea AC LAN.""" from __future__ import annotations from typing import TYPE_CHECKING, Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.const import ( CONF_TOKEN, ) if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from .const import CONF_KEY TO_REDACT = {CONF_TOKEN, CONF_KEY} async def async_get_config_entry_diagnostics( hass: HomeAssistant, # noqa: ARG001 entry: ConfigEntry, ) -> dict[str, Any]: """Return diagnostics for a config entry. Returns ------- Dictionary of config """ return {"entry": async_redact_data(entry.as_dict(), TO_REDACT)}
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/fan.py
Python
"""Midea Fan entries.""" import logging from typing import Any, cast from homeassistant.components.fan import FanEntity, FanEntityFeature from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_DEVICE_ID, CONF_SWITCHES, Platform, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from midealocal.device import DeviceType from midealocal.devices.ac import DeviceAttributes as ACAttributes from midealocal.devices.ac import MideaACDevice from midealocal.devices.b6 import MideaB6Device from midealocal.devices.ce import DeviceAttributes as CEAttributes from midealocal.devices.ce import MideaCEDevice from midealocal.devices.fa import MideaFADevice from midealocal.devices.x40 import DeviceAttributes as X40Attributes from midealocal.devices.x40 import MideaX40Device from .const import DEVICES, DOMAIN from .midea_devices import MIDEA_DEVICES from .midea_entity import MideaEntity _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up fan entries.""" device_id = config_entry.data.get(CONF_DEVICE_ID) device = hass.data[DOMAIN][DEVICES].get(device_id) extra_switches = config_entry.options.get(CONF_SWITCHES, []) devs: list[ MideaFAFan | MideaB6Fan | MideaACFreshAirFan | MideaCEFan | MideaX40Fan ] = [] for entity_key, config in cast( "dict", MIDEA_DEVICES[device.device_type]["entities"], ).items(): if config["type"] == Platform.FAN and ( config.get("default") or entity_key in extra_switches ): if device.device_type == DeviceType.FA: devs.append(MideaFAFan(device, entity_key)) elif device.device_type == DeviceType.B6: devs.append(MideaB6Fan(device, entity_key)) elif device.device_type == DeviceType.AC: devs.append(MideaACFreshAirFan(device, entity_key)) elif device.device_type == DeviceType.CE: devs.append(MideaCEFan(device, entity_key)) elif device.device_type == DeviceType.X40: devs.append(MideaX40Fan(device, entity_key)) async_add_entities(devs) # HA version >= 2024,8 support TURN_ON | TURN_OFF,for future changes, ref PR #285 try: FAN_FEATURE_TURN_ON_OFF = FanEntityFeature["TURN_ON"] | FanEntityFeature["TURN_OFF"] except KeyError: FAN_FEATURE_TURN_ON_OFF = FanEntityFeature(0) class MideaFan(MideaEntity, FanEntity): """Midea Fan Entries Base Class.""" _enable_turn_on_off_backwards_compatibility = False # 2024.8~2025.1 @property def preset_modes(self) -> list[str] | None: """Midea Fan preset modes.""" return ( self._device.preset_modes if hasattr(self._device, "preset_modes") else None ) @property def is_on(self) -> bool: """Midea Fan is on.""" return cast("bool", self._device.get_attribute("power")) @property def oscillating(self) -> bool: """Midea Fan oscillating.""" return cast("bool", self._device.get_attribute("oscillate")) @property def preset_mode(self) -> str | None: """Midea Fan preset mode.""" return cast("str", self._device.get_attribute("mode")) @property def fan_speed(self) -> int | None: """Midea Fan fan speed.""" return cast("int", self._device.get_attribute("fan_speed")) def turn_off(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea Fan turn off.""" self._device.set_attribute(attr="power", value=False) def oscillate(self, oscillating: bool) -> None: """Midea Fan oscillate.""" self._device.set_attribute(attr="oscillate", value=oscillating) def set_preset_mode(self, preset_mode: str) -> None: """Midea Fan set preset mode.""" self._device.set_attribute(attr="mode", value=preset_mode.capitalize()) @property def percentage(self) -> int | None: """Midea Fan percentage.""" if not self.fan_speed: return None return int(round(self.fan_speed * self.percentage_step)) # noqa: RUF046 def set_percentage(self, percentage: int) -> None: """Midea Fan set percentage.""" fan_speed = round(percentage / self.percentage_step) self._device.set_attribute(attr="fan_speed", value=fan_speed) async def async_set_percentage(self, percentage: int) -> None: """Midea Fan async set percentage.""" if percentage == 0: await self.async_turn_off() else: await self.hass.async_add_executor_job(self.set_percentage, percentage) def update_state(self, status: Any) -> None: # noqa: ANN401, ARG002 """Midea Fan update state.""" if not self.hass: _LOGGER.warning( "Fan update_state skipped for %s [%s]: HASS is None", self.name, type(self), ) return self.schedule_update_ha_state() class MideaFAFan(MideaFan): """Midea FA Fan Entries.""" _device: MideaFADevice def __init__(self, device: MideaFADevice, entity_key: str) -> None: """Midea FA Fan entity init.""" super().__init__(device, entity_key) self._attr_supported_features = ( FanEntityFeature.SET_SPEED | FanEntityFeature.OSCILLATE | FanEntityFeature.PRESET_MODE | FAN_FEATURE_TURN_ON_OFF ) self._attr_speed_count = self._device.speed_count def turn_on( self, percentage: int | None = None, preset_mode: str | None = None, **kwargs: Any, # noqa: ANN401, ARG002 ) -> None: """Midea FA Fan turn on.""" fan_speed = int(percentage / self.percentage_step + 0.5) if percentage else None self._device.turn_on(fan_speed=fan_speed, mode=preset_mode) class MideaB6Fan(MideaFan): """Midea B6 Fan Entries.""" _device: MideaB6Device def __init__(self, device: MideaB6Device, entity_key: str) -> None: """Midea B6 Fan entity init.""" super().__init__(device, entity_key) self._attr_supported_features = ( FanEntityFeature.SET_SPEED | FanEntityFeature.PRESET_MODE | FAN_FEATURE_TURN_ON_OFF ) self._attr_speed_count = self._device.speed_count def turn_on( self, percentage: int | None = None, preset_mode: str | None = None, **kwargs: Any, # noqa: ANN401, ARG002 ) -> None: """Midea B6 Fan turn on.""" fan_speed = int(percentage / self.percentage_step + 0.5) if percentage else None self._device.turn_on(fan_speed=fan_speed, mode=preset_mode) class MideaACFreshAirFan(MideaFan): """Midea AC Fresh Air Fan Entries.""" _device: MideaACDevice def __init__(self, device: MideaACDevice, entity_key: str) -> None: """Midea AC Fresh Air Fan entity init.""" super().__init__(device, entity_key) self._attr_supported_features = ( FanEntityFeature.SET_SPEED | FanEntityFeature.PRESET_MODE | FAN_FEATURE_TURN_ON_OFF ) self._attr_speed_count = 100 @property def preset_modes(self) -> list[str] | None: """Midea AC Fan preset modes.""" return cast("list", self._device.fresh_air_fan_speeds) @property def is_on(self) -> bool: """Midea AC Fan is on.""" return cast("bool", self._device.get_attribute(ACAttributes.fresh_air_power)) @property def fan_speed(self) -> int: """Midea AC Fan fan speed.""" return cast("int", self._device.get_attribute(ACAttributes.fresh_air_fan_speed)) def turn_on( self, percentage: int | None = None, # noqa: ARG002 preset_mode: str | None = None, # noqa: ARG002 **kwargs: Any, # noqa: ANN401, ARG002 ) -> None: """Midea AC Fan tun on.""" self._device.set_attribute(attr=ACAttributes.fresh_air_power, value=True) def turn_off(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea AC Fan turn off.""" self._device.set_attribute(attr=ACAttributes.fresh_air_power, value=False) def set_percentage(self, percentage: int) -> None: """Midea AC Fan set percentage.""" fan_speed = int(percentage / self.percentage_step + 0.5) self._device.set_attribute( attr=ACAttributes.fresh_air_fan_speed, value=fan_speed, ) def set_preset_mode(self, preset_mode: str) -> None: """Midea AC Fan set preset mode.""" self._device.set_attribute(attr=ACAttributes.fresh_air_mode, value=preset_mode) @property def preset_mode(self) -> str | None: """Midea AC Fan preset mode.""" return cast("str", self._device.get_attribute(attr=ACAttributes.fresh_air_mode)) class MideaCEFan(MideaFan): """Midea CE Fan Entries.""" _device: MideaCEDevice def __init__(self, device: MideaCEDevice, entity_key: str) -> None: """Midea CE Fan entity init.""" super().__init__(device, entity_key) self._attr_supported_features = ( FanEntityFeature.SET_SPEED | FanEntityFeature.PRESET_MODE | FAN_FEATURE_TURN_ON_OFF ) self._attr_speed_count = self._device.speed_count def turn_on( self, percentage: int | None = None, # noqa: ARG002 preset_mode: str | None = None, # noqa: ARG002 **kwargs: Any, # noqa: ANN401, ARG002 ) -> None: """Midea CE Fan turn on.""" self._device.set_attribute(attr=CEAttributes.power, value=True) async def async_set_percentage(self, percentage: int) -> None: """Midea CE Fan async set percentage.""" await self.hass.async_add_executor_job(self.set_percentage, percentage) class MideaX40Fan(MideaFan): """Midea X40 Fan Entries.""" _device: MideaX40Device def __init__(self, device: MideaX40Device, entity_key: str) -> None: """Midea X40 Fan entity init.""" super().__init__(device, entity_key) self._attr_supported_features = ( FanEntityFeature.SET_SPEED | FanEntityFeature.OSCILLATE | FAN_FEATURE_TURN_ON_OFF ) self._attr_speed_count = 2 @property def is_on(self) -> bool: """Midea X40 Fan is on.""" return cast("int", self._device.get_attribute(attr=X40Attributes.fan_speed)) > 0 def turn_on( self, percentage: int | None = None, # noqa: ARG002 preset_mode: str | None = None, # noqa: ARG002 **kwargs: Any, # noqa: ANN401, ARG002 ) -> None: """Midea X40 Fan turn on.""" self._device.set_attribute(attr=X40Attributes.fan_speed, value=1) def turn_off(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea X40 Fan turn off.""" self._device.set_attribute(attr=X40Attributes.fan_speed, value=0)
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/humidifier.py
Python
"""Midea Humidifier entries.""" import logging from typing import Any, TypeAlias, cast from homeassistant.components.humidifier import ( HumidifierDeviceClass, HumidifierEntity, HumidifierEntityFeature, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DEVICE_ID, CONF_SWITCHES, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from midealocal.device import DeviceType from midealocal.devices.a1 import MideaA1Device from midealocal.devices.fd import MideaFDDevice from .const import DEVICES, DOMAIN from .midea_devices import MIDEA_DEVICES from .midea_entity import MideaEntity _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up humidifier entries.""" device_id = config_entry.data.get(CONF_DEVICE_ID) device = hass.data[DOMAIN][DEVICES].get(device_id) extra_switches = config_entry.options.get(CONF_SWITCHES, []) devs: list[MideaA1Humidifier | MideaFDHumidifier] = [] for entity_key, config in cast( "dict", MIDEA_DEVICES[device.device_type]["entities"], ).items(): if config["type"] == Platform.HUMIDIFIER and ( config.get("default") or entity_key in extra_switches ): if device.device_type == DeviceType.A1: devs.append(MideaA1Humidifier(device, entity_key)) if device.device_type == DeviceType.FD: devs.append(MideaFDHumidifier(device, entity_key)) async_add_entities(devs) MideaHumidifierDevice: TypeAlias = MideaFDDevice | MideaA1Device class MideaHumidifier(MideaEntity, HumidifierEntity): """Midea Humidifier Entries Base Class.""" _device: MideaHumidifierDevice def __init__(self, device: MideaHumidifierDevice, entity_key: str) -> None: """Midea Humidifier entity init.""" super().__init__(device, entity_key) @property def current_humidity(self) -> float | None: """Midea Humidifier current humidity.""" return cast("float", self._device.get_attribute("current_humidity")) @property def target_humidity(self) -> float: """Midea Humidifier target humidity.""" return cast("float", self._device.get_attribute("target_humidity")) @property def mode(self) -> str: """Midea Humidifier mode.""" return cast("str", self._device.get_attribute("mode")) @property def available_modes(self) -> list[str] | None: """Midea Humidifier available modes.""" return cast("list", self._device.modes) def set_humidity(self, humidity: int) -> None: """Midea Humidifier set humidity.""" self._device.set_attribute("target_humidity", humidity) def set_mode(self, mode: str) -> None: """Midea Humidifier set mode.""" self._device.set_attribute("mode", mode) @property def is_on(self) -> bool: """Midea Humidifier is on.""" return cast("bool", self._device.get_attribute(attr="power")) def turn_on(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea Humidifier turn on.""" self._device.set_attribute(attr="power", value=True) def turn_off(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea Humidifier turn off.""" self._device.set_attribute(attr="power", value=False) def update_state(self, status: Any) -> None: # noqa: ANN401, ARG002 """Midea Humidifier update state.""" if not self.hass: _LOGGER.warning( "Humidifier update_state skipped for %s [%s]: HASS is None", self.name, type(self), ) return self.schedule_update_ha_state() class MideaA1Humidifier(MideaHumidifier): """Midea A1 Humidifier Entries.""" _device: MideaA1Device def __init__(self, device: MideaA1Device, entity_key: str) -> None: """Midea A1 Humidifier entity init.""" super().__init__(device, entity_key) self._attr_min_humidity: float = 35 self._attr_max_humidity: float = 85 self._attr_device_class = HumidifierDeviceClass.DEHUMIDIFIER self._attr_supported_features = HumidifierEntityFeature.MODES class MideaFDHumidifier(MideaHumidifier): """Midea FD Humidifier Entries.""" _device: MideaFDDevice def __init__(self, device: MideaFDDevice, entity_key: str) -> None: """Midea FD Humidifier entity init.""" super().__init__(device, entity_key) self._attr_min_humidity: float = 35 self._attr_max_humidity: float = 85 self._attr_device_class = HumidifierDeviceClass.HUMIDIFIER self._attr_supported_features = HumidifierEntityFeature.MODES
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/light.py
Python
"""Midea Light entries.""" import logging from typing import Any, cast from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP_KELVIN, ATTR_EFFECT, ColorMode, LightEntity, LightEntityFeature, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DEVICE_ID, CONF_SWITCHES, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from midealocal.devices.x13 import DeviceAttributes as X13Attributes from midealocal.devices.x13 import Midea13Device from .const import DEVICES, DOMAIN from .midea_devices import MIDEA_DEVICES from .midea_entity import MideaEntity _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up light entries.""" device_id = config_entry.data.get(CONF_DEVICE_ID) device = hass.data[DOMAIN][DEVICES].get(device_id) extra_switches = config_entry.options.get(CONF_SWITCHES, []) devs = [] for entity_key, config in cast( "dict", MIDEA_DEVICES[device.device_type]["entities"], ).items(): if config["type"] == Platform.LIGHT and ( config.get("default") or entity_key in extra_switches ): devs.append(MideaLight(device, entity_key)) async_add_entities(devs) def _calc_supported_features(device: Midea13Device) -> LightEntityFeature: supported_features = LightEntityFeature(0) if device.get_attribute(X13Attributes.effect): supported_features |= LightEntityFeature.EFFECT return supported_features def _calc_supported_color_modes(device: Midea13Device) -> set[ColorMode]: # https://github.com/home-assistant/core/blob/c34731185164aaf44419977c4086e9a7dd6c0a7f/homeassistant/components/light/__init__.py#L1278 supported = set[ColorMode]() if device.get_attribute(X13Attributes.color_temperature) is not None: supported.add(ColorMode.COLOR_TEMP) if device.get_attribute(X13Attributes.rgb_color) is not None: supported.add(ColorMode.HS) if not supported and device.get_attribute(X13Attributes.brightness) is not None: supported = {ColorMode.BRIGHTNESS} if not supported: supported = {ColorMode.ONOFF} return supported class MideaLight(MideaEntity, LightEntity): """Midea Light Entries.""" _attr_color_mode: ColorMode | str | None = None _attr_supported_color_modes: set[ColorMode] | set[str] | None = None _attr_supported_features: LightEntityFeature = LightEntityFeature(0) _device: Midea13Device def __init__(self, device: Midea13Device, entity_key: str) -> None: """Midea Light entity init.""" super().__init__(device, entity_key) self._attr_supported_features = _calc_supported_features(device) self._attr_supported_color_modes = _calc_supported_color_modes(device) self._attr_color_mode = self._calc_color_mode(self._attr_supported_color_modes) def _calc_color_mode(self, supported: set[ColorMode]) -> ColorMode: """Midea Light calculate color mode. Returns ------- Calculated color mode """ # https://github.com/home-assistant/core/blob/c34731185164aaf44419977c4086e9a7dd6c0a7f/homeassistant/components/light/__init__.py#L925 if ColorMode.HS in supported and self.hs_color is not None: return ColorMode.HS if ColorMode.COLOR_TEMP in supported and self.color_temp_kelvin is not None: return ColorMode.COLOR_TEMP if ColorMode.BRIGHTNESS in supported and self.brightness is not None: return ColorMode.BRIGHTNESS if ColorMode.ONOFF in supported: return ColorMode.ONOFF return ColorMode.UNKNOWN @property def is_on(self) -> bool: """Midea Light is on.""" return cast("bool", self._device.get_attribute(X13Attributes.power)) @property def brightness(self) -> int | None: """Midea Light brightness.""" return cast("int", self._device.get_attribute(X13Attributes.brightness)) @property def rgb_color(self) -> tuple[int, int, int] | None: """Midea Light rgb color.""" return cast("tuple", self._device.get_attribute(X13Attributes.rgb_color)) @property def color_temp(self) -> int | None: """Midea Light color temperature.""" if not self.color_temp_kelvin: return None return round(1000000 / self.color_temp_kelvin) # https://developers.home-assistant.io/blog/2024/12/14/kelvin-preferred-color-temperature-unit @property def color_temp_kelvin(self) -> int | None: """Midea Light color temperature kelvin.""" return cast("int", self._device.get_attribute(X13Attributes.color_temperature)) @property def min_color_temp_kelvin(self) -> int: """Midea Light min color temperature kelvin.""" return self._device.color_temp_range[0] @property def max_color_temp_kelvin(self) -> int: """Midea Light max color temperature kelvin.""" return self._device.color_temp_range[1] @property def effect_list(self) -> list[str] | None: """Midea Light effect list.""" return cast("list", self._device.effects) @property def effect(self) -> str | None: """Midea Light effect.""" return cast("str", self._device.get_attribute(X13Attributes.effect)) def turn_on(self, **kwargs: Any) -> None: # noqa: ANN401 """Midea Light turn on.""" if not self.is_on: self._device.set_attribute(attr=X13Attributes.power, value=True) for key, value in kwargs.items(): if key == ATTR_BRIGHTNESS: self._device.set_attribute(attr=X13Attributes.brightness, value=value) if key == ATTR_COLOR_TEMP_KELVIN: self._device.set_attribute( attr=X13Attributes.color_temperature, value=value, ) if key == ATTR_EFFECT: self._device.set_attribute(attr=X13Attributes.effect, value=value) def turn_off(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea Light turn off.""" self._device.set_attribute(attr=X13Attributes.power, value=False) def update_state(self, status: Any) -> None: # noqa: ANN401,ARG002 """Midea Light update state.""" if not self.hass: _LOGGER.warning( "Light update_state skipped for %s [%s]: HASS is None", self.name, type(self), ) return self.schedule_update_ha_state()
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/lock.py
Python
"""Lock entities for Midea Lan.""" from typing import Any, cast from homeassistant.components.lock import LockEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DEVICE_ID, CONF_SWITCHES, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DEVICES, DOMAIN from .midea_devices import MIDEA_DEVICES from .midea_entity import MideaEntity async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up entities for device.""" device_id = config_entry.data.get(CONF_DEVICE_ID) device = hass.data[DOMAIN][DEVICES].get(device_id) extra_switches = config_entry.options.get(CONF_SWITCHES, []) locks = [] for entity_key, config in cast( "dict", MIDEA_DEVICES[device.device_type]["entities"], ).items(): if config["type"] == Platform.LOCK and entity_key in extra_switches: dev = MideaLock(device, entity_key) locks.append(dev) async_add_entities(locks) class MideaLock(MideaEntity, LockEntity): """Represent a Midea lock entity.""" @property def is_locked(self) -> bool: """Return true if state is locked.""" return cast("bool", self._device.get_attribute(self._entity_key)) def lock(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Lock the lock.""" self._device.set_attribute(attr=self._entity_key, value=True) def unlock(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Unlock the lock.""" self._device.set_attribute(attr=self._entity_key, value=False) def open(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Open the lock.""" self.unlock()
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/midea_devices.py
Python
"""Devices configuration for Midea Lan.""" from typing import Any from homeassistant.components.binary_sensor import BinarySensorDeviceClass from homeassistant.components.sensor import SensorDeviceClass, SensorStateClass from homeassistant.const import ( CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_MILLION, PERCENTAGE, Platform, UnitOfEnergy, UnitOfPower, UnitOfTemperature, UnitOfTime, UnitOfVolume, ) from midealocal.devices.a1 import DeviceAttributes as A1Attributes from midealocal.devices.ac import DeviceAttributes as ACAttributes from midealocal.devices.ad import DeviceAttributes as ADAttributes from midealocal.devices.b0 import DeviceAttributes as B0Attributes from midealocal.devices.b1 import DeviceAttributes as B1Attributes from midealocal.devices.b3 import DeviceAttributes as B3Attributes from midealocal.devices.b4 import DeviceAttributes as B4Attributes from midealocal.devices.b6 import DeviceAttributes as B6Attributes from midealocal.devices.bf import DeviceAttributes as BFAttributes from midealocal.devices.c2 import DeviceAttributes as C2Attributes from midealocal.devices.c3 import DeviceAttributes as C3Attributes from midealocal.devices.ca import DeviceAttributes as CAAttributes from midealocal.devices.cc import DeviceAttributes as CCAttributes from midealocal.devices.cd import DeviceAttributes as CDAttributes from midealocal.devices.ce import DeviceAttributes as CEAttributes from midealocal.devices.cf import DeviceAttributes as CFAttributes from midealocal.devices.da import DeviceAttributes as DAAttributes from midealocal.devices.db import DeviceAttributes as DBAttributes from midealocal.devices.dc import DeviceAttributes as DCAttributes from midealocal.devices.e1 import DeviceAttributes as E1Attributes from midealocal.devices.e2 import DeviceAttributes as E2Attributes from midealocal.devices.e3 import DeviceAttributes as E3Attributes from midealocal.devices.e6 import DeviceAttributes as E6Attributes from midealocal.devices.e8 import DeviceAttributes as E8Attributes from midealocal.devices.ea import DeviceAttributes as EAAttributes from midealocal.devices.ec import DeviceAttributes as ECAttributes from midealocal.devices.ed import DeviceAttributes as EDAttributes from midealocal.devices.fa import DeviceAttributes as FAAttributes from midealocal.devices.fb import DeviceAttributes as FBAttributes from midealocal.devices.fc import DeviceAttributes as FCAttributes from midealocal.devices.fd import DeviceAttributes as FDAttributes from midealocal.devices.x26 import DeviceAttributes as X26Attributes from midealocal.devices.x34 import DeviceAttributes as X34Attributes from midealocal.devices.x40 import DeviceAttributes as X40Attributes """ Entity Naming Rule: 1. `name` used in web UI enable/disable extra sensor/control setting 2. entity `_attr_name` exist will ignore `translation_key` 3. no `_attr_name` and no `translation_key` will try `device_class` 4. refer to `midea_entity.py` comments for translation order - for entity translation: - 1. set "translation_key" - 2. add translation to `translations/{language}.json` """ MIDEA_DEVICES: dict[int, dict[str, dict[str, Any] | str]] = { 0x13: { "name": "Light", "entities": { "light": { "type": Platform.LIGHT, "icon": "mdi:lightbulb", "default": True, }, }, }, 0x26: { "name": "Bathroom Master", "entities": { X26Attributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, X26Attributes.current_humidity: { "type": Platform.SENSOR, "name": "Current Humidity", "device_class": SensorDeviceClass.HUMIDITY, "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, X26Attributes.current_radar: { "type": Platform.BINARY_SENSOR, "name": "Occupancy Status", "device_class": BinarySensorDeviceClass.MOTION, }, X26Attributes.main_light: { "type": Platform.SWITCH, "translation_key": "main_light", "name": "Main Light", "icon": "mdi:lightbulb", }, X26Attributes.night_light: { "type": Platform.SWITCH, "translation_key": "night_light", "name": "Night Light", "icon": "mdi:lightbulb", }, X26Attributes.mode: { "type": Platform.SELECT, "translation_key": "mode", "name": "Mode", "options": "preset_modes", "icon": "mdi:fan", }, X26Attributes.direction: { "type": Platform.SELECT, "translation_key": "direction", "name": "Direction", "options": "directions", "icon": "mdi:arrow-split-vertical", }, }, }, 0x34: { "name": "Sink Dishwasher", "entities": { X34Attributes.door: { "type": Platform.BINARY_SENSOR, "name": "Door", "icon": "mdi:box-shadow", "device_class": BinarySensorDeviceClass.DOOR, }, X34Attributes.rinse_aid: { "type": Platform.BINARY_SENSOR, "translation_key": "rinse_aid", "name": "Rinse Aid Shortage", "icon": "mdi:bottle-tonic", "device_class": BinarySensorDeviceClass.PROBLEM, }, X34Attributes.salt: { "type": Platform.BINARY_SENSOR, "translation_key": "salt", "name": "Salt Shortage", "icon": "mdi:drag", "device_class": BinarySensorDeviceClass.PROBLEM, }, X34Attributes.humidity: { "type": Platform.SENSOR, "name": "Humidity", "device_class": SensorDeviceClass.HUMIDITY, "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, X34Attributes.progress: { "type": Platform.SENSOR, "translation_key": "progress", "name": "Progress", "icon": "mdi:rotate-360", }, X34Attributes.status: { "type": Platform.SENSOR, "translation_key": "status", "name": "Status", "icon": "mdi:information", }, X34Attributes.storage_remaining: { "type": Platform.SENSOR, "translation_key": "storage_remaining", "name": "Storage Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.HOURS, "state_class": SensorStateClass.MEASUREMENT, }, X34Attributes.temperature: { "type": Platform.SENSOR, "name": "Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, X34Attributes.time_remaining: { "type": Platform.SENSOR, "translation_key": "time_remaining", "name": "Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, X34Attributes.child_lock: { "type": Platform.LOCK, "translation_key": "child_lock", "name": "Child Lock", }, X34Attributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, X34Attributes.storage: { "type": Platform.SWITCH, "translation_key": "storage", "name": "Storage", "icon": "mdi:repeat-variant", }, X34Attributes.mode: { "type": Platform.SENSOR, "translation_key": "mode", "name": "Working Mode", "icon": "mdi:dishwasher", }, X34Attributes.error_code: { "type": Platform.SENSOR, "translation_key": "error_code", "name": "Error Code", "icon": "mdi:alert-box", }, X34Attributes.softwater: { "type": Platform.SENSOR, "translation_key": "softwater", "name": "Softwater Level", "icon": "mdi:shaker-outline", }, X34Attributes.bright: { "type": Platform.SENSOR, "translation_key": "bright", "name": "Bright Level", "icon": "mdi:star-four-points", }, }, }, 0x40: { "name": "Integrated Ceiling Fan", "entities": { "fan": { "type": Platform.FAN, "icon": "mdi:fan", "default": True, }, X40Attributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, X40Attributes.light: { "type": Platform.SWITCH, "translation_key": "light", "name": "Light", "icon": "mdi:lightbulb", }, X40Attributes.ventilation: { "type": Platform.SWITCH, "translation_key": "ventilation", "name": "Ventilation", "icon": "mdi:air-filter", }, X40Attributes.smelly_sensor: { "type": Platform.SWITCH, "translation_key": "smelly_sensor", "name": "Smelly Sensor", "icon": "mdi:scent", }, X40Attributes.direction: { "type": Platform.SELECT, "translation_key": "direction", "name": "Direction", "options": "directions", "icon": "mdi:arrow-split-vertical", }, }, }, 0xA1: { "name": "Dehumidifier", "entities": { "humidifier": { "type": Platform.HUMIDIFIER, "icon": "mdi:air-humidifier", "default": True, }, A1Attributes.child_lock: { "type": Platform.LOCK, "translation_key": "child_lock", "name": "Child Lock", }, A1Attributes.anion: { "type": Platform.SWITCH, "translation_key": "anion", "name": "Anion", "icon": "mdi:vanish", }, A1Attributes.prompt_tone: { "type": Platform.SWITCH, "translation_key": "prompt_tone", "name": "Prompt Tone", "icon": "mdi:bell", }, A1Attributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, A1Attributes.swing: { "type": Platform.SWITCH, "translation_key": "swing", "name": "Swing", "icon": "mdi:pan-horizontal", }, A1Attributes.fan_speed: { "type": Platform.SELECT, "translation_key": "fan_speed", "name": "Fan Speed", "options": "fan_speeds", "icon": "mdi:fan", }, A1Attributes.water_level_set: { "type": Platform.SELECT, "translation_key": "water_level_set", "name": "Water Level Setting", "options": "water_level_sets", "icon": "mdi:cup-water", }, A1Attributes.current_humidity: { "type": Platform.SENSOR, "name": "Current Humidity", "device_class": SensorDeviceClass.HUMIDITY, "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, A1Attributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, A1Attributes.tank: { "type": Platform.SENSOR, "translation_key": "tank", "name": "Tank", "icon": "mdi:cup-water", "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, A1Attributes.tank_full: { "type": Platform.BINARY_SENSOR, "translation_key": "tank_full", "name": "Tank status", "icon": "mdi:alert-circle", "device_class": BinarySensorDeviceClass.PROBLEM, }, }, }, 0xAC: { "name": "Air Conditioner", "entities": { "climate": { "type": Platform.CLIMATE, "translation_key": "climate_key", "icon": "mdi:air-conditioner", "default": True, }, "fresh_air": { "type": Platform.FAN, "translation_key": "fresh_air", "name": "Fresh Air", "icon": "mdi:fan", }, ACAttributes.aux_heating: { "type": Platform.SWITCH, "translation_key": "aux_heating", "name": "Aux Heating", "icon": "mdi:heat-wave", }, ACAttributes.boost_mode: { "type": Platform.SWITCH, "translation_key": "boost_mode", "name": "Boost Mode", "icon": "mdi:turbine", }, ACAttributes.breezeless: { "type": Platform.SWITCH, "translation_key": "breezeless", "name": "Breezeless", "icon": "mdi:tailwind", }, ACAttributes.comfort_mode: { "type": Platform.SWITCH, "translation_key": "comfort_mode", "name": "Comfort Mode", "icon": "mdi:alpha-c-circle", }, ACAttributes.dry: { "type": Platform.SWITCH, "translation_key": "dry", "name": "Dry", "icon": "mdi:air-filter", }, ACAttributes.eco_mode: { "type": Platform.SWITCH, "translation_key": "eco_mode", "name": "ECO Mode", "icon": "mdi:leaf-circle", }, ACAttributes.frost_protect: { "type": Platform.SWITCH, "translation_key": "frost_protect", "name": "Frost Protect", "icon": "mdi:snowflake-alert", }, ACAttributes.indirect_wind: { "type": Platform.SWITCH, "translation_key": "indirect_wind", "name": "Indirect Wind", "icon": "mdi:tailwind", }, ACAttributes.natural_wind: { "type": Platform.SWITCH, "translation_key": "natural_wind", "name": "Natural Wind", "icon": "mdi:tailwind", }, ACAttributes.prompt_tone: { "type": Platform.SWITCH, "translation_key": "prompt_tone", "name": "Prompt Tone", "icon": "mdi:bell", }, ACAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, ACAttributes.screen_display: { "type": Platform.SWITCH, "translation_key": "screen_display", "name": "Screen Display", "icon": "mdi:television-ambient-light", }, ACAttributes.screen_display_alternate: { "type": Platform.SWITCH, "translation_key": "screen_display_alternate", "name": "Screen Display Alternate", "icon": "mdi:television-ambient-light", }, ACAttributes.sleep_mode: { "type": Platform.SWITCH, "translation_key": "sleep_mode", "name": "Sleep Mode", "icon": "mdi:power-sleep", }, ACAttributes.smart_eye: { "type": Platform.SWITCH, "translation_key": "smart_eye", "name": "Smart Eye", "icon": "mdi:eye", }, ACAttributes.swing_horizontal: { "type": Platform.SWITCH, "translation_key": "swing_horizontal", "name": "Swing Horizontal", "icon": "mdi:arrow-split-vertical", }, ACAttributes.swing_vertical: { "type": Platform.SWITCH, "translation_key": "swing_vertical", "name": "Swing Vertical", "icon": "mdi:arrow-split-horizontal", }, ACAttributes.full_dust: { "type": Platform.BINARY_SENSOR, "translation_key": "full_dust", "name": "Full of Dust", "icon": "mdi:alert-circle", "device_class": BinarySensorDeviceClass.PROBLEM, }, ACAttributes.indoor_humidity: { "type": Platform.SENSOR, "translation_key": "indoor_humidity", "name": "Indoor Humidity", "device_class": SensorDeviceClass.HUMIDITY, "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, ACAttributes.indoor_temperature: { "type": Platform.SENSOR, "translation_key": "indoor_temperature", "name": "Indoor Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, ACAttributes.outdoor_temperature: { "type": Platform.SENSOR, "translation_key": "outdoor_temperature", "name": "Outdoor Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, ACAttributes.total_energy_consumption: { "type": Platform.SENSOR, "translation_key": "total_energy_consumption", "name": "Total Energy Consumption", "device_class": SensorDeviceClass.ENERGY, "unit": UnitOfEnergy.KILO_WATT_HOUR, "state_class": SensorStateClass.TOTAL_INCREASING, }, ACAttributes.current_energy_consumption: { "type": Platform.SENSOR, "translation_key": "current_energy_consumption", "name": "Current Energy Consumption", "device_class": SensorDeviceClass.ENERGY, "unit": UnitOfEnergy.KILO_WATT_HOUR, "state_class": SensorStateClass.TOTAL_INCREASING, }, ACAttributes.realtime_power: { "type": Platform.SENSOR, "translation_key": "realtime_power", "name": "Realtime Power", "device_class": SensorDeviceClass.POWER, "unit": UnitOfPower.WATT, "state_class": SensorStateClass.MEASUREMENT, }, ACAttributes.wind_lr_angle: { "type": Platform.SELECT, "translation_key": "wind_lr_angle", "name": "Airflow Horizontal", "options": "wind_lr_angles", "icon": "mdi:pan-horizontal", }, ACAttributes.wind_ud_angle: { "type": Platform.SELECT, "translation_key": "wind_ud_angle", "name": "Airflow Vertical", "options": "wind_ud_angles", "icon": "mdi:pan-vertical", }, ACAttributes.fan_speed: { "type": Platform.NUMBER, "translation_key": "fan_speed_percent", "name": "Fan Speed Percent", "icon": "mdi:fan", "max": 100, "min": 1, "step": 1, }, }, }, 0xAD: { "name": "Air Detector", "entities": { ADAttributes.temperature: { "type": Platform.SENSOR, "name": "Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, ADAttributes.humidity: { "type": Platform.SENSOR, "name": "Humidity", "device_class": SensorDeviceClass.HUMIDITY, "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, ADAttributes.temperature_raw: { "type": Platform.SENSOR, "name": "Temperature Raw", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, ADAttributes.humidity_raw: { "type": Platform.SENSOR, "name": "Humidity Raw", "device_class": SensorDeviceClass.HUMIDITY, "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, ADAttributes.temperature_compensate: { "type": Platform.SENSOR, "name": "Temperature Compensate", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, ADAttributes.humidity_compensate: { "type": Platform.SENSOR, "name": "Humidity Compensate", "device_class": SensorDeviceClass.HUMIDITY, "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, ADAttributes.tvoc: { "type": Platform.SENSOR, "name": "Tvoc", "icon": "mdi:heat-wave", "device_class": SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS, "unit": CONCENTRATION_PARTS_PER_MILLION, "state_class": SensorStateClass.MEASUREMENT, }, ADAttributes.co2: { "type": Platform.SENSOR, "name": "Carbon Dioxide", "device_class": SensorDeviceClass.CO2, "unit": CONCENTRATION_PARTS_PER_MILLION, "state_class": SensorStateClass.MEASUREMENT, }, ADAttributes.pm25: { "type": Platform.SENSOR, "name": "PM 2.5", "device_class": SensorDeviceClass.PM25, "unit": CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, "state_class": SensorStateClass.MEASUREMENT, }, ADAttributes.hcho: { "type": Platform.SENSOR, "name": "Methanal", "icon": "mdi:molecule", "device_class": SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS, "unit": CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, "state_class": SensorStateClass.MEASUREMENT, }, ADAttributes.presets_function: { "type": Platform.BINARY_SENSOR, "name": "Presets Function", "device_class": BinarySensorDeviceClass.RUNNING, }, ADAttributes.fall_asleep_status: { "type": Platform.BINARY_SENSOR, "name": "Asleep Status", "icon": "mdi:sleep", "device_class": BinarySensorDeviceClass.RUNNING, }, ADAttributes.screen_extinction_timeout: { "type": Platform.SENSOR, "name": "Screen Extinction Timeout", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, ADAttributes.portable_sense: { "type": Platform.BINARY_SENSOR, "name": "Portable Sense", "device_class": BinarySensorDeviceClass.RUNNING, }, ADAttributes.night_mode: { "type": Platform.BINARY_SENSOR, "name": "Night Mode", "device_class": BinarySensorDeviceClass.RUNNING, }, ADAttributes.screen_status: { "type": Platform.BINARY_SENSOR, "name": "Screen Status", "device_class": BinarySensorDeviceClass.RUNNING, }, ADAttributes.led_status: { "type": Platform.BINARY_SENSOR, "name": "Ambient Lighting Status", "device_class": BinarySensorDeviceClass.RUNNING, }, ADAttributes.arofene_link: { "type": Platform.BINARY_SENSOR, "name": "Methanal Status", "device_class": BinarySensorDeviceClass.PLUG, }, ADAttributes.header_exist: { "type": Platform.BINARY_SENSOR, "name": "Header Status", "device_class": BinarySensorDeviceClass.PLUG, }, ADAttributes.radar_exist: { "type": Platform.BINARY_SENSOR, "name": "Radar Status", "device_class": BinarySensorDeviceClass.RUNNING, }, ADAttributes.header_led_status: { "type": Platform.BINARY_SENSOR, "name": "Breathing Light", "device_class": BinarySensorDeviceClass.RUNNING, }, }, }, 0xB0: { "name": "Microwave Oven", "entities": { B0Attributes.door: { "type": Platform.BINARY_SENSOR, "name": "Door", "icon": "mdi:box-shadow", "device_class": BinarySensorDeviceClass.DOOR, }, B0Attributes.tank_ejected: { "type": Platform.BINARY_SENSOR, "translation_key": "tank_ejected", "name": "Tank Ejected", "icon": "mdi:cup-water", "device_class": BinarySensorDeviceClass.PROBLEM, }, B0Attributes.water_change_reminder: { "type": Platform.BINARY_SENSOR, "translation_key": "water_change_reminder", "name": "Water Change Reminder", "icon": "mdi:cup-water", "device_class": BinarySensorDeviceClass.PROBLEM, }, B0Attributes.water_shortage: { "type": Platform.BINARY_SENSOR, "translation_key": "water_shortage", "name": "Water Shortage", "icon": "mdi:cup-water", "device_class": BinarySensorDeviceClass.PROBLEM, }, B0Attributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, B0Attributes.status: { "type": Platform.SENSOR, "translation_key": "status", "name": "Status", "icon": "mdi:information", }, B0Attributes.time_remaining: { "type": Platform.SENSOR, "translation_key": "time_remaining", "name": "Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.SECONDS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xB1: { "name": "Electric Oven", "entities": { B1Attributes.door: { "type": Platform.BINARY_SENSOR, "name": "Door", "icon": "mdi:box-shadow", "device_class": BinarySensorDeviceClass.DOOR, }, B1Attributes.tank_ejected: { "type": Platform.BINARY_SENSOR, "translation_key": "tank_ejected", "name": "Tank ejected", "icon": "mdi:cup-water", "device_class": BinarySensorDeviceClass.PROBLEM, }, B1Attributes.water_change_reminder: { "type": Platform.BINARY_SENSOR, "translation_key": "water_change_reminder", "name": "Water Change Reminder", "icon": "mdi:cup-water", "device_class": BinarySensorDeviceClass.PROBLEM, }, B1Attributes.water_shortage: { "type": Platform.BINARY_SENSOR, "translation_key": "water_shortage", "name": "Water Shortage", "icon": "mdi:cup-water", "device_class": BinarySensorDeviceClass.PROBLEM, }, B1Attributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, B1Attributes.status: { "type": Platform.SENSOR, "translation_key": "status", "name": "Status", "icon": "mdi:information", }, B1Attributes.time_remaining: { "type": Platform.SENSOR, "translation_key": "time_remaining", "name": "Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.SECONDS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xB3: { "name": "Dish Sterilizer", "entities": { B3Attributes.top_compartment_door: { "type": Platform.BINARY_SENSOR, "translation_key": "top_compartment_door", "name": "Top Compartment Door", "icon": "mdi:box-shadow", "device_class": BinarySensorDeviceClass.DOOR, }, B3Attributes.top_compartment_preheating: { "type": Platform.BINARY_SENSOR, "translation_key": "top_compartment_preheating", "name": "Top Compartment Preheating", "icon": "mdi:heat-wave", "device_class": BinarySensorDeviceClass.RUNNING, }, B3Attributes.top_compartment_cooling: { "type": Platform.BINARY_SENSOR, "translation_key": "top_compartment_cooling", "name": "Top Compartment Cooling", "icon": "snowflake-variant", "device_class": BinarySensorDeviceClass.RUNNING, }, B3Attributes.middle_compartment_door: { "type": Platform.BINARY_SENSOR, "translation_key": "middle_compartment_door", "name": "Middle Compartment Door", "icon": "mdi:box-shadow", "device_class": BinarySensorDeviceClass.DOOR, }, B3Attributes.middle_compartment_preheating: { "type": Platform.BINARY_SENSOR, "translation_key": "middle_compartment_preheating", "name": "Middle Compartment Preheating", "icon": "mdi:heat-wave", "device_class": BinarySensorDeviceClass.RUNNING, }, B3Attributes.middle_compartment_cooling: { "type": Platform.BINARY_SENSOR, "translation_key": "middle_compartment_cooling", "name": "Middle Compartment Cooling", "icon": "snowflake-variant", "device_class": BinarySensorDeviceClass.RUNNING, }, B3Attributes.bottom_compartment_door: { "type": Platform.BINARY_SENSOR, "translation_key": "bottom_compartment_door", "name": "Bottom Compartment Door", "icon": "mdi:box-shadow", "device_class": BinarySensorDeviceClass.DOOR, }, B3Attributes.bottom_compartment_preheating: { "type": Platform.BINARY_SENSOR, "translation_key": "bottom_compartment_preheating", "name": "Bottom Compartment Preheating", "icon": "mdi:heat-wave", "device_class": BinarySensorDeviceClass.RUNNING, }, B3Attributes.bottom_compartment_cooling: { "type": Platform.BINARY_SENSOR, "translation_key": "bottom_compartment_cooling", "name": "Bottom Compartment Cooling", "icon": "snowflake-variant", "device_class": BinarySensorDeviceClass.RUNNING, }, B3Attributes.top_compartment_status: { "type": Platform.SENSOR, "translation_key": "top_compartment_status", "name": "Top Compartment Status", "icon": "mdi:information", }, B3Attributes.top_compartment_temperature: { "type": Platform.SENSOR, "translation_key": "top_compartment_temperature", "name": "Top Compartment Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, B3Attributes.top_compartment_remaining: { "type": Platform.SENSOR, "translation_key": "top_compartment_remaining", "name": "Top Compartment Remaining", "unit": UnitOfTime.SECONDS, "state_class": SensorStateClass.MEASUREMENT, }, B3Attributes.middle_compartment_status: { "type": Platform.SENSOR, "translation_key": "middle_compartment_status", "name": "Middle Compartment Status", "icon": "mdi:information", }, B3Attributes.middle_compartment_temperature: { "type": Platform.SENSOR, "translation_key": "middle_compartment_temperature", "name": "Middle Compartment Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, B3Attributes.middle_compartment_remaining: { "type": Platform.SENSOR, "translation_key": "middle_compartment_remaining", "name": "Middle Compartment Remaining", "unit": UnitOfTime.SECONDS, "state_class": SensorStateClass.MEASUREMENT, }, B3Attributes.bottom_compartment_status: { "type": Platform.SENSOR, "translation_key": "bottom_compartment_status", "name": "Bottom Compartment Status", "icon": "mdi:information", }, B3Attributes.bottom_compartment_temperature: { "type": Platform.SENSOR, "translation_key": "bottom_compartment_temperature", "name": "Bottom Compartment Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, B3Attributes.bottom_compartment_remaining: { "type": Platform.SENSOR, "translation_key": "bottom_compartment_remaining", "name": "Bottom Compartment Remaining", "unit": UnitOfTime.SECONDS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xB4: { "name": "Toaster", "entities": { B4Attributes.door: { "type": Platform.BINARY_SENSOR, "name": "Door", "icon": "mdi:box-shadow", "device_class": BinarySensorDeviceClass.DOOR, }, B4Attributes.tank_ejected: { "type": Platform.BINARY_SENSOR, "translation_key": "tank_ejected", "name": "Tank ejected", "icon": "mdi:cup-water", "device_class": BinarySensorDeviceClass.PROBLEM, }, B4Attributes.water_change_reminder: { "type": Platform.BINARY_SENSOR, "translation_key": "water_change_reminder", "name": "Water Change Reminder", "icon": "mdi:cup-water", "device_class": BinarySensorDeviceClass.PROBLEM, }, B4Attributes.water_shortage: { "type": Platform.BINARY_SENSOR, "translation_key": "water_shortage", "name": "Water Shortage", "icon": "mdi:cup-water", "device_class": BinarySensorDeviceClass.PROBLEM, }, B4Attributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, B4Attributes.status: { "type": Platform.SENSOR, "translation_key": "status", "name": "Status", "icon": "mdi:information", }, B4Attributes.time_remaining: { "type": Platform.SENSOR, "translation_key": "time_remaining", "name": "Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.SECONDS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xB6: { "name": "Range Hood", "entities": { "fan": { "type": Platform.FAN, "icon": "mdi:fan", "default": True, }, B6Attributes.light: { "type": Platform.SWITCH, "translation_key": "light", "name": "Light", "icon": "mdi:lightbulb", }, B6Attributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, B6Attributes.cleaning_reminder: { "type": Platform.BINARY_SENSOR, "translation_key": "cleaning_reminder", "name": "Cleaning Reminder", "icon": "mdi:alert-circle", "device_class": BinarySensorDeviceClass.PROBLEM, }, B6Attributes.oilcup_full: { "type": Platform.BINARY_SENSOR, "translation_key": "oilcup_full", "name": "Oil-cup Full", "icon": "mdi:cup", "device_class": BinarySensorDeviceClass.PROBLEM, }, B6Attributes.fan_level: { "type": Platform.SENSOR, "translation_key": "fan_level", "name": "Fan level", "icon": "mdi:fan", "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xBF: { "name": "Microwave Steam Oven", "entities": { BFAttributes.tank_ejected: { "type": Platform.BINARY_SENSOR, "translation_key": "tank_ejected", "name": "Tank ejected", "icon": "mdi:cup-water", "device_class": BinarySensorDeviceClass.PROBLEM, }, BFAttributes.water_change_reminder: { "type": Platform.BINARY_SENSOR, "translation_key": "water_change_reminder", "name": "Water Change Reminder", "icon": "mdi:cup-water", "device_class": BinarySensorDeviceClass.PROBLEM, }, BFAttributes.door: { "type": Platform.BINARY_SENSOR, "name": "Door", "icon": "mdi:box-shadow", "device_class": BinarySensorDeviceClass.DOOR, }, BFAttributes.water_shortage: { "type": Platform.BINARY_SENSOR, "translation_key": "water_shortage", "name": "Water Shortage", "icon": "mdi:cup-water", "device_class": BinarySensorDeviceClass.PROBLEM, }, BFAttributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, BFAttributes.status: { "type": Platform.SENSOR, "translation_key": "status", "name": "Status", "icon": "mdi:information", }, BFAttributes.time_remaining: { "type": Platform.SENSOR, "translation_key": "time_remaining", "name": "Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.SECONDS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xC2: { "name": "Toilet", "entities": { C2Attributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, C2Attributes.sensor_light: { "type": Platform.SWITCH, "translation_key": "sensor_light", "name": "Sensor Light", "icon": "mdi:lightbulb", }, C2Attributes.foam_shield: { "type": Platform.SWITCH, "translation_key": "foam_shield", "name": "Foam Shield", "icon": "mdi:chart-bubble", }, C2Attributes.child_lock: { "type": Platform.LOCK, "translation_key": "child_lock", "name": "Child Lock", }, C2Attributes.seat_status: { "type": Platform.BINARY_SENSOR, "translation_key": "seat_status", "name": "Seat Status", "icon": "mdi:seat-legroom-normal", }, C2Attributes.lid_status: { "type": Platform.BINARY_SENSOR, "translation_key": "lid_status", "name": "Lid Status", "icon": "mdi:toilet", }, C2Attributes.light_status: { "type": Platform.BINARY_SENSOR, "name": "Light Status", "icon": "mdi:lightbulb", "device_class": BinarySensorDeviceClass.LIGHT, }, C2Attributes.water_temperature: { "type": Platform.SENSOR, "translation_key": "water_temperature", "name": "Water Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, C2Attributes.seat_temperature: { "type": Platform.SENSOR, "translation_key": "seat_temperature", "name": "Seat Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, C2Attributes.filter_life: { "type": Platform.SENSOR, "translation_key": "filter_life", "name": "Filter Life", "icon": "mdi:toilet", "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, C2Attributes.dry_level: { "type": Platform.NUMBER, "translation_key": "dry_level", "name": "Dry Level", "icon": "mdi:fire", "max": "max_dry_level", "min": 0, "step": 1, }, C2Attributes.water_temp_level: { "type": Platform.NUMBER, "translation_key": "water_temp_level", "name": "Water Temperature Level", "icon": "mdi:fire", "max": "max_water_temp_level", "min": 0, "step": 1, }, C2Attributes.seat_temp_level: { "type": Platform.NUMBER, "translation_key": "seat_temp_level", "name": "Seat Temperature Level", "icon": "mdi:fire", "max": "max_seat_temp_level", "min": 0, "step": 1, }, }, }, 0xC3: { "name": "Heat Pump Wi-Fi Controller", "entities": { "climate_zone1": { "type": Platform.CLIMATE, "translation_key": "climate_zone1", "name": "Zone1 Thermostat", "icon": "mdi:air-conditioner", "zone": 0, "default": True, }, "climate_zone2": { "type": Platform.CLIMATE, "translation_key": "climate_zone2", "name": "Zone2 Thermostat", "icon": "mdi:air-conditioner", "zone": 1, "default": False, }, "water_heater": { "type": Platform.WATER_HEATER, "translation_key": "domestic_hot_water", "name": "Domestic hot water", "icon": "mdi:heat-pump", "default": True, }, C3Attributes.disinfect: { "type": Platform.SWITCH, "translation_key": "disinfect", "name": "Disinfect", "icon": "mdi:water-plus-outline", }, C3Attributes.dhw_power: { "type": Platform.SWITCH, "translation_key": "dhw_power", "name": "DHW Power", "icon": "mdi:power", }, C3Attributes.eco_mode: { "type": Platform.SWITCH, "translation_key": "eco_mode", "name": "ECO Mode", "icon": "mdi:leaf-circle", }, C3Attributes.fast_dhw: { "type": Platform.SWITCH, "translation_key": "fast_dhw", "name": "Fast DHW", "icon": "mdi:rotate-orbit", }, C3Attributes.silent_mode: { "type": Platform.SWITCH, "translation_key": "silent_mode", "name": "Silent Mode", "icon": "mdi:fan-remove", }, C3Attributes.SILENT_LEVEL: { "type": Platform.SELECT, "translation_key": "silent_level", "name": "Silent Level", "icon": "mdi:fan-remove", "options": "silent_modes", }, C3Attributes.tbh: { "type": Platform.SWITCH, "translation_key": "tbh", "name": "TBH", "icon": "mdi:water-boiler", }, C3Attributes.zone1_curve: { "type": Platform.SWITCH, "translation_key": "zone1_curve", "name": "Zone1 Curve", "icon": "mdi:chart-bell-curve-cumulative", }, C3Attributes.zone2_curve: { "type": Platform.SWITCH, "translation_key": "zone2_curve", "name": "Zone2 Curve", "icon": "mdi:chart-bell-curve-cumulative", }, C3Attributes.zone1_power: { "type": Platform.SWITCH, "translation_key": "zone1_power", "name": "Zone1 Power", "icon": "mdi:power", }, C3Attributes.zone2_power: { "type": Platform.SWITCH, "translation_key": "zone2_power", "name": "Zone2 Power", "icon": "mdi:power", }, C3Attributes.zone1_water_temp_mode: { "type": Platform.BINARY_SENSOR, "translation_key": "zone1_water_temp_mode", "name": "Zone1 Water-temperature Mode", "icon": "mdi:coolant-temperature", "device_class": BinarySensorDeviceClass.RUNNING, }, C3Attributes.zone2_water_temp_mode: { "type": Platform.BINARY_SENSOR, "translation_key": "zone2_water_temp_mode", "name": "Zone2 Water-temperature Mode", "icon": "mdi:coolant-temperature", "device_class": BinarySensorDeviceClass.RUNNING, }, C3Attributes.zone1_room_temp_mode: { "type": Platform.BINARY_SENSOR, "translation_key": "zone1_room_temp_mode", "name": "Zone1 Room-temperature Mode", "icon": "mdi:home-thermometer-outline", "device_class": BinarySensorDeviceClass.RUNNING, }, C3Attributes.zone2_room_temp_mode: { "type": Platform.BINARY_SENSOR, "translation_key": "zone2_room_temp_mode", "name": "Zone2 Room-temperature Mode", "icon": "mdi:home-thermometer-outline", "device_class": BinarySensorDeviceClass.RUNNING, }, C3Attributes.error_code: { "type": Platform.SENSOR, "translation_key": "error_code", "name": "Error Code", "icon": "mdi:alpha-e-circle", }, C3Attributes.tank_actual_temperature: { "type": Platform.SENSOR, "translation_key": "tank_actual_temperature", "name": "Tank Actual Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, C3Attributes.status_dhw: { "type": Platform.BINARY_SENSOR, "translation_key": "status_dhw", "name": "DHW status", "icon": "mdi:heat-pump", "device_class": BinarySensorDeviceClass.RUNNING, }, C3Attributes.status_tbh: { "type": Platform.BINARY_SENSOR, "translation_key": "status_tbh", "name": "TBH status", "icon": "mdi:water-boiler", "device_class": BinarySensorDeviceClass.RUNNING, }, C3Attributes.status_ibh: { "type": Platform.BINARY_SENSOR, "translation_key": "status_ibh", "name": "IBH status", "icon": "mdi:coolant-temperature", "device_class": BinarySensorDeviceClass.RUNNING, }, C3Attributes.status_heating: { "type": Platform.BINARY_SENSOR, "translation_key": "status_heating", "name": "Heating status", "icon": "mdi:heat-pump", "device_class": BinarySensorDeviceClass.RUNNING, }, C3Attributes.total_energy_consumption: { "type": Platform.SENSOR, "translation_key": "total_energy_consumption", "name": "Total energy consumption", "device_class": SensorDeviceClass.ENERGY, "unit": UnitOfEnergy.KILO_WATT_HOUR, "state_class": SensorStateClass.TOTAL_INCREASING, }, C3Attributes.total_produced_energy: { "type": Platform.SENSOR, "translation_key": "total_produced_energy", "name": "Total produced energy", "device_class": SensorDeviceClass.ENERGY, "unit": UnitOfEnergy.KILO_WATT_HOUR, "state_class": SensorStateClass.TOTAL_INCREASING, }, C3Attributes.outdoor_temperature: { "type": Platform.SENSOR, "translation_key": "outdoor_temperature", "name": "Outdoor Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xCA: { "name": "Refrigerator", "entities": { CAAttributes.bar_door: { "type": Platform.BINARY_SENSOR, "translation_key": "bar_door", "name": "Bar Door", "icon": "mdi:door", "device_class": BinarySensorDeviceClass.DOOR, }, CAAttributes.bar_door_overtime: { "type": Platform.BINARY_SENSOR, "translation_key": "bar_door_overtime", "name": "Bar Door Overtime", "icon": "mdi:alert-circle", "device_class": BinarySensorDeviceClass.PROBLEM, }, CAAttributes.flex_zone_door: { "type": Platform.BINARY_SENSOR, "translation_key": "flex_zone_door", "name": "Flex Door", "icon": "mdi:door", "device_class": BinarySensorDeviceClass.DOOR, }, CAAttributes.flex_zone_door_overtime: { "type": Platform.BINARY_SENSOR, "translation_key": "flex_zone_door_overtime", "name": "Flex Zone Door", "icon": "mdi:alert-circle", "device_class": BinarySensorDeviceClass.PROBLEM, }, CAAttributes.freezer_door: { "type": Platform.BINARY_SENSOR, "translation_key": "freezer_door", "name": "Freezer Door", "icon": "mdi:door", "device_class": BinarySensorDeviceClass.DOOR, }, CAAttributes.freezer_door_overtime: { "type": Platform.BINARY_SENSOR, "translation_key": "freezer_door_overtime", "name": "Freezer Door Overtime", "icon": "mdi:alert-circle", "device_class": BinarySensorDeviceClass.PROBLEM, }, CAAttributes.refrigerator_door: { "type": Platform.BINARY_SENSOR, "translation_key": "refrigerator_door", "name": "Refrigerator Door", "icon": "mdi:door", "device_class": BinarySensorDeviceClass.DOOR, }, CAAttributes.refrigerator_door_overtime: { "type": Platform.BINARY_SENSOR, "translation_key": "refrigerator_door_overtime", "name": "Refrigerator Door Overtime", "icon": "mdi:alert-circle", "device_class": BinarySensorDeviceClass.PROBLEM, }, CAAttributes.flex_zone_actual_temp: { "type": Platform.SENSOR, "translation_key": "flex_zone_actual_temp", "name": "Flex Zone Actual Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, CAAttributes.flex_zone_setting_temp: { "type": Platform.SENSOR, "translation_key": "flex_zone_setting_temp", "name": "Flex Zone Setting Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, CAAttributes.freezer_actual_temp: { "type": Platform.SENSOR, "translation_key": "freezer_actual_temp", "name": "Freezer Actual Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, CAAttributes.freezer_setting_temp: { "type": Platform.SENSOR, "translation_key": "freezer_setting_temp", "name": "Freezer Setting Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, CAAttributes.energy_consumption: { "type": Platform.SENSOR, "translation_key": "energy_consumption", "name": "Energy Consumption", "device_class": SensorDeviceClass.ENERGY, "unit": UnitOfEnergy.KILO_WATT_HOUR, "state_class": SensorStateClass.TOTAL_INCREASING, }, CAAttributes.refrigerator_actual_temp: { "type": Platform.SENSOR, "translation_key": "refrigerator_actual_temp", "name": "Refrigerator Actual Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, CAAttributes.refrigerator_setting_temp: { "type": Platform.SENSOR, "translation_key": "refrigerator_setting_temp", "name": "Refrigerator Setting Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, CAAttributes.right_flex_zone_actual_temp: { "type": Platform.SENSOR, "translation_key": "right_flex_zone_actual_temp", "name": "Right Flex Zone Actual Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, CAAttributes.right_flex_zone_setting_temp: { "type": Platform.SENSOR, "translation_key": "right_flex_zone_setting_temp", "name": "Right Flex Zone Setting Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, CAAttributes.microcrystal_fresh: { "type": Platform.BINARY_SENSOR, "translation_key": "microcrystal_fresh", "name": "Microcrystal Fresh", "icon": "mdi:origin", }, CAAttributes.electronic_smell: { "type": Platform.BINARY_SENSOR, "translation_key": "electronic_smell", "name": "Deodorizing sterilizing", "icon": "mdi:air-filter", }, CAAttributes.humidity: { "type": Platform.SENSOR, "translation_key": "humidity", "name": "Humidity", "icon": "mdi:water-opacity", }, CAAttributes.variable_mode: { "type": Platform.SENSOR, "translation_key": "variable_mode", "name": "Variable Mode", "icon": "mdi:nut", }, }, }, 0xCC: { "name": "MDV Wi-Fi Controller", "entities": { "climate": { "type": Platform.CLIMATE, "icon": "hass:air-conditioner", "default": True, }, CCAttributes.aux_heating: { "type": Platform.SWITCH, "translation_key": "aux_heating", "name": "Aux Heating", "icon": "mdi:heat-wave", }, CCAttributes.eco_mode: { "type": Platform.SWITCH, "translation_key": "eco_mode", "name": "ECO Mode", "icon": "mdi:leaf-circle", }, CCAttributes.night_light: { "type": Platform.SWITCH, "translation_key": "night_light", "name": "Night Light", "icon": "mdi:lightbulb", }, CCAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, CCAttributes.sleep_mode: { "type": Platform.SWITCH, "translation_key": "sleep_mode", "name": "Sleep Mode", "icon": "mdi:power-sleep", }, CCAttributes.swing: { "type": Platform.SWITCH, "translation_key": "swing", "name": "Swing", "icon": "mdi:arrow-split-horizontal", }, CCAttributes.indoor_temperature: { "type": Platform.SENSOR, "translation_key": "indoor_temperature", "name": "Indoor Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xCD: { "name": "Heat Pump Water Heater", "entities": { "water_heater": { "type": Platform.WATER_HEATER, "icon": "mdi:heat-pump", "default": True, }, CDAttributes.compressor_status: { "type": Platform.BINARY_SENSOR, "translation_key": "compressor_status", "name": "Compressor Status", "icon": "mdi:drag", "device_class": BinarySensorDeviceClass.RUNNING, }, CDAttributes.compressor_temperature: { "type": Platform.SENSOR, "translation_key": "compressor_temperature", "name": "Compressor Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, CDAttributes.condenser_temperature: { "type": Platform.SENSOR, "translation_key": "condenser_temperature", "name": "Condenser Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, CDAttributes.outdoor_temperature: { "type": Platform.SENSOR, "translation_key": "outdoor_temperature", "name": "Outdoor Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, CDAttributes.water_level: { "type": Platform.SENSOR, "translation_key": "water_level", "name": "Water Level", "icon": "mdi:cup-water", }, CDAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, }, }, 0xCE: { "name": "Fresh Air Appliance", "entities": { "fan": { "type": Platform.FAN, "icon": "mdi:fan", "default": True, }, CEAttributes.filter_cleaning_reminder: { "type": Platform.BINARY_SENSOR, "translation_key": "filter_cleaning_reminder", "name": "Filter Cleaning Reminder", "icon": "mdi:alert-circle", "device_class": BinarySensorDeviceClass.PROBLEM, }, CEAttributes.filter_change_reminder: { "type": Platform.BINARY_SENSOR, "translation_key": "filter_change_reminder", "name": "Filter Change Reminder", "icon": "mdi:alert-circle", "device_class": BinarySensorDeviceClass.PROBLEM, }, CEAttributes.current_humidity: { "type": Platform.SENSOR, "name": "Current Humidity", "device_class": SensorDeviceClass.HUMIDITY, "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, CEAttributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, CEAttributes.co2: { "type": Platform.SENSOR, "name": "Carbon Dioxide", "device_class": SensorDeviceClass.CO2, "unit": CONCENTRATION_PARTS_PER_MILLION, "state_class": SensorStateClass.MEASUREMENT, }, CEAttributes.hcho: { "type": Platform.SENSOR, "translation_key": "hcho", "name": "Methanal", "icon": "mdi:molecule", "unit": CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, "state_class": SensorStateClass.MEASUREMENT, }, CEAttributes.pm25: { "type": Platform.SENSOR, "name": "PM 2.5", "device_class": SensorDeviceClass.PM25, "unit": CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, "state_class": SensorStateClass.MEASUREMENT, }, CEAttributes.child_lock: { "type": Platform.LOCK, "translation_key": "child_lock", "name": "Child Lock", }, CEAttributes.aux_heating: { "type": Platform.SWITCH, "translation_key": "aux_heating", "name": "Aux Heating", "icon": "mdi:heat-wave", }, CEAttributes.eco_mode: { "type": Platform.SWITCH, "translation_key": "eco_mode", "name": "ECO Mode", "icon": "mdi:leaf-circle", }, CEAttributes.link_to_ac: { "type": Platform.SWITCH, "translation_key": "link_to_ac", "name": "Link to AC", "icon": "mdi:link", }, CEAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, CEAttributes.powerful_purify: { "type": Platform.SWITCH, "translation_key": "powerful_purify", "name": "Powerful Purification", "icon": "mdi:turbine", }, CEAttributes.sleep_mode: { "type": Platform.SWITCH, "translation_key": "sleep_mode", "name": "Sleep Mode", "icon": "mdi:power-sleep", }, }, }, 0xCF: { "name": "Heat Pump", "entities": { "climate": { "type": Platform.CLIMATE, "icon": "hass:air-conditioner", "default": True, }, CFAttributes.aux_heating: { "type": Platform.SWITCH, "translation_key": "aux_heating", "name": "Aux Heating", "icon": "mdi:heat-wave", }, CFAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, CFAttributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xDA: { "name": "Top Load Washer", "entities": { DAAttributes.time_remaining: { "type": Platform.SENSOR, "translation_key": "time_remaining", "name": "Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, DAAttributes.wash_time: { "type": Platform.SENSOR, "translation_key": "wash_time", "name": "Wash time", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, DAAttributes.soak_time: { "type": Platform.SENSOR, "translation_key": "soak_time", "name": "Soak time", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, DAAttributes.dehydration_time: { "type": Platform.SENSOR, "translation_key": "dehydration_time", "name": "Dehydration time", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, DAAttributes.dehydration_speed: { "type": Platform.SENSOR, "translation_key": "dehydration_speed", "name": "Dehydration speed", "icon": "mdi:speedometer", }, DAAttributes.error_code: { "type": Platform.SENSOR, "translation_key": "error_code", "name": "Error code", "icon": "mdi:washing-machine-alert", }, DAAttributes.rinse_count: { "type": Platform.SENSOR, "translation_key": "rinse_count", "name": "Rinse count", "icon": "mdi:water-sync", }, DAAttributes.rinse_level: { "type": Platform.SENSOR, "translation_key": "rinse_level", "name": "Rinse level", "icon": "mdi:hydraulic-oil-level", }, DAAttributes.wash_level: { "type": Platform.SENSOR, "translation_key": "wash_level", "name": "Rinse count", "icon": "mdi:hydraulic-oil-level", }, DAAttributes.wash_strength: { "type": Platform.SENSOR, "translation_key": "wash_strength", "name": "Wash strength", "icon": "mdi:network-strength-4-cog", }, DAAttributes.softener: { "type": Platform.SENSOR, "translation_key": "softener", "name": "Softener", "icon": "mdi:tshirt-crew", }, DAAttributes.detergent: { "type": Platform.SENSOR, "translation_key": "detergent", "name": "Detergent", "icon": "mdi:spray-bottle", }, DAAttributes.program: { "type": Platform.SENSOR, "translation_key": "program", "name": "Program", "icon": "mdi:progress-wrench", }, DAAttributes.progress: { "type": Platform.SENSOR, "translation_key": "progress", "name": "Progress", "icon": "mdi:rotate-360", }, DAAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, DAAttributes.start: { "type": Platform.SWITCH, "translation_key": "start", "name": "Start", "icon": "mdi:motion-play-outline", }, }, }, 0xDB: { "name": "Front Load Washer", "entities": { DBAttributes.time_remaining: { "type": Platform.SENSOR, "translation_key": "time_remaining", "name": "Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, DBAttributes.progress: { "type": Platform.SENSOR, "translation_key": "progress", "name": "Progress", "icon": "mdi:rotate-360", }, DBAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, DBAttributes.start: { "type": Platform.SWITCH, "translation_key": "start", "name": "Start", "icon": "mdi:motion-play-outline", }, DBAttributes.status: { "type": Platform.SENSOR, "translation_key": "status", "name": "Status", "icon": "mdi:auto-mode", }, DBAttributes.mode: { "type": Platform.SENSOR, "translation_key": "mode", "name": "Mode", "icon": "mdi:auto-mode", }, DBAttributes.dehydration_speed: { "type": Platform.SENSOR, "translation_key": "dehydration_speed", "name": "Dehydration Speed", "icon": "mdi:speedometer", }, DBAttributes.water_level: { "type": Platform.SENSOR, "translation_key": "water_level", "name": "Water Level", "icon": "mdi:cup-water", }, DBAttributes.program: { "type": Platform.SENSOR, "translation_key": "program", "name": "Program", "icon": "mdi:washing-machine", }, DBAttributes.temperature: { "type": Platform.SENSOR, "translation_key": "temperature", "name": "Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, DBAttributes.detergent: { "type": Platform.SENSOR, "translation_key": "detergent", "name": "Detergent", "icon": "mdi:water", }, DBAttributes.softener: { "type": Platform.SENSOR, "translation_key": "softener", "name": "Softener", "icon": "mdi:water-outline", }, DBAttributes.wash_time: { "type": Platform.SENSOR, "translation_key": "wash_time", "name": "Wash Time", "icon": "mdi:dishwasher", }, DBAttributes.dehydration_time: { "type": Platform.SENSOR, "translation_key": "dehydration_time", "name": "Dehydration Time", "icon": "mdi:dishwasher", }, DBAttributes.wash_time_value: { "type": Platform.SENSOR, "translation_key": "wash_time_value", "name": "Wash Time Value", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, DBAttributes.dehydration_time_value: { "type": Platform.SENSOR, "translation_key": "dehydration_time_value", "name": "Dehydration Time Value", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, DBAttributes.stains: { "type": Platform.SENSOR, "translation_key": "stains", "name": "Stains", "icon": "mdi:water-outline", }, DBAttributes.dirty_degree: { "type": Platform.SENSOR, "translation_key": "dirty_degree", "name": "Dirty_degree", "icon": "mdi:water-outline", }, }, }, 0xDC: { "name": "Clothes Dryer", "entities": { DCAttributes.time_remaining: { "type": Platform.SENSOR, "translation_key": "time_remaining", "name": "Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, DCAttributes.progress: { "type": Platform.SENSOR, "translation_key": "progress", "name": "Progress", "icon": "mdi:rotate-360", }, DCAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, DCAttributes.start: { "type": Platform.SWITCH, "translation_key": "start", "name": "Start", "icon": "mdi:motion-play-outline", }, DCAttributes.status: { "type": Platform.SENSOR, "translation_key": "status", "name": "Status", "icon": "mdi:auto-mode", }, DCAttributes.program: { "type": Platform.SENSOR, "translation_key": "program", "name": "Program", "icon": "mdi:washing-machine", }, DCAttributes.dry_temperature: { "type": Platform.SENSOR, "translation_key": "dry_temperature", "name": "Dry Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, DCAttributes.intensity: { "type": Platform.SENSOR, "translation_key": "intensity", "name": "Intensity", "icon": "mdi:waves-arrow-up", }, DCAttributes.dryness_level: { "type": Platform.SENSOR, "translation_key": "dryness_level", "name": "Dryness Level", "icon": "mdi:spirit-level", }, DCAttributes.error_code: { "type": Platform.SENSOR, "translation_key": "error_code", "name": "Error Code", "icon": "mdi:code-block-tags", }, DCAttributes.door_warn: { "type": Platform.SENSOR, "translation_key": "door_warn", "name": "Door Warn", "icon": "mdi:alert-box", }, DCAttributes.ai_switch: { "type": Platform.SENSOR, "translation_key": "ai_switch", "name": "AI Switch", "icon": "mdi:toggle-switch", }, DCAttributes.material: { "type": Platform.SENSOR, "translation_key": "material", "name": "Material", "icon": "mdi:material-design", }, DCAttributes.water_box: { "type": Platform.SENSOR, "translation_key": "water_box", "name": "Water Box", "icon": "mdi:cup-water", }, }, }, 0xE1: { "name": "Dishwasher", "entities": { E1Attributes.door: { "type": Platform.BINARY_SENSOR, "name": "Door", "icon": "mdi:box-shadow", "device_class": BinarySensorDeviceClass.DOOR, }, E1Attributes.rinse_aid: { "type": Platform.BINARY_SENSOR, "translation_key": "rinse_aid", "name": "Rinse Aid Shortage", "icon": "mdi:bottle-tonic", "device_class": BinarySensorDeviceClass.PROBLEM, }, E1Attributes.salt: { "type": Platform.BINARY_SENSOR, "translation_key": "salt", "name": "Salt Shortage", "icon": "mdi:drag", "device_class": BinarySensorDeviceClass.PROBLEM, }, E1Attributes.humidity: { "type": Platform.SENSOR, "name": "Humidity", "device_class": SensorDeviceClass.HUMIDITY, "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, E1Attributes.progress: { "type": Platform.SENSOR, "translation_key": "progress", "name": "Progress", "icon": "mdi:rotate-360", }, E1Attributes.status: { "type": Platform.SENSOR, "translation_key": "status", "name": "Status", "icon": "mdi:information", }, E1Attributes.storage_remaining: { "type": Platform.SENSOR, "translation_key": "storage_remaining", "name": "Storage Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.HOURS, "state_class": SensorStateClass.MEASUREMENT, }, E1Attributes.temperature: { "type": Platform.SENSOR, "name": "Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, E1Attributes.time_remaining: { "type": Platform.SENSOR, "translation_key": "time_remaining", "name": "Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, E1Attributes.child_lock: { "type": Platform.LOCK, "translation_key": "child_lock", "name": "Child Lock", }, E1Attributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, E1Attributes.storage: { "type": Platform.SWITCH, "translation_key": "storage", "name": "Storage", "icon": "mdi:repeat-variant", }, E1Attributes.mode: { "type": Platform.SENSOR, "translation_key": "mode", "name": "Working Mode", "icon": "mdi:dishwasher", }, E1Attributes.error_code: { "type": Platform.SENSOR, "translation_key": "error_code", "name": "Error Code", "icon": "mdi:alert-box", }, E1Attributes.softwater: { "type": Platform.SENSOR, "translation_key": "softwater", "name": "Softwater Level", "icon": "mdi:shaker-outline", }, E1Attributes.bright: { "type": Platform.SENSOR, "translation_key": "bright", "name": "Bright Level", "icon": "mdi:star-four-points", }, }, }, 0xE2: { "name": "Electric Water Heater", "entities": { "water_heater": { "type": Platform.WATER_HEATER, "icon": "mdi:meter-electric-outline", "default": True, }, E2Attributes.heating: { "type": Platform.BINARY_SENSOR, "translation_key": "heating", "name": "Heating", "icon": "mdi:heat-wave", "device_class": BinarySensorDeviceClass.RUNNING, }, E2Attributes.keep_warm: { "type": Platform.BINARY_SENSOR, "translation_key": "keep_warm", "name": "Keep Warm", "icon": "mdi:menu", "device_class": BinarySensorDeviceClass.RUNNING, }, E2Attributes.protection: { "type": Platform.BINARY_SENSOR, "translation_key": "protection", "name": "Protection", "icon": "mdi:shield-check", "device_class": BinarySensorDeviceClass.RUNNING, }, E2Attributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, E2Attributes.heating_time_remaining: { "type": Platform.SENSOR, "translation_key": "heating_time_remaining", "name": "Heating Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, E2Attributes.heating_power: { "type": Platform.SENSOR, "translation_key": "heating_power", "name": "Heating Power", "device_class": SensorDeviceClass.POWER, "unit": UnitOfPower.WATT, "state_class": SensorStateClass.MEASUREMENT, }, E2Attributes.water_consumption: { "type": Platform.SENSOR, "translation_key": "water_consumption", "name": "Water Consumption", "icon": "mdi:water", "unit": UnitOfVolume.LITERS, "state_class": SensorStateClass.TOTAL_INCREASING, }, E2Attributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, E2Attributes.variable_heating: { "type": Platform.SWITCH, "translation_key": "variable_heating", "name": "Variable Heating", "icon": "mdi:waves", }, E2Attributes.whole_tank_heating: { "type": Platform.SWITCH, "translation_key": "whole_tank_heating", "name": "Whole Tank Heating", "icon": "mdi:restore", }, }, }, 0xE3: { "name": "Gas Water Heater", "entities": { "water_heater": { "type": Platform.WATER_HEATER, "icon": "mdi:meter-gas", "default": True, }, E3Attributes.burning_state: { "type": Platform.BINARY_SENSOR, "translation_key": "burning_state", "name": "Burning State", "icon": "mdi:fire", "device_class": BinarySensorDeviceClass.RUNNING, }, E3Attributes.protection: { "type": Platform.BINARY_SENSOR, "translation_key": "protection", "name": "Protection", "icon": "mdi:shield-check", "device_class": BinarySensorDeviceClass.RUNNING, }, E3Attributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, E3Attributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, E3Attributes.smart_volume: { "type": Platform.SWITCH, "translation_key": "smart_volume", "name": "Smart Volume", "icon": "mdi:recycle", }, E3Attributes.zero_cold_water: { "type": Platform.SWITCH, "translation_key": "zero_cold_water", "name": "Zero Cold Water", "icon": "mdi:restore", }, E3Attributes.zero_cold_pulse: { "type": Platform.SWITCH, "translation_key": "zero_cold_pulse", "name": "Zero Cold Water (Pulse)", "icon": "mdi:restore-alert", }, }, }, 0xE6: { "name": "Gas Boilers", "entities": { "water_heater_heating": { "type": Platform.WATER_HEATER, "translation_key": "heating", "name": "Heating", "icon": "mdi:meter-gas", "use": 0, "default": True, }, "water_heater_bathing": { "type": Platform.WATER_HEATER, "translation_key": "bathing", "name": "Bathing", "icon": "mdi:meter-gas", "use": 1, "default": True, }, E6Attributes.heating_working: { "type": Platform.BINARY_SENSOR, "translation_key": "heating_working", "name": "Heating Working Status", "icon": "mdi:fire", "device_class": BinarySensorDeviceClass.RUNNING, }, E6Attributes.bathing_working: { "type": Platform.BINARY_SENSOR, "translation_key": "bathing_working", "name": "Bathing Working Status", "icon": "mdi:fire", "device_class": BinarySensorDeviceClass.RUNNING, }, E6Attributes.heating_leaving_temperature: { "type": Platform.SENSOR, "translation_key": "heating_leaving_temperature", "name": "Heating Leaving Water Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, E6Attributes.bathing_leaving_temperature: { "type": Platform.SENSOR, "translation_key": "bathing_leaving_temperature", "name": "Bathing Leaving Water Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, E6Attributes.main_power: { "type": Platform.SWITCH, "translation_key": "main_power", "name": "Main Power", "icon": "mdi:power", }, E6Attributes.heating_power: { "type": Platform.SWITCH, "translation_key": "heating_power", "name": "Heating Power", "icon": "mdi:heating-coil", }, E6Attributes.cold_water_single: { "type": Platform.SWITCH, "translation_key": "cold_water_single", "name": "Cold Water Single", "icon": "mdi:water", }, E6Attributes.cold_water_dot: { "type": Platform.SWITCH, "translation_key": "cold_water_dot", "name": "Cold Water Dot", "icon": "mdi:water-outline", }, E6Attributes.heating_modes: { "type": Platform.SELECT, "translation_key": "mode", "options": "heating_modes", "name": "Heating Modes", "icon": "mdi:auto-mode", }, }, }, 0xE8: { "name": "Electric Slow Cooker", "entities": { E8Attributes.finished: { "type": Platform.BINARY_SENSOR, "translation_key": "finished", "name": "Finished", "icon": "", }, E8Attributes.water_shortage: { "type": Platform.BINARY_SENSOR, "translation_key": "water_shortage", "name": "Water Shortage", "icon": "mdi:drag", "device_class": BinarySensorDeviceClass.PROBLEM, }, E8Attributes.status: { "type": Platform.SENSOR, "translation_key": "status", "name": "Status", "icon": "mdi:information", }, E8Attributes.time_remaining: { "type": Platform.SENSOR, "translation_key": "time_remaining", "name": "Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.SECONDS, "state_class": SensorStateClass.MEASUREMENT, }, E8Attributes.keep_warm_remaining: { "type": Platform.SENSOR, "translation_key": "keep_warm_remaining", "name": "Keep Warm Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.SECONDS, "state_class": SensorStateClass.MEASUREMENT, }, E8Attributes.working_time: { "type": Platform.SENSOR, "translation_key": "working_time", "name": "Working Time", "icon": "mdi:progress-clock", "unit": UnitOfTime.SECONDS, "state_class": SensorStateClass.MEASUREMENT, }, E8Attributes.target_temperature: { "type": Platform.SENSOR, "translation_key": "target_temperature", "name": "Target Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, E8Attributes.current_temperature: { "type": Platform.SENSOR, "translation_key": "current_temperature", "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xEA: { "name": "Electric Rice Cooker", "entities": { EAAttributes.cooking: { "type": Platform.BINARY_SENSOR, "translation_key": "cooking", "name": "Cooking", "icon": "mdi:fire", "device_class": BinarySensorDeviceClass.RUNNING, }, EAAttributes.keep_warm: { "type": Platform.BINARY_SENSOR, "translation_key": "keep_warm", "name": "Keep Warm", "icon": "mdi:menu", "device_class": BinarySensorDeviceClass.RUNNING, }, EAAttributes.bottom_temperature: { "type": Platform.SENSOR, "translation_key": "bottom_temperature", "name": "Bottom Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, EAAttributes.keep_warm_time: { "type": Platform.SENSOR, "translation_key": "keep_warm_time", "name": "Keep Warm Time", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, EAAttributes.mode: { "type": Platform.SENSOR, "translation_key": "mode", "name": "Mode", "icon": "mdi:orbit", }, EAAttributes.progress: { "type": Platform.SENSOR, "translation_key": "progress", "name": "Progress", "icon": "mdi:rotate-360", }, EAAttributes.time_remaining: { "type": Platform.SENSOR, "translation_key": "time_remaining", "name": "Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, EAAttributes.top_temperature: { "type": Platform.SENSOR, "translation_key": "top_temperature", "name": "Top Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xEC: { "name": "Electric Pressure Cooker", "entities": { ECAttributes.cooking: { "type": Platform.BINARY_SENSOR, "translation_key": "cooking", "name": "Cooking", "icon": "mdi:fire", "device_class": BinarySensorDeviceClass.RUNNING, }, ECAttributes.with_pressure: { "type": Platform.BINARY_SENSOR, "translation_key": "with_pressure", "name": "With Pressure", "icon": "mdi:information", "device_class": BinarySensorDeviceClass.RUNNING, }, ECAttributes.bottom_temperature: { "type": Platform.SENSOR, "translation_key": "bottom_temperature", "name": "Bottom Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, ECAttributes.keep_warm_time: { "type": Platform.SENSOR, "translation_key": "keep_warm_time", "name": "Keep Warm Time", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, ECAttributes.mode: { "type": Platform.SENSOR, "translation_key": "mode", "name": "Mode", "icon": "mdi:orbit", }, ECAttributes.progress: { "type": Platform.SENSOR, "translation_key": "progress", "name": "Progress", "icon": "mdi:rotate-360", }, ECAttributes.time_remaining: { "type": Platform.SENSOR, "translation_key": "time_remaining", "name": "Time Remaining", "icon": "mdi:progress-clock", "unit": UnitOfTime.MINUTES, "state_class": SensorStateClass.MEASUREMENT, }, ECAttributes.top_temperature: { "type": Platform.SENSOR, "translation_key": "top_temperature", "name": "Top Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xED: { "name": "Water Drinking Appliance", "entities": { EDAttributes.child_lock: { "type": Platform.LOCK, "translation_key": "child_lock", "name": "Child Lock", }, EDAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, EDAttributes.filter1: { "type": Platform.SENSOR, "translation_key": "filter1_days", "name": "Filter1 Available Days", "icon": "mdi:air-filter", "unit": UnitOfTime.DAYS, "state_class": SensorStateClass.MEASUREMENT, }, EDAttributes.filter2: { "type": Platform.SENSOR, "translation_key": "filter2_days", "name": "Filter2 Available Days", "icon": "mdi:air-filter", "unit": UnitOfTime.DAYS, "state_class": SensorStateClass.MEASUREMENT, }, EDAttributes.filter3: { "type": Platform.SENSOR, "translation_key": "filter3_days", "name": "Filter3 Available Days", "icon": "mdi:air-filter", "unit": UnitOfTime.DAYS, "state_class": SensorStateClass.MEASUREMENT, }, EDAttributes.life1: { "type": Platform.SENSOR, "translation_key": "filter1_life", "name": "Filter1 Life Level", "icon": "mdi:percent", "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, EDAttributes.life2: { "type": Platform.SENSOR, "translation_key": "filter2_life", "name": "Filter2 Life Level", "icon": "mdi:percent", "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, EDAttributes.life3: { "type": Platform.SENSOR, "translation_key": "filter3_life", "name": "Filter3 Life Level", "icon": "mdi:percent", "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, EDAttributes.in_tds: { "type": Platform.SENSOR, "translation_key": "in_tds", "name": "In TDS", "icon": "mdi:water", "unit": CONCENTRATION_PARTS_PER_MILLION, "state_class": SensorStateClass.MEASUREMENT, }, EDAttributes.out_tds: { "type": Platform.SENSOR, "translation_key": "out_tds", "name": "Out TDS", "icon": "mdi:water-plus", "unit": CONCENTRATION_PARTS_PER_MILLION, "state_class": SensorStateClass.MEASUREMENT, }, EDAttributes.water_consumption: { "type": Platform.SENSOR, "translation_key": "water_consumption", "name": "Water Consumption", "icon": "mdi:water-pump", "unit": UnitOfVolume.LITERS, "state_class": SensorStateClass.TOTAL_INCREASING, }, }, }, 0xFA: { "name": "Fan", "entities": { "fan": { "type": Platform.FAN, "icon": "mdi:fan", "default": True, }, FAAttributes.oscillation_mode: { "type": Platform.SELECT, "translation_key": "oscillation_mode", "name": "Oscillation Mode", "options": "oscillation_modes", "icon": "mdi:swap-horizontal-variant", }, FAAttributes.oscillation_angle: { "type": Platform.SELECT, "translation_key": "oscillation_angle", "name": "Oscillation Angle", "options": "oscillation_angles", "icon": "mdi:pan-horizontal", }, FAAttributes.tilting_angle: { "type": Platform.SELECT, "translation_key": "tilting_angle", "name": "Tilting Angle", "options": "tilting_angles", "icon": "mdi:pan-vertical", }, FAAttributes.child_lock: { "type": Platform.LOCK, "translation_key": "child_lock", "name": "Child Lock", }, FAAttributes.oscillate: { "type": Platform.SWITCH, "translation_key": "oscillate", "name": "Oscillate", "icon": "mdi:swap-horizontal-bold", }, FAAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, }, }, 0xFB: { "name": "Electric Heater", "entities": { "climate": { "type": Platform.CLIMATE, "icon": "mdi:air-conditioner", "default": True, }, FBAttributes.child_lock: { "type": Platform.LOCK, "translation_key": "child_lock", "name": "Child Lock", }, FBAttributes.heating_level: { "type": Platform.NUMBER, "translation_key": "heating_level", "name": "Heating Level", "icon": "mdi:fire", "max": 10, "min": 1, "step": 1, }, FBAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, FBAttributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xFC: { "name": "Air Purifier", "entities": { FCAttributes.child_lock: { "type": Platform.LOCK, "translation_key": "child_lock", "name": "Child Lock", }, FCAttributes.anion: { "type": Platform.SWITCH, "translation_key": "anion", "name": "Anion", "icon": "mdi:vanish", }, FCAttributes.prompt_tone: { "type": Platform.SWITCH, "translation_key": "prompt_tone", "name": "Prompt Tone", "icon": "mdi:bell", }, FCAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, FCAttributes.standby: { "type": Platform.SWITCH, "translation_key": "standby", "name": "Standby", "icon": "mdi:smoke-detector-variant", }, FCAttributes.detect_mode: { "type": Platform.SELECT, "translation_key": "detect_mode", "name": "Detect Mode", "options": "detect_modes", "icon": "mdi:smoke-detector-variant", }, FCAttributes.mode: { "type": Platform.SELECT, "translation_key": "mode", "name": "Mode", "options": "modes", "icon": "mdi:rotate-360", }, FCAttributes.fan_speed: { "type": Platform.SELECT, "translation_key": "fan_speed", "name": "Fan Speed", "options": "fan_speeds", "icon": "mdi:fan", }, FCAttributes.screen_display: { "type": Platform.SELECT, "translation_key": "screen_display", "name": "Screen Display", "options": "screen_displays", "icon": "mdi:television-ambient-light", }, FCAttributes.pm25: { "type": Platform.SENSOR, "name": "PM 2.5", "device_class": SensorDeviceClass.PM25, "unit": CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, "state_class": SensorStateClass.MEASUREMENT, }, FCAttributes.tvoc: { "type": Platform.SENSOR, "translation_key": "tvoc", "name": "TVOC", "icon": "mdi:heat-wave", "unit": CONCENTRATION_PARTS_PER_MILLION, "state_class": SensorStateClass.MEASUREMENT, }, FCAttributes.hcho: { "type": Platform.SENSOR, "translation_key": "hcho", "name": "Methanal", "icon": "mdi:molecule", "unit": CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, "state_class": SensorStateClass.MEASUREMENT, }, FCAttributes.filter1_life: { "type": Platform.SENSOR, "translation_key": "filter1_life", "name": "Filter1 Life Level", "icon": "mdi:air-filter", "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, FCAttributes.filter2_life: { "type": Platform.SENSOR, "translation_key": "filter2_life", "name": "Filter2 Life Level", "icon": "mdi:air-filter", "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, }, }, 0xFD: { "name": "Humidifier", "entities": { Platform.HUMIDIFIER: { "type": Platform.HUMIDIFIER, "icon": "mdi:air-humidifier", "default": True, }, FDAttributes.disinfect: { "type": Platform.SWITCH, "translation_key": "disinfect", "name": "Disinfect", "icon": "mdi:water-plus-outline", }, FDAttributes.prompt_tone: { "type": Platform.SWITCH, "translation_key": "prompt_tone", "name": "Prompt Tone", "icon": "mdi:bell", }, FDAttributes.power: { "type": Platform.SWITCH, "translation_key": "power", "name": "Power", "icon": "mdi:power", }, FDAttributes.fan_speed: { "type": Platform.SELECT, "translation_key": "fan_speed", "name": "Fan Speed", "options": "fan_speeds", "icon": "mdi:fan", }, FDAttributes.screen_display: { "type": Platform.SELECT, "translation_key": "screen_display", "name": "Screen Display", "options": "screen_displays", "icon": "mdi:television-ambient-light", }, FDAttributes.current_humidity: { "type": Platform.SENSOR, "name": "Current Humidity", "device_class": SensorDeviceClass.HUMIDITY, "unit": PERCENTAGE, "state_class": SensorStateClass.MEASUREMENT, }, FDAttributes.current_temperature: { "type": Platform.SENSOR, "name": "Current Temperature", "device_class": SensorDeviceClass.TEMPERATURE, "unit": UnitOfTemperature.CELSIUS, "state_class": SensorStateClass.MEASUREMENT, }, }, }, }
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/midea_entity.py
Python
"""Base entity for Midea Lan.""" import logging from typing import Any, cast from homeassistant.const import MAJOR_VERSION, MINOR_VERSION from homeassistant.core import callback if (MAJOR_VERSION, MINOR_VERSION) >= (2023, 9): from homeassistant.helpers.device_registry import DeviceInfo else: from homeassistant.helpers.entity import ( # type: ignore[attr-defined] DeviceInfo, ) from homeassistant.helpers.entity import Entity from midealocal.device import MideaDevice from .const import DOMAIN from .midea_devices import MIDEA_DEVICES _LOGGER = logging.getLogger(__name__) class MideaEntity(Entity): """Base Midea entity.""" def __init__(self, device: MideaDevice, entity_key: str) -> None: """Initialize Midea base entity.""" self._device = device self._device.register_update(self.update_state) self._config = cast( "dict", MIDEA_DEVICES[self._device.device_type]["entities"], )[entity_key] self._entity_key = entity_key self._unique_id = f"{DOMAIN}.{self._device.device_id}_{entity_key}" self.entity_id = self._unique_id self._device_name = self._device.name # HA language setting: # 1. hass.config.language: Settings / System / General settings # 2. user language setting in user profile setting # Entity name translation based on hass.config.language # add language in /config/configuration.yaml will disable web UI setting # homeassistant: # language: zh-Hans # noqa: ERA001 # Translating the name and attributes of entities: # https://developers.home-assistant.io/blog/2023/03/27/entity_name_translations/#translating-entity-name # https://developers.home-assistant.io/docs/internationalization/core # translation_key: if defined, Home Assistant will try to find a # translation in translations/<lang>.json. # If translation exists -> UI shows the translated string. # If translation not found -> fallback to "name" / device_class / entity_id. self._attr_translation_key = self._config.get("translation_key") # has_entity_name: MUST be True in modern HA (old False behavior is deprecated). self._attr_has_entity_name = True # Step 1: translation_key is defined # - If translation is found in the current language: # -> UI displays the translated string. if self._attr_translation_key is not None: # skip set attr_name and use translation_key pass # set attr_name to None will only show device name without translaion_key # Step 2: No translation_key # but english "name" is explicitly set in config: # -> UI displays this name directly (highest priority). elif self._config.get("name") is not None: self._attr_name = self._config["name"] # Step 3: No translation_key, no name, # fallback to device_class default label. # Example: device_class = temperature -> "Temperature". elif "device_class" in self._config: self._attr_name = None # Let HA generate from device_class # Step 4: Nothing available, else: self._attr_name = ( f"{self._device_name} {self._config.get('name')}" if "name" in self._config else f"{self._device_name}" ) @property def device(self) -> MideaDevice: """Return device structure.""" return self._device @property def device_info(self) -> DeviceInfo: """Return device info.""" return { "manufacturer": "Midea", "model": f"{MIDEA_DEVICES[self._device.device_type]['name']} " f"{self._device.model}" f" ({self._device.subtype})", "identifiers": {(DOMAIN, str(self._device.device_id))}, "name": self._device_name, } @property def unique_id(self) -> str: """Return entity unique id.""" return self._unique_id @property def should_poll(self) -> bool: """Return true is integration should poll.""" return False @property def available(self) -> bool: """Return entity availability.""" return bool(self._device.available) @property def icon(self) -> str: """Return entity icon.""" return cast("str", self._config.get("icon")) @callback def update_state(self, status: Any) -> None: # noqa: ANN401 """Update entity state.""" if not self.hass: _LOGGER.warning( "MideaEntity update_state for %s [%s] with status %s: HASS is None", self.name, type(self), status, ) return if self.hass.is_stopping: _LOGGER.debug( "MideaEntity update_state for %s [%s] with status %s: HASS is stopping", self.name, type(self), status, ) return if self._entity_key in status or "available" in status: self.schedule_update_ha_state()
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/number.py
Python
"""Number for Midea Lan.""" from typing import Any, cast from homeassistant.components.number import NumberEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DEVICE_ID, CONF_SWITCHES, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from midealocal.device import MideaDevice from .const import DEVICES, DOMAIN from .midea_devices import MIDEA_DEVICES from .midea_entity import MideaEntity async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up numbers for device.""" device_id = config_entry.data.get(CONF_DEVICE_ID) device = hass.data[DOMAIN][DEVICES].get(device_id) extra_switches = config_entry.options.get(CONF_SWITCHES, []) numbers = [] for entity_key, config in cast( "dict", MIDEA_DEVICES[device.device_type]["entities"], ).items(): if config["type"] == Platform.NUMBER and entity_key in extra_switches: dev = MideaNumber(device, entity_key) numbers.append(dev) async_add_entities(numbers) class MideaNumber(MideaEntity, NumberEntity): """Represent a Midea number sensor.""" def __init__(self, device: MideaDevice, entity_key: str) -> None: """Midea number sensor init.""" super().__init__(device, entity_key) self._max_value = self._config.get("max") self._min_value = self._config.get("min") self._step_value = self._config.get("step") @property def native_min_value(self) -> float: """Return minimum value.""" return cast( "float", ( self._min_value if isinstance(self._min_value, int) else ( self._device.get_attribute(attr=self._min_value) if self._device.get_attribute(attr=self._min_value) else getattr(self._device, self._min_value) ) ), ) @property def native_max_value(self) -> float: """Return maximum value.""" return cast( "float", ( self._max_value if isinstance(self._max_value, int) else ( self._device.get_attribute(attr=self._max_value) if self._device.get_attribute(attr=self._max_value) else getattr(self._device, self._max_value) ) ), ) @property def native_step(self) -> float: """Return step value.""" return cast( "float", ( self._step_value if isinstance(self._step_value, int) else ( self._device.get_attribute(attr=self._step_value) if self._device.get_attribute(attr=self._step_value) else getattr(self._device, self._step_value) ) ), ) @property def native_value(self) -> float: """Return value.""" return cast("float", self._device.get_attribute(self._entity_key)) def set_native_value(self, value: Any) -> None: # noqa: ANN401 """Set value.""" self._device.set_attribute(self._entity_key, value)
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/select.py
Python
"""Select for Midea Lan.""" from typing import cast from homeassistant.components.select import SelectEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DEVICE_ID, CONF_SWITCHES, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from midealocal.device import MideaDevice from .const import DEVICES, DOMAIN from .midea_devices import MIDEA_DEVICES from .midea_entity import MideaEntity async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up selects for device.""" device_id = config_entry.data.get(CONF_DEVICE_ID) device = hass.data[DOMAIN][DEVICES].get(device_id) extra_switches = config_entry.options.get(CONF_SWITCHES, []) selects = [] for entity_key, config in cast( "dict", MIDEA_DEVICES[device.device_type]["entities"], ).items(): if config["type"] == Platform.SELECT and entity_key in extra_switches: dev = MideaSelect(device, entity_key) selects.append(dev) async_add_entities(selects) class MideaSelect(MideaEntity, SelectEntity): """Represent a Midea select.""" def __init__(self, device: MideaDevice, entity_key: str) -> None: """Midea select init.""" super().__init__(device, entity_key) self._options_name = self._config.get("options") @property def options(self) -> list[str]: """Return entity options.""" return cast("list", getattr(self._device, self._options_name)) @property def current_option(self) -> str: """Return entity current option.""" return cast("str", self._device.get_attribute(self._entity_key)) def select_option(self, option: str) -> None: """Select entity option.""" self._device.set_attribute(self._entity_key, option)
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/sensor.py
Python
"""Sensor for Midea Lan.""" from typing import Any, cast from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DEVICE_ID, CONF_SENSORS, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import StateType from .const import DEVICES, DOMAIN from .midea_devices import MIDEA_DEVICES from .midea_entity import MideaEntity async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up sensors for device.""" device_id = config_entry.data.get(CONF_DEVICE_ID) device = hass.data[DOMAIN][DEVICES].get(device_id) extra_sensors = config_entry.options.get(CONF_SENSORS, []) sensors = [] for entity_key, config in cast( "dict", MIDEA_DEVICES[device.device_type]["entities"], ).items(): if config["type"] == Platform.SENSOR and entity_key in extra_sensors: sensor = MideaSensor(device, entity_key) sensors.append(sensor) async_add_entities(sensors) class MideaSensor(MideaEntity, SensorEntity): """Represent a Midea sensor.""" @property def native_value(self) -> StateType: """Return entity value.""" return cast("StateType", self._device.get_attribute(self._entity_key)) @property def device_class(self) -> SensorDeviceClass: """Return device class.""" return cast("SensorDeviceClass", self._config.get("device_class")) @property def state_class(self) -> SensorStateClass | None: """Return state state.""" return cast("SensorStateClass | None", self._config.get("state_class")) @property def native_unit_of_measurement(self) -> str | None: """Return unit of measurement.""" return cast("str | None", self._config.get("unit")) @property def capability_attributes(self) -> dict[str, Any] | None: """Return capabilities.""" return {"state_class": self.state_class} if self.state_class else {}
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/switch.py
Python
"""Switch for Midea Lan.""" from typing import Any, cast from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DEVICE_ID, CONF_SWITCHES, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import ToggleEntity from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DEVICES, DOMAIN from .midea_devices import MIDEA_DEVICES from .midea_entity import MideaEntity async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up switches for device.""" device_id = config_entry.data.get(CONF_DEVICE_ID) device = hass.data[DOMAIN][DEVICES].get(device_id) extra_switches = config_entry.options.get(CONF_SWITCHES, []) switches = [] for entity_key, config in cast( "dict", MIDEA_DEVICES[device.device_type]["entities"], ).items(): if config["type"] == Platform.SWITCH and entity_key in extra_switches: dev = MideaSwitch(device, entity_key) switches.append(dev) async_add_entities(switches) class MideaSwitch(MideaEntity, ToggleEntity): """Represent a Midea switch.""" @property def is_on(self) -> bool: """Return true if switch is on.""" return cast("bool", self._device.get_attribute(self._entity_key)) def turn_on(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Turn on switch.""" self._device.set_attribute(attr=self._entity_key, value=True) def turn_off(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Turn off switch.""" self._device.set_attribute(attr=self._entity_key, value=False)
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
custom_components/midea_ac_lan/water_heater.py
Python
"""Midea Water Heater entries.""" import functools as ft import logging from typing import Any, ClassVar, TypeAlias, cast from homeassistant.components.water_heater import ( WaterHeaterEntity, WaterHeaterEntityFeature, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_TEMPERATURE, CONF_DEVICE_ID, CONF_SWITCHES, PRECISION_HALVES, PRECISION_WHOLE, STATE_OFF, STATE_ON, Platform, UnitOfTemperature, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from midealocal.device import DeviceType from midealocal.devices.c3 import DeviceAttributes as C3Attributes from midealocal.devices.c3 import MideaC3Device from midealocal.devices.cd import DeviceAttributes as CDAttributes from midealocal.devices.cd import MideaCDDevice from midealocal.devices.e2 import DeviceAttributes as E2Attributes from midealocal.devices.e2 import MideaE2Device from midealocal.devices.e3 import MideaE3Device from midealocal.devices.e6 import DeviceAttributes as E6Attributes from midealocal.devices.e6 import MideaE6Device from .const import DEVICES, DOMAIN from .midea_devices import MIDEA_DEVICES from .midea_entity import MideaEntity _LOGGER = logging.getLogger(__name__) E2_TEMPERATURE_MAX = 75 E2_TEMPERATURE_MIN = 30 E3_TEMPERATURE_MAX = 65 E3_TEMPERATURE_MIN = 35 async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up water heater entries.""" device_id = config_entry.data.get(CONF_DEVICE_ID) device = hass.data[DOMAIN][DEVICES].get(device_id) extra_switches = config_entry.options.get(CONF_SWITCHES, []) devs: list[ MideaE2WaterHeater | MideaE3WaterHeater | MideaE6WaterHeater | MideaC3WaterHeater | MideaCDWaterHeater ] = [] for entity_key, config in cast( "dict", MIDEA_DEVICES[device.device_type]["entities"], ).items(): if config["type"] == Platform.WATER_HEATER and ( config.get("default") or entity_key in extra_switches ): if device.device_type == DeviceType.E2: devs.append(MideaE2WaterHeater(device, entity_key)) elif device.device_type == DeviceType.E3: devs.append(MideaE3WaterHeater(device, entity_key)) elif device.device_type == DeviceType.E6: devs.append(MideaE6WaterHeater(device, entity_key, config["use"])) elif device.device_type == DeviceType.C3: devs.append(MideaC3WaterHeater(device, entity_key)) elif device.device_type == DeviceType.CD: devs.append(MideaCDWaterHeater(device, entity_key)) async_add_entities(devs) MideaWaterHeaterDevice: TypeAlias = ( MideaE2Device | MideaE3Device | MideaC3Device | MideaE6Device | MideaCDDevice ) class MideaWaterHeater(MideaEntity, WaterHeaterEntity): """Midea Water Heater Entries Base Class.""" _device: MideaWaterHeaterDevice def __init__(self, device: MideaWaterHeaterDevice, entity_key: str) -> None: """Midea Water Heater entity init.""" super().__init__(device, entity_key) self._operations: list[str] = [] @property def supported_features(self) -> WaterHeaterEntityFeature: """Midea Water Heater supported features.""" return WaterHeaterEntityFeature.TARGET_TEMPERATURE @property def extra_state_attributes(self) -> dict[str, Any]: """Midea Water Heater extra state attributes.""" attrs: dict[str, Any] = self._device.attributes if hasattr(self._device, "temperature_step"): attrs["target_temperature_step"] = self._device.temperature_step return attrs @property def min_temp(self) -> float: """Midea Water Heater min temperature.""" raise NotImplementedError @property def max_temp(self) -> float: """Midea Water Heater max temperature.""" raise NotImplementedError @property def precision(self) -> float: """Midea Water Heater precision.""" return float(PRECISION_WHOLE) @property def temperature_unit(self) -> UnitOfTemperature: """Midea Water Heater temperature unix.""" return UnitOfTemperature.CELSIUS @property def current_operation(self) -> str | None: """Midea Water Heater current operation.""" return cast( "str", ( self._device.get_attribute("mode") if self._device.get_attribute("power") else STATE_OFF ), ) @property def current_temperature(self) -> float: """Midea Water Heater current temperature.""" return cast("float", self._device.get_attribute("current_temperature")) @property def target_temperature(self) -> float: """Midea Water Heater target temperature.""" return cast("float", self._device.get_attribute("target_temperature")) def set_temperature(self, **kwargs: Any) -> None: # noqa: ANN401 """Midea Water Heater set temperature.""" if ATTR_TEMPERATURE not in kwargs: return # input target_temperature should be float temperature = float(kwargs[ATTR_TEMPERATURE]) self._device.set_attribute("target_temperature", temperature) def set_operation_mode(self, operation_mode: str) -> None: """Midea Water Heater set operation mode.""" self._device.set_attribute(attr="mode", value=operation_mode) @property def operation_list(self) -> list[str] | None: """Midea Water Heater operation list.""" if not hasattr(self._device, "preset_modes"): return None return cast("list", self._device.preset_modes) def turn_on(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea Water Heater turn on.""" self._device.set_attribute(attr="power", value=True) def turn_off(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea Water Heater turn off.""" self._device.set_attribute(attr="power", value=False) async def async_turn_on(self, **kwargs: Any) -> None: # noqa: ANN401 """Midea Water Heater async turn on.""" await self.hass.async_add_executor_job(ft.partial(self.turn_on, **kwargs)) async def async_turn_off(self, **kwargs: Any) -> None: # noqa: ANN401 """Midea Water Heater async off.""" await self.hass.async_add_executor_job(ft.partial(self.turn_off, **kwargs)) def update_state(self, status: Any) -> None: # noqa: ANN401, ARG002 """Midea Water Heater update state.""" if not self.hass: _LOGGER.warning( "Water update_state skipped for %s [%s]: HASS is None", self.name, type(self), ) return self.schedule_update_ha_state() class MideaE2WaterHeater(MideaWaterHeater): """Midea E2 Water Heater Entries.""" _device: MideaE2Device def __init__(self, device: MideaE2Device, entity_key: str) -> None: """Midea E2 Water Heater entity init.""" super().__init__(device, entity_key) @property def current_operation(self) -> str: """Midea E2 Water Heater current operation.""" return str( STATE_ON if self._device.get_attribute(E2Attributes.power) else STATE_OFF, ) @property def min_temp(self) -> float: """Midea E2 Water Heater min temperature.""" return E2_TEMPERATURE_MIN @property def max_temp(self) -> float: """Midea E2 Water Heater max temperature.""" return E2_TEMPERATURE_MAX @property def supported_features(self) -> WaterHeaterEntityFeature: """Midea E2 Water Heater supported features.""" return ( WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.ON_OFF ) class MideaE3WaterHeater(MideaWaterHeater): """Midea E3 Water Heater Entries.""" _device: MideaE3Device def __init__(self, device: MideaE3Device, entity_key: str) -> None: """Midea E3 Water Heater entity init.""" super().__init__(device, entity_key) @property def min_temp(self) -> float: """Midea E3 Water Heater min temperature.""" return E3_TEMPERATURE_MIN @property def max_temp(self) -> float: """Midea E3 Water Heater max temperature.""" return E3_TEMPERATURE_MAX @property def precision(self) -> float: """Midea E3 Water Heater precision.""" return float( PRECISION_HALVES if self._device.precision_halves else PRECISION_WHOLE, ) @property def current_operation(self) -> str: """Midea E3 Water Heater current operation.""" return str( STATE_ON if self._device.get_attribute("power") else STATE_OFF, ) class MideaC3WaterHeater(MideaWaterHeater): """Midea C3 Water Heater Entries.""" _device: MideaC3Device def __init__(self, device: MideaC3Device, entity_key: str) -> None: """Midea C3 Water Heater entity init.""" super().__init__(device, entity_key) @property def current_operation(self) -> str: """Midea C3 Water Heater current operation.""" return str( ( STATE_ON if self._device.get_attribute(C3Attributes.dhw_power) else STATE_OFF ), ) @property def current_temperature(self) -> float: """Midea C3 Water Heater current temperature.""" return cast( "float", self._device.get_attribute(C3Attributes.tank_actual_temperature), ) @property def target_temperature(self) -> float: """Midea C3 Water Heater target temperature.""" return cast("float", self._device.get_attribute(C3Attributes.dhw_target_temp)) def set_temperature(self, **kwargs: Any) -> None: # noqa: ANN401 """Midea C3 Water Heater set temperature.""" if ATTR_TEMPERATURE not in kwargs: return temperature = float(kwargs[ATTR_TEMPERATURE]) self._device.set_attribute(C3Attributes.dhw_target_temp, temperature) @property def min_temp(self) -> float: """Midea C3 Water Heater min temperature.""" return cast("float", self._device.get_attribute(C3Attributes.dhw_temp_min)) @property def max_temp(self) -> float: """Midea C3 Water Heater max temperature.""" return cast("float", self._device.get_attribute(C3Attributes.dhw_temp_max)) def turn_on(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea C3 Water Heater turn on.""" self._device.set_attribute(attr=C3Attributes.dhw_power, value=True) def turn_off(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea C3 Water Heater turn off.""" self._device.set_attribute(attr=C3Attributes.dhw_power, value=False) class MideaE6WaterHeater(MideaWaterHeater): """Midea E6 Water Heater Entries.""" _device: MideaE6Device _powers: ClassVar[list[E6Attributes]] = [ E6Attributes.heating_power, E6Attributes.main_power, ] _current_temperatures: ClassVar[list[E6Attributes]] = [ E6Attributes.heating_leaving_temperature, E6Attributes.bathing_leaving_temperature, ] _target_temperatures: ClassVar[list[E6Attributes]] = [ E6Attributes.heating_temperature, E6Attributes.bathing_temperature, ] def __init__(self, device: MideaE6Device, entity_key: str, use: int) -> None: """Midea E6 Water Heater entity init.""" super().__init__(device, entity_key) self._use = use self._power_attr = MideaE6WaterHeater._powers[self._use] self._current_temperature_attr = MideaE6WaterHeater._current_temperatures[ self._use ] self._target_temperature_attr = MideaE6WaterHeater._target_temperatures[ self._use ] @property def current_operation(self) -> str: """Midea E6 Water Heater current operation.""" if self._use == 0: # for heating return str( ( STATE_ON if self._device.get_attribute(E6Attributes.main_power) and self._device.get_attribute(E6Attributes.heating_power) else STATE_OFF ), ) # for bathing return str( ( STATE_ON if self._device.get_attribute(E6Attributes.main_power) else STATE_OFF ), ) @property def current_temperature(self) -> float: """Midea E6 Water Heater current temperature.""" return cast("float", self._device.get_attribute(self._current_temperature_attr)) @property def target_temperature(self) -> float: """Midea E6 Water Heater target temperature.""" return cast("float", self._device.get_attribute(self._target_temperature_attr)) def set_temperature(self, **kwargs: Any) -> None: # noqa: ANN401 """Midea E6 Water Heater set temperature.""" if ATTR_TEMPERATURE not in kwargs: return temperature = float(kwargs[ATTR_TEMPERATURE]) self._device.set_attribute(self._target_temperature_attr, temperature) @property def min_temp(self) -> float: """Midea E6 Water Heater min temperature.""" min_temperature = cast( "list[str]", self._device.get_attribute(E6Attributes.min_temperature), ) return cast( "float", min_temperature[self._use], ) @property def max_temp(self) -> float: """Midea E6 Water Heater max temperature.""" max_temperature = cast( "list[str]", self._device.get_attribute(E6Attributes.max_temperature), ) return cast( "float", max_temperature[self._use], ) def turn_on(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea E6 Water Heater turn on.""" self._device.set_attribute(attr=self._power_attr, value=True) def turn_off(self, **kwargs: Any) -> None: # noqa: ANN401, ARG002 """Midea E6 Water Heater turn off.""" self._device.set_attribute(attr=self._power_attr, value=False) class MideaCDWaterHeater(MideaWaterHeater): """Midea CD Water Heater Entries.""" _device: MideaCDDevice def __init__(self, device: MideaCDDevice, entity_key: str) -> None: """Midea CD Water Heater entity init.""" super().__init__(device, entity_key) @property def supported_features(self) -> WaterHeaterEntityFeature: """Midea CD Water Heater supported features.""" return ( WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.OPERATION_MODE ) @property def min_temp(self) -> float: """Midea CD Water Heater min temperature.""" return cast("float", self._device.get_attribute(CDAttributes.min_temperature)) @property def max_temp(self) -> float: """Midea CD Water Heater max temperature.""" return cast("float", self._device.get_attribute(CDAttributes.max_temperature))
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
scripts/install.sh
Shell
#!/bin/bash # # origin https://github.com/al-one/hass-xiaomi-miot/blob/master/install.sh # # wget -q -O - https://raw.githubusercontent.com/wuwentao/midea_ac_lan/master/scripts/install.sh | bash - # wget -q -O - https://raw.githubusercontent.com/wuwentao/midea_ac_lan/master/scripts/install.sh | ARCHIVE_TAG=v0.4.2 bash - set -e [ -z "$DOMAIN" ] && DOMAIN="midea_ac_lan" [ -z "$REPO_PATH" ] && REPO_PATH="wuwentao/midea_ac_lan" REPO_NAME=$(basename "$REPO_PATH") [ -z "$ARCHIVE_TAG" ] && ARCHIVE_TAG="$1" [ -z "$ARCHIVE_TAG" ] && ARCHIVE_TAG="master" [ -z "$HUB_DOMAIN" ] && HUB_DOMAIN="github.com" ARCHIVE_URL="https://$HUB_DOMAIN/$REPO_PATH/archive/$ARCHIVE_TAG.zip" if [ "$ARCHIVE_TAG" = "latest" ]; then ARCHIVE_URL="https://$HUB_DOMAIN/$REPO_PATH/releases/$ARCHIVE_TAG/download/$DOMAIN.zip" fi if [ "$DOMAIN" = "hacs" ]; then if [ "$ARCHIVE_TAG" = "main" ] || [ "$ARCHIVE_TAG" = "china" ]; then ARCHIVE_TAG="latest" fi ARCHIVE_URL="https://$HUB_DOMAIN/$REPO_PATH/releases/$ARCHIVE_TAG/download/$DOMAIN.zip" fi RED_COLOR='\033[0;31m' GREEN_COLOR='\033[0;32m' GREEN_YELLOW='\033[1;33m' NO_COLOR='\033[0m' declare haPath declare ccPath declare -a paths=( "$PWD" "$PWD/config" "/config" "$HOME/.homeassistant" "/usr/share/hassio/homeassistant" ) function info () { echo -e "${GREEN_COLOR}INFO: $1${NO_COLOR}";} function warn () { echo -e "${GREEN_YELLOW}WARN: $1${NO_COLOR}";} function error () { echo -e "${RED_COLOR}ERROR: $1${NO_COLOR}"; if [ "$2" != "false" ]; then exit 1;fi; } function checkRequirement () { if [ -z "$(command -v "$1")" ]; then error "'$1' is not installed" fi } checkRequirement "wget" checkRequirement "unzip" info "Archive URL: $ARCHIVE_URL" info "Trying to find the correct directory..." for path in "${paths[@]}"; do if [ -n "$haPath" ]; then break fi if [ -f "$path/home-assistant.log" ]; then haPath="$path" else if [ -d "$path/.storage" ] && [ -f "$path/configuration.yaml" ]; then haPath="$path" fi fi done if [ -n "$haPath" ]; then info "Found Home Assistant configuration directory at '$haPath'" cd "$haPath" || error "Could not change path to $haPath" ccPath="$haPath/custom_components" if [ ! -d "$ccPath" ]; then info "Creating custom_components directory..." mkdir "$ccPath" fi info "Changing to the custom_components directory..." cd "$ccPath" || error "Could not change path to $ccPath" info "Downloading..." wget -t 2 -O "$ccPath/$ARCHIVE_TAG.zip" "$ARCHIVE_URL" if [ -d "$ccPath/$DOMAIN" ]; then warn "custom_components/$DOMAIN directory already exist, cleaning up..." rm -R "$ccPath/$DOMAIN" fi ver=${ARCHIVE_TAG/#v/} if [ ! -d "$ccPath/$REPO_NAME-$ver" ]; then ver=$ARCHIVE_TAG fi info "Unpacking..." str="/releases/" if [ ${ARCHIVE_URL/${str}/} = $ARCHIVE_URL ]; then unzip -o "$ccPath/$ARCHIVE_TAG.zip" -d "$ccPath" >/dev/null 2>&1 else dir="$ccPath/$REPO_NAME-$ver/custom_components/$DOMAIN" mkdir -p $dir unzip -o "$ccPath/$ARCHIVE_TAG.zip" -d $dir >/dev/null 2>&1 fi if [ ! -d "$ccPath/$REPO_NAME-$ver" ]; then error "Could not find $REPO_NAME-$ver directory" false error "找不到文件夹: $REPO_NAME-$ver" fi cp -rf "$ccPath/$REPO_NAME-$ver/custom_components/$DOMAIN" "$ccPath" info "Removing temp files..." rm -rf "$ccPath/$ARCHIVE_TAG.zip" rm -rf "$ccPath/$REPO_NAME-$ver" info "Installation complete." info "安装成功!" echo info "Remember to restart Home Assistant before you configure it." info "请重启 Home Assistant" else echo error "Could not find the directory for Home Assistant" false error "找不到 Home Assistant 根目录" false echo "Manually change the directory to the root of your Home Assistant configuration" echo "With the user that is running Home Assistant and run the script again" echo "请手动进入 Home Assistant 根目录后再次执行此脚本" exit 1 fi
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
scripts/mypy.sh
Shell
#!/usr/bin/env bash set -e cd "$(dirname "$0")/.." pyver=$(python -c 'import platform; major, minor, path = platform.python_version_tuple(); print(f"{major}.{minor}")') mypy --config-file mypy-$pyver.ini .
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
scripts/run.sh
Shell
#!/usr/bin/env bash set -e cd "$(dirname "$0")/.." # Create config dir if not present if [[ ! -d "${PWD}/config" ]]; then mkdir -p "${PWD}/config" hass --config "${PWD}/config" --script ensure_config fi # Set the path to custom_components ## This let's us have the structure we want <root>/custom_components/vaillant_vsmart ## while at the same time have Home Assistant configuration inside <root>/config ## without resulting to symlinks. export PYTHONPATH="${PYTHONPATH}:${PWD}/custom_components" # Start Home Assistant hass --config "${PWD}/config" --debug
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
scripts/setup.sh
Shell
#!/usr/bin/env bash set -e cd "$(dirname "$0")/.." # Install pre-commit hooks on commit pre-commit install pre-commit install --hook-type commit-msg npm install --no-fund @commitlint/config-conventional # Create config dir if not present if [[ ! -d "${PWD}/config" ]]; then mkdir -p "${PWD}/config" hass --config "${PWD}/config" --script ensure_config fi
wuwentao/midea_ac_lan
1,530
Auto-configure and then control your Midea M-Smart devices (Air conditioner, Fan, Water heater, Washer, etc) via local area network.
Python
wuwentao
Hello World
config/dev.env.js
JavaScript
'use strict' const merge = require('webpack-merge') const prodEnv = require('./prod.env') module.exports = merge(prodEnv, { NODE_ENV: '"development"' })
wwenj/Canvas-Drawing-board
3
一个vue-cli2.+搭建的基于canvas的画板
Vue
wwenj
zu
贝壳找房
config/index.js
JavaScript
'use strict' // Template version: 1.2.4 // see http://vuejs-templates.github.io/webpack for documentation. const path = require('path') module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // Various Dev Server settings host: 'localhost', // can be overwritten by process.env.HOST port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined autoOpenBrowser: false, errorOverlay: true, notifyOnErrors: true, poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- // Use Eslint Loader? // If true, your code will be linted during bundling and // linting errors and warnings will be shown in the console. useEslint: true, // If true, eslint errors and warnings will also be shown in the error overlay // in the browser. showEslintErrorsInOverlay: false, /** * Source Maps */ // https://webpack.js.org/configuration/devtool/#development devtool: 'eval-source-map', // If you have problems debugging vue-files in devtools, // set this to false - it *may* help // https://vue-loader.vuejs.org/en/options.html#cachebusting cacheBusting: true, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false, }, build: { // Template for index.html index: path.resolve(__dirname, '../dist/index.html'), // Paths assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', /** * Source Maps */ productionSourceMap: true, // https://webpack.js.org/configuration/devtool/#production devtool: '#source-map', // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report } }
wwenj/Canvas-Drawing-board
3
一个vue-cli2.+搭建的基于canvas的画板
Vue
wwenj
zu
贝壳找房
config/prod.env.js
JavaScript
'use strict' module.exports = { NODE_ENV: '"production"' }
wwenj/Canvas-Drawing-board
3
一个vue-cli2.+搭建的基于canvas的画板
Vue
wwenj
zu
贝壳找房
index.html
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Drawing</title> <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/> <meta name="format-detection" content="telephone=no,email=no,date=no,address=no"> <link rel="stylesheet" type="text/css" href="src/assets/css/MaterialIcons.css"> <link rel="stylesheet" type="text/css" href="//pub.wangxuefeng.com.cn/code/class/css/googleFont.css"> <style type="text/css">html,body{height: 100%}</style> </head> <body> <div id="app"></div> <!-- built files will be auto injected --> </body> </html>
wwenj/Canvas-Drawing-board
3
一个vue-cli2.+搭建的基于canvas的画板
Vue
wwenj
zu
贝壳找房
postcss.config.js
JavaScript
module.exports = {};
wwenj/Canvas-Drawing-board
3
一个vue-cli2.+搭建的基于canvas的画板
Vue
wwenj
zu
贝壳找房
src/App.vue
Vue
<template> <div id="app"> <router-view/> </div> </template> <script> export default { name: 'app' } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } </style>
wwenj/Canvas-Drawing-board
3
一个vue-cli2.+搭建的基于canvas的画板
Vue
wwenj
zu
贝壳找房
src/assets/css/MaterialIcons.css
CSS
@font-face { font-family: 'Material Icons'; font-style: normal; font-weight: 400; src: url(https://pub.wangxuefeng.com.cn/code/class/css/v37/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2) format('woff2'); } /* fallback */ @font-face { font-family: 'Material Icons'; font-style: normal; font-weight: 400; src: url(https://fonts.gstatic.com/s/materialicons/v37/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2) format('woff2'); } .material-icons { font-family: 'Material Icons'; font-weight: normal; font-style: normal; font-size: 24px; line-height: 1; letter-spacing: normal; text-transform: none; display: inline-block; white-space: nowrap; word-wrap: normal; direction: ltr; -webkit-font-feature-settings: 'liga'; -webkit-font-smoothing: antialiased; }
wwenj/Canvas-Drawing-board
3
一个vue-cli2.+搭建的基于canvas的画板
Vue
wwenj
zu
贝壳找房
src/components/draw.vue
Vue
<template> <div class="layout"> <div class="header"> <div class="logo"> 作业批改 </div> <div class="nav" style="position:fixed;top: 10px;"> <mu-flat-button v-for="tab in tabs" :key="tab.name" :label="tab.name" class="tab demo-flat-button" :icon="tab.icon" @click="tabfun(tab.fun)" color="#6e86fd" backgroundColor="#FFFFFF" /> <a href="javascript:void(0);" ref="download" download="picture.png" v-show="false"></a> </div> </div> <div class="content-left"> <div class="setterSize"> <span>线条粗细:{{penSize}}</span> <mu-slider class="demo-slider" v-model="penSize" :step="1" :max="10" :min="1" color="secondary" track-color="secondary" /> </div> <div class="choose-color"> <span v-for='(item, index) in colors' :class='{activeSpan: isSpanActive == index}' :style='{backgroundColor: item}' @click='colorSpanClick(index, item)'></span> </div> <mu-paper class="demo-menu"> <mu-menu v-for="tool in tools" :key="tool.name"> <mu-menu-item :title="tool.name" :leftIcon="tool.icon" @click="drawType(tool)" :class="{'selected':tool.ischoose}" /> </mu-menu> </mu-paper> </div> <div class="content"> <div class="content-right"> <div class="body" :style="{width:canvasSize.width + 'px',height: canvasSize.height + 'px' }"> <canvas id="canvas" ref="canvas" :style="{cursor:curcursor}"></canvas> <canvas id="canvas_bak" ref="canvas_bak" :style="{cursor:curcursor}"></canvas> </div> </div> </div> </div> </template> <script> export default { mounted() { this.initCanvas() this.addkeyBoardlistener() this.drawType(this.tools[0]) }, data() { return { isSpanActive: 0, canvasSize: { width: window.innerWidth * 0.8, height: window.innerHeight }, canvas: this.$refs.canvas, context: null, canvas_bak: this.$refs.canvas_bak, context_bak: null, imageUrl: 'src/assets/img/15.jpg', color: { hex: '#FF0000' }, colors: ['#FF0000', '#000000', '#0000FF'], penSize: 2, canDraw: false, curcursor: 'auto', cancelList: [], tools: [{ name: '铅笔(CTRL+P)', icon: 'mode_edit', fun: 'pencil', ischoose: false, }, { name: '直线(CTRL+L)', icon: 'remove', fun: 'line', ischoose: false }, { name: '矩形(CTRL+R)', icon: 'crop_square', fun: 'square', ischoose: false }, { name: '正确(CTRL+O)', icon: 'check', fun: 'right', ischoose: false }, { name: '错误(CTRL+W)', icon: 'close', fun: 'wrong', ischoose: false }, { name: '星星(CTRL+B)', icon: 'star_border', fun: 'star', ischoose: false }, { name: '文字(CTRL+T)', icon: 'title', fun: 'text', ischoose: false } // , { // name: '橡皮', // icon: 'border_style', // fun: 'rubber', // ischoose: false // } ], tabs: [ { name: '清除(ctrl+c)', icon: 'clear', fun: 'clear' }, { name: '保存(ctrl+s)', icon: 'system_update_alt', fun: 'save' }, { name: '上一步(ctrl+z)', icon: 'reply', fun: 'cancel' } ] } }, methods: { initCanvas() { let imgs = new Image(); imgs.src = this.imageUrl; this.canvas = document.getElementById("canvas") this.canvas_bak = document.getElementById("canvas_bak") this.context = this.canvas.getContext('2d') this.context_bak = this.canvas_bak.getContext('2d') this.canvas.width = this.canvasSize.width this.canvas_bak.width = this.canvasSize.width imgs.onload = () => { let sWidth = imgs.width let sHeight = imgs.height imgs.width = this.canvas.width this.canvas.height = this.canvas.width * sHeight / sWidth this.canvas_bak.height = this.canvas_bak.width * sHeight / sWidth imgs.height = this.canvas.height this.canvasSize.height = this.canvas.height this.context.drawImage(imgs, 0, 0, this.canvas.width, this.canvas.height) this.context.drawImage(imgs, 0, 0, this.canvas_bak.width, this.canvas_bak.height) } }, colorSpanClick(index, item) { this.isSpanActive = index; this.color.hex = item; }, drawType(pen) { switch (pen.fun) { case 'pencil': this.curcursor = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAQAAABKfvVzAAAAZ0lEQVR4AdXOrQ2AMBRF4bMc/zOUOSrYoYI5cQQwpAieQDW3qQBO7Xebxx8bWAk5/CASmRHzRHtB+d0Bkw0W5ZiT0SYbFcl6u/2eeJHbxIHOhWO6Er6/y9syXpMul5PLefAGKZ1/rwtTimwbWLpiCgAAAABJRU5ErkJggg==') 3 21, auto" break case 'rubber': this.curcursor = 'pointer' break case 'square': case 'line': this.curcursor = 'crosshair' break case 'right': case 'wrong': case 'star': this.curcursor = 'copy' break case 'text': this.curcursor = 'text' break default: this.curcursor = 'auto' break; } this.draw_graph(pen.fun) this.chooseImg(pen) }, //选择功能按钮 修改样式 chooseImg(obj) { for (let i = 0; i < this.tools.length; i++) { this.tools[i].ischoose = false } obj.ischoose = true }, tabfun(fun) { if (fun === 'clear') { this.clearContext('1') } else if (fun === 'save') { this.downloadImage() } else if (fun === 'cancel') { this.cancel() } }, timesDraw(graphType) { let image = new Image() if (graphType != 'rubber') { image.src = this.canvas_bak.toDataURL() image.onload = () => { this.context.drawImage(image, 0, 0, image.width, image.height, 0, 0, this.canvasSize.width, this.canvasSize.height) this.clearContext() } } this.saveImageToAry() }, drawRight(ctx, x, y) { ctx.beginPath() this.clearContext() ctx.lineJoin = 'round' ctx.lineCap = 'round' ctx.moveTo(x - 20, y - 20) ctx.lineTo(x - 5, y - 5) ctx.lineTo(x + 30, y - 40) ctx.stroke() }, drawWrong(ctx, x, y) { ctx.beginPath() this.clearContext() ctx.lineJoin = 'round' ctx.lineCap = 'round' ctx.moveTo(x - 20, y - 20) ctx.lineTo(x, y) ctx.moveTo(x - 20, y) ctx.lineTo(x, y - 20) ctx.stroke() }, drawStar(ctx, x, y) { ctx.beginPath() this.clearContext() for (let i = 0; i <= 5; i++) { let nx = x - 18 * Math.sin(Math.PI / 180 * 360 / 5 * i * 2) let ny = y - 18 * Math.cos(Math.PI / 180 * 360 / 5 * i * 2) ctx.lineTo(nx, ny) } ctx.fillStyle = this.color.hex; ctx.fill(); }, drawText(ctx, x, y) { let text = prompt('请输入批改文案(文案为单行,若要输入多行,请多次输入)'); if (text) { ctx.font = "20px Roboto,Lato,sans-serif"; ctx.fillStyle = this.color.hex; ctx.fillText(text, x, y + 6); } else { ctx.stroke() this.clearContext() return 0; } }, draw_graph(graphType) { this.canvas_bak.style.zIndex = 1 //先画在蒙版上 再复制到画布上 this.canDraw = false let startX, startY, endX, endY let mousedown = (e) => { this.context.strokeStyle = this.color.hex this.context_bak.strokeStyle = this.color.hex this.context_bak.lineWidth = this.penSize e = e || window.event var rect = this.canvas.getBoundingClientRect(); startX = e.pageX - rect.left startY = e.pageY - rect.top this.context_bak.moveTo(startX, startY) this.canDraw = true if (graphType == 'pencil') { this.context_bak.beginPath() } else if (graphType == 'rubber') { this.context.clearRect(startX - this.penSize * 10, startY - this.penSize * 10, this.penSize * 20, this.penSize * 20); } } let mouseup = (e) => { e = e || window.event var rect = this.canvas.getBoundingClientRect(); endX = e.pageX - rect.left endY = e.pageY - rect.top this.canDraw = false if (graphType === 'right' || graphType === 'wrong' || graphType === 'text' || graphType === 'star') { console.log('goon'); if (graphType === 'right') { this.drawRight(this.context_bak, endX, endY) } else if (graphType === 'wrong') { this.drawWrong(this.context_bak, endX, endY) } else if (graphType === 'star') { this.drawStar(this.context_bak, endX, endY) } else if (graphType === 'text') { this.drawText(this.context_bak, endX, endY) } } else { if (Math.abs(endX - startX) < 3 && Math.abs(endY - startY) < 3) { this.context_bak.stroke() this.clearContext() return 0; } } //鼠标离开 把蒙版canvas的图片生成到canvas中 this.timesDraw(graphType) } // 鼠标移动 let mousemove = (e) => { e = e || window.event var rect = this.canvas.getBoundingClientRect(); let x = e.pageX - rect.left let y = e.pageY - rect.top //方块 4条直线搞定 if (graphType == 'square') { if (this.canDraw) { this.context_bak.beginPath() this.clearContext() this.context_bak.lineJoin = 'round' this.context_bak.moveTo(startX, startY) this.context_bak.lineTo(x, startY) this.context_bak.lineTo(x, y) this.context_bak.lineTo(startX, y) this.context_bak.lineTo(startX, startY) this.context_bak.stroke() } //直线 } else if (graphType == 'line') { if (this.canDraw) { this.context_bak.beginPath() this.clearContext() this.context_bak.lineCap = 'round' this.context_bak.moveTo(startX, startY) this.context_bak.lineTo(x, y) this.context_bak.stroke() } //画笔 } else if (graphType == 'pencil') { if (this.canDraw) { this.context_bak.lineCap = 'round' this.context_bak.lineJoin = 'round' this.context_bak.lineTo(x, y) this.context_bak.stroke() } //橡皮擦 不管有没有在画都出现小方块 按下鼠标 开始清空区域(会清除背景 的图片 需要另找解决方案) } else if (graphType == 'rubber') { this.context_bak.lineWidth = 1 this.clearContext() this.context_bak.beginPath() this.context_bak.strokeStyle = '#000000' this.context_bak.moveTo(x - this.penSize * 10, y - this.penSize * 10) this.context_bak.lineTo(x + this.penSize * 10, y - this.penSize * 10) this.context_bak.lineTo(x + this.penSize * 10, y + this.penSize * 10) this.context_bak.lineTo(x - this.penSize * 10, y + this.penSize * 10) this.context_bak.lineTo(x - this.penSize * 10, y - this.penSize * 10) this.context_bak.stroke() if (this.canDraw) { this.context.clearRect(x - this.penSize * 10, y - this.penSize * 10, this.penSize * 20, this.penSize * 20) } } } //鼠标离开区域以外 不显示橡皮擦 let mouseout = () => { if (graphType === 'rubber') { this.clearContext(); } } this.canvas_bak.onmousedown = () => { mousedown() } this.canvas_bak.onmousemove = () => { mousemove() } this.canvas_bak.onmouseup = () => { mouseup() } this.canvas_bak.onmouseout = () => { mouseout() } }, clearContext(type) { if (!type) { this.context_bak.clearRect(0, 0, this.canvasSize.width, this.canvasSize.height) } else { this.context.clearRect(0, 0, this.canvasSize.width, this.canvasSize.height) this.context_bak.clearRect(0, 0, this.canvasSize.width, this.canvasSize.height) this.initCanvas() } }, downloadImage() { this.$refs.download.href = this.canvas.toDataURL() this.$refs.download.click() }, cancel() { console.log(this.cancelList); if (this.cancelList.length !== 0) { this.context.putImageData(this.cancelList.pop(), 0, 0); } console.log(this.cancelList); }, //保存历史 用于撤销 saveImageToAry() { console.log('saveImageToAry'); console.log(this.cancelList); let width = this.context.canvas.width; let height = this.context.canvas.height; this.cancelList.push(this.context.getImageData(0, 0, width, height)); console.log(this.cancelList); }, addkeyBoardlistener() { document.onkeydown = (event) => { let e = event || window.event || arguments.callee.caller.arguments[0]; if (e.ctrlKey) { switch (e.keyCode) { case 90: this.cancel() break case 67: this.clearContext('1') break case 83: this.downloadImage() break case 80: this.drawType(this.tools[0]) break case 76: this.drawType(this.tools[1]) break case 82: this.drawType(this.tools[2]) break case 79: this.drawType(this.tools[3]) break case 87: this.drawType(this.tools[4]) break case 66: this.drawType(this.tools[5]) break case 84: this.drawType(this.tools[6]) break } } } } } } </script> <style scoped> * { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } canvas { position: absolute; z-index: 0; left: 0; right: 0; width: 100%; height: 100%; } .layout { background-color: rgb(236, 236, 236); /* height: 100%; */ } .header { background-color: #6e86fd; position: fixed; left: 0; top: 0; width: 100%; z-index: 999; } .logo { font-size: 24px; color: white; display: inline-block; padding: 10px 20px; } .logo:hover { transform: rotateY(666turn); transition-delay: 1s; transition-property: all; transition-duration: 59s; transition-timing-function: cubic-bezier(.34, 0, .84, 1); } .nav { display: inline-block; width: calc(100% - 150px); margin: 0 auto; } .content { overflow: hidden; /* height: calc(100% - 56px); */ margin-top: 56px; } .content-left { min-width: 2rem; width: 15%; float: left; height: 100%; background-color: white; position: fixed; left: 0; top: 56px; } .content-right { width: 85%; display: inline-block; margin-left: 15%; padding: 10px 20px; background-color: rgba(0, 0, 0, 0) } .breadcrumb { margin: 10px 0; } .body { position: relative; background-color: white; border-radius: 5px; height: 100%; margin: 0 auto; } .setterSize { padding: 5%; font-size: 0.5rem; } .choose-color { display: flex; justify-content: space-around; margin-bottom: 16px; } .choose-color span { display: inline-block; width: 30px; height: 30px; border-radius: 2px; cursor: pointer; transition: all .2s; } .choose-color .activeSpan { border-radius: 15px; } .demo-menu { display: inline-block; margin: 0px auto; width: 100%; } .mu-paper, .mu-menu, .mu-menu-item-wrapper { overflow: hidden; width: 100%; } .selected { background: rgba(0, 0, 0, 0.35) !important; } .tab { margin-right: 5px } </style>
wwenj/Canvas-Drawing-board
3
一个vue-cli2.+搭建的基于canvas的画板
Vue
wwenj
zu
贝壳找房
src/main.js
JavaScript
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import MuseUI from 'muse-ui' import 'muse-ui/dist/muse-ui.css' Vue.use(MuseUI) Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<App/>', components: { App} })
wwenj/Canvas-Drawing-board
3
一个vue-cli2.+搭建的基于canvas的画板
Vue
wwenj
zu
贝壳找房
src/router/index.js
JavaScript
import Vue from 'vue' import Router from 'vue-router' import draw from '@/components/draw' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'draw', component: draw } ] })
wwenj/Canvas-Drawing-board
3
一个vue-cli2.+搭建的基于canvas的画板
Vue
wwenj
zu
贝壳找房
src/cloudflare.rs
Rust
use std::time::Duration; use anyhow::Result; use serde::{de::DeserializeOwned, Deserialize, Serialize}; #[derive(Debug)] pub struct CloudflareClient { http_client: reqwest::blocking::Client, token: String, } #[derive(Debug, Clone, Deserialize)] pub struct DnsRecord { pub id: String, pub content: String, pub comment: String, } #[derive(Debug, Serialize)] struct UpdateDnsRecordRequest<'a> { content: &'a str, comment: &'a str, } #[derive(Debug, Deserialize)] struct Response<T> { result: T, success: bool, } #[derive(Debug, Deserialize)] struct Zone { id: String, } impl CloudflareClient { pub fn new(api_token: String) -> Self { Self { http_client: reqwest::blocking::ClientBuilder::new() .timeout(Duration::from_secs(10)) .build() .unwrap(), token: api_token, } } pub fn get_public_ip_address(&self) -> Result<String> { let body = self .http_client .get("https://cloudflare.com/cdn-cgi/trace") .send()? .text()?; let raw_ip = body .lines() .find_map(|line| line.strip_prefix("ip=")) .ok_or_else(|| anyhow::anyhow!("public IP address not found in Cloudflare trace"))?; Ok(raw_ip.to_owned()) } pub fn get_zone_id(&self, name: &str) -> Result<String> { let result: Vec<Zone> = self.send_get_request(&format!( "https://api.cloudflare.com/client/v4/zones?name={}", name ))?; if result.len() != 1 { anyhow::bail!("zone not found"); } Ok(result[0].id.to_owned()) } pub fn get_a_record(&self, zone_id: &str, fqdn: &str) -> Result<DnsRecord> { let result: Vec<DnsRecord> = self.send_get_request(&format!( "https://api.cloudflare.com/client/v4/zones/{}/dns_records?name={}&type=A", zone_id, fqdn ))?; if result.is_empty() { anyhow::bail!("A record not found for {}", fqdn); } if result.len() != 1 { anyhow::bail!("more than 1 A record found for {}", fqdn); } Ok(result[0].clone()) } pub fn update_a_record( &self, zone_id: &str, record_id: &str, content: &str, comment: &str, ) -> Result<DnsRecord> { let response = self .http_client .patch(format!( "https://api.cloudflare.com/client/v4/zones/{}/dns_records/{}", zone_id, record_id )) .json(&UpdateDnsRecordRequest { content, comment }) .header("Authorization", format!("Bearer {}", self.token)) .send()?; if !response.status().is_success() { anyhow::bail!("unsuccessful status code: {}", response.status()); } let response: Response<DnsRecord> = response.json()?; if !response.success { anyhow::bail!("unsuccessful Cloudflare request"); } Ok(response.result) } fn send_get_request<T>(&self, url: &str) -> Result<T> where T: DeserializeOwned, { let response = self .http_client .get(url) .header("Authorization", format!("Bearer {}", self.token)) .send()?; if !response.status().is_success() { anyhow::bail!("unsuccessful status code: {}", response.status()); } let response: Response<T> = response.json()?; if !response.success { anyhow::bail!("unsuccessful Cloudflare request"); } Ok(response.result) } }
xJonathanLEI/cfdydns
0
Cloudflare dynamic DNS client
Rust
xJonathanLEI
Jonathan LEI
src/main.rs
Rust
use std::{ thread::sleep, time::{Duration, SystemTime}, }; use anyhow::Result; use clap::Parser; use colored::Colorize; use log::{debug, error, info, trace}; mod cloudflare; use cloudflare::CloudflareClient; const COMMENT: &str = "Maintained by cfdydns"; #[derive(Debug, Parser)] #[clap(about)] struct Cli { /// Fully-qualified domain name to set A record on. #[clap(long, env = "CFDYDNS_FQDN")] fqdn: String, /// Zone name of the FQDN (e.g. `example.com`). #[clap(long, env = "CFDYDNS_ZONE")] zone: String, /// Cloudflare API token with the `DNS: Edit` permission for the target zone. #[clap(long, env = "CFDYDNS_API_TOKEN")] api_token: String, /// Number of seconds to wait between each check. #[clap(long, env = "CFDYDNS_INTERVAL", default_value = "300")] interval: u64, } fn main() -> Result<()> { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "cfdydns=debug"); } env_logger::init(); let cli = Cli::parse(); let client = CloudflareClient::new(cli.api_token); trace!("Looking up zone ID for {}", cli.zone); let zone_id = client.get_zone_id(&cli.zone)?; debug!( "Zone ID for {}: {}", cli.zone, zone_id.to_string().bright_yellow() ); let interval = Duration::from_secs(cli.interval); loop { let start_time = SystemTime::now(); if let Err(err) = run_once(&client, &zone_id, &cli.fqdn) { error!("Error running bot: {}", err); } let end_time = SystemTime::now(); let run_time = end_time.duration_since(start_time)?; if run_time < interval { let wait_time = interval - run_time; trace!( "Sleeping for {} seconds before next check", wait_time.as_secs_f32() ); sleep(wait_time); } } } fn run_once(client: &CloudflareClient, zone_id: &str, fqdn: &str) -> Result<()> { trace!("Looking up public IPv4 address"); let public_ip = client.get_public_ip_address()?; debug!("Public IPv4 address: {}", public_ip.bright_yellow()); let a_record = client.get_a_record(zone_id, fqdn)?; if a_record.content == public_ip && a_record.comment == COMMENT { debug!("Cloudflare A record is up to date"); } else { trace!("Updating Cloudflare A record"); client.update_a_record(zone_id, &a_record.id, &public_ip, COMMENT)?; info!( "Successfully updated Cloudflare A record to: {}", public_ip.bright_yellow() ); } Ok(()) }
xJonathanLEI/cfdydns
0
Cloudflare dynamic DNS client
Rust
xJonathanLEI
Jonathan LEI
src/lib.rs
Rust
//! Speculos client written in Rust for Ledger integration testing. #![deny(missing_docs)] use std::{ borrow::Cow, error::Error, fmt::Display, io::{BufRead, BufReader}, path::Path, process::{Child, Command, Stdio}, time::Duration, }; use reqwest::{Client, ClientBuilder}; use serde::{Deserialize, Serialize, ser::SerializeSeq}; /// Speculos client. /// /// The Speculos process owned by [`SpeculosClient`] will be terminated upon dropping. #[derive(Debug)] pub struct SpeculosClient { process: Child, port: u16, client: Client, } /// Ledger device model. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DeviceModel { /// Ledger Nano S. Nanos, /// Ledger Nano X. Nanox, /// Ledger Nano S Plus. Nanosp, /// Ledger Blue. Blue, /// Ledger Stax. Stax, /// Ledger Flex. Flex, } /// Speculos automation rule. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct AutomationRule<'a> { /// Exact text match. #[serde(skip_serializing_if = "Option::is_none")] pub text: Option<Cow<'a, str>>, /// Regex text match. #[serde(skip_serializing_if = "Option::is_none")] pub regexp: Option<Cow<'a, str>>, /// X coordinate match. #[serde(skip_serializing_if = "Option::is_none")] pub x: Option<u32>, /// Y coordinate match. #[serde(skip_serializing_if = "Option::is_none")] pub y: Option<u32>, /// Conditions for this rule to be activated. pub conditions: &'a [AutomationCondition<'a>], /// Actions to perform when this rule is applied. pub actions: &'a [AutomationAction<'a>], } /// Speculos automation actions. #[derive(Debug, Clone, PartialEq, Eq)] pub enum AutomationAction<'a> { /// Press or release a button. Button { /// The button whose pressed status is to be updated. button: Button, /// The pressed status to change to. pressed: bool, }, /// Touch or release the screen. Finger { /// The X coordinate whose touched status is to be updated. x: u32, /// The Y coordinate whose touched status is to be updated. y: u32, /// The touched status to change to. touched: bool, }, /// Set a variable to a boolean value. Setbool { /// Name of the variable to be updated. varname: Cow<'a, str>, /// The new variable value. value: bool, }, /// Exit speculos. Exit, } /// Condition for Speculos automation rules. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AutomationCondition<'a> { /// Name of the variable to be updated. pub varname: Cow<'a, str>, /// The new variable value. pub value: bool, } /// Ledger buttons. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Button { /// The left button. Left, /// The right button. Right, } /// Speculos client errors. #[derive(Debug)] pub enum SpeculosError { /// System IO errors. IoError(std::io::Error), /// HTTP errors from `reqwest. ReqwestError(reqwest::Error), } #[derive(Serialize)] struct PostApduRequest<'a> { #[serde(with = "hex")] data: &'a [u8], } #[derive(Deserialize)] struct PostApduResponse { #[serde(with = "hex")] data: Vec<u8>, } #[derive(Serialize)] struct PostAutomationRequest<'a> { version: u32, rules: &'a [AutomationRule<'a>], } impl SpeculosClient { /// Creates a new [`SpeculosClient`] by launching the `speculos` command with a default timeout /// of 10 seconds. /// /// This method requires the `speculos` command to be available from `PATH`. /// /// Use different `port` values when launching multiple instances to avoid port conflicts. pub fn new<P: AsRef<Path>>( model: DeviceModel, port: u16, app: P, ) -> Result<Self, SpeculosError> { Self::new_with_timeout(model, port, app, Duration::from_secs(10)) } /// Creates a new [`SpeculosClient`] by launching the `speculos` command with a custom timeout. /// /// This method requires the `speculos` command to be available from `PATH`. /// /// Use different `port` values when launching multiple instances to avoid port conflicts. pub fn new_with_timeout<P: AsRef<Path>>( model: DeviceModel, port: u16, app: P, timeout: Duration, ) -> Result<Self, SpeculosError> { let mut process = Command::new("speculos") .args([ "--api-port", &port.to_string(), "--apdu-port", "0", "-m", model.slug(), "--display", "headless", &app.as_ref().display().to_string(), ]) .stderr(Stdio::piped()) .spawn()?; // Wait for process to be ready by monitoring stderr if let Some(stderr) = process.stderr.take() { let reader = BufReader::new(stderr); for line in reader.lines().map_while(Result::ok) { if line.contains("launcher: using default app name & version") { break; } } } Ok(Self { process, port, client: ClientBuilder::new().timeout(timeout).build().unwrap(), }) } /// Sends an APDU command via the API. /// /// This method accepts and returns raw bytes. The caller should handle parsing. /// /// A common choice is to use `APDUCommand` and `APDUAnswer` types from the `coins-ledger` /// crate. pub async fn apdu(&self, data: &[u8]) -> Result<Vec<u8>, SpeculosError> { let response = self .client .post(format!("http://localhost:{}/apdu", self.port)) .json(&PostApduRequest { data }) .send() .await?; let body = response.json::<PostApduResponse>().await.unwrap(); Ok(body.data) } /// Sends an automation request via the API. pub async fn automation(&self, rules: &[AutomationRule<'_>]) -> Result<(), SpeculosError> { let response = self .client .post(format!("http://localhost:{}/automation", self.port)) .json(&PostAutomationRequest { version: 1, rules }) .send() .await?; response.error_for_status()?; Ok(()) } } impl Drop for SpeculosClient { fn drop(&mut self) { let _ = self.process.kill(); } } impl DeviceModel { /// Gets the model slug to be used on Speculos. pub const fn slug(&self) -> &'static str { match self { Self::Nanos => "nanos", Self::Nanox => "nanox", Self::Nanosp => "nanosp", Self::Blue => "blue", Self::Stax => "stax", Self::Flex => "flex", } } } impl<'a> Serialize for AutomationCondition<'a> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let mut seq = serializer.serialize_seq(Some(2))?; seq.serialize_element(&self.varname)?; seq.serialize_element(&self.value)?; seq.end() } } impl<'a> Serialize for AutomationAction<'a> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match self { Self::Button { button, pressed } => { let mut seq = serializer.serialize_seq(Some(3))?; seq.serialize_element("button")?; seq.serialize_element(&match button { Button::Left => 1, Button::Right => 2, })?; seq.serialize_element(pressed)?; seq.end() } Self::Finger { x, y, touched } => { let mut seq = serializer.serialize_seq(Some(4))?; seq.serialize_element("finger")?; seq.serialize_element(&x)?; seq.serialize_element(&y)?; seq.serialize_element(touched)?; seq.end() } Self::Setbool { varname, value } => { let mut seq = serializer.serialize_seq(Some(3))?; seq.serialize_element("setbool")?; seq.serialize_element(varname)?; seq.serialize_element(value)?; seq.end() } Self::Exit => { let mut seq = serializer.serialize_seq(Some(1))?; seq.serialize_element("exit")?; seq.end() } } } } impl From<std::io::Error> for SpeculosError { fn from(value: std::io::Error) -> Self { Self::IoError(value) } } impl From<reqwest::Error> for SpeculosError { fn from(value: reqwest::Error) -> Self { Self::ReqwestError(value) } } impl Display for SpeculosError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::IoError(error) => write!(f, "{}", error), Self::ReqwestError(error) => write!(f, "{}", error), } } } impl Error for SpeculosError {}
xJonathanLEI/speculos-client
0
Speculos client written in Rust for Ledger integration testing
Rust
xJonathanLEI
Jonathan LEI
src/cli.rs
Rust
use clap::{builder::TypedValueParser, error::ErrorKind, Arg, Command, Error}; use url::Url; #[derive(Debug, Clone)] pub enum UpstreamSpec { Raw(Url), Dns(DnsSpec), } #[derive(Debug, Clone)] pub struct DnsSpec { pub host_port: String, pub path: String, } #[derive(Clone)] pub struct UpstreamSpecParser; impl TypedValueParser for UpstreamSpecParser { type Value = UpstreamSpec; fn parse_ref( &self, cmd: &Command, _arg: Option<&Arg>, value: &std::ffi::OsStr, ) -> Result<Self::Value, Error> { match value.to_str() { Some(raw) => match raw.strip_prefix("dns:") { Some(dns) => { let (host_port, path) = match dns.find('/') { Some(ind_slash) => (&dns[0..ind_slash], &dns[ind_slash..]), None => (dns, "/"), }; let host_port = if host_port.contains(':') { host_port.to_owned() } else { // Default Starknet RPC port: 9545 format!("{}:9545", host_port) }; Ok(UpstreamSpec::Dns(DnsSpec { host_port, path: path.to_owned(), })) } None => Ok(UpstreamSpec::Raw(Url::parse(raw).map_err(|_| { cmd.clone().error(ErrorKind::InvalidValue, "invalid url") })?)), }, None => Err(cmd .clone() .error(ErrorKind::InvalidValue, "invalid utf-8 spec")), } } }
xJonathanLEI/starknet-lb
4
Pending block-aware Starknet-native RPC load balancer
Rust
xJonathanLEI
Jonathan LEI
src/head.rs
Rust
use std::cmp::Ordering; #[derive(Debug, Clone, Copy)] pub enum ChainHead { Confirmed(ConfirmedHead), Pending(PendingHead), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ConfirmedHead { pub height: u64, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PendingHead { pub height: u64, pub tx_count: usize, } impl Eq for ChainHead {} impl PartialEq<ChainHead> for ChainHead { fn eq(&self, other: &ChainHead) -> bool { match (self, other) { (Self::Confirmed(left), Self::Confirmed(right)) => left == right, (Self::Confirmed(left), Self::Pending(right)) => left == right, (Self::Pending(left), Self::Confirmed(right)) => left == right, (Self::Pending(left), Self::Pending(right)) => left == right, } } } impl Ord for ChainHead { fn cmp(&self, other: &Self) -> Ordering { match (self, other) { (Self::Confirmed(left), Self::Confirmed(right)) => left.cmp(right), // Workaround for not having `Ord` between types. This is safe. See: // // https://users.rust-lang.org/t/implement-ord-to-compare-different-types/73106 (Self::Confirmed(left), Self::Pending(right)) => unsafe { left.partial_cmp(right).unwrap_unchecked() }, // Workaround for not having `Ord` between types. This is safe. See: // // https://users.rust-lang.org/t/implement-ord-to-compare-different-types/73106 (Self::Pending(left), Self::Confirmed(right)) => unsafe { left.partial_cmp(right).unwrap_unchecked() }, (Self::Pending(left), Self::Pending(right)) => left.cmp(right), } } } impl PartialOrd<ChainHead> for ChainHead { fn partial_cmp(&self, other: &ChainHead) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq<ConfirmedHead> for PendingHead { fn eq(&self, other: &ConfirmedHead) -> bool { self.tx_count == 0 && self.height == other.height + 1 } } impl PartialEq<PendingHead> for ConfirmedHead { fn eq(&self, other: &PendingHead) -> bool { other.tx_count == 0 && other.height == self.height + 1 } } impl Ord for ConfirmedHead { fn cmp(&self, other: &Self) -> Ordering { self.height.cmp(&other.height) } } impl PartialOrd<ConfirmedHead> for ConfirmedHead { fn partial_cmp(&self, other: &ConfirmedHead) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for PendingHead { fn cmp(&self, other: &Self) -> Ordering { match self.height.cmp(&other.height) { Ordering::Equal => self.tx_count.cmp(&other.tx_count), ordering => ordering, } } } impl PartialOrd<PendingHead> for PendingHead { fn partial_cmp(&self, other: &PendingHead) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialOrd<ConfirmedHead> for PendingHead { fn partial_cmp(&self, other: &ConfirmedHead) -> Option<Ordering> { Some(match self.height.cmp(&(other.height + 1)) { Ordering::Equal => { if self.tx_count == 0 { Ordering::Equal } else { Ordering::Greater } } ordering => ordering, }) } } impl PartialOrd<PendingHead> for ConfirmedHead { fn partial_cmp(&self, other: &PendingHead) -> Option<Ordering> { Some(match (self.height + 1).cmp(&other.height) { Ordering::Equal => { if other.tx_count == 0 { Ordering::Equal } else { Ordering::Less } } ordering => ordering, }) } }
xJonathanLEI/starknet-lb
4
Pending block-aware Starknet-native RPC load balancer
Rust
xJonathanLEI
Jonathan LEI
src/load_balancer.rs
Rust
use anyhow::Result; use reqwest::Client; use crate::upstream_store::UpstreamStore; pub struct LoadBalancer { store: UpstreamStore, http_client: Client, } impl LoadBalancer { pub fn new(store: UpstreamStore) -> Self { Self { store, http_client: Client::new(), } } pub async fn route(&self, request: String) -> Result<String> { match self.store.get_upstream() { Some(endpoint) => Ok(self .http_client .post(endpoint) .header("Content-Type", "application/json") .body(request) .send() .await? .text() .await?), None => Err(anyhow::anyhow!("no available upstream")), } } }
xJonathanLEI/starknet-lb
4
Pending block-aware Starknet-native RPC load balancer
Rust
xJonathanLEI
Jonathan LEI
src/main.rs
Rust
use std::{sync::Arc, time::Duration}; use anyhow::Result; use axum::{extract::State, response::IntoResponse, routing::post, Router}; use clap::Parser; mod cli; use cli::{UpstreamSpec, UpstreamSpecParser}; mod head; mod load_balancer; use load_balancer::LoadBalancer; mod upstream_resolver; mod upstream_store; use upstream_store::UpstreamStoreManager; mod upstream_tracker; mod shutdown; /// 10 seconds. const GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10); #[derive(Debug, Parser)] struct Cli { /// Port to listen on. #[clap(long, default_value = "9546")] port: u16, /// Upstream JSON-RPC endpoints. #[clap(long = "upstream", value_parser = UpstreamSpecParser)] upstreams: Vec<UpstreamSpec>, } #[tokio::main] async fn main() -> Result<()> { let cli = Cli::parse(); let (store, store_shutdown) = UpstreamStoreManager::new().start(cli.upstreams)?; let load_balancer = LoadBalancer::new(store); let axum_app = Router::new() .route("/", post(proxy)) // TOOD: implement actual multi-version support .route("/rpc/v0_7", post(proxy)) .route("/rpc/v0_8", post(proxy)) .with_state(Arc::new(load_balancer)); let axum_listener = tokio::net::TcpListener::bind(("0.0.0.0", cli.port)).await?; let mut sigterm_handle = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; let ctrl_c_handle = tokio::signal::ctrl_c(); println!("Listening on 0.0.0.0:{}", cli.port); // TODO: axum graceful shutdown tokio::select! { _ = sigterm_handle.recv() => {}, _ = ctrl_c_handle => {}, _ = axum::serve(axum_listener, axum_app) => {}, } tokio::select! { _ = tokio::time::sleep(GRACEFUL_SHUTDOWN_TIMEOUT) => { anyhow::bail!("timeout waiting for graceful shutdown"); }, _ = store_shutdown.shutdown() => {}, } Ok(()) } async fn proxy(State(lb): State<Arc<LoadBalancer>>, raw_body: String) -> impl IntoResponse { // TODO: make proxy semantic-aware instead of blindly sending raw text // TODO: proper error handling match lb.route(raw_body).await { Ok(value) => ( [(axum::http::header::CONTENT_TYPE, "application/json")], value, ), Err(err) => ( [(axum::http::header::CONTENT_TYPE, "text/plain")], err.to_string(), ), } }
xJonathanLEI/starknet-lb
4
Pending block-aware Starknet-native RPC load balancer
Rust
xJonathanLEI
Jonathan LEI
src/shutdown.rs
Rust
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender}; use tokio_util::sync::CancellationToken; pub struct ShutdownHandle { cancel_signal: CancellationToken, finish_handle: UnboundedReceiver<()>, } pub struct FinishSignal { sender: UnboundedSender<()>, } impl ShutdownHandle { pub fn new() -> (Self, FinishSignal) { let cancel_signal = CancellationToken::new(); let (finish_sender, finish_receiver) = tokio::sync::mpsc::unbounded_channel(); ( Self { cancel_signal, finish_handle: finish_receiver, }, FinishSignal { sender: finish_sender, }, ) } pub fn cancellation_token(&self) -> CancellationToken { self.cancel_signal.clone() } pub async fn shutdown(mut self) { self.cancel_signal.cancel(); self.finish_handle.recv().await; } } impl FinishSignal { pub fn finish(&self) { self.sender.send(()).unwrap(); } }
xJonathanLEI/starknet-lb
4
Pending block-aware Starknet-native RPC load balancer
Rust
xJonathanLEI
Jonathan LEI
src/upstream_resolver.rs
Rust
use std::time::Duration; use anyhow::Result; use tokio::{net::lookup_host, sync::mpsc::UnboundedSender}; use url::Url; use crate::{ cli::UpstreamSpec, shutdown::ShutdownHandle, upstream_store::{UpstreamId, UpstreamResolvedEvent, UpstreamStoreManagerEvent}, }; const RESOLVER_POLL_INTERVAL: Duration = Duration::from_secs(1); pub struct UpstreamResolver { upstream_specs: Vec<UpstreamSpec>, resolved_upstreams: Vec<UpstreamId>, channel: UnboundedSender<UpstreamStoreManagerEvent>, } impl UpstreamResolver { pub fn new( upstream_specs: Vec<UpstreamSpec>, channel: UnboundedSender<UpstreamStoreManagerEvent>, ) -> Self { Self { upstream_specs, resolved_upstreams: vec![], channel, } } pub fn start(mut self) -> ShutdownHandle { let (shutdown_handle, finish_handle) = ShutdownHandle::new(); let cancellation_token = shutdown_handle.cancellation_token(); tokio::spawn(async move { self.run_once().await; loop { tokio::select! { _ = cancellation_token.cancelled() => { finish_handle.finish(); break; }, _ = tokio::time::sleep(RESOLVER_POLL_INTERVAL) => { self.run_once().await; }, } } }); shutdown_handle } async fn run_once(&mut self) { if let Err(err) = self.run_inner().await { // TODO: log properly eprintln!("Resolver error: {}", err); } } async fn run_inner(&mut self) -> Result<()> { let mut latest_upstreams: Vec<UpstreamId> = vec![]; for spec in self.upstream_specs.iter() { match spec { UpstreamSpec::Raw(url) => latest_upstreams.push(url.to_owned().into()), UpstreamSpec::Dns(dns_spec) => match lookup_host(&dns_spec.host_port).await { Ok(resolution) => { for name in resolution { latest_upstreams.push( Url::parse(&format!("http://{}{}", name, dns_spec.path))?.into(), ) } } Err(_) => { // This can happen in Kubernetes when the upstream headless service is still // being deployed. It should be safe to ignore during deployment. // // Nevertheless, a warning is still printed for visibility. eprintln!("Warning: cannot resolve DNS name: {}", dns_spec.host_port); } }, } } // The assumption here is that the upstream list is probably quite small, so using a `Vec` // should be faster than `HashSet` diffing. In any case the perf difference should // benegligible. let mut addition = vec![]; let mut removal = vec![]; let mut updated_list = vec![]; while let Some(existing_upstream) = self.resolved_upstreams.pop() { if !latest_upstreams .iter() .any(|latest| existing_upstream.endpoint == latest.endpoint) { removal.push(existing_upstream); } else { updated_list.push(existing_upstream); } } while let Some(latest_upstream) = latest_upstreams.pop() { if !updated_list .iter() .any(|existing| existing == &latest_upstream) { addition.push(latest_upstream.clone()); updated_list.push(latest_upstream); } } if !addition.is_empty() || !removal.is_empty() { let _ = self .channel .send(UpstreamStoreManagerEvent::UpstreamResolved( UpstreamResolvedEvent { addition, removal }, )); } self.resolved_upstreams = updated_list; Ok(()) } }
xJonathanLEI/starknet-lb
4
Pending block-aware Starknet-native RPC load balancer
Rust
xJonathanLEI
Jonathan LEI
src/upstream_store.rs
Rust
use std::{collections::HashMap, iter::once, sync::Arc}; use anyhow::Result; use arc_swap::ArcSwap; use rand::{thread_rng, Rng}; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender}; use url::Url; use crate::{ cli::UpstreamSpec, head::ChainHead, shutdown::{FinishSignal, ShutdownHandle}, upstream_resolver::UpstreamResolver, upstream_tracker::UpstreamTracker, }; pub struct UpstreamStoreManager { event_sender: UnboundedSender<UpstreamStoreManagerEvent>, event_receiver: UnboundedReceiver<UpstreamStoreManagerEvent>, store: UpstreamStore, tracker_handles: HashMap<UpstreamId, ShutdownHandle>, } #[derive(Clone)] pub struct UpstreamStore { upstreams: Arc<ArcSwap<Vec<Upstream>>>, } pub enum UpstreamStoreManagerEvent { NewHead, UpstreamResolved(UpstreamResolvedEvent), } pub struct UpstreamResolvedEvent { pub addition: Vec<UpstreamId>, pub removal: Vec<UpstreamId>, } #[derive(Debug, Clone)] pub struct Upstream { pub id: UpstreamId, pub head: Arc<ArcSwap<Option<ChainHead>>>, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct UpstreamId { pub endpoint: Url, } impl UpstreamStoreManager { pub fn new() -> Self { let (head_sender, head_receiver) = tokio::sync::mpsc::unbounded_channel(); Self { event_sender: head_sender, event_receiver: head_receiver, store: UpstreamStore { upstreams: Arc::new(ArcSwap::from_pointee(vec![])), }, tracker_handles: HashMap::new(), } } pub fn start( mut self, upstream_specs: Vec<UpstreamSpec>, ) -> Result<(UpstreamStore, ShutdownHandle)> { let store = self.store.clone(); let resolver = UpstreamResolver::new(upstream_specs, self.event_sender.clone()); let resolver_handle = resolver.start(); let (shutdown_handle, finish_handle) = ShutdownHandle::new(); let cancellation_token = shutdown_handle.cancellation_token(); // TODO: implement a way to detect readiness, as currently the app starts up with no // available upstreams and will fail first few requests. tokio::spawn(async move { loop { tokio::select! { _ = cancellation_token.cancelled() => { self.shutdown(resolver_handle, finish_handle).await; break; } Some(event) = self.event_receiver.recv() => { self.handle_event(event).await; }, } } }); Ok((store, shutdown_handle)) } async fn handle_event(&mut self, event: UpstreamStoreManagerEvent) { match event { UpstreamStoreManagerEvent::NewHead => { // TODO: use this as a tick to build cache. } UpstreamStoreManagerEvent::UpstreamResolved(event) => { let mut updated_upstreams = vec![]; for upstream_id in event.addition { println!("Adding a new upstream: {}", upstream_id.endpoint); let upstream_head = Arc::new(ArcSwap::from_pointee(None)); let endpoint = upstream_id.endpoint.clone(); updated_upstreams.push(Upstream { id: upstream_id.clone(), head: upstream_head.clone(), }); self.tracker_handles.insert( upstream_id, UpstreamTracker::new(upstream_head, endpoint, self.event_sender.clone()) .start(), ); } for existing_upstream in self.store.upstreams.load().iter() { if !event .removal .iter() .any(|to_remove| &existing_upstream.id == to_remove) { updated_upstreams.push(existing_upstream.to_owned()); } } self.store.upstreams.swap(Arc::new(updated_upstreams)); for upstream_id in event.removal { println!("Removing upstream: {}", upstream_id.endpoint); // We don't wait for trackers to finish shutting down, so it might be the case // that when `UpstreamStoreManager::shutdown()` resolves, some removed trackers // would still be running. // // If this matters in the future, add a new event type that reports tracker // shutdown progress so it can be tracked here in `UpstreamStoreManager`. match self.tracker_handles.remove(&upstream_id) { Some(handle) => { tokio::spawn(handle.shutdown()); } None => { // This should never happen and indicates a bug. However, it's probably // not worth crashing the entire load balancer just for this. eprintln!("Warning: tracker task handle not found"); } } } } } } async fn shutdown(self, resolver_handler: ShutdownHandle, finish_handle: FinishSignal) { // Wait for all background tasks to finish futures_util::future::join_all( self.tracker_handles .into_values() .map(|handle| handle.shutdown()) .chain(once(resolver_handler.shutdown())), ) .await; finish_handle.finish(); } } impl UpstreamStore { pub fn get_upstream(&self) -> Option<Url> { // TODO: make request context available to be able to route non-real-time-sensitive requests // to lagging upstreams. // TODO: use the manager event loop (currently useless) to build cache for common request // targets to avoid having to loop through all upstreams on every single request. let upstreams = self.upstreams.load(); let available = if let Some(max_head) = upstreams .iter() .filter_map(|upstream| *upstream.head.load_full()) .max() { upstreams .iter() .filter(|upstream| { upstream .head .load_full() .is_some_and(|head| head >= max_head) }) .collect::<Vec<_>>() } else { vec![] }; if available.is_empty() { None } else { let mut rng = thread_rng(); let chosen = &available[rng.gen_range(0..available.len())]; Some(chosen.id.endpoint.clone()) } } } impl From<Url> for UpstreamId { fn from(value: Url) -> Self { Self { endpoint: value } } }
xJonathanLEI/starknet-lb
4
Pending block-aware Starknet-native RPC load balancer
Rust
xJonathanLEI
Jonathan LEI
src/upstream_tracker.rs
Rust
use std::{sync::Arc, time::Duration}; use anyhow::Result; use arc_swap::ArcSwap; use starknet::{ core::types::{BlockId, BlockTag, MaybePendingBlockWithTxHashes}, providers::{jsonrpc::HttpTransport, JsonRpcClient, Provider}, }; use tokio::sync::mpsc::UnboundedSender; use url::Url; use crate::{ head::{ChainHead, ConfirmedHead, PendingHead}, shutdown::ShutdownHandle, upstream_store::UpstreamStoreManagerEvent, }; // TODO: make this configurable for each upstream group. const TRACKER_POLL_INTERVAL: Duration = Duration::from_secs(1); const TRACKER_POLL_TIMEOUT: Duration = Duration::from_secs(2); // TODO: support block stream subscription via WebSocket instead of polling pub struct UpstreamTracker { head: Arc<ArcSwap<Option<ChainHead>>>, client: JsonRpcClient<HttpTransport>, channel: UnboundedSender<UpstreamStoreManagerEvent>, } impl UpstreamTracker { pub fn new( head: Arc<ArcSwap<Option<ChainHead>>>, rpc_url: Url, channel: UnboundedSender<UpstreamStoreManagerEvent>, ) -> Self { Self { head, client: JsonRpcClient::new(HttpTransport::new_with_client( rpc_url, reqwest::ClientBuilder::new() .timeout(TRACKER_POLL_TIMEOUT) .build() .unwrap(), )), channel, } } pub fn start(self) -> ShutdownHandle { let (shutdown_handle, finish_handle) = ShutdownHandle::new(); let cancellation_token = shutdown_handle.cancellation_token(); tokio::spawn(async move { self.run_once().await; loop { tokio::select! { _ = cancellation_token.cancelled() => { finish_handle.finish(); break; }, _ = tokio::time::sleep(TRACKER_POLL_INTERVAL) => { self.run_once().await; }, } } }); shutdown_handle } async fn run_once(&self) { if let Err(err) = self.run_inner().await { // TODO: log properly eprintln!("Tracker error: {}", err); } } async fn run_inner(&self) -> Result<()> { let new_head = match self .client .get_block_with_tx_hashes(BlockId::Tag(BlockTag::Pending)) .await? { MaybePendingBlockWithTxHashes::Block(block_with_tx_hashes) => { ChainHead::Confirmed(ConfirmedHead { height: block_with_tx_hashes.block_number, }) } MaybePendingBlockWithTxHashes::PendingBlock(pending_block_with_tx_hashes) => { // TODO: maintain headers internally to be able to _actually_ check longest chain, // as this pending block could be on an abandoned fork. let pending_height = match self .client .get_block_with_tx_hashes(BlockId::Hash( pending_block_with_tx_hashes.parent_hash, )) .await? { MaybePendingBlockWithTxHashes::Block(block_with_tx_hashes) => { block_with_tx_hashes.block_number + 1 } MaybePendingBlockWithTxHashes::PendingBlock(_) => { anyhow::bail!("unexpected pending block") } }; ChainHead::Pending(PendingHead { height: pending_height, tx_count: pending_block_with_tx_hashes.transactions.len(), }) } }; self.head.store(Arc::new(Some(new_head))); let _ = self.channel.send(UpstreamStoreManagerEvent::NewHead); Ok(()) } }
xJonathanLEI/starknet-lb
4
Pending block-aware Starknet-native RPC load balancer
Rust
xJonathanLEI
Jonathan LEI
scripts/build_bench_wasm.sh
Shell
#!/usr/bin/env bash # Make sure `wasm32-wasi` target and `cargo-wasi` are installed set -e function generate_wasm() { cargo wasi build --bench=$1 --release cp $(ls -t $REPO_ROOT/target/wasm32-wasi/release/deps/$1*.rustc.wasm | head -n 1) $REPO_ROOT/target/bench-wasm/$1.wasm } SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) REPO_ROOT=$( dirname -- $SCRIPT_DIR ) rm -rf $REPO_ROOT/target/bench-wasm mkdir -p $REPO_ROOT/target/bench-wasm cd $REPO_ROOT/veedo-core benches=( compute_100k_iterations inverse_100k_iterations ) for bench in ${benches[@]}; do generate_wasm $bench done
xJonathanLEI/veedo-rs
2
Rust implementation of VeeDo, a STARK-based Verifiable Delay Function
Rust
xJonathanLEI
Jonathan LEI
scripts/run_bench_wasm.sh
Shell
#!/usr/bin/env bash # Build benchmark wasm artifacts with `build_bench_wasm.sh` first set -e SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) REPO_ROOT=$( dirname -- $SCRIPT_DIR ) RUNTIME="$1" if [ -z "$RUNTIME" ]; then echo "Runtime not specified" exit 1 fi benches=( compute_100k_iterations inverse_100k_iterations ) for bench in ${benches[@]}; do if [[ "$RUNTIME" == "wasmtime" ]]; then # https://github.com/bytecodealliance/wasmtime/issues/7384 $RUNTIME run --dir=. -- $REPO_ROOT/target/bench-wasm/$bench.wasm --bench else $RUNTIME run --dir=. $REPO_ROOT/target/bench-wasm/$bench.wasm -- --bench fi done
xJonathanLEI/veedo-rs
2
Rust implementation of VeeDo, a STARK-based Verifiable Delay Function
Rust
xJonathanLEI
Jonathan LEI
veedo-codegen/src/lib.rs
Rust
use std::fmt::Write; use proc_macro::TokenStream; use ruint::aliases::U256; use sha2::{Digest, Sha256}; use veedo_ff::{FieldElement, PRIME}; const N_STATE: u64 = 2; const N_COLS: u64 = 10; const LENGTH: u64 = 256; const FIELD_ELEMENT: &str = "::veedo_ff::FieldElement"; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum CubeRootOperation { Square, Multiplication, } #[proc_macro] pub fn round_constants(_input: TokenStream) -> TokenStream { let mut output = String::new(); write_round_constants(&mut output).unwrap(); output.parse().unwrap() } #[proc_macro] pub fn mds_matrix(_input: TokenStream) -> TokenStream { let mut output = String::new(); write_mds_matrix(&mut output).unwrap(); output.parse().unwrap() } #[proc_macro] pub fn fn_cube_root(_input: TokenStream) -> TokenStream { let mut output = String::new(); write_fn_cube_root(&mut output).unwrap(); output.parse().unwrap() } fn write_round_constants(buf: &mut String) -> std::fmt::Result { let constants = generate_constants(); writeln!( buf, "pub const ROUND_CONSTANTS: [[{}; 2]; {}] = [", FIELD_ELEMENT, constants.len() )?; for constant in constants { let x_raw = constant.0 .0 .0; let y_raw = constant.1 .0 .0; writeln!(buf, " [")?; writeln!( buf, " {}::new_unchecked(::veedo_ff::BigInteger128::new({:?})),", FIELD_ELEMENT, x_raw )?; writeln!( buf, " {}::new_unchecked(::veedo_ff::BigInteger128::new({:?})),", FIELD_ELEMENT, y_raw )?; writeln!(buf, " ],")?; } writeln!(buf, "];")?; Ok(()) } fn write_mds_matrix(buf: &mut String) -> std::fmt::Result { let matrix = [ [ FieldElement::from(0x9adea15e459e2a62c3166a2a2054c3d_u128), FieldElement::from(0x187ccb0e2b63d835f7cf33d7555ca95d_u128), ], [ FieldElement::from(0x1da2b56d14370ab50833f82f3966c9d7_u128), FieldElement::from(0x207e36a32b1da58011ae276251516aa4_u128), ], ]; // Also generate the inverse matrix. let inverse_matrix = [ [ matrix[1][1] / (matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]), matrix[0][1] / (matrix[0][1] * matrix[1][0] - matrix[0][0] * matrix[1][1]), ], [ matrix[1][0] / (matrix[0][1] * matrix[1][0] - matrix[0][0] * matrix[1][1]), matrix[0][0] / (matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]), ], ]; for (name, matrix) in [ ("MDS_MATRIX", matrix), ("MDS_MATRIX_INVERSE", inverse_matrix), ] { writeln!(buf, "pub const {}: [[{}; 2]; 2] = [", name, FIELD_ELEMENT)?; for vector in matrix.iter() { let x_raw = vector[0].0 .0; let y_raw = vector[1].0 .0; writeln!(buf, " [")?; writeln!( buf, " {}::new_unchecked(::veedo_ff::BigInteger128::new({:?})),", FIELD_ELEMENT, x_raw )?; writeln!( buf, " {}::new_unchecked(::veedo_ff::BigInteger128::new({:?})),", FIELD_ELEMENT, y_raw )?; writeln!(buf, " ],")?; } writeln!(buf, "];")?; } Ok(()) } #[allow(clippy::assertions_on_constants)] fn write_fn_cube_root(buf: &mut String) -> std::fmt::Result { const POW: u128 = (2 * PRIME - 1) / 3; assert!(POW != 0, "exponent must not be zero"); const POW_LIMBS: [u64; 2] = [POW as u64, (POW >> 64) as u64]; let mut ops = vec![]; let mut square_count = 0; let mut multiply_count = 0; for bit in veedo_ff::BitIteratorBE::without_leading_zeros(POW_LIMBS).skip(1) { ops.push(CubeRootOperation::Square); square_count += 1; if bit { ops.push(CubeRootOperation::Multiplication); multiply_count += 1; } } writeln!(buf, "#[inline(always)]")?; writeln!(buf, "/// Finds cube root of a field element.")?; writeln!(buf, "///")?; writeln!( buf, "/// The function is unrolled at compile time to save the runtime iteration \ over exponent bits. It contains {} squaring and {} multiplication operations.", square_count, multiply_count )?; writeln!( buf, "pub fn cube_root(x: &{}) -> {} {{", FIELD_ELEMENT, FIELD_ELEMENT, )?; // This optimization is possible due to non-zero exp. writeln!(buf, " let mut res = *x;")?; for op in ops { match op { CubeRootOperation::Square => writeln!(buf, " res.square_in_place();")?, CubeRootOperation::Multiplication => writeln!(buf, " res *= x;")?, } } writeln!(buf, " res")?; writeln!(buf, "}}")?; Ok(()) } fn generate_constants() -> Vec<(FieldElement, FieldElement)> { let mut constant_seq = vec![]; for idx in 0..LENGTH { for col in 0..N_COLS { for state in 0..N_STATE { let mut hasher = Sha256::new(); hasher.update(format!("Veedo_{}_{}_{}", state, col, idx)); let hash: [u8; 32] = hasher.finalize().into(); let item = U256::from_be_bytes(hash); let item: u128 = (item % U256::from(PRIME)).try_into().unwrap(); constant_seq.push(item); } } } constant_seq .chunks_exact(2) .map(|chunk| (FieldElement::from(chunk[0]), FieldElement::from(chunk[1]))) .collect() }
xJonathanLEI/veedo-rs
2
Rust implementation of VeeDo, a STARK-based Verifiable Delay Function
Rust
xJonathanLEI
Jonathan LEI
veedo-core/benches/compute_100k_iterations.rs
Rust
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use veedo_core::compute_delay_function; pub fn criterion_benchmark(c: &mut Criterion) { c.bench_function("compute_100k_iterations", |b| { b.iter(|| { black_box(compute_delay_function(100_000, 1, 1)); }); }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
xJonathanLEI/veedo-rs
2
Rust implementation of VeeDo, a STARK-based Verifiable Delay Function
Rust
xJonathanLEI
Jonathan LEI
veedo-core/benches/inverse_100k_iterations.rs
Rust
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use veedo_core::inverse_delay_function; pub fn criterion_benchmark(c: &mut Criterion) { c.bench_function("inverse_100k_iterations", |b| { b.iter(|| { black_box(inverse_delay_function( 100_000, 0x211dadda75e061abcecee71984cff62e_u128, 0xc6b3e7be7a6b9627af264ab9a2e5ce5_u128, )); }); }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
xJonathanLEI/veedo-rs
2
Rust implementation of VeeDo, a STARK-based Verifiable Delay Function
Rust
xJonathanLEI
Jonathan LEI
veedo-core/src/compute_multi_thread.rs
Rust
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use veedo_ff::{BigInteger128, FieldElement}; use crate::{ constants::{MDS_MATRIX, ROUND_CONSTANTS}, utils::cube_root, }; /// The computation thread state that's shared between the 2 worker threads. /// /// Two slots are used as it's possible for one thread to have the next cube root ready before the /// other thread has even consumed the current root. With just one slot, the current thread would /// then have to check whether the existing value has been consumed by the other thread or not, /// adding overhead to the synchronization. /// /// Having more than 2 slots would not add any performance benefit, as it's impossible for one /// thread to get ahead of the other by more than one slot due to the matrix multiplication step. #[derive(Debug, Clone)] struct SyncState<'a> { even_root: &'a AtomicFieldElement, odd_root: &'a AtomicFieldElement, count: &'a AtomicUsize, } /// A [`FieldElement`] value backed by two [`AtomicU64`] fields to be used in the thread /// synchronization context. #[derive(Debug, Default)] struct AtomicFieldElement { low: AtomicU64, high: AtomicU64, } pub fn compute_delay_function(n_iters: usize, x: u128, y: u128) -> (FieldElement, FieldElement) { let x_montgomery = FieldElement::from(x); let y_montgomery = FieldElement::from(y); let x_state = SyncState { even_root: &AtomicFieldElement::default(), odd_root: &AtomicFieldElement::default(), count: &AtomicUsize::new(0), }; let y_state = SyncState { even_root: &AtomicFieldElement::default(), odd_root: &AtomicFieldElement::default(), count: &AtomicUsize::new(0), }; std::thread::scope(|s| { let x_thread = s.spawn(|| compute_in_thread::<0>(n_iters, x_montgomery, &x_state, &y_state)); let y_thread = s.spawn(|| compute_in_thread::<1>(n_iters, y_montgomery, &y_state, &x_state)); // Joining never fails as the computation threads never panic. let x = unsafe { x_thread.join().unwrap_unchecked() }; let y = unsafe { y_thread.join().unwrap_unchecked() }; (x, y) }) } #[inline(always)] fn compute_in_thread<const SLOT: usize>( n_iters: usize, init_value: FieldElement, current_state: &SyncState, other_state: &SyncState, ) -> FieldElement { let mut current = init_value; let mut count = 0; for round_constant in ROUND_CONSTANTS.iter().cycle().take(n_iters) { // Compute cube root. This is the most expensive part of the iteration. current = cube_root(&current); count += 1; let is_even = count % 2 == 0; // There's no need to make sure the other thread has already read the slot, as it's simply // impossible for the current thread to be 2 slots ahead of the other. let current_root = if is_even { current_state.even_root } else { current_state.odd_root }; current_root.low.store(current.0 .0[0], Ordering::Release); current_root.high.store(current.0 .0[1], Ordering::Release); current_state.count.store(count, Ordering::Release); // Finish half of the matrix multiplication and constant addition steps which do not depend // on the other thread. current = current * MDS_MATRIX[SLOT][SLOT] + round_constant[SLOT]; // Wait for the state value from the other thread let other = { loop { if other_state.count.load(Ordering::Acquire) >= count { break; } } let other_root = if is_even { other_state.even_root } else { other_state.odd_root }; FieldElement::new_unchecked(BigInteger128::new([ other_root.low.load(Ordering::Acquire), other_root.high.load(Ordering::Acquire), ])) }; // Finish the round by completing the other half of the matrix multiplication. current += other * if SLOT == 0 { MDS_MATRIX[0][1] } else { MDS_MATRIX[1][0] }; } current }
xJonathanLEI/veedo-rs
2
Rust implementation of VeeDo, a STARK-based Verifiable Delay Function
Rust
xJonathanLEI
Jonathan LEI
veedo-core/src/compute_single_thread.rs
Rust
use veedo_ff::FieldElement; use crate::constants::{MDS_MATRIX_INVERSE, ROUND_CONSTANTS}; #[cfg(target_arch = "wasm32")] pub fn compute_delay_function(n_iters: usize, x: u128, y: u128) -> (FieldElement, FieldElement) { use crate::{constants::MDS_MATRIX, utils::cube_root}; let (mut x, mut y) = (FieldElement::from(x), FieldElement::from(y)); for round_constant in ROUND_CONSTANTS.iter().cycle().take(n_iters) { // Compute cube root. (x, y) = (cube_root(&x), cube_root(&y)); // Multiply with the matrix and add constants. (x, y) = ( x * MDS_MATRIX[0][0] + y * MDS_MATRIX[0][1] + round_constant[0], x * MDS_MATRIX[1][0] + y * MDS_MATRIX[1][1] + round_constant[1], ); } (x, y) } pub fn inverse_delay_function(n_iters: usize, x: u128, y: u128) -> (FieldElement, FieldElement) { let (mut x, mut y) = (FieldElement::from(x), FieldElement::from(y)); for round_constant in ROUND_CONSTANTS .iter() .rev() .cycle() .skip(ROUND_CONSTANTS.len() - (n_iters % ROUND_CONSTANTS.len())) .take(n_iters) { // Undo round constant addition. (x, y) = (x - round_constant[0], y - round_constant[1]); // Undo matrix multiplication. (x, y) = ( x * MDS_MATRIX_INVERSE[0][0] + y * MDS_MATRIX_INVERSE[0][1], x * MDS_MATRIX_INVERSE[1][0] + y * MDS_MATRIX_INVERSE[1][1], ); // Undo cube root. (x, y) = (x * x * x, y * y * y); } (x, y) }
xJonathanLEI/veedo-rs
2
Rust implementation of VeeDo, a STARK-based Verifiable Delay Function
Rust
xJonathanLEI
Jonathan LEI
veedo-core/src/constants.rs
Rust
veedo_codegen::round_constants!(); veedo_codegen::mds_matrix!();
xJonathanLEI/veedo-rs
2
Rust implementation of VeeDo, a STARK-based Verifiable Delay Function
Rust
xJonathanLEI
Jonathan LEI
veedo-core/src/lib.rs
Rust
mod constants; mod utils; #[cfg(not(target_arch = "wasm32"))] mod compute_multi_thread; mod compute_single_thread; #[cfg(not(target_arch = "wasm32"))] pub use compute_multi_thread::compute_delay_function; #[cfg(target_arch = "wasm32")] pub use compute_single_thread::compute_delay_function; // The inverse function is so fast that with a state size of 2, the threading overhead exceeds the // benefit from parallelization. Therefore, the single-threaded implementation is always used even // when threading is available. pub use compute_single_thread::inverse_delay_function; #[cfg(test)] mod tests { use veedo_ff::FieldElement; use super::*; #[test] #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] fn test_compute_delay_function() { let res = compute_delay_function(40960, 1, 1); assert_eq!( res.0, FieldElement::from(0xbb0f72c981ff840c10857b5af871006_u128), "Wrong x value" ); assert_eq!( res.1, FieldElement::from(0xefccc63f8534a514165c22a32bf0911_u128), "Wrong y value" ); } #[test] #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] fn test_compute_delay_function_with_initial_state() { let res = compute_delay_function( 20480, 0x28d5eafa6da4b52d946184fc5cb5aa8a_u128, 0xeacfd8b416443d9a3f8e8d7c4b4f492_u128, ); assert_eq!( res.0, FieldElement::from(0x17ce4ec2dcdd566b7249175175a0e77a_u128), "Wrong x value" ); assert_eq!( res.1, FieldElement::from(0x18ef1f3b87b66c371199d2e41982c9a_u128), "Wrong y value" ); } #[test] #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] fn test_inverse_delay_function() { let res = inverse_delay_function( 40960, 0xbb0f72c981ff840c10857b5af871006_u128, 0xefccc63f8534a514165c22a32bf0911_u128, ); assert_eq!(res.0, FieldElement::from(1), "Wrong x value"); assert_eq!(res.1, FieldElement::from(1), "Wrong y value"); } #[test] #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] fn test_inverse_delay_function_with_initial_state() { let res = inverse_delay_function( 20480, 0x17ce4ec2dcdd566b7249175175a0e77a_u128, 0x18ef1f3b87b66c371199d2e41982c9a_u128, ); assert_eq!( res.0, FieldElement::from(0x28d5eafa6da4b52d946184fc5cb5aa8a_u128), "Wrong x value" ); assert_eq!( res.1, FieldElement::from(0xeacfd8b416443d9a3f8e8d7c4b4f492_u128), "Wrong y value" ); } }
xJonathanLEI/veedo-rs
2
Rust implementation of VeeDo, a STARK-based Verifiable Delay Function
Rust
xJonathanLEI
Jonathan LEI
veedo-core/src/utils.rs
Rust
use veedo_ff::Field; veedo_codegen::fn_cube_root!();
xJonathanLEI/veedo-rs
2
Rust implementation of VeeDo, a STARK-based Verifiable Delay Function
Rust
xJonathanLEI
Jonathan LEI
veedo-ff/src/lib.rs
Rust
use ark_ff::fields::{Fp128, MontBackend, MontConfig}; pub use ark_ff::{BigInteger128, BitIteratorBE, Field}; pub const PRIME: u128 = 0x30000003000000010000000000000001; #[derive(MontConfig)] #[modulus = "63802944035360449460622495747797942273"] #[generator = "3"] pub struct FrConfig; pub type FieldElement = Fp128<MontBackend<FrConfig, 2>>;
xJonathanLEI/veedo-rs
2
Rust implementation of VeeDo, a STARK-based Verifiable Delay Function
Rust
xJonathanLEI
Jonathan LEI
benches/cs.rs
Rust
use criterion::{criterion_group, criterion_main, Criterion}; use std::sync::Mutex; use std::sync::Barrier; const THREADS: usize = 8; const ITER: usize = 2000; static BARRIER: Barrier = Barrier::new(THREADS+1); static MUTEX: Mutex<usize> = Mutex::new(0); static PARKING_LOT_MUTEX: parking_lot::Mutex<usize> = parking_lot::Mutex::new(0); static BCS_MUTEX: bcs::Mutex<usize> = bcs::Mutex::new(0); fn mutate(data: &mut usize) { *data = data.wrapping_mul(1337).isqrt().wrapping_add(7).pow(2); } fn cs_mutex() { #[inline(never)] fn iter() { BARRIER.wait(); for _ in 0..ITER { let mut guard = MUTEX.lock().unwrap(); mutate(&mut *guard); } BARRIER.wait(); } for _ in 0..THREADS { std::thread::spawn(iter); } BARRIER.wait(); BARRIER.wait(); } fn cs_parking_lot_mutex() { #[inline(never)] fn iter() { BARRIER.wait(); for _ in 0..ITER { let mut guard = PARKING_LOT_MUTEX.lock(); mutate(&mut *guard); } BARRIER.wait(); } for _ in 0..THREADS { std::thread::spawn(iter); } BARRIER.wait(); BARRIER.wait(); } fn cs_bcs_mutex() { #[inline(never)] fn iter() { BARRIER.wait(); for _ in 0..ITER { BCS_MUTEX.with(mutate); } BARRIER.wait(); } for _ in 0..THREADS { std::thread::spawn(iter); } BARRIER.wait(); BARRIER.wait(); } fn criterion_benchmark(c: &mut Criterion) { c.bench_function("mutex", |b| b.iter(|| cs_mutex())); c.bench_function("cs_parking_lot_mutex", |b| b.iter(|| cs_parking_lot_mutex())); c.bench_function("bcs_mutex", |b| b.iter(|| cs_bcs_mutex())); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
xacrimon/bcs
0
Rust
xacrimon
Joel Wejdenstål
linköping university
src/lib.rs
Rust
use std::cell::UnsafeCell; use std::hint; use std::marker::PhantomData; use std::mem::{ManuallyDrop}; use std::pin::pin; use std::ptr::{self, NonNull}; use std::sync::atomic::{self, AtomicBool, AtomicPtr, Ordering}; use std::thread::{self, Thread}; thread_local! { static TOKEN: AtomicBool = const { AtomicBool::new(false) }; } struct Parker(AtomicPtr<()>); impl Parker { fn new() -> Self { Self(AtomicPtr::new(ptr::null_mut())) } fn park(&self) { let mut b = 0; while self.0.load(Ordering::Relaxed).is_null() { b += 1; hint::spin_loop(); if b > 10 { self.park_slow(); break; } } atomic::fence(Ordering::Acquire); } #[cold] fn park_slow(&self) { let event = pin!(( UnsafeCell::new(ManuallyDrop::new(thread::current())), AtomicPtr::<()>::new(ptr::null_mut()), )); let ptr = self.0.swap( &*event as *const _ as *const () as *mut (), Ordering::Release, ); if ptr.is_null() { while event.1.load(Ordering::Relaxed).is_null() { thread::park(); } } else { unsafe { ManuallyDrop::drop(&mut *event.0.get()) }; } } fn unpark(&self) { let ptr = self.0.swap(ptr::dangling_mut(), Ordering::Release); if !ptr.is_null() { atomic::fence(Ordering::Acquire); let event = ptr as *mut (UnsafeCell<ManuallyDrop<Thread>>, AtomicPtr<()>); unsafe { let thread = ManuallyDrop::take(&mut *(*event).0.get()); (*event).1.store(ptr::dangling_mut(), Ordering::Release); thread.unpark(); } } } } struct Node<T> { next: AtomicPtr<Self>, callback: fn(*mut Self, *mut T), parker: Parker, } pub struct Mutex<T> { data: UnsafeCell<T>, tail: AtomicPtr<Node<T>>, } impl<T> Mutex<T> { pub const fn new(data: T) -> Self { Self { data: UnsafeCell::new(data), tail: AtomicPtr::new(std::ptr::null_mut()), } } pub fn with<F>(&self, f: F) where F: FnOnce(&mut T), { #[repr(C)] struct Entry<T, F> { node: Node<T>, func: ManuallyDrop<F>, _marker: PhantomData<T>, } impl<T, F> Entry<T, F> where F: FnOnce(&mut T), { fn callback(node: *mut Node<T>, data: *mut T) { unsafe { let entry = &mut *(node as *mut Entry<T, F>); let data = &mut *data; let func = ManuallyDrop::take(&mut entry.func); func(data); } } } let entry = pin!(Entry { node: Node { next: AtomicPtr::new(ptr::null_mut()), callback: Entry::<T, F>::callback, parker: Parker::new(), }, func: ManuallyDrop::new(f), _marker: PhantomData, }); self.submit(&raw const entry.node as *mut Node<T>); entry.node.parker.park(); } fn submit(&self, node: *mut Node<T>) { unsafe { (*node).next = AtomicPtr::new(node); let tail = self.tail.swap(node, Ordering::Release); if tail.is_null() { return self.process(ptr::null_mut(), node); } atomic::fence(Ordering::Acquire); if (*tail) .next .compare_exchange(tail, node, Ordering::Release, Ordering::Acquire) .is_err() { return self.process(tail, node); } } } #[cold] fn process(&self, mut unparked: *mut Node<T>, mut node: *mut Node<T>) { unsafe { loop { ((*node).callback)(node, self.data.get()); let mut next = (*node).next.load(Ordering::Acquire); if next == node { if self .tail .compare_exchange(node, ptr::null_mut(), Ordering::Release, Ordering::Relaxed) .is_ok() { (*node).parker.unpark(); return while let Some(node) = NonNull::new(unparked) { unparked = node.as_ref().next.load(Ordering::Relaxed); node.as_ref().parker.unpark(); }; } match (*node).next.compare_exchange( node, unparked, Ordering::Release, Ordering::Acquire, ) { Ok(_) => return, Err(new) => next = new, } } (*node).next.store(unparked, Ordering::Relaxed); unparked = node; node = next; } } } } unsafe impl<T: Send> Send for Mutex<T> {} unsafe impl<T: Send> Sync for Mutex<T> {}
xacrimon/bcs
0
Rust
xacrimon
Joel Wejdenstål
linköping university
derive/src/lib.rs
Rust
use proc_macro2::{Span, TokenStream}; use quote::{ToTokens, quote, quote_spanned}; use syn::{ parse::{Parse, ParseStream}, spanned::Spanned, visit_mut::VisitMut, }; use synstructure::{AddBounds, decl_derive}; fn collect_derive(s: synstructure::Structure) -> TokenStream { fn find_collect_meta(attrs: &[syn::Attribute]) -> syn::Result<Option<&syn::Attribute>> { let mut found = None; for attr in attrs { if attr.path().is_ident("collect") && found.replace(attr).is_some() { return Err(syn::parse::Error::new_spanned( attr.path(), "Cannot specify multiple `#[collect]` attributes! Consider merging them.", )); } } Ok(found) } // Deriving `Collect` must be done with care, because an implementation of `Drop` is not // necessarily safe for `Collect` types. This derive macro has three available modes to ensure // that this is safe: // 1) Require that the type be 'static with `#[collect(require_static)]`. // 2) Prohibit a `Drop` impl on the type with `#[collect(no_drop)]` // 3) Allow a custom `Drop` impl that might be unsafe with `#[collect(unsafe_drop)]`. Such // `Drop` impls must *not* access garbage collected pointers during `Drop::drop`. #[derive(PartialEq)] enum Mode { RequireStatic, NoDrop, UnsafeDrop, } let mut mode = None; let mut override_bound = None; let mut gc_lifetime = None; let mut internal = false; fn usage_error(meta: &syn::meta::ParseNestedMeta, msg: &str) -> syn::parse::Error { meta.error(format_args!( "{msg}. `#[collect(...)]` requires one mode (`require_static`, `no_drop`, or `unsafe_drop`) and optionally `bound = \"...\"`." )) } let result = match find_collect_meta(&s.ast().attrs) { Ok(Some(attr)) => attr.parse_nested_meta(|meta| { if meta.path.is_ident("bound") { if override_bound.is_some() { return Err(usage_error(&meta, "multiple bounds specified")); } let lit: syn::LitStr = meta.value()?.parse()?; override_bound = Some(lit); return Ok(()); } if meta.path.is_ident("gc_lifetime") { if gc_lifetime.is_some() { return Err(usage_error(&meta, "multiple `'gc` lifetimes specified")); } let lit: syn::Lifetime = meta.value()?.parse()?; gc_lifetime = Some(lit); return Ok(()); } if meta.path.is_ident("internal") { internal = true; return Ok(()); } meta.input.parse::<syn::parse::Nothing>()?; if mode.is_some() { return Err(usage_error(&meta, "multiple modes specified")); } else if meta.path.is_ident("require_static") { mode = Some(Mode::RequireStatic); } else if meta.path.is_ident("no_drop") { mode = Some(Mode::NoDrop); } else if meta.path.is_ident("unsafe_drop") { mode = Some(Mode::UnsafeDrop); } else { return Err(usage_error(&meta, "unknown option")); } Ok(()) }), Ok(None) => Ok(()), Err(err) => Err(err), }; if let Err(err) = result { return err.to_compile_error(); } let base = if internal { quote!(crate::dmm) } else { quote!(::tcvm::dmm) }; let Some(mode) = mode else { panic!( "{}", "deriving `Collect` requires a `#[collect(...)]` attribute" ); }; let where_clause = if mode == Mode::RequireStatic { quote!(where Self: 'static) } else { override_bound .as_ref() .map(|x| { x.parse() .expect("`#[collect]` failed to parse explicit trait bound expression") }) .unwrap_or_else(|| quote!()) }; let mut errors = vec![]; let collect_impl = if mode == Mode::RequireStatic { let mut impl_struct = s.clone(); impl_struct.add_bounds(AddBounds::None); impl_struct.gen_impl(quote! { gen unsafe impl<'gc> #base::Collect<'gc> for @Self #where_clause { const NEEDS_TRACE: bool = false; } }) } else { let mut impl_struct = s.clone(); let mut needs_trace_expr = TokenStream::new(); quote!(false).to_tokens(&mut needs_trace_expr); let mut static_bindings = vec![]; // Ignore all bindings that have `#[collect(require_static)]` For each binding with // `#[collect(require_static)]`, we push a bound of the form `FieldType: 'static` to // `static_bindings`, which will be added to the genererated `Collect` impl. The presence of // the bound guarantees that the field cannot hold any `Gc` pointers, so it's safe to ignore // that field in `needs_trace` and `trace` impl_struct.filter(|b| match find_collect_meta(&b.ast().attrs) { Ok(Some(attr)) => { let mut static_binding = false; let result = attr.parse_nested_meta(|meta| { if meta.input.is_empty() && meta.path.is_ident("require_static") { static_binding = true; static_bindings.push(b.ast().ty.clone()); Ok(()) } else { Err(meta.error("Only `#[collect(require_static)]` is supported on a field")) } }); errors.extend(result.err()); !static_binding } Ok(None) => true, Err(err) => { errors.push(err); true } }); for static_binding in static_bindings { impl_struct.add_where_predicate(syn::parse_quote! { #static_binding: 'static }); } // `#[collect(require_static)]` only makes sense on fields, not enum variants. Emit an error // if it is used in the wrong place if let syn::Data::Enum(..) = impl_struct.ast().data { for v in impl_struct.variants() { for attr in v.ast().attrs { if attr.path().is_ident("collect") { errors.push(syn::parse::Error::new_spanned( attr.path(), "`#[collect]` is not suppported on enum variants", )); } } } } // We've already called `impl_struct.filter`, so we we won't try to include `NEEDS_TRACE` // for the types of fields that have `#[collect(require_static)]` for v in impl_struct.variants() { for b in v.bindings() { let ty = &b.ast().ty; // Resolving the span at the call site makes rustc emit a 'the error originates a // derive macro note' We only use this span on tokens that need to resolve to items // (e.g. `gc_arena::Collect`), so this won't cause any hygiene issues let call_span = b.ast().span().resolved_at(Span::call_site()); quote_spanned!(call_span=> || <#ty as #base::Collect>::NEEDS_TRACE ) .to_tokens(&mut needs_trace_expr); } } // Likewise, this will skip any fields that have `#[collect(require_static)]` let trace_body = impl_struct.each(|bi| { // See the above handling of `NEEDS_TRACE` for an explanation of this let call_span = bi.ast().span().resolved_at(Span::call_site()); quote_spanned!(call_span=> { // Use a temporary variable to ensure that all tokens in the call to // `gc_arena::Collect::trace` have the same hygiene information. If we used // #bi directly, then we would have a mix of hygiene contexts, which would // cause rustc to produce sub-optimal error messagse due to its inability to // merge the spans. This is purely for diagnostic purposes, and has no effect // on correctness let bi = #bi; cc.trace(bi); } ) }); // If we have no configured `'gc` lifetime and the type has a *single* generic lifetime, use // that one. if gc_lifetime.is_none() { let mut all_lifetimes = impl_struct .ast() .generics .params .iter() .filter_map(|p| match p { syn::GenericParam::Lifetime(lt) => Some(lt), _ => None, }); if let Some(lt) = all_lifetimes.next() { if all_lifetimes.next().is_none() { gc_lifetime = Some(lt.lifetime.clone()); } else { panic!( "deriving `Collect` on a type with multiple lifetime parameters requires a `#[collect(gc_lifetime = ...)]` attribute" ); } } }; if override_bound.is_some() { impl_struct.add_bounds(AddBounds::None); } else { impl_struct.add_bounds(AddBounds::Generics); }; if let Some(gc_lifetime) = gc_lifetime { impl_struct.gen_impl(quote! { gen unsafe impl #base::Collect<#gc_lifetime> for @Self #where_clause { const NEEDS_TRACE: bool = #needs_trace_expr; #[inline] fn trace<Trace: #base::collect::Trace<#gc_lifetime>>(&self, cc: &mut Trace) { match *self { #trace_body } } } }) } else { impl_struct.gen_impl(quote! { gen unsafe impl<'gc> #base::Collect<'gc> for @Self #where_clause { const NEEDS_TRACE: bool = #needs_trace_expr; #[inline] fn trace<Trace: #base::collect::Trace<'gc>>(&self, cc: &mut Trace) { match *self { #trace_body } } } }) } }; let drop_impl = if mode == Mode::NoDrop { let mut drop_struct = s.clone(); drop_struct.add_bounds(AddBounds::None).gen_impl(quote! { gen impl #base::__MustNotImplDrop for @Self {} }) } else { quote!() }; let errors = errors.into_iter().map(|e| e.to_compile_error()); quote! { #collect_impl #drop_impl #(#errors)* } } decl_derive! { [Collect, attributes(collect)] => /// Derives the `Collect` trait needed to trace a gc type. /// /// To derive `Collect`, an additional attribute is required on the struct/enum called /// `collect`. This has several optional arguments, but the only required argument is the derive /// strategy. This can be one of /// /// - `#[collect(require_static)]` - Adds a `'static` bound, which allows for a no-op trace /// implementation. This is the ideal choice where possible. /// - `#[collect(no_drop)]` - The typical safe tracing derive strategy which only has to add a /// requirement that your struct/enum does not have a custom implementation of `Drop`. /// - `#[collect(unsafe_drop)]` - The most versatile tracing derive strategy which allows a /// custom drop implementation. However, this strategy can lead to unsoundness if care is not /// taken (see the above explanation of `Drop` interactions). /// /// The `collect` attribute also accepts a number of optional configuration settings: /// /// - `#[collect(bound = "<code>")]` - Replaces the default generated `where` clause with the /// given code. This can be an empty string to add no `where` clause, or otherwise must start /// with `"where"`, e.g., `#[collect(bound = "where T: Collect")]`. Note that this option is /// ignored for `require_static` mode since the only bound it produces is `Self: 'static`. /// Also note that providing an explicit bound in this way is safe, and only changes the trait /// bounds used to enable the implementation of `Collect`. /// /// - `#[collect(gc_lifetime = "<lifetime>")]` - the `Collect` trait requires a `'gc` lifetime /// parameter. If there is no lifetime parameter on the type, then `Collect` will be /// implemented for all `'gc` lifetimes. If there is one lifetime on the type, this is assumed /// to be the `'gc` lifetime. In the very unusual case that there are two or more lifetime /// parameters, you must specify *which* lifetime should be used as the `'gc` lifetime. /// /// Options may be passed to the `collect` attribute together, e.g., /// `#[collect(no_drop, bound = "")]`. /// /// The `collect` attribute may also be used on any field of an enum or struct, however the /// only allowed usage is to specify the strategy as `require_static` (no other strategies are /// allowed, and no optional settings can be specified). This will add a `'static` bound to the /// type of the field (regardless of an explicit `bound` setting) in exchange for not having /// to trace into the given field (the ideal choice where possible). Note that if the entire /// struct/enum is marked with `require_static` then this is unnecessary. collect_derive } // Not public API; implementation detail of `gc_arena::Rootable!`. // Replaces all `'_` lifetimes in a type by the specified named lifetime. // Syntax: `__unelide_lifetimes!('lt; SomeType)`. #[doc(hidden)] #[proc_macro] pub fn __unelide_lifetimes(input: proc_macro::TokenStream) -> proc_macro::TokenStream { struct Input { lt: syn::Lifetime, ty: syn::Type, } impl Parse for Input { fn parse(input: ParseStream) -> syn::Result<Self> { let lt: syn::Lifetime = input.parse()?; let _: syn::Token!(;) = input.parse()?; let ty: syn::Type = input.parse()?; Ok(Self { lt, ty }) } } struct UnelideLifetimes(syn::Lifetime); impl VisitMut for UnelideLifetimes { fn visit_lifetime_mut(&mut self, i: &mut syn::Lifetime) { if i.ident == "_" { *i = self.0.clone(); } } } let mut input = syn::parse_macro_input!(input as Input); UnelideLifetimes(input.lt).visit_type_mut(&mut input.ty); input.ty.to_token_stream().into() }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/allocator_api.rs
Rust
use core::{alloc::Layout, marker::PhantomData, ptr::NonNull}; use std::alloc::{AllocError, Allocator, Global}; use crate::dmm::{collect::Collect, context::Mutation, metrics::Metrics, types::Invariant}; #[derive(Clone)] pub struct MetricsAlloc<'gc, A = Global> { metrics: Metrics, allocator: A, _marker: Invariant<'gc>, } impl<'gc> MetricsAlloc<'gc> { #[inline] pub fn new(mc: &Mutation<'gc>) -> Self { Self::new_in(mc, Global) } /// `MetricsAlloc` is normally branded with the `'gc` branding lifetime to ensure that it is not /// placed in the wrong arena or used outside of the enclosing arena. /// /// This is actually completely artificial and only used as a lint: `gc_arena::metrics::Metrics` /// has no lifetime at all. Therefore, we can safely provide a method that returns a /// `MetricsAlloc` with an arbitrary lifetime. /// /// NOTE: Use `MetricsAlloc::new` if at all possible, because it is harder to misuse. #[inline] pub fn from_metrics(metrics: Metrics) -> Self { Self::from_metrics_in(metrics, Global) } } impl<'gc, A> MetricsAlloc<'gc, A> { #[inline] pub fn new_in(mc: &Mutation<'gc>, allocator: A) -> Self { Self { metrics: mc.metrics().clone(), allocator, _marker: PhantomData, } } #[inline] pub fn from_metrics_in(metrics: Metrics, allocator: A) -> Self { Self { metrics, allocator, _marker: PhantomData, } } } unsafe impl<'gc, A: Allocator> Allocator for MetricsAlloc<'gc, A> { #[inline] fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { let ptr = self.allocator.allocate(layout)?; self.metrics.mark_external_allocation(layout.size()); Ok(ptr) } #[inline] unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { unsafe { self.metrics.mark_external_deallocation(layout.size()); self.allocator.deallocate(ptr, layout); } } #[inline] fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { let ptr = self.allocator.allocate_zeroed(layout)?; self.metrics.mark_external_allocation(layout.size()); Ok(ptr) } #[inline] unsafe fn grow( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { unsafe { let ptr = self.allocator.grow(ptr, old_layout, new_layout)?; self.metrics .mark_external_allocation(new_layout.size() - old_layout.size()); Ok(ptr) } } #[inline] unsafe fn grow_zeroed( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { unsafe { let ptr = self.allocator.grow_zeroed(ptr, old_layout, new_layout)?; self.metrics .mark_external_allocation(new_layout.size() - old_layout.size()); Ok(ptr) } } #[inline] unsafe fn shrink( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { unsafe { let ptr = self.allocator.shrink(ptr, old_layout, new_layout)?; self.metrics .mark_external_deallocation(old_layout.size() - new_layout.size()); Ok(ptr) } } } unsafe impl<'gc, A: 'static> Collect<'gc> for MetricsAlloc<'gc, A> { const NEEDS_TRACE: bool = false; } unsafe impl<'gc> Collect<'gc> for Global { const NEEDS_TRACE: bool = false; }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/arena.rs
Rust
use core::marker::PhantomData; use std::boxed::Box; use crate::dmm::{ Collect, context::{Context, Finalization, Mutation, Phase, RunUntil, Stop}, metrics::Metrics, }; /// A trait that produces a [`Collect`]-able type for the given lifetime. This is used to produce /// the root [`Collect`] instance in an [`Arena`]. /// /// In order to use an implementation of this trait in an [`Arena`], it must implement /// `Rootable<'a>` for *any* possible `'a`. This is necessary so that the `Root` types can be /// branded by the unique, invariant lifetimes that makes an `Arena` sound. pub trait Rootable<'a> { type Root: ?Sized + 'a; } /// A marker type used by the `Rootable!` macro instead of a bare trait object. /// /// Prevents having to include extra ?Sized bounds on every `for<'a> Rootable<'a>`. #[doc(hidden)] pub struct __DynRootable<T: ?Sized>(PhantomData<T>); impl<'a, T: ?Sized + Rootable<'a>> Rootable<'a> for __DynRootable<T> { type Root = <T as Rootable<'a>>::Root; } /// A convenience macro for quickly creating a type that implements `Rootable`. /// /// The macro takes a single argument, which should be a generic type with elided lifetimes. /// When used as a root object, every instance of the elided lifetime will be replaced with /// the branding lifetime. /// /// ``` /// # use gc_arena::{Arena, Collect, Gc, Rootable}; /// # /// # fn main() { /// #[derive(Collect)] /// #[collect(no_drop)] /// struct MyRoot<'gc> { /// ptr: Gc<'gc, i32>, /// } /// /// type MyArena = Arena<Rootable![MyRoot<'_>]>; /// /// // If desired, the branding lifetime can also be explicitely named: /// type MyArena2 = Arena<Rootable!['gc => MyRoot<'gc>]>; /// # } /// ``` /// /// The macro can also be used to create implementations of `Rootable` that use other generic /// parameters, though in complex cases it may be better to implement `Rootable` directly. /// /// ``` /// # use gc_arena::{Arena, Collect, Gc, Rootable}; /// # /// # fn main() { /// #[derive(Collect)] /// #[collect(no_drop)] /// struct MyGenericRoot<'gc, T> { /// ptr: Gc<'gc, T>, /// } /// /// type MyGenericArena<T> = Arena<Rootable![MyGenericRoot<'_, T>]>; /// # } /// ``` #[macro_export] macro_rules! Rootable { ($gc:lifetime => $root:ty) => { // Instead of generating an impl of `Rootable`, we use a trait object. Thus, we avoid the // need to generate a new type for each invocation of this macro. $crate::__DynRootable::<dyn for<$gc> $crate::Rootable<$gc, Root = $root>> }; ($root:ty) => { $crate::Rootable!['__gc => $crate::__unelide_lifetimes!('__gc; $root)] }; } /// A helper type alias for a `Rootable::Root` for a specific lifetime. pub type Root<'a, R> = <R as Rootable<'a>>::Root; #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] pub enum CollectionPhase { /// The arena is done with a collection cycle and is waiting to be restarted. Sleeping, /// The arena is currently tracing objects from the root to determine reachability. Marking, /// The arena has finished tracing, all reachable objects are marked. This may transition /// back to `Marking` if write barriers occur. Marked, /// The arena has determined a set of unreachable objects and has started freeing them. At this /// point, marking is no longer taking place so the root may have reachable, unmarked pointers. Sweeping, } /// A generic, garbage collected arena. /// /// Garbage collected arenas allow for isolated sets of garbage collected objects with zero-overhead /// garbage collected pointers. It provides incremental mark and sweep garbage collection which /// must be manually triggered outside the `mutate` method, and works best when units of work inside /// `mutate` can be kept relatively small. It is designed primarily to be a garbage collector for /// scripting language runtimes. /// /// The arena API is able to provide extremely cheap Gc pointers because it is based around /// "generativity". During construction and access, the root type is branded by a unique, invariant /// lifetime `'gc` which ensures that `Gc` pointers must be contained inside the root object /// hierarchy and cannot escape the arena callbacks or be smuggled inside another arena. This way, /// the arena can be sure that during mutation, all `Gc` pointers come from the arena we expect /// them to come from, and that they're all either reachable from root or have been allocated during /// the current `mutate` call. When not inside the `mutate` callback, the arena knows that all `Gc` /// pointers must be either reachable from root or they are unreachable and safe to collect. In /// this way, incremental garbage collection can be achieved (assuming "sufficiently small" calls /// to `mutate`) that is both extremely safe and zero overhead vs what you would write in C with raw /// pointers and manually ensuring that invariants are held. pub struct Arena<R> where R: for<'a> Rootable<'a>, { context: Box<Context>, root: Root<'static, R>, } impl<R> Arena<R> where R: for<'a> Rootable<'a>, for<'a> Root<'a, R>: Sized, { /// Create a new arena with the given garbage collector tuning parameters. You must provide a /// closure that accepts a `&Mutation<'gc>` and returns the appropriate root. pub fn new<F>(f: F) -> Arena<R> where F: for<'gc> FnOnce(&'gc Mutation<'gc>) -> Root<'gc, R>, { unsafe { let context = Box::new(Context::new()); // Note - we cast the `&Mutation` to a `'static` lifetime here, // instead of transmuting the root type returned by `f`. Transmuting the root // type is allowed in nightly versions of rust // (see https://github.com/rust-lang/rust/pull/101520#issuecomment-1252016235) // but is not yet stable. Casting the `&Mutation` is completely invisible // to the callback `f` (since it needs to handle an arbitrary lifetime), // and lets us stay compatible with older versions of Rust let mc: &'static Mutation<'_> = &*(context.mutation_context() as *const _); let root: Root<'static, R> = f(mc); Arena { context, root } } } /// Similar to `new`, but allows for constructor that can fail. pub fn try_new<F, E>(f: F) -> Result<Arena<R>, E> where F: for<'gc> FnOnce(&'gc Mutation<'gc>) -> Result<Root<'gc, R>, E>, { unsafe { let context = Box::new(Context::new()); let mc: &'static Mutation<'_> = &*(context.mutation_context() as *const _); let root: Root<'static, R> = f(mc)?; Ok(Arena { context, root }) } } #[inline] pub fn map_root<R2>( mut self, f: impl for<'gc> FnOnce(&'gc Mutation<'gc>, Root<'gc, R>) -> Root<'gc, R2>, ) -> Arena<R2> where R2: for<'a> Rootable<'a>, for<'a> Root<'a, R2>: Sized, { self.context.root_barrier(); let new_root: Root<'static, R2> = unsafe { let mc: &'static Mutation<'_> = &*(self.context.mutation_context() as *const _); f(mc, self.root) }; Arena { context: self.context, root: new_root, } } #[inline] pub fn try_map_root<R2, E>( mut self, f: impl for<'gc> FnOnce(&'gc Mutation<'gc>, Root<'gc, R>) -> Result<Root<'gc, R2>, E>, ) -> Result<Arena<R2>, E> where R2: for<'a> Rootable<'a>, for<'a> Root<'a, R2>: Sized, { self.context.root_barrier(); let new_root: Root<'static, R2> = unsafe { let mc: &'static Mutation<'_> = &*(self.context.mutation_context() as *const _); f(mc, self.root)? }; Ok(Arena { context: self.context, root: new_root, }) } } impl<R> Arena<R> where R: for<'a> Rootable<'a>, { /// The primary means of interacting with a garbage collected arena. Accepts a callback which /// receives a `&Mutation<'gc>` and a reference to the root, and can return any non garbage /// collected value. The callback may "mutate" any part of the object graph during this call, /// but no garbage collection will take place during this method. #[inline] pub fn mutate<F, T>(&self, f: F) -> T where F: for<'gc> FnOnce(&'gc Mutation<'gc>, &'gc Root<'gc, R>) -> T, { unsafe { let mc: &'static Mutation<'_> = &*(self.context.mutation_context() as *const _); let root: &'static Root<'_, R> = &*(&self.root as *const _); f(mc, root) } } /// An alternative version of [`Arena::mutate`] which allows mutating the root set, at the /// cost of an extra write barrier. #[inline] pub fn mutate_root<F, T>(&mut self, f: F) -> T where F: for<'gc> FnOnce(&'gc Mutation<'gc>, &'gc mut Root<'gc, R>) -> T, { self.context.root_barrier(); unsafe { let mc: &'static Mutation<'_> = &*(self.context.mutation_context() as *const _); let root: &'static mut Root<'_, R> = &mut *(&mut self.root as *mut _); f(mc, root) } } #[inline] pub fn metrics(&self) -> &Metrics { self.context.metrics() } #[inline] pub fn collection_phase(&self) -> CollectionPhase { match self.context.phase() { Phase::Mark => { if self.context.gray_remaining() { CollectionPhase::Marking } else { CollectionPhase::Marked } } Phase::Sweep => CollectionPhase::Sweeping, Phase::Sleep => CollectionPhase::Sleeping, Phase::Drop => unreachable!(), } } } impl<R> Arena<R> where R: for<'a> Rootable<'a>, for<'a> Root<'a, R>: Collect<'a>, { /// Run incremental garbage collection until the allocation debt is zero. /// /// This will run through ALL phases of the collection cycle until the debt is zero, including /// implicitly finishing the current cycle and starting a new one (transitioning from /// [`CollectionPhase::Sweeping`] to [`CollectionPhase::Sleeping`]). Since this method runs /// until debt is zero with no guaranteed return at any specific transition, you may need to use /// other methods like [`Arena::mark_debt`] and [`Arena::cycle_debt`] if you need to keep close /// track of the current collection phase. /// /// There is no minimum unit of work enforced here, so it may be faster to only call this method /// when the allocation debt is above some minimum threshold. #[inline] pub fn collect_debt(&mut self) { unsafe { self.context .do_collection(&self.root, RunUntil::PayDebt, Stop::Full); } } /// Run only the *marking* part of incremental garbage collection until allocation debt is zero. /// /// This does *not* transition collection past the [`CollectionPhase::Marked`] /// phase. Does nothing if the collection phase is [`CollectionPhase::Marked`] or /// [`CollectionPhase::Sweeping`], otherwise acts like [`Arena::collect_debt`]. /// /// If this method stops because the arena is now fully marked (the collection phase is /// [`CollectionPhase::Marked`]), then a [`MarkedArena`] object will be returned to allow /// you to examine the state of the fully marked arena. #[inline] pub fn mark_debt(&mut self) -> Option<MarkedArena<'_, R>> { unsafe { self.context .do_collection(&self.root, RunUntil::PayDebt, Stop::FullyMarked); } if self.context.phase() == Phase::Mark && !self.context.gray_remaining() { Some(MarkedArena(self)) } else { None } } /// Runs ALL of the remaining *marking* part of the current garbage collection cycle. /// /// Similarly to [`Arena::mark_debt`], this does not transition collection past the /// [`CollectionPhase::Marked`] phase, and does nothing if the collector is currently in the /// [`CollectionPhase::Marked`] phase or the [`CollectionPhase::Sweeping`] phase. /// /// This method will always fully mark the arena and return a [`MarkedArena`] object as long as /// the current phase is not [`CollectionPhase::Sweeping`]. #[inline] pub fn finish_marking(&mut self) -> Option<MarkedArena<'_, R>> { unsafe { self.context .do_collection(&self.root, RunUntil::Stop, Stop::FullyMarked); } if self.context.phase() == Phase::Mark && !self.context.gray_remaining() { Some(MarkedArena(self)) } else { None } } /// Run the *current* collection cycle until the allocation debt is zero. /// /// This is nearly identical to the [`Arena::collect_debt`] method, except it /// *always* returns immediately when a cycle is finished (when phase transitions /// to [`CollectionPhase::Sleeping`]), and will never transition directly from /// [`CollectionPhase::Sweeping`] to [`CollectionPhase::Marking`] within a single call, even if /// there is enough outstanding debt to do so. /// /// This mostly only important when the user of an `Arena` needs to closely track collection /// phases, otherwise [`Arena::collect_debt`] simpler to use. #[inline] pub fn cycle_debt(&mut self) { unsafe { self.context .do_collection(&self.root, RunUntil::PayDebt, Stop::FinishCycle); } } /// Run the current garbage collection cycle to completion, stopping once garbage collection /// has entered the [`CollectionPhase::Sleeping`] phase. If the collector is currently sleeping, /// then this restarts the collector and performs a full collection before transitioning back to /// the sleep phase. #[inline] pub fn finish_cycle(&mut self) { unsafe { self.context .do_collection(&self.root, RunUntil::Stop, Stop::FinishCycle); } } } pub struct MarkedArena<'a, R: for<'b> Rootable<'b>>(&'a mut Arena<R>); impl<'a, R> MarkedArena<'a, R> where R: for<'b> Rootable<'b>, for<'b> Root<'b, R>: Collect<'b>, { /// Examine the state of a fully marked arena. /// /// Allows you to determine whether `GcWeak` pointers are "dead" (aka, soon-to-be-dropped) and /// potentially resurrect them for this cycle. /// /// Note that the arena is guaranteed to be *fully marked* only at the *beginning* of this /// callback, any mutation that resurrects a pointer or triggers a write barrier can immediately /// invalidate this. #[inline] pub fn finalize<F, T>(self, f: F) -> T where F: for<'gc> FnOnce(&'gc Finalization<'gc>, &'gc Root<'gc, R>) -> T, { unsafe { let mc: &'static Finalization<'_> = &*(self.0.context.finalization_context() as *const _); let root: &'static Root<'_, R> = &*(&self.0.root as *const _); f(mc, root) } } /// Immediately transition the arena out of [`CollectionPhase::Marked`] to /// [`CollectionPhase::Sweeping`]. #[inline] pub fn start_sweeping(self) { unsafe { self.0 .context .do_collection(&self.0.root, RunUntil::Stop, Stop::AtSweep); } assert_eq!(self.0.context.phase(), Phase::Sweep); } } /// Create a temporary arena without a root object and perform the given operation on it. /// /// No garbage collection will be done until the very end of the call, at which point all /// allocations will be collected. /// /// This is a convenience function that makes it a little easier to quickly test code that uses /// `gc-arena`, it is not very useful on its own. pub fn rootless_mutate<F, R>(f: F) -> R where F: for<'gc> FnOnce(&'gc Mutation<'gc>) -> R, { unsafe { let context = Context::new(); f(context.mutation_context()) } }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/barrier.rs
Rust
//! Write barrier management. use core::borrow::Borrow; use core::mem; use core::ops::{ Deref, DerefMut, Index, Range, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive, }; use std::collections::{BTreeMap, VecDeque}; use std::vec::Vec; use std::{collections::HashMap, hash::BuildHasher, hash::Hash}; #[cfg(doc)] use crate::Gc; #[cfg(doc)] use core::ops::IndexMut; /// An (interiorly-)mutable reference inside a GC'd object graph. /// /// This type can only exist behind a reference; it is typically obtained by calling /// [`Gc::write`] on a [`Gc`] pointer or by using the [`field!`] projection macro /// on a pre-existing `&Write<T>`. #[non_exhaustive] #[repr(transparent)] pub struct Write<T: ?Sized> { // Public so that the `field!` macro can pattern-match on it; the `non_exhaustive` attribute // prevents 3rd-party code from instanciating the struct directly. #[doc(hidden)] pub __inner: T, } impl<T: ?Sized> Deref for Write<T> { type Target = T; #[inline(always)] fn deref(&self) -> &Self::Target { &self.__inner } } impl<T: ?Sized> DerefMut for Write<T> { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.__inner } } impl<T: IndexWrite<I> + ?Sized, I> Index<I> for Write<T> { type Output = Write<T::Output>; #[inline] fn index(&self, index: I) -> &Self::Output { // SAFETY: `IndexWrite` guarantees that the `Index` impl is `Write`-compatible. unsafe { Write::assume(&self.__inner[index]) } } } impl<T: ?Sized> Write<T> { /// Asserts that the given reference can be safely written to. /// /// # Safety /// In order to maintain the invariants of the garbage collector, no new [`Gc`] pointers /// may be adopted by the referenced value as a result of the interior mutability enabled /// by this wrapper, unless [`Gc::write`] is invoked manually on the parent [`Gc`] /// pointer during the current arena callback. #[inline(always)] pub unsafe fn assume(v: &T) -> &Self { // SAFETY: `Self` is `repr(transparent)`. unsafe { mem::transmute(v) } } /// Gets a writable reference to non-GC'd data. /// /// This is safe, as `'static` types can never hold [`Gc`] pointers. #[inline] pub fn from_static(v: &T) -> &Self where T: 'static, { // SAFETY: `Self` is `repr(transparent)`. unsafe { mem::transmute(v) } } /// Gets a writable reference from a `&mut T`. /// /// This is safe, as exclusive access already implies writability. #[inline] pub fn from_mut(v: &mut T) -> &mut Self { // SAFETY: `Self` is `repr(transparent)`. unsafe { mem::transmute(v) } } /// Implementation detail of `write_field!`; same safety requirements as `assume`. #[inline(always)] #[doc(hidden)] pub unsafe fn __from_ref_and_ptr(v: &T, _: *const T) -> &Self { unsafe { // SAFETY: `Self` is `repr(transparent)`. mem::transmute(v) } } /// Unlocks the referenced value, providing full interior mutability. #[inline] pub fn unlock(&self) -> &T::Unlocked where T: Unlock, { // SAFETY: a `&Write<T>` implies that a write barrier was triggered on the parent `Gc`. unsafe { self.__inner.unlock_unchecked() } } /// Propagates a write barrier through a smart pointer dereference. #[inline(always)] pub fn as_deref(&self) -> &Write<T::Target> where T: DerefWrite, { // SAFETY: `DerefWrite` guarantees that the `Deref` impl is `Write`-compatible. unsafe { Write::assume(&*self) } } } impl<T> Write<Option<T>> { /// Converts from `&Write<Option<T>>` to `Option<&Write<T>>`. #[inline(always)] pub fn as_write(&self) -> Option<&Write<T>> { // SAFETY: this is simple destructuring unsafe { match &self.__inner { None => None, Some(v) => Some(Write::assume(v)), } } } } impl<T, E> Write<Result<T, E>> { /// Converts from `&Write<Result<T, E>>` to `Result<&Write<T>, &Write<E>>`. #[inline(always)] pub fn as_write(&self) -> Result<&Write<T>, &Write<E>> { // SAFETY: this is simple destructuring unsafe { match &self.__inner { Ok(v) => Ok(Write::assume(v)), Err(e) => Err(Write::assume(e)), } } } } /// Types which preserve write barriers when dereferenced. /// /// # Safety /// Implementing this trait is a promise that the corresponding [`Deref`] impl /// (and [`DerefMut`], if it exists) can be used to project a [`Write`] reference. /// /// In particular, both `Deref::deref` and `DerefMut::deref_mut`: /// - must return a reference into the *same* GC'd object as the input; /// - must not adopt new [`Gc`] pointers. pub unsafe trait DerefWrite: Deref {} // SAFETY: All these types have pure & non-GC-traversing Deref(Mut) impls unsafe impl<T: ?Sized> DerefWrite for &T {} unsafe impl<T: ?Sized> DerefWrite for std::boxed::Box<T> {} unsafe impl<T> DerefWrite for Vec<T> {} unsafe impl<T: ?Sized> DerefWrite for std::rc::Rc<T> {} unsafe impl<T: ?Sized> DerefWrite for std::sync::Arc<T> {} /// Types which preserve write barriers when indexed. /// /// # Safety /// Implementing this trait is a promise that the corresponding [`Index<I>`] impl /// (and [`IndexMut<I>`], if it exists) can be used to project a [`Write`] reference. /// /// In particular, both `Index::index` and `IndexMut::index_mut`: /// - must return a reference into the *same* GC'd object as the input; /// - must not adopt new [`Gc`] pointers. pub unsafe trait IndexWrite<I: ?Sized>: Index<I> {} // SAFETY: All these types have pure & non-GC-traversing Index(Mut) impls // Note that we don't write `impl<..., I> IndexWrite<I> for ... where ...: Index<I>`, // as this would allow arbitrary implementations through third-party `I` types. unsafe impl<T> IndexWrite<usize> for [T] {} unsafe impl<T> IndexWrite<Range<usize>> for [T] {} unsafe impl<T> IndexWrite<RangeFrom<usize>> for [T] {} unsafe impl<T> IndexWrite<RangeInclusive<usize>> for [T] {} unsafe impl<T> IndexWrite<RangeTo<usize>> for [T] {} unsafe impl<T> IndexWrite<RangeToInclusive<usize>> for [T] {} unsafe impl<T, I, const N: usize> IndexWrite<I> for [T; N] where [T]: IndexWrite<I> {} unsafe impl<T, I> IndexWrite<I> for Vec<T> where [T]: IndexWrite<I>, Self: Index<I>, { } unsafe impl<T> IndexWrite<usize> for VecDeque<T> {} unsafe impl<K, V, Q> IndexWrite<&Q> for BTreeMap<K, V> where K: Borrow<Q> + Ord, Q: Ord + ?Sized, { } unsafe impl<K, V, S, Q> IndexWrite<&Q> for HashMap<K, V, S> where K: Eq + Hash + Borrow<Q>, Q: Eq + Hash + ?Sized, S: BuildHasher, { } /// Types that support additional operations (typically, mutation) when behind a write barrier. pub trait Unlock { /// This will typically be a cell-like type providing some sort of interior mutability. type Unlocked: ?Sized; /// Provides unsafe access to the unlocked type, *without* triggering a write barrier. /// /// # Safety /// /// In order to maintain the invariants of the garbage collector, no new `Gc` pointers /// may be adopted by as a result of the interior mutability afforded by the unlocked value, /// unless the write barrier for the containing `Gc` pointer is invoked manually before /// collection is triggered. unsafe fn unlock_unchecked(&self) -> &Self::Unlocked; } /// Macro for named field projection behind [`Write`] references. /// /// # Usage /// /// ``` /// # use gc_arena::barrier::{field, Write}; /// struct Container<T> { /// field: T, /// } /// /// fn project<T>(v: &Write<Container<T>>) -> &Write<T> { /// field!(v, Container, field) /// } /// ``` /// /// # Limitations /// /// This macro only support structs with named fields; tuples and enums aren't supported. #[doc(inline)] pub use crate::__field as field; // Actual macro item, hidden so that it doesn't show at the crate root. #[macro_export] #[doc(hidden)] macro_rules! __field { ($value:expr, $type:path, $field:ident) => { // SAFETY: // For this to be sound, we need to prevent deref coercions from happening, as they may // access nested `Gc` pointers, which would violate the write barrier invariant. This is // guaranteed as follows: // - the destructuring pattern, unlike a simple field access, cannot call `Deref`; // - the `ref` binding mode also forbids (under edition 2024) going through simple // references (i.e. it will reject `&Write<&Type>`s); // - similarly, the `__from_ref_and_ptr` method takes both a reference (for the lifetime) // and a pointer, causing a compilation failure if the first argument was coerced. match $value { &$crate::barrier::Write { __inner: $type { ref $field, .. }, .. } => unsafe { $crate::barrier::Write::__from_ref_and_ptr($field, $field as *const _) }, } }; } /// Shorthand for [`field!`]`(...).`[`unlock()`](Write::unlock). #[doc(inline)] pub use crate::__unlock as unlock; // Actual macro item, hidden so that it doesn't show at the crate root. #[macro_export] #[doc(hidden)] macro_rules! __unlock { ($value:expr, $type:path, $field:ident) => { $crate::barrier::field!($value, $type, $field).unlock() }; }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/collect.rs
Rust
use crate::dmm::{Gc, GcWeak}; pub use tcvm_derive::Collect; /// A trait for garbage collected objects that can be placed into `Gc` pointers. This trait is /// unsafe, because `Gc` pointers inside an Arena are assumed never to be dangling, and in order to /// ensure this certain rules must be followed: /// /// 1. `Collect::trace` *must* trace over *every* `Gc` and `GcWeak` pointer held inside this type. /// 2. Held `Gc` and `GcWeak` pointers must not be accessed inside `Drop::drop` since during drop /// any such pointer may be dangling. /// 3. Internal mutability *must* not be used to adopt new `Gc` or `GcWeak` pointers without /// calling appropriate write barrier operations during the same arena mutation. /// /// It is, however, possible to implement this trait safely by procedurally deriving it (see /// [`gc_arena_derive::Collect`]), which requires that every field in the structure also implement /// `Collect`, and ensures that `Drop` cannot safely be implemented. Internally mutable types like /// `Cell` and `RefCell` do not implement `Collect` in such a way that it is possible to store /// `Gc` pointers inside them, so write barrier requirements cannot be broken when procedurally /// deriving `Collect`. A safe way of providing internal mutability in this case is to use /// [`crate::lock::Lock<T>`] and [`crate::lock::RefLock<T>`], which provides internal mutability /// while ensuring that write barriers are correctly executed. pub unsafe trait Collect<'gc> { /// As an optimization, if this type can never hold a `Gc` pointer and `trace` is unnecessary /// to call, you may set this to `false`. The default value is `true`, signaling that /// `Collect::trace` must be called. const NEEDS_TRACE: bool = true; /// *Must* call [`Trace::trace_gc`] (resp. [`Trace::trace_gc_weak`]) on all directly owned /// [`Gc`] (resp. [`GcWeak`]) pointers. If this type holds inner types that implement `Collect`, /// a valid implementation would simply call [`Trace::trace`] on all the held values to ensure /// this. /// /// # Tracing pointers /// /// [`Gc`] and [`GcWeak`] have their own implementations of `Collect` which in turn call /// [`Trace::trace_gc`] and [`Trace::trace_gc_weak`] respectively. Because of this, it is not /// actually ever necessary to call [`Trace::trace_gc`] and [`Trace::trace_gc_weak`] directly, /// but be careful! It is important that owned pointers *themselves* are traced and NOT their /// contents (the content type will usually also implement `Collect`, so this is easy to /// accidentally do). /// /// It is always okay to use the [`Trace::trace_gc`] and [`Trace::trace_gc_weak`] directly as a /// potentially less risky alternative when manually implementing `Collect`. #[inline] #[allow(unused_variables)] fn trace<T: Trace<'gc>>(&self, cc: &mut T) {} } /// The trait that is passed to the [`Collect::trace`] method. /// /// Though [`Collect::trace`] is primarily used during the marking phase of the mark and sweep /// collector, this is a trait rather than a concrete type to facilitate other kinds of uses. /// /// This trait is not itself unsafe, but implementers of [`Collect`] *must* uphold the safety /// guarantees of [`Collect`] when using this trait. pub trait Trace<'gc> { /// Trace a [`Gc`] pointer (of any real type). fn trace_gc(&mut self, gc: Gc<'gc, ()>); /// Trace a [`GcWeak`] pointer (of any real type). fn trace_gc_weak(&mut self, gc: GcWeak<'gc, ()>); /// This is a convenience method that calls [`Collect::trace`] but automatically adds a /// [`Collect::NEEDS_TRACE`] check around it. /// /// Manual implementations of [`Collect`] are encouraged to use this to ensure that there /// is a [`Collect::NEEDS_TRACE`] check without having to implement it manually. This can be /// important in cases where the [`Collect::trace`] method impl is not `#[inline]` or does not /// have its own early exit. /// /// There is generally no need for custom `Trace` implementations to override this method. #[inline] fn trace<C: Collect<'gc> + ?Sized>(&mut self, value: &C) where Self: Sized, { if C::NEEDS_TRACE { value.trace(self); } } }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/collect_impl.rs
Rust
use core::cell::{Cell, RefCell}; use core::marker::PhantomData; use std::boxed::Box; use std::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::string::String; use std::vec::Vec; use crate::dmm::collect::{Collect, Trace}; /// If a type is static, we know that it can never hold `Gc` pointers, so it is safe to provide a /// simple empty `Collect` implementation. #[macro_export] macro_rules! static_collect { ($type:ty) => { unsafe impl<'gc> Collect<'gc> for $type where $type: 'static, { const NEEDS_TRACE: bool = false; } }; } static_collect!(bool); static_collect!(char); static_collect!(u8); static_collect!(u16); static_collect!(u32); static_collect!(u64); static_collect!(usize); static_collect!(i8); static_collect!(i16); static_collect!(i32); static_collect!(i64); static_collect!(isize); static_collect!(f32); static_collect!(f64); static_collect!(String); static_collect!(str); static_collect!(std::ffi::CString); static_collect!(core::ffi::CStr); static_collect!(core::any::TypeId); static_collect!(std::path::Path); static_collect!(std::path::PathBuf); static_collect!(std::ffi::OsStr); static_collect!(std::ffi::OsString); /// SAFETY: We know that a `&'static` reference cannot possibly point to `'gc` data, so it is safe /// to keep in a rooted objet and we do not have to trace through it. /// /// HOWEVER, There is an extra bound here that seems superfluous. If we have a `&'static T`, why do /// we require `T: 'static`, shouldn't this be implied, otherwise a `&'static T` would not be well- /// formed? WELL, there are currently some neat compiler bugs, observe... /// /// ```rust,compile_fail /// let arena = Arena::<Rootable![&'static Gc<'gc, i32>]>::new(Default::default(), |mc| { /// Box::leak(Box::new(Gc::new(mc, 4))) /// }); /// ``` /// /// At the time of this writing, without the extra `T: static` bound, the above code compiles and /// produces an arena with a reachable but un-traceable `Gc<'gc, i32>`, and this is unsound. This /// *is* ofc the stored type of the root, since the Arena is actually constructing a `&'static /// Gc<'static, i32>` as the root object, but this should still not rightfully compile due to the /// signature of the constructor callback passed to `Arena::new`. In fact, the 'static lifetime is a /// red herring, it is possible to change the internals of `Arena` such that the 'gc lifetime given /// to the callback is *not* 'static, and the problem persists. /// /// It should not be required to have this extra lifetime bound, and yet! It fixes the above issue /// perfectly and the given example of unsoundness no longer compiles. So, until this rustc bug /// is fixed... /// /// DO NOT REMOVE THIS EXTRA `T: 'static` BOUND unsafe impl<'gc, T: ?Sized + 'static> Collect<'gc> for &'static T { const NEEDS_TRACE: bool = false; } unsafe impl<'gc, T: ?Sized + Collect<'gc>> Collect<'gc> for Box<T> { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { cc.trace(&**self) } } unsafe impl<'gc, T: Collect<'gc>> Collect<'gc> for [T] { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for t in self.iter() { cc.trace(t) } } } unsafe impl<'gc, T: Collect<'gc>> Collect<'gc> for Option<T> { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { if let Some(t) = self.as_ref() { cc.trace(t) } } } unsafe impl<'gc, T: Collect<'gc>, E: Collect<'gc>> Collect<'gc> for Result<T, E> { const NEEDS_TRACE: bool = T::NEEDS_TRACE || E::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { match self { Ok(r) => cc.trace(r), Err(e) => cc.trace(e), } } } unsafe impl<'gc, T: Collect<'gc>> Collect<'gc> for Vec<T> { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for t in self { cc.trace(t) } } } unsafe impl<'gc, T: Collect<'gc>> Collect<'gc> for VecDeque<T> { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for t in self { cc.trace(t) } } } unsafe impl<'gc, T: Collect<'gc>> Collect<'gc> for LinkedList<T> { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for t in self { cc.trace(t) } } } unsafe impl<'gc, K, V, S> Collect<'gc> for HashMap<K, V, S> where K: Collect<'gc>, V: Collect<'gc>, S: 'static, { const NEEDS_TRACE: bool = K::NEEDS_TRACE || V::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for (k, v) in self { cc.trace(k); cc.trace(v); } } } unsafe impl<'gc, T, S> Collect<'gc> for HashSet<T, S> where T: Collect<'gc>, S: 'static, { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for v in self { cc.trace(v); } } } unsafe impl<'gc, K, V> Collect<'gc> for BTreeMap<K, V> where K: Collect<'gc>, V: Collect<'gc>, { const NEEDS_TRACE: bool = K::NEEDS_TRACE || V::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for (k, v) in self { cc.trace(k); cc.trace(v); } } } unsafe impl<'gc, T> Collect<'gc> for BTreeSet<T> where T: Collect<'gc>, { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for v in self { cc.trace(v); } } } unsafe impl<'gc, T> Collect<'gc> for BinaryHeap<T> where T: Collect<'gc>, { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for v in self { cc.trace(v); } } } unsafe impl<'gc, T> Collect<'gc> for Rc<T> where T: ?Sized + Collect<'gc>, { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { cc.trace(&**self); } } unsafe impl<'gc, T> Collect<'gc> for std::sync::Arc<T> where T: ?Sized + Collect<'gc>, { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { cc.trace(&**self); } } unsafe impl<'gc, T> Collect<'gc> for Cell<T> where T: 'static, { const NEEDS_TRACE: bool = false; } unsafe impl<'gc, T> Collect<'gc> for RefCell<T> where T: 'static, { const NEEDS_TRACE: bool = false; } // SAFETY: `PhantomData` is a ZST, and therefore doesn't store anything unsafe impl<'gc, T> Collect<'gc> for PhantomData<T> { const NEEDS_TRACE: bool = false; } unsafe impl<'gc, T: Collect<'gc>, const N: usize> Collect<'gc> for [T; N] { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for t in self { cc.trace(t) } } } macro_rules! impl_tuple { () => ( unsafe impl<'gc> Collect<'gc> for () { const NEEDS_TRACE: bool = false; } ); ($($name:ident)+) => ( unsafe impl<'gc, $($name,)*> Collect<'gc> for ($($name,)*) where $($name: Collect<'gc>,)* { const NEEDS_TRACE: bool = false $(|| $name::NEEDS_TRACE)*; #[allow(non_snake_case)] #[inline] fn trace<TR: Trace<'gc> >(&self, cc: &mut TR) { let ($($name,)*) = self; $(cc.trace($name);)* } } ); } impl_tuple! {} impl_tuple! {A} impl_tuple! {A B} impl_tuple! {A B C} impl_tuple! {A B C D} impl_tuple! {A B C D E} impl_tuple! {A B C D E F} impl_tuple! {A B C D E F G} impl_tuple! {A B C D E F G H} impl_tuple! {A B C D E F G H I} impl_tuple! {A B C D E F G H I J} impl_tuple! {A B C D E F G H I J K} impl_tuple! {A B C D E F G H I J K L} impl_tuple! {A B C D E F G H I J K L M} impl_tuple! {A B C D E F G H I J K L M N} impl_tuple! {A B C D E F G H I J K L M N O} impl_tuple! {A B C D E F G H I J K L M N O P}
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/context.rs
Rust
use core::{ cell::{Cell, UnsafeCell}, mem, ops::{ControlFlow, Deref, DerefMut}, ptr::NonNull, }; use std::{boxed::Box, vec::Vec}; use crate::dmm::{ Gc, GcWeak, collect::{Collect, Trace}, metrics::Metrics, types::{GcBox, GcBoxHeader, GcBoxInner, GcColor, Invariant}, }; /// Handle value given by arena callbacks during construction and mutation. Allows allocating new /// `Gc` pointers and internally mutating values held by `Gc` pointers. #[repr(transparent)] pub struct Mutation<'gc> { context: Context, _invariant: Invariant<'gc>, } impl<'gc> Mutation<'gc> { #[inline] pub fn metrics(&self) -> &Metrics { self.context.metrics() } /// IF we are in the marking phase AND the `parent` pointer is colored black AND the `child` (if /// given) is colored white, then change the `parent` color to gray and enqueue it for tracing. /// /// This operation is known as a "backwards write barrier". Calling this method is one of the /// safe ways for the value in the `parent` pointer to use internal mutability to adopt the /// `child` pointer without invalidating the color invariant. /// /// If the `child` parameter is given, then calling this method ensures that the `parent` /// pointer may safely adopt the `child` pointer. If no `child` is given, then calling this /// method is more general, and it ensures that the `parent` pointer may adopt *any* child /// pointer(s) before collection is next triggered. #[inline] pub fn backward_barrier(&self, parent: Gc<'gc, ()>, child: Option<Gc<'gc, ()>>) { self.context.backward_barrier( unsafe { GcBox::erase(parent.ptr) }, child.map(|p| unsafe { GcBox::erase(p.ptr) }), ) } /// A version of [`Mutation::backward_barrier`] that allows adopting a [`GcWeak`] child. #[inline] pub fn backward_barrier_weak(&self, parent: Gc<'gc, ()>, child: GcWeak<'gc, ()>) { self.context .backward_barrier_weak(unsafe { GcBox::erase(parent.ptr) }, unsafe { GcBox::erase(child.inner.ptr) }) } /// IF we are in the marking phase AND the `parent` pointer (if given) is colored black, AND /// the `child` is colored white, then immediately change the `child` to gray and enqueue it /// for tracing. /// /// This operation is known as a "forwards write barrier". Calling this method is one of the /// safe ways for the value in the `parent` pointer to use internal mutability to adopt the /// `child` pointer without invalidating the color invariant. /// /// If the `parent` parameter is given, then calling this method ensures that the `parent` /// pointer may safely adopt the `child` pointer. If no `parent` is given, then calling this /// method is more general, and it ensures that the `child` pointer may be adopted by *any* /// parent pointer(s) before collection is next triggered. #[inline] pub fn forward_barrier(&self, parent: Option<Gc<'gc, ()>>, child: Gc<'gc, ()>) { self.context .forward_barrier(parent.map(|p| unsafe { GcBox::erase(p.ptr) }), unsafe { GcBox::erase(child.ptr) }) } /// A version of [`Mutation::forward_barrier`] that allows adopting a [`GcWeak`] child. #[inline] pub fn forward_barrier_weak(&self, parent: Option<Gc<'gc, ()>>, child: GcWeak<'gc, ()>) { self.context .forward_barrier_weak(parent.map(|p| unsafe { GcBox::erase(p.ptr) }), unsafe { GcBox::erase(child.inner.ptr) }) } #[inline] pub(crate) fn allocate<T: Collect<'gc> + 'gc>(&self, t: T) -> NonNull<GcBoxInner<T>> { self.context.allocate(t) } #[inline] pub(crate) fn upgrade(&self, gc_box: GcBox) -> bool { self.context.upgrade(gc_box) } } /// Handle value given to finalization callbacks in `MarkedArena`. /// /// Derefs to `Mutation<'gc>` to allow for arbitrary mutation, but adds additional powers to examine /// the state of the fully marked arena. #[repr(transparent)] pub struct Finalization<'gc> { context: Context, _invariant: Invariant<'gc>, } impl<'gc> Deref for Finalization<'gc> { type Target = Mutation<'gc>; fn deref(&self) -> &Self::Target { // SAFETY: Finalization and Mutation are #[repr(transparent)] unsafe { mem::transmute::<&Self, &Mutation>(&self) } } } impl<'gc> Finalization<'gc> { #[inline] pub(crate) fn resurrect(&self, gc_box: GcBox) { self.context.resurrect(gc_box) } } impl<'gc> Trace<'gc> for Context { fn trace_gc(&mut self, gc: Gc<'gc, ()>) { let gc_box = unsafe { GcBox::erase(gc.ptr) }; Context::trace(self, gc_box) } fn trace_gc_weak(&mut self, gc: GcWeak<'gc, ()>) { let gc_box = unsafe { GcBox::erase(gc.inner.ptr) }; Context::trace_weak(self, gc_box) } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub(crate) enum Phase { Mark, Sweep, Sleep, Drop, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub(crate) enum RunUntil { // Run collection until we reach the stop condition *or* debt is zero. PayDebt, // Run collection until we reach our stop condition. Stop, } #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] pub(crate) enum Stop { // Don't proceed past the end of marking, *just* before the sweep phase FullyMarked, // Don't proceed past the very beginning of the sweep phase AtSweep, // Stop once we reach the end of the current cycle and are in `Phase::Sleep`. FinishCycle, // Stop once we have done an entire cycle as a single atomic unit. This is the maximum amount // of work that a call to `Context::do_collection` will do, since a full collection as a single // atomic unit means that all unreachable values *must* already be freed. Full, } pub(crate) struct Context { metrics: Metrics, phase: Phase, // A linked list of all allocated `GcBox`es. all: Cell<Option<GcBox>>, // A copy of the head of `all` at the end of `Phase::Mark`. // During `Phase::Sweep`, we free all white allocations on this list. // Any allocations created *during* `Phase::Sweep` will be added to `all`, // but `sweep` will *not* be updated. This ensures that we keep allocations // alive until we've had a chance to trace them. sweep: Option<GcBox>, // The most recent black object that we encountered during `Phase::Sweep`. // When we free objects, we update this `GcBox.next` to remove them from // the linked list. sweep_prev: Cell<Option<GcBox>>, /// Does the root needs to be traced? /// This should be `true` at the beginning of `Phase::Mark`. root_needs_trace: bool, /// A queue of gray objects, used during `Phase::Mark`. /// This holds traceable objects that have yet to be traced. gray: Queue<GcBox>, // A queue of gray objects that became gray as a result // of a write barrier. gray_again: Queue<GcBox>, } impl Drop for Context { fn drop(&mut self) { struct DropAll<'a>(&'a Metrics, Option<GcBox>); impl<'a> Drop for DropAll<'a> { fn drop(&mut self) { if let Some(gc_box) = self.1.take() { let mut drop_resume = DropAll(self.0, Some(gc_box)); while let Some(mut gc_box) = drop_resume.1.take() { let header = gc_box.header(); drop_resume.1 = header.next(); let gc_size = header.size_of_box(); // SAFETY: the context owns its GC'd objects unsafe { if header.is_live() { gc_box.drop_in_place(); self.0.mark_gc_dropped(gc_size); } gc_box.dealloc(); self.0.mark_gc_freed(gc_size); } } } } } let cx = PhaseGuard::enter(self, Some(Phase::Drop)); DropAll(&cx.metrics, cx.all.get()); } } impl Context { pub(crate) unsafe fn new() -> Context { let metrics = Metrics::new(); Context { phase: Phase::Sleep, metrics: metrics.clone(), all: Cell::new(None), sweep: None, sweep_prev: Cell::new(None), root_needs_trace: true, gray: Queue::new(), gray_again: Queue::new(), } } #[inline] pub(crate) unsafe fn mutation_context<'gc>(&self) -> &Mutation<'gc> { unsafe { mem::transmute::<&Self, &Mutation>(&self) } } #[inline] pub(crate) unsafe fn finalization_context<'gc>(&self) -> &Finalization<'gc> { unsafe { mem::transmute::<&Self, &Finalization>(&self) } } #[inline] pub(crate) fn metrics(&self) -> &Metrics { &self.metrics } #[inline] pub(crate) fn root_barrier(&mut self) { if self.phase == Phase::Mark { self.root_needs_trace = true; } } #[inline] pub(crate) fn phase(&self) -> Phase { self.phase } #[inline] pub(crate) fn gray_remaining(&self) -> bool { !self.gray.is_empty() || !self.gray_again.is_empty() || self.root_needs_trace } // Do some collection work until either we have achieved our `target` (paying off debt or // finishing a full collection) or we have reached the `stop` condition. // // In order for this to be safe, at the time of call no `Gc` pointers can be live that are not // reachable from the given root object. // // If we are currently in `Phase::Sleep` and have positive debt, this will immediately // transition the collector to `Phase::Mark`. #[deny(unsafe_op_in_unsafe_fn)] pub(crate) unsafe fn do_collection<'gc, R: Collect<'gc> + ?Sized>( &mut self, root: &R, run_until: RunUntil, stop: Stop, ) { let mut cx = PhaseGuard::enter(self, None); if run_until == RunUntil::PayDebt && !(cx.metrics.allocation_debt() > 0.0) { return; } let mut has_slept = false; loop { match cx.phase { Phase::Sleep => { has_slept = true; // Immediately enter the mark phase cx.switch(Phase::Mark); } Phase::Mark => { if cx.mark_one(root).is_break() { if stop <= Stop::FullyMarked { break; } else { // If we have no gray objects left, we enter the sweep phase. cx.switch(Phase::Sweep); // Set `sweep to the current head of our `all` linked list. Any new // allocations during the newly-entered `Phase:Sweep` will update `all`, // but will *not* be reachable from `this.sweep`. cx.sweep = cx.all.get(); } } } Phase::Sweep => { if stop <= Stop::AtSweep { break; } else if cx.sweep_one().is_break() { // Begin a new cycle. // // We reset our debt if we have done an entire collection cycle (marking and // sweeping) as a single atomic unit. This keeps inherited debt from growing // without bound. cx.metrics.finish_cycle(has_slept); cx.root_needs_trace = true; cx.switch(Phase::Sleep); // We treat a stop condition of `Stop::Finish` as special for the purposes // of logging, and log that we finished a cycle. if stop == Stop::FinishCycle { return; } // Otherwise we always break if we have performed a full cycle as a single // atomic unit, because there cannot be any more work to do in this case. if has_slept { // We shouldn't be stopping here if the stop condition is something like // `Stop::AtSweep`, but this should be impossible since the only way to // get here is to have gone through the entire cycle. assert!(stop == Stop::Full); break; } } } Phase::Drop => unreachable!(), } if run_until == RunUntil::PayDebt && !(cx.metrics.allocation_debt() > 0.0) { break; } } } fn allocate<'gc, T: Collect<'gc>>(&self, t: T) -> NonNull<GcBoxInner<T>> { let header = GcBoxHeader::new::<T>(); header.set_next(self.all.get()); header.set_live(true); header.set_needs_trace(T::NEEDS_TRACE); let alloc_size = header.size_of_box(); // Make the generated code easier to optimize into `T` being constructed in place or at the // very least only memcpy'd once. // For more information, see: https://github.com/kyren/gc-arena/pull/14 let (gc_box, ptr) = unsafe { let mut uninitialized = Box::new(mem::MaybeUninit::<GcBoxInner<T>>::uninit()); core::ptr::write(uninitialized.as_mut_ptr(), GcBoxInner::new(header, t)); let ptr = NonNull::new_unchecked(Box::into_raw(uninitialized) as *mut GcBoxInner<T>); (GcBox::erase(ptr), ptr) }; self.all.set(Some(gc_box)); if self.phase == Phase::Sweep && self.sweep_prev.get().is_none() { self.sweep_prev.set(self.all.get()); } self.metrics.mark_gc_allocated(alloc_size); ptr } #[inline] fn backward_barrier(&self, parent: GcBox, child: Option<GcBox>) { // During the marking phase, if we are mutating a black object, we may add a white object to // it and invalidate the invariant that black objects may not point to white objects. Turn // the black parent object gray to prevent this. // // NOTE: This also adds the pointer to the gray_again queue even if `header.needs_trace()` // is false, but this is not harmful (just wasteful). There's no reason to call a barrier on // a pointer that can't adopt other pointers, so we skip the check. if self.phase == Phase::Mark && parent.header().color() == GcColor::Black && child .map(|c| matches!(c.header().color(), GcColor::White | GcColor::WhiteWeak)) .unwrap_or(true) { // Outline the actual barrier code (which is somewhat expensive and won't be executed // often) to promote the inlining of the write barrier. #[cold] fn barrier(this: &Context, parent: GcBox) { this.make_gray_again(parent); } barrier(&self, parent); } } #[inline] fn backward_barrier_weak(&self, parent: GcBox, child: GcBox) { if self.phase == Phase::Mark && parent.header().color() == GcColor::Black && child.header().color() == GcColor::White { // Outline the actual barrier code (which is somewhat expensive and won't be executed // often) to promote the inlining of the write barrier. #[cold] fn barrier(this: &Context, parent: GcBox) { this.make_gray_again(parent); } barrier(&self, parent); } } #[inline] fn forward_barrier(&self, parent: Option<GcBox>, child: GcBox) { // During the marking phase, if we are mutating a black object, we may add a white object // to it and invalidate the invariant that black objects may not point to white objects. // Immediately trace the child white object to turn it gray (or black) to prevent this. if self.phase == Phase::Mark && parent .map(|p| p.header().color() == GcColor::Black) .unwrap_or(true) { // Outline the actual barrier code (which is somewhat expensive and won't be executed // often) to promote the inlining of the write barrier. #[cold] fn barrier(this: &Context, child: GcBox) { this.trace(child); } barrier(&self, child); } } #[inline] fn forward_barrier_weak(&self, parent: Option<GcBox>, child: GcBox) { // During the marking phase, if we are mutating a black object, we may add a white object // to it and invalidate the invariant that black objects may not point to white objects. // Immediately trace the child white object to turn it gray (or black) to prevent this. if self.phase == Phase::Mark && parent .map(|p| p.header().color() == GcColor::Black) .unwrap_or(true) { // Outline the actual barrier code (which is somewhat expensive and won't be executed // often) to promote the inlining of the write barrier. #[cold] fn barrier(this: &Context, child: GcBox) { this.trace_weak(child); } barrier(&self, child); } } #[inline] fn trace(&self, gc_box: GcBox) { let header = gc_box.header(); let color = header.color(); match color { GcColor::Black | GcColor::Gray => {} GcColor::White | GcColor::WhiteWeak => { if header.needs_trace() { // A white traceable object is not in the gray queue, becomes gray and enters // the normal gray queue. header.set_color(GcColor::Gray); debug_assert!(header.is_live()); self.gray.push(gc_box); } else { // A white object that doesn't need tracing simply becomes black. header.set_color(GcColor::Black); } // Only marking the *first* time counts as a mark metric. if color == GcColor::White { self.metrics.mark_gc_marked(header.size_of_box()); } } } } #[inline] fn trace_weak(&self, gc_box: GcBox) { let header = gc_box.header(); if header.color() == GcColor::White { header.set_color(GcColor::WhiteWeak); self.metrics.mark_gc_marked(header.size_of_box()); } } /// Determines whether or not a Gc pointer is safe to be upgraded. /// This is used by weak pointers to determine if it can safely upgrade to a strong pointer. #[inline] fn upgrade(&self, gc_box: GcBox) -> bool { let header = gc_box.header(); // This object has already been freed, definitely not safe to upgrade. if !header.is_live() { return false; } // Consider the different possible phases of the GC: // * In `Phase::Sleep`, the GC is not running, so we can upgrade. // If the newly-created `Gc` or `GcCell` survives the current `arena.mutate` // call, then the situtation is equivalent to having copied an existing `Gc`/`GcCell`, // or having created a new allocation. // // * In `Phase::Mark`: // If the newly-created `Gc` or `GcCell` survives the current `arena.mutate` // call, then it must have been stored somewhere, triggering a write barrier. // This will ensure that the new `Gc`/`GcCell` gets traced (if it's now reachable) // before we transition to `Phase::Sweep`. // // * In `Phase::Sweep`: // If the allocation is `WhiteWeak`, then it's impossible for it to have been freshly- // created during this `Phase::Sweep`. `WhiteWeak` is only set when a white `GcWeak/ // GcWeakCell` is traced. A `GcWeak/GcWeakCell` must be created from an existing `Gc/ // GcCell` via `downgrade()`, so `WhiteWeak` means that a `GcWeak` / `GcWeakCell` existed // during the last `Phase::Mark.` // // Therefore, a `WhiteWeak` object is guaranteed to be deallocated during this // `Phase::Sweep`, and we must not upgrade it. // // Conversely, it's always safe to upgrade a white object that is not `WhiteWeak`. // In order to call `upgrade`, you must have a `GcWeak/GcWeakCell`. Since it is // not `WhiteWeak` there cannot have been any `GcWeak/GcWeakCell`s during the // last `Phase::Mark`, so the weak pointer must have been created during this // `Phase::Sweep`. This is only possible if the underlying allocation was freshly-created // - if the allocation existed during `Phase::Mark` but was not traced, then it // must have been unreachable, which means that the user wouldn't have been able to call // `downgrade`. Therefore, we can safely upgrade, knowing that the object will not be // freed during this phase, despite being white. if self.phase == Phase::Sweep && header.color() == GcColor::WhiteWeak { return false; } true } #[inline] fn resurrect(&self, gc_box: GcBox) { let header = gc_box.header(); debug_assert_eq!(self.phase, Phase::Mark); debug_assert!(header.is_live()); let color = header.color(); if matches!(header.color(), GcColor::White | GcColor::WhiteWeak) { header.set_color(GcColor::Gray); self.gray.push(gc_box); // Only marking the *first* time counts as a mark metric. if color == GcColor::White { self.metrics.mark_gc_marked(header.size_of_box()); } } } fn mark_one<'gc, R: Collect<'gc> + ?Sized>(&mut self, root: &R) -> ControlFlow<()> { // We look for an object first in the normal gray queue, then the "gray again" queue. // Processing "gray again" objects later gives them more time to be mutated again without // triggering another write barrier. let next_gray = if let Some(gc_box) = self.gray.pop() { Some(gc_box) } else if let Some(gc_box) = self.gray_again.pop() { Some(gc_box) } else { None }; if let Some(gc_box) = next_gray { // We always mark work for objects processed from both the gray and "gray again" queue. // When objects are placed into the "gray again" queue due to a write barrier, the // original work is *undone*, so we do it again here. self.metrics.mark_gc_traced(gc_box.header().size_of_box()); gc_box.header().set_color(GcColor::Black); // If we have an object in the gray queue, take one, trace it, and turn it black. // Our `Collect::trace` call may panic, and if it does the object will be lost from // the gray queue but potentially incompletely traced. By catching a panic during // `Arena::collect()`, this could lead to memory unsafety. // // So, if the `Collect::trace` call panics, we need to add the popped object back to the // `gray_again` queue. If the panic is caught, this will maybe give some time for its // trace method to not panic before attempting to collect it again. struct DropGuard<'a> { context: &'a mut Context, gc_box: GcBox, } impl<'a> Drop for DropGuard<'a> { fn drop(&mut self) { self.context.make_gray_again(self.gc_box); } } let guard = DropGuard { context: self, gc_box, }; debug_assert!(gc_box.header().is_live()); unsafe { gc_box.trace_value(guard.context) } mem::forget(guard); ControlFlow::Continue(()) } else if self.root_needs_trace { // We treat the root object as gray if `root_needs_trace` is set, and we process it at // the end of the gray queue for the same reason as the "gray again" objects. root.trace(self); self.root_needs_trace = false; ControlFlow::Continue(()) } else { ControlFlow::Break(()) } } fn sweep_one(&mut self) -> ControlFlow<()> { let Some(mut sweep) = self.sweep else { self.sweep_prev.set(None); return ControlFlow::Break(()); }; let sweep_header = sweep.header(); let sweep_size = sweep_header.size_of_box(); let next_box = sweep_header.next(); self.sweep = next_box; match sweep_header.color() { // If the next object in the sweep portion of the main list is white, we // need to remove it from the main object list and destruct it. GcColor::White => { if let Some(sweep_prev) = self.sweep_prev.get() { sweep_prev.header().set_next(next_box); } else { // If `sweep_prev` is None, then the sweep pointer is also the // beginning of the main object list, so we need to adjust it. debug_assert_eq!(self.all.get(), Some(sweep)); self.all.set(next_box); } // SAFETY: this object is white, and wasn't traced by a `GcWeak` during this cycle, // meaning it cannot have either strong or weak pointers, so we can drop the whole // object. unsafe { if sweep_header.is_live() { // If the alive flag is set, that means we haven't dropped the inner value // of this object, sweep.drop_in_place(); self.metrics.mark_gc_dropped(sweep_size); } sweep.dealloc(); self.metrics.mark_gc_freed(sweep_size); } } // Keep the `GcBox` as part of the linked list if we traced a weak pointer to it. The // weak pointer still needs access to the `GcBox` to be able to check if the object // is still alive. We can only deallocate the `GcBox`, once there are no weak pointers // left. GcColor::WhiteWeak => { self.sweep_prev.set(Some(sweep)); sweep_header.set_color(GcColor::White); if sweep_header.is_live() { sweep_header.set_live(false); // SAFETY: Since this object is white, that means there are no more strong // pointers to this object, only weak pointers, so we can safely drop its // contents. unsafe { sweep.drop_in_place() } self.metrics.mark_gc_dropped(sweep_size); } self.metrics.mark_gc_remembered(sweep_size); } // If the next object in the sweep portion of the main list is black, we // need to keep it but turn it back white. GcColor::Black => { self.sweep_prev.set(Some(sweep)); sweep_header.set_color(GcColor::White); self.metrics.mark_gc_remembered(sweep_size); } // No gray objects should be in this part of the main list, they should // be added to the beginning of the list before the sweep pointer, so it // should not be possible for us to encounter them here. GcColor::Gray => { debug_assert!(false, "unexpected gray object in sweep list") } } ControlFlow::Continue(()) } // Take a black pointer and turn it gray and put it in the `gray_again` queue. fn make_gray_again(&self, gc_box: GcBox) { let header = gc_box.header(); debug_assert_eq!(header.color(), GcColor::Black); header.set_color(GcColor::Gray); self.gray_again.push(gc_box); self.metrics.mark_gc_untraced(header.size_of_box()); } } /// Helper type for managing phase transitions. struct PhaseGuard<'a> { cx: &'a mut Context, } impl<'a> Deref for PhaseGuard<'a> { type Target = Context; #[inline(always)] fn deref(&self) -> &Context { &self.cx } } impl<'a> DerefMut for PhaseGuard<'a> { #[inline(always)] fn deref_mut(&mut self) -> &mut Context { &mut self.cx } } impl<'a> PhaseGuard<'a> { fn enter(cx: &'a mut Context, phase: Option<Phase>) -> Self { if let Some(phase) = phase { cx.phase = phase; } Self { cx } } fn switch(&mut self, phase: Phase) { self.cx.phase = phase; } } // A shared, internally mutable `Vec<T>` that avoids the overhead of `RefCell`. Used for the "gray" // and "gray again" queues. // // SAFETY: We do not return any references at all to the contents of the internal `UnsafeCell`, nor // do we provide any methods with callbacks. Since this type is `!Sync`, only one reference to the // `UnsafeCell` contents can be alive at any given time, thus we cannot violate aliasing rules. #[derive(Default)] struct Queue<T> { vec: UnsafeCell<Vec<T>>, } impl<T> Queue<T> { fn new() -> Self { Self { vec: UnsafeCell::new(Vec::new()), } } fn is_empty(&self) -> bool { unsafe { (*self.vec.get().cast_const()).is_empty() } } fn push(&self, val: T) { unsafe { (*self.vec.get()).push(val); } } fn pop(&self) -> Option<T> { unsafe { (*self.vec.get()).pop() } } }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/dynamic_roots.rs
Rust
use core::{cell::RefCell, fmt, mem}; use std::{ rc::{Rc, Weak}, vec::Vec, }; use crate::dmm::{ Gc, Mutation, Rootable, arena::Root, collect::{Collect, Trace}, metrics::Metrics, }; /// A way of registering GC roots dynamically. /// /// Use this type as (a part of) an [`Arena`](crate::Arena) root to enable dynamic rooting of /// GC'd objects through [`DynamicRoot`] handles. // // SAFETY: This allows us to convert `Gc<'gc>` pointers to `Gc<'static>` and back, and this is VERY // sketchy. We know it is safe because: // 1) The `DynamicRootSet` must be created inside an arena and is branded with an invariant `'gc` // lifetime. // 2) When stashing a `Gc<'gc, R>` pointer, the invariant `'gc` lifetimes must match. // 3) When fetching, we make sure that the `DynamicRoot` `slots` field points to the same object // as the `slots` field in the `DynamicRootSet`. We never drop this `Rc` or change the `Weak` // held in any `DynamicRoot`, so if they both point to the same object, the original `Gc` // pointer *must* have originally been stashed using *this* set. Therefore, it is safe to cast // it back to whatever our current `'gc` lifetime is. #[derive(Copy, Clone)] pub struct DynamicRootSet<'gc>(Gc<'gc, Inner<'gc>>); unsafe impl<'gc> Collect<'gc> for DynamicRootSet<'gc> { fn trace<T: Trace<'gc>>(&self, cc: &mut T) { cc.trace(&self.0); } } impl<'gc> DynamicRootSet<'gc> { /// Creates a new, empty root set. pub fn new(mc: &Mutation<'gc>) -> Self { DynamicRootSet(Gc::new( mc, Inner { slots: Rc::new(RefCell::new(Slots::new(mc.metrics().clone()))), }, )) } /// Puts a root inside this root set. /// /// The returned handle can be freely stored outside the current arena, and will keep the root /// alive across garbage collections. pub fn stash<R: for<'a> Rootable<'a>>( &self, mc: &Mutation<'gc>, root: Gc<'gc, Root<'gc, R>>, ) -> DynamicRoot<R> { // SAFETY: We are adopting a new `Gc` pointer, so we must invoke a write barrier. mc.backward_barrier(Gc::erase(self.0), Some(Gc::erase(root))); let mut slots = self.0.slots.borrow_mut(); let index = slots.add(unsafe { Gc::cast(root) }); let ptr = unsafe { mem::transmute::<Gc<'gc, Root<'gc, R>>, Gc<'static, Root<'static, R>>>(root) }; let slots = unsafe { mem::transmute::<Weak<RefCell<Slots<'gc>>>, Weak<RefCell<Slots<'static>>>>( Rc::downgrade(&self.0.slots), ) }; DynamicRoot { ptr, slots, index } } /// Gets immutable access to the given root. /// /// # Panics /// /// Panics if the handle doesn't belong to this root set. For the non-panicking variant, use /// [`try_fetch`](Self::try_fetch). #[inline] pub fn fetch<R: for<'r> Rootable<'r>>(&self, root: &DynamicRoot<R>) -> Gc<'gc, Root<'gc, R>> { if self.contains(root) { unsafe { mem::transmute::<Gc<'static, Root<'static, R>>, Gc<'gc, Root<'gc, R>>>(root.ptr) } } else { panic!("mismatched root set") } } /// Gets immutable access to the given root, or returns an error if the handle doesn't belong /// to this root set. #[inline] pub fn try_fetch<R: for<'r> Rootable<'r>>( &self, root: &DynamicRoot<R>, ) -> Result<Gc<'gc, Root<'gc, R>>, MismatchedRootSet> { if self.contains(root) { Ok(unsafe { mem::transmute::<Gc<'static, Root<'static, R>>, Gc<'gc, Root<'gc, R>>>(root.ptr) }) } else { Err(MismatchedRootSet(())) } } /// Tests if the given handle belongs to this root set. #[inline] pub fn contains<R: for<'r> Rootable<'r>>(&self, root: &DynamicRoot<R>) -> bool { // NOTE: We are making an assumption about how `Weak` works that is currently true and // surely MUST continue to be true, but is possibly under-specified in the stdlib. We are // assuming that if the `Weak` pointer held in the given `DynamicRoot` points to a *dropped* // root set, that `Weak::as_ptr` will return a pointer that cannot possibly belong to a // live `Rc`. let ours = unsafe { mem::transmute::<*const RefCell<Slots<'gc>>, *const RefCell<Slots<'static>>>( Rc::as_ptr(&self.0.slots), ) }; let theirs = Weak::as_ptr(&root.slots); ours == theirs } } /// Handle to a `Gc` pointer held inside a [`DynamicRootSet`] which is `'static` and can be held /// outside of the arena. pub struct DynamicRoot<R: for<'gc> Rootable<'gc>> { ptr: Gc<'static, Root<'static, R>>, slots: Weak<RefCell<Slots<'static>>>, index: Index, } impl<R: for<'gc> Rootable<'gc>> Drop for DynamicRoot<R> { fn drop(&mut self) { if let Some(slots) = self.slots.upgrade() { slots.borrow_mut().dec(self.index); } } } impl<R: for<'gc> Rootable<'gc>> Clone for DynamicRoot<R> { fn clone(&self) -> Self { if let Some(slots) = self.slots.upgrade() { slots.borrow_mut().inc(self.index); } Self { ptr: self.ptr, slots: self.slots.clone(), index: self.index, } } } impl<R: for<'gc> Rootable<'gc>> DynamicRoot<R> { /// Get a pointer to the held object. /// /// This returns [`Gc::as_ptr`] for the [`Gc`] provided when the `DynamicRoot` is stashed. /// /// # Safety /// /// It is possible to use this to reconstruct the original `Gc` pointer by calling the unsafe /// [`Gc::from_ptr`], but this is incredibly dangerous! /// /// First, if the [`DynamicRootSet`] in which the `DynamicRoot` was stashed has been collected, /// then either the returned pointer or other transitive `Gc` pointers objects may be dangling. /// The parent `DynamicRootSet` *must* still be uncollected in order to do this soundly. /// /// Second, the `'gc` lifetime returned here is unbound, so it is meaningless and can allow /// improper mixing of objects across arenas. The returned `'gc` lifetime must be bound to only /// the arena that holds the parent `DynamicRootSet`. #[inline] pub fn as_ptr<'gc>(&self) -> *const Root<'gc, R> { unsafe { mem::transmute::<&Root<'static, R>, &Root<'gc, R>>(&self.ptr) as *const _ } } } /// Error returned when trying to fetch a [`DynamicRoot`] from the wrong [`DynamicRootSet`]. #[derive(Debug)] pub struct MismatchedRootSet(()); impl fmt::Display for MismatchedRootSet { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("mismatched root set") } } impl std::error::Error for MismatchedRootSet {} struct Inner<'gc> { slots: Rc<RefCell<Slots<'gc>>>, } unsafe impl<'gc> Collect<'gc> for Inner<'gc> { fn trace<T: Trace<'gc>>(&self, cc: &mut T) { cc.trace(&*self.slots.borrow()); } } type Index = usize; // By avoiding Option<usize>, `Slot` can go from 24 bytes to 16. // // usize::MAX can never be a valid index without using more than `usize::MAX` memory in the slots // vec, which is impossible. const NULL_INDEX: Index = usize::MAX; enum Slot<'gc> { Vacant { next_free: Index }, Occupied { root: Gc<'gc, ()>, ref_count: usize }, } unsafe impl<'gc> Collect<'gc> for Slot<'gc> { fn trace<T: Trace<'gc>>(&self, cc: &mut T) { match self { Slot::Vacant { .. } => {} Slot::Occupied { root, ref_count: _ } => cc.trace_gc(*root), } } } struct Slots<'gc> { metrics: Metrics, slots: Vec<Slot<'gc>>, next_free: Index, } impl<'gc> Drop for Slots<'gc> { fn drop(&mut self) { self.metrics .mark_external_deallocation(self.slots.capacity() * mem::size_of::<Slot>()); } } unsafe impl<'gc> Collect<'gc> for Slots<'gc> { fn trace<T: Trace<'gc>>(&self, cc: &mut T) { cc.trace(&self.slots); } } impl<'gc> Slots<'gc> { fn new(metrics: Metrics) -> Self { Self { metrics, slots: Vec::new(), next_free: NULL_INDEX, } } fn add(&mut self, p: Gc<'gc, ()>) -> Index { // Occupied slot refcount starts at 0. A refcount of 0 and a set ptr implies that there is // *one* live reference. if self.next_free != NULL_INDEX { let idx = self.next_free; let slot = &mut self.slots[idx]; match *slot { Slot::Vacant { next_free } => { self.next_free = next_free; } Slot::Occupied { .. } => panic!("free slot linked list corrupted"), } *slot = Slot::Occupied { root: p, ref_count: 0, }; idx } else { let idx = self.slots.len(); let old_capacity = self.slots.capacity(); self.slots.push(Slot::Occupied { root: p, ref_count: 0, }); let new_capacity = self.slots.capacity(); debug_assert!(new_capacity >= old_capacity); if new_capacity > old_capacity { self.metrics.mark_external_allocation( (new_capacity - old_capacity) * mem::size_of::<Slot>(), ); } idx } } fn inc(&mut self, idx: Index) { match &mut self.slots[idx] { Slot::Occupied { ref_count, .. } => { *ref_count = ref_count .checked_add(1) .expect("DynamicRoot refcount overflow!"); } Slot::Vacant { .. } => panic!("taken slot has been improperly freed"), } } fn dec(&mut self, idx: Index) { let slot = &mut self.slots[idx]; match slot { Slot::Occupied { ref_count, .. } => { if *ref_count == 0 { *slot = Slot::Vacant { next_free: self.next_free, }; self.next_free = idx; } else { *ref_count -= 1; } } Slot::Vacant { .. } => panic!("taken slot has been improperly freed"), } } }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/gc.rs
Rust
use core::{ alloc::Layout, borrow::Borrow, fmt::{self, Debug, Display, Pointer}, hash::{Hash, Hasher}, marker::PhantomData, ops::Deref, ptr::NonNull, }; use crate::dmm::{ Finalization, barrier::{Unlock, Write}, collect::{Collect, Trace}, context::Mutation, gc_weak::GcWeak, static_collect::Static, types::{GcBox, GcBoxHeader, GcBoxInner, GcColor, Invariant}, }; /// A garbage collected pointer to a type T. Implements Copy, and is implemented as a plain machine /// pointer. You can only allocate `Gc` pointers through a `&Mutation<'gc>` inside an arena type, /// and through "generativity" such `Gc` pointers may not escape the arena they were born in or /// be stored inside TLS. This, combined with correct `Collect` implementations, means that `Gc` /// pointers will never be dangling and are always safe to access. pub struct Gc<'gc, T: ?Sized + 'gc> { pub(crate) ptr: NonNull<GcBoxInner<T>>, pub(crate) _invariant: Invariant<'gc>, } impl<'gc, T: Debug + ?Sized + 'gc> Debug for Gc<'gc, T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, fmt) } } impl<'gc, T: ?Sized + 'gc> Pointer for Gc<'gc, T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Pointer::fmt(&Gc::as_ptr(*self), fmt) } } impl<'gc, T: Display + ?Sized + 'gc> Display for Gc<'gc, T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, fmt) } } impl<'gc, T: ?Sized + 'gc> Copy for Gc<'gc, T> {} impl<'gc, T: ?Sized + 'gc> Clone for Gc<'gc, T> { #[inline] fn clone(&self) -> Gc<'gc, T> { *self } } unsafe impl<'gc, T: ?Sized + 'gc> Collect<'gc> for Gc<'gc, T> { #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { cc.trace_gc(Self::erase(*self)) } } impl<'gc, T: ?Sized + 'gc> Deref for Gc<'gc, T> { type Target = T; #[inline] fn deref(&self) -> &T { unsafe { &self.ptr.as_ref().value } } } impl<'gc, T: ?Sized + 'gc> AsRef<T> for Gc<'gc, T> { #[inline] fn as_ref(&self) -> &T { unsafe { &self.ptr.as_ref().value } } } impl<'gc, T: ?Sized + 'gc> Borrow<T> for Gc<'gc, T> { #[inline] fn borrow(&self) -> &T { unsafe { &self.ptr.as_ref().value } } } impl<'gc, T: Collect<'gc> + 'gc> Gc<'gc, T> { #[inline] pub fn new(mc: &Mutation<'gc>, t: T) -> Gc<'gc, T> { Gc { ptr: mc.allocate(t), _invariant: PhantomData, } } } impl<'gc, T: 'static> Gc<'gc, T> { /// Create a new `Gc` pointer from a static value. /// /// This method does not require that the type `T` implement `Collect`. This uses [`Static`] /// internally to automatically provide a trivial `Collect` impl and is equivalent to the /// following code: /// /// ```rust /// # use gc_arena::{Gc, Static}; /// # fn main() { /// # gc_arena::arena::rootless_mutate(|mc| { /// struct MyStaticStruct; /// let p = Gc::new(mc, Static(MyStaticStruct)); /// // This is allowed because `Static` is `#[repr(transparent)]` /// let p: Gc<MyStaticStruct> = unsafe { Gc::cast(p) }; /// # }); /// # } /// ``` #[inline] pub fn new_static(mc: &Mutation<'gc>, t: T) -> Gc<'gc, T> { let p = Gc::new(mc, Static(t)); // SAFETY: `Static` is `#[repr(transparent)]`. unsafe { Gc::cast::<T>(p) } } } impl<'gc, T: ?Sized + 'gc> Gc<'gc, T> { /// Cast a `Gc` pointer to a different type. /// /// # Safety /// It must be valid to dereference a `*mut U` that has come from casting a `*mut T`. #[inline] pub unsafe fn cast<U: 'gc>(this: Gc<'gc, T>) -> Gc<'gc, U> { Gc { ptr: NonNull::cast(this.ptr), _invariant: PhantomData, } } /// Cast a `Gc` to the unit type. /// /// This is exactly the same as `unsafe { Gc::cast::<()>(this) }`, but we can provide this /// method safely because it is always safe to dereference a `*mut ()` that has come from /// casting a `*mut T`. #[inline] pub fn erase(this: Gc<'gc, T>) -> Gc<'gc, ()> { unsafe { Gc::cast(this) } } /// Retrieve a `Gc` from a raw pointer obtained from `Gc::as_ptr` /// /// # Safety /// The provided pointer must have been obtained from `Gc::as_ptr`, and the pointer must not /// have been collected yet. #[inline] pub unsafe fn from_ptr(ptr: *const T) -> Gc<'gc, T> { unsafe { let layout = Layout::new::<GcBoxHeader>(); let (_, header_offset) = layout.extend(Layout::for_value(&*ptr)).unwrap(); let header_offset = -(header_offset as isize); let ptr = (ptr as *mut T).byte_offset(header_offset) as *mut GcBoxInner<T>; Gc { ptr: NonNull::new_unchecked(ptr), _invariant: PhantomData, } } } } impl<'gc, T: Unlock + ?Sized + 'gc> Gc<'gc, T> { /// Shorthand for [`Gc::write`]`(mc, self).`[`unlock()`](Write::unlock). #[inline] pub fn unlock(self, mc: &Mutation<'gc>) -> &'gc T::Unlocked { Gc::write(mc, self).unlock() } } impl<'gc, T: ?Sized + 'gc> Gc<'gc, T> { /// Obtains a long-lived reference to the contents of this `Gc`. /// /// Unlike `AsRef` or `Deref`, the returned reference isn't bound to the `Gc` itself, and /// will stay valid for the entirety of the current arena callback. #[inline] pub fn as_ref(self: Gc<'gc, T>) -> &'gc T { // SAFETY: The returned reference cannot escape the current arena callback, as `&'gc T` // never implements `Collect` (unless `'gc` is `'static`, which is impossible here), and // so cannot be stored inside the GC root. unsafe { &self.ptr.as_ref().value } } #[inline] pub fn downgrade(this: Gc<'gc, T>) -> GcWeak<'gc, T> { GcWeak { inner: this } } /// Triggers a write barrier on this `Gc`, allowing for safe mutation. /// /// This triggers an unrestricted *backwards* write barrier on this pointer, meaning that it is /// guaranteed that this pointer can safely adopt *any* arbitrary child pointers (until the next /// time that collection is triggered). /// /// It returns a reference to the inner `T` wrapped in a `Write` marker to allow for /// unrestricted mutation on the held type or any of its directly held fields. #[inline] pub fn write(mc: &Mutation<'gc>, gc: Self) -> &'gc Write<T> { unsafe { mc.backward_barrier(Gc::erase(gc), None); // SAFETY: the write barrier stays valid until the end of the current callback. Write::assume(gc.as_ref()) } } /// Returns true if two `Gc`s point to the same allocation. /// /// Similarly to `Rc::ptr_eq` and `Arc::ptr_eq`, this function ignores the metadata of `dyn` /// pointers. #[inline] pub fn ptr_eq(this: Gc<'gc, T>, other: Gc<'gc, T>) -> bool { // TODO: Equivalent to `core::ptr::addr_eq`: // https://github.com/rust-lang/rust/issues/116324 Gc::as_ptr(this) as *const () == Gc::as_ptr(other) as *const () } #[inline] pub fn as_ptr(gc: Gc<'gc, T>) -> *const T { unsafe { let inner = gc.ptr.as_ptr(); core::ptr::addr_of!((*inner).value) as *const T } } /// Returns true when a pointer is *dead* during finalization. This is equivalent to /// `GcWeak::is_dead` for strong pointers. /// /// Any strong pointer reachable from the root will never be dead, BUT there can be strong /// pointers reachable only through other weak pointers that can be dead. #[inline] pub fn is_dead(_: &Finalization<'gc>, gc: Gc<'gc, T>) -> bool { let inner = unsafe { gc.ptr.as_ref() }; matches!(inner.header.color(), GcColor::White | GcColor::WhiteWeak) } /// Manually marks a dead `Gc` pointer as reachable and keeps it alive. /// /// Equivalent to `GcWeak::resurrect` for strong pointers. Manually marks this pointer and /// all transitively held pointers as reachable, thus keeping them from being dropped this /// collection cycle. #[inline] pub fn resurrect(fc: &Finalization<'gc>, gc: Gc<'gc, T>) { unsafe { fc.resurrect(GcBox::erase(gc.ptr)); } } } impl<'gc, T: PartialEq + ?Sized + 'gc> PartialEq for Gc<'gc, T> { fn eq(&self, other: &Self) -> bool { (**self).eq(other) } fn ne(&self, other: &Self) -> bool { (**self).ne(other) } } impl<'gc, T: Eq + ?Sized + 'gc> Eq for Gc<'gc, T> {} impl<'gc, T: PartialOrd + ?Sized + 'gc> PartialOrd for Gc<'gc, T> { fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { (**self).partial_cmp(other) } fn le(&self, other: &Self) -> bool { (**self).le(other) } fn lt(&self, other: &Self) -> bool { (**self).lt(other) } fn ge(&self, other: &Self) -> bool { (**self).ge(other) } fn gt(&self, other: &Self) -> bool { (**self).gt(other) } } impl<'gc, T: Ord + ?Sized + 'gc> Ord for Gc<'gc, T> { fn cmp(&self, other: &Self) -> core::cmp::Ordering { (**self).cmp(other) } } impl<'gc, T: Hash + ?Sized + 'gc> Hash for Gc<'gc, T> { fn hash<H: Hasher>(&self, state: &mut H) { (**self).hash(state) } }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/gc_weak.rs
Rust
use crate::dmm::Mutation; use crate::dmm::collect::{Collect, Trace}; use crate::dmm::context::Finalization; use crate::dmm::gc::Gc; use crate::dmm::types::GcBox; use core::fmt::{self, Debug}; pub struct GcWeak<'gc, T: ?Sized + 'gc> { pub(crate) inner: Gc<'gc, T>, } impl<'gc, T: ?Sized + 'gc> Copy for GcWeak<'gc, T> {} impl<'gc, T: ?Sized + 'gc> Clone for GcWeak<'gc, T> { #[inline] fn clone(&self) -> GcWeak<'gc, T> { *self } } impl<'gc, T: ?Sized + 'gc> Debug for GcWeak<'gc, T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "(GcWeak)") } } unsafe impl<'gc, T: ?Sized + 'gc> Collect<'gc> for GcWeak<'gc, T> { #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { cc.trace_gc_weak(Self::erase(*self)) } } impl<'gc, T: ?Sized + 'gc> GcWeak<'gc, T> { /// If the `GcWeak` pointer can be safely upgraded to a strong pointer, upgrade it. /// /// This will fail if the value the `GcWeak` points to is dropped, or if we are in the /// [`crate::arena::CollectionPhase::Sweeping`] phase and we know the pointer *will* be dropped. #[inline] pub fn upgrade(self, mc: &Mutation<'gc>) -> Option<Gc<'gc, T>> { let ptr = unsafe { GcBox::erase(self.inner.ptr) }; mc.upgrade(ptr).then(|| self.inner) } /// Returns whether the value referenced by this `GcWeak` has already been dropped. /// /// # Note /// /// This is not the same as using [`GcWeak::upgrade`] and checking if the result is `None`! A /// `GcWeak` pointer can fail to upgrade *without* having been dropped if the current collection /// phase is [`crate::arena::CollectionPhase::Sweeping`] and the pointer *will* be dropped. /// /// It is not safe to use this to use this and casting as a substitute for [`GcWeak::upgrade`]. #[inline] pub fn is_dropped(self) -> bool { !unsafe { self.inner.ptr.as_ref() }.header.is_live() } /// Returns true when a pointer is *dead* during finalization. /// /// This is a weaker condition than being *dropped*, as the pointer *may* still be valid. Being /// *dead* means that there were no strong pointers pointing to this weak pointer that were /// found by the marking phase, and if it is not already dropped, it *will* be dropped as soon /// as collection resumes. /// /// If the pointer is still valid, it may be resurrected using `GcWeak::upgrade` or /// `GcWeak::resurrect`. /// /// NOTE: This returns true if the pointer was destined to be collected at the **start** of the /// current finalization callback. Resurrecting one pointer can transitively resurrect others, /// and this method does not reflect this from within the same finalization call! If transitive /// resurrection is important, you may have to carefully call finalize multiple times for one /// collection cycle with marking stages in-between, and in the precise order that you want. #[inline] pub fn is_dead(self, fc: &Finalization<'gc>) -> bool { Gc::is_dead(fc, self.inner) } /// Manually marks a dead (but non-dropped) `GcWeak` as strongly reachable and keeps it alive. /// /// This is similar to a write barrier in that it moves the collection phase back to `Marking` /// if it is not already there. All transitively held pointers from this will also be marked as /// reachable once marking resumes. /// /// Returns the upgraded `Gc` pointer as a convenience. Whether or not the strong pointer is /// stored anywhere, the value and all transitively reachable values are still guaranteed to not /// be dropped this collection cycle. #[inline] pub fn resurrect(self, fc: &Finalization<'gc>) -> Option<Gc<'gc, T>> { // SAFETY: We know that we are currently marking, so any non-dropped pointer is safe to // resurrect. if unsafe { self.inner.ptr.as_ref() }.header.is_live() { Gc::resurrect(fc, self.inner); Some(self.inner) } else { None } } /// Returns true if two `GcWeak`s point to the same allocation. /// /// Similarly to `Rc::ptr_eq` and `Arc::ptr_eq`, this function ignores the metadata of `dyn` /// pointers. #[inline] pub fn ptr_eq(this: GcWeak<'gc, T>, other: GcWeak<'gc, T>) -> bool { // TODO: Equivalent to `core::ptr::addr_eq`: // https://github.com/rust-lang/rust/issues/116324 this.as_ptr() as *const () == other.as_ptr() as *const () } #[inline] pub fn as_ptr(self) -> *const T { Gc::as_ptr(self.inner) } /// Cast the internal pointer to a different type. /// /// # Safety /// It must be valid to dereference a `*mut U` that has come from casting a `*mut T`. #[inline] pub unsafe fn cast<U: 'gc>(this: GcWeak<'gc, T>) -> GcWeak<'gc, U> { unsafe { let inner = Gc::cast::<U>(this.inner); GcWeak { inner } } } /// Cast a `GcWeak` to the unit type. /// /// This is exactly the same as `unsafe { GcWeak::cast::<()>(this) }`, but we can provide this /// method safely because it is always safe to dereference a `*mut ()` that has come from /// casting a `*mut T`. #[inline] pub fn erase(this: GcWeak<'gc, T>) -> GcWeak<'gc, ()> { GcWeak { inner: Gc::erase(this.inner), } } /// Retrieve a `GcWeak` from a raw pointer obtained from `GcWeak::as_ptr` /// /// # Safety /// The provided pointer must have been obtained from `GcWeak::as_ptr` or `Gc::as_ptr`, and /// the pointer must not have been *fully* collected yet (it may be a dropped but valid weak /// pointer). #[inline] pub unsafe fn from_ptr(ptr: *const T) -> GcWeak<'gc, T> { let inner = unsafe { Gc::from_ptr(ptr) }; GcWeak { inner } } }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/hashbrown.rs
Rust
mod inner { use core::hash::{BuildHasher, Hash}; use std::alloc::Allocator; use crate::dmm::barrier::IndexWrite; use crate::dmm::collect::{Collect, Trace}; unsafe impl<'gc, K, V, S, A> Collect<'gc> for hashbrown::HashMap<K, V, S, A> where K: Collect<'gc>, V: Collect<'gc>, S: 'static, A: Allocator + Clone + Collect<'gc>, { const NEEDS_TRACE: bool = K::NEEDS_TRACE || V::NEEDS_TRACE || A::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for (k, v) in self { cc.trace(k); cc.trace(v); } cc.trace(self.allocator()); } } unsafe impl<'gc, T, S, A> Collect<'gc> for hashbrown::HashSet<T, S, A> where T: Collect<'gc>, S: 'static, A: Allocator + Clone + Collect<'gc>, { const NEEDS_TRACE: bool = T::NEEDS_TRACE || A::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for v in self { cc.trace(v); } cc.trace(self.allocator()); } } unsafe impl<'gc, T, A> Collect<'gc> for hashbrown::HashTable<T, A> where T: Collect<'gc>, A: Allocator + Clone + Collect<'gc>, { const NEEDS_TRACE: bool = T::NEEDS_TRACE || A::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { for v in self { cc.trace(v); } cc.trace(self.allocator()); } } unsafe impl<K, V, S, A, Q> IndexWrite<&Q> for hashbrown::HashMap<K, V, S, A> where K: Eq + Hash, Q: Hash + hashbrown::Equivalent<K> + ?Sized, S: BuildHasher, A: Allocator, { } }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/lock.rs
Rust
//! GC-aware interior mutability types. use core::{ cell::{BorrowError, BorrowMutError, Cell, OnceCell, Ref, RefCell, RefMut}, cmp::Ordering, fmt, }; use crate::dmm::{ Gc, Mutation, barrier::Unlock, collect::{Collect, Trace}, }; // Helper macro to factor out the common parts of locks types. macro_rules! make_lock_wrapper { ( $(#[$meta:meta])* locked = $locked_type:ident as $gc_locked_type:ident; unlocked = $unlocked_type:ident unsafe $unsafe_unlock_method:ident; $( impl $Sized:ident { $($sized_items:tt)* } impl ?Sized { $($unsized_items:tt)* } )? ) => { /// A wrapper around a [` #[doc = stringify!($unlocked_type)] /// `] that implements [`Collect`]. /// /// Only provides safe read access to the wrapped [` #[doc = stringify!($unlocked_type)] /// `], full write access requires unsafety. /// /// If the ` #[doc = stringify!($locked_type)] /// ` is directly held in a [`Gc`] pointer, safe mutable access is provided, /// since methods on [`Gc`] can ensure that the write barrier is called. $(#[$meta])* #[repr(transparent)] pub struct $locked_type<T $(: ?$Sized)?> { cell: $unlocked_type<T>, } #[doc = concat!("An alias for `Gc<'gc, ", stringify!($locked_type), "<T>>`.")] pub type $gc_locked_type<'gc, T> = Gc<'gc, $locked_type<T>>; $( impl<T> $locked_type<T> { #[inline] pub fn new(t: T) -> $locked_type<T> { Self { cell: $unlocked_type::new(t) } } #[inline] pub fn into_inner(self) -> T { self.cell.into_inner() } $($sized_items)* } impl<T: ?$Sized> $locked_type<T> { #[inline] pub fn as_ptr(&self) -> *mut T { self.cell.as_ptr() } $($unsized_items)* #[doc = concat!("Access the wrapped [`", stringify!($unlocked_type), "`].")] /// /// # Safety /// In order to maintain the invariants of the garbage collector, no new [`Gc`] /// pointers may be adopted by this type as a result of the interior mutability /// afforded by directly accessing the inner [` #[doc = stringify!($unlocked_type)] /// `], unless the write barrier for the containing [`Gc`] pointer is invoked manually /// before collection is triggered. #[inline] pub unsafe fn $unsafe_unlock_method(&self) -> &$unlocked_type<T> { &self.cell } #[inline] pub fn get_mut(&mut self) -> &mut T { self.cell.get_mut() } } )? impl<T $(: ?$Sized)?> Unlock for $locked_type<T> { type Unlocked = $unlocked_type<T>; #[inline] unsafe fn unlock_unchecked(&self) -> &Self::Unlocked { &self.cell } } impl<T> From<T> for $locked_type<T> { #[inline] fn from(t: T) -> Self { Self { cell: t.into() } } } impl<T> From<$unlocked_type<T>> for $locked_type<T> { #[inline] fn from(cell: $unlocked_type<T>) -> Self { Self { cell } } } }; } make_lock_wrapper!( #[derive(Default)] locked = Lock as GcLock; unlocked = Cell unsafe as_cell; impl Sized { #[inline] pub fn get(&self) -> T where T: Copy { self.cell.get() } #[inline] pub fn take(&self) -> T where T: Default { // Despite mutating the contained value, this doesn't need a write barrier, as // the return value of `Default::default` can never contain (non-leaked) `Gc` pointers. // // The reason for this is somewhat subtle, and boils down to lifetime parametricity. // Because Rust doesn't allow naming concrete lifetimes, and because `Default` doesn't // have any lifetime parameters, any potential `'gc` lifetime in `T` must be // existentially quantified. As such, a `Default` implementation that tries to smuggle // a branded `Gc` pointer or `Mutation` through external state (e.g. thread // locals) must use unsafe code and cannot be sound in the first place, as it has no // way to ensure that the smuggled data has the correct `'gc` brand. self.cell.take() } } impl ?Sized {} ); impl<T: Copy + fmt::Debug> fmt::Debug for Lock<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("Lock").field(&self.cell).finish() } } impl<'gc, T: Copy + 'gc> Gc<'gc, Lock<T>> { #[inline] pub fn get(self) -> T { self.cell.get() } #[inline] pub fn set(self, mc: &Mutation<'gc>, t: T) { self.unlock(mc).set(t); } } unsafe impl<'gc, T: Collect<'gc> + Copy + 'gc> Collect<'gc> for Lock<T> { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { // Okay, so this calls `T::trace` on a *copy* of `T`. // // This is theoretically a correctness issue, because technically `T` could have interior // mutability and modify the copy, and this modification would be lost. // // However, currently there is not a type in rust that allows for interior mutability that // is also `Copy`, so this *currently* impossible to even observe. // // I am assured that this requirement is technially "only" a lint, and could be relaxed in // the future. If this requirement is ever relaxed in some way, fixing this is relatively // easy, by setting the value of the cell to the copy we make, after tracing (via a drop // guard in case of panics). Additionally, this is not a safety issue, only a correctness // issue, the changes will "just" be lost after this call returns. // // It could be fixed now, but since it is not even testable because it is currently // *impossible*, I did not bother. One day this may need to be implemented! cc.trace(&self.get()); } } // Can't use `#[derive]` because of the non-standard bounds. impl<T: Copy> Clone for Lock<T> { #[inline] fn clone(&self) -> Self { Self::new(self.get()) } } // Can't use `#[derive]` because of the non-standard bounds. impl<T: PartialEq + Copy> PartialEq for Lock<T> { #[inline] fn eq(&self, other: &Self) -> bool { self.get() == other.get() } } // Can't use `#[derive]` because of the non-standard bounds. impl<T: Eq + Copy> Eq for Lock<T> {} // Can't use `#[derive]` because of the non-standard bounds. impl<T: PartialOrd + Copy> PartialOrd for Lock<T> { #[inline] fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.get().partial_cmp(&other.get()) } } // Can't use `#[derive]` because of the non-standard bounds. impl<T: Ord + Copy> Ord for Lock<T> { #[inline] fn cmp(&self, other: &Self) -> Ordering { self.get().cmp(&other.get()) } } make_lock_wrapper!( #[derive(Clone, Default, Eq, PartialEq, Ord, PartialOrd)] locked = RefLock as GcRefLock; unlocked = RefCell unsafe as_ref_cell; impl Sized { #[inline] pub fn take(&self) -> T where T: Default { // See comment in `Lock::take`. self.cell.take() } } impl ?Sized { #[track_caller] #[inline] pub fn borrow<'a>(&'a self) -> Ref<'a, T> { self.cell.borrow() } #[inline] pub fn try_borrow<'a>(&'a self) -> Result<Ref<'a, T>, BorrowError> { self.cell.try_borrow() } } ); impl<T: fmt::Debug + ?Sized> fmt::Debug for RefLock<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut fmt = fmt.debug_tuple("RefLock"); match self.try_borrow() { Ok(borrow) => fmt.field(&borrow), Err(_) => { // The RefLock is mutably borrowed so we can't look at its value // here. Show a placeholder instead. fmt.field(&format_args!("<borrowed>")) } } .finish() } } impl<'gc, T: ?Sized + 'gc> Gc<'gc, RefLock<T>> { #[track_caller] #[inline] pub fn borrow(self) -> Ref<'gc, T> { RefLock::borrow(self.as_ref()) } #[inline] pub fn try_borrow(self) -> Result<Ref<'gc, T>, BorrowError> { RefLock::try_borrow(self.as_ref()) } #[track_caller] #[inline] pub fn borrow_mut(self, mc: &Mutation<'gc>) -> RefMut<'gc, T> { self.unlock(mc).borrow_mut() } #[inline] pub fn try_borrow_mut(self, mc: &Mutation<'gc>) -> Result<RefMut<'gc, T>, BorrowMutError> { self.unlock(mc).try_borrow_mut() } } unsafe impl<'gc, T: Collect<'gc> + 'gc + ?Sized> Collect<'gc> for RefLock<T> { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { cc.trace(&*self.borrow()); } } make_lock_wrapper!( #[derive(Clone, Eq, PartialEq)] locked = OnceLock as GcOnceLock; unlocked = OnceCell unsafe as_once_cell; ); // Can't use `#[derive]` because of the non-standard bounds. impl<T> Default for OnceLock<T> { #[inline] fn default() -> Self { Self::new() } } impl<T: fmt::Debug> fmt::Debug for OnceLock<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut d = fmt.debug_tuple("OnceLock"); match self.get() { Some(v) => d.field(v), None => d.field(&format_args!("<uninit>")), }; d.finish() } } impl<T> OnceLock<T> { #[inline] pub fn new() -> Self { Self { cell: OnceCell::new(), } } #[inline] pub fn get(&self) -> Option<&T> { self.cell.get() } #[inline] pub fn get_mut(&mut self) -> Option<&mut T> { self.cell.get_mut() } } unsafe impl<'gc, T: Collect<'gc>> Collect<'gc> for OnceLock<T> { const NEEDS_TRACE: bool = T::NEEDS_TRACE; #[inline] fn trace<C: Trace<'gc>>(&self, cc: &mut C) { if let Some(val) = self.get() { cc.trace(val); } } } impl<'gc, T: 'gc> Gc<'gc, OnceLock<T>> { #[inline] pub fn get(self) -> Option<&'gc T> { self.as_ref().get() } #[inline] pub fn set(self, mc: &Mutation<'gc>, value: T) -> Result<(), T> { // SAFETY: we emit a write barrier if (and only if) the value is modified. let result = self.cell.set(value); if result.is_ok() { mc.backward_barrier(Gc::erase(self), None); } result } #[inline] pub fn get_or_init<F>(self, mc: &Mutation<'gc>, f: F) -> &'gc T where F: FnOnce() -> T, { // SAFETY: we emit a write barrier if (and only if) the value is modified. self.as_ref().cell.get_or_init(|| { mc.backward_barrier(Gc::erase(self), None); f() }) } }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/metrics.rs
Rust
use core::cell::Cell; use std::rc::Rc; /// Tuning parameters for a given garbage collected [`crate::Arena`]. /// /// Any allocation that occurs during a collection cycle will incur "debt" that is exactly equal to /// the allocated bytes. This "debt" is paid off by running the collection algorithm some amount of /// time proportional to the debt. Exactly how much "debt" is paid off and in what proportion by the /// different parts of the collection algorithm is configured by the chosen values here. We refer to /// the amount of "debt" paid off by running the collection algorithm as "work". /// /// The most important idea behind choosing these tuning parameters is that we always want the /// collector (when it is not sleeping) to deterministically run *faster* than allocation. We do /// this so we can be *completely sure* that once collection starts, the collection cycle will /// finish and memory will not grow without bound. If we are tuning for low pause time however, /// it is also important that not *too* many costly operations are run within a single call to /// [`crate::Arena::collect_debt`], and this goal is in tension with the first, more important goal. /// /// How these two goals are balanced is that we must choose our tuning parameters so that the /// total amount of "work" performed to either *remember* or *free* one byte of allocated data /// is always *less than one*, as this makes the collector deterministically run faster than the /// rate of allocation (which is crucial). The closer the amount of "work" performed to remember /// or free one byte is to 1.0, the slower the collector will go and the higher the maximum amount /// of used memory will be. The closer the amount of "work" performed to remember or free one /// byte is to 0.0, the faster the collector will go and the closer it will get to behaving like a /// stop-the-world collector. /// /// All live pointers in a cycle are either remembered or freed once, but it is important that /// *both paths* require less than one unit of "work" per byte to fully complete. There is no way to /// predict a priori the ratio of remembered vs forgotten values, so if either path takes too close /// to or over 1.0 unit of work per byte to complete, collection may run too slowly. /// /// # Factors that control the time the GC sleeps /// /// `sleep_factor` is fairly self explanatory. Setting this too low will reduce the time of the /// [`crate::arena::CollectionPhase::Sleeping`] phase but this is not harmful (it can even be set /// to zero to keep the collector always running!), setting it much larger than 1.0 will make the /// collector wait a very long time before collecting again, and usually not what you want. /// /// `min_sleep` is also self explanatory and usually does not need changing from the default value. /// It should always be relatively small. /// /// # Timing factors for remembered values /// /// Every live `Gc` value in an [`crate::Arena`] that is reachable from the root is "remembered". /// Every remembered value will always have exactly three things done to it in a given cycle: /// /// 1) It will at some point be found and marked as reachable (and potentially queued for tracing). /// When this happens, `mark_factor * alloc_size` work is recorded. /// 2) Entries in the queue for tracing will eventually be traced by having their /// [`crate::Collect::trace`] method called. At this time, `trace_factor * alloc_size` work is /// recorded. Calling `Collect::trace` will usually mark other pointers as reachable and queue /// them for tracing if they have not already been, so this step may also transitively perform /// other work, but each step is only performed exactly once for each individual remembered /// value. /// 3) During the [`crate::arena::CollectionPhase::Sweeping`] phase, each remembered value has to /// be iterated over in the sweep list and removed from it. This a small, constant amount of /// work that is very fast, but it should always perform *some* work to keep pause time low, so /// `keep_factor * alloc_size` work is recorded. /// /// # Timing factors for forgotten values /// /// Allocated values that are not reachable in a GC cycle are simpler than /// remembered values. Only two operations are performed on them, and only during /// [`crate::arena::CollectionPhase::Sweeping`]: dropping and freeing. /// /// If a value is unreachable, then when it is encountered in the free list it will be dropped (and /// `drop_factor * alloc_size` work will be recorded), and then the memory backing the value will be /// freed (and `free_factor * alloc_size` work will be recorded). /// /// # Timing factors for weakly reachable values /// /// There is actually a *third* possible path for a value to take in a collection cycle which is a /// hybrid of the two, but thankfully it is not too complex. /// /// If a value is (newly) weakly reachable this cycle, first the pointer will be marked as /// (weakly) reachable (`mark_factor * alloc_size` work is recorded), then during sweeping it will /// be *dropped* (`drop_factor * alloc_size` work is recorded), and then *kept* (`keep_factor * /// alloc_size` work is recorded). /// /// # Summary /// /// This may seem complicated but it is actually not too difficult to make sure that the GC will not /// stall: *every path that a pointer can take must never do 1.0 or more unit of work per byte within /// a cycle*. /// /// The important formulas to check are: /// /// - We need to make sure that remembered values are processed faster than allocation: /// `mark_factor + trace_factor + keep_factor < 1.0` /// - We need to make sure that forgotten values are processed faster than allocation: /// `drop_factor + free_factor < 1.0` /// - We need to make sure that weakly remembered values are processed faster than allocation: /// `mark_factor + drop_factor + keep_factor < 1.0` /// /// It is also important to note that this is not an exhaustive list of all the possible paths a /// pointer can take, but every path will always be a *subset* of one of the above paths. The above /// formulas represent every possible the worst case: for example, if a weakly reachable value has /// already been dropped then only `mark_factor + keep_factor` work will be recorded, and if we /// can prove that a reachable value has [`crate::Collect::NEEDS_TRACE`] set to false, then only /// `mark_factor + keep_factor` work will be recorded. This is not important to remember though, it /// is true that when the collector elides work it may not actually record that work as performed, /// but this will only *speed up* collection, it can never cause the collector to stall. #[derive(Debug, Copy, Clone)] pub struct Pacing { /// Controls the length of the [`crate::arena::CollectionPhase::Sleeping`] phase. /// /// At the start of a new GC cycle, the collector will wait until the live size reaches /// `<current heap size> + <previous remembered size> * sleep_factor` before starting /// collection. /// /// External memory is ***not*** included in the "remembered size" for the purposes of /// calculating a new cycle's sleep period. pub sleep_factor: f64, /// The minimum length of the [`crate::arena::CollectionPhase::Sleeping`] phase. /// /// if the calculated sleep amount using `sleep_factor` is lower than `min_sleep`, this will /// be used instead. This is mostly useful when the heap is very small to prevent rapidly /// restarting collections. pub min_sleep: usize, /// The multiplicative factor for "work" performed per byte when a `Gc` value is first marked as /// reachable. pub mark_factor: f64, /// The multiplicative factor for "work" performed per byte when a `Gc` value has its /// [`crate::Collect::trace`] method called. pub trace_factor: f64, /// The multiplicative factor for "work" performed per byte when a reachable `Gc` value is /// iterated over during [`crate::arena::CollectionPhase::Sweeping`]. pub keep_factor: f64, /// The multiplicative factor for "work" performed per byte when a `Gc` value that is forgotten /// or only weakly reachable is dropped during [`crate::arena::CollectionPhase::Sweeping`]. pub drop_factor: f64, /// The multiplicative factor for "work" performed per byte when a forgotten `Gc` value is freed /// during [`crate::arena::CollectionPhase::Sweeping`]. pub free_factor: f64, } impl Pacing { pub const DEFAULT: Pacing = Pacing { sleep_factor: 0.5, min_sleep: 4096, mark_factor: 0.1, trace_factor: 0.4, keep_factor: 0.05, drop_factor: 0.2, free_factor: 0.3, }; /// A good default "stop-the-world" [`Pacing`] configuration. /// /// This has all of the work factors set to zero so that as soon as the collector wakes from /// sleep, it will immediately perform a full collection. /// /// It is important to set the sleep factor fairly high when configuring a collector this way /// (close to or even somewhat larger than 1.0). pub const STOP_THE_WORLD: Pacing = Pacing { sleep_factor: 1.0, min_sleep: 4096, mark_factor: 0.0, trace_factor: 0.0, keep_factor: 0.0, drop_factor: 0.0, free_factor: 0.0, }; } impl Default for Pacing { #[inline] fn default() -> Pacing { Self::DEFAULT } } #[derive(Debug, Default)] struct MetricsInner { pacing: Cell<Pacing>, total_gcs: Cell<usize>, total_gc_bytes: Cell<usize>, total_external_bytes: Cell<usize>, wakeup_amount: Cell<f64>, artificial_debt: Cell<f64>, // The number of external bytes that have been marked as allocated at the beginning of this // cycle. external_bytes_start: Cell<usize>, // Statistics for `Gc` allocations and deallocations that happen during a GC cycle. allocated_gc_bytes: Cell<usize>, dropped_gc_bytes: Cell<usize>, freed_gc_bytes: Cell<usize>, // Statistics for `Gc` pointers that have been marked as non-white this cycle. marked_gcs: Cell<usize>, marked_gc_bytes: Cell<usize>, // Statistics for `Gc` pointers that have their contents traced. traced_gcs: Cell<usize>, traced_gc_bytes: Cell<usize>, // Statistics for reachable `Gc` pointers as they are iterated through during the sweep phase. remembered_gcs: Cell<usize>, remembered_gc_bytes: Cell<usize>, } #[derive(Clone)] pub struct Metrics(Rc<MetricsInner>); impl Metrics { pub(crate) fn new() -> Self { Self(Default::default()) } /// Sets the pacing parameters used by the collection algorithm. /// /// The factors that affect the gc sleep time will not take effect until the start of the next /// collection. #[inline] pub fn set_pacing(&self, pacing: Pacing) { self.0.pacing.set(pacing); } /// Returns the current number of `Gc`s allocated that have not yet been freed. #[inline] pub fn total_gc_count(&self) -> usize { self.0.total_gcs.get() } /// Returns the total bytes allocated by all live `Gc` pointers. #[inline] pub fn total_gc_allocation(&self) -> usize { self.0.total_gc_bytes.get() } /// Returns the total bytes that have been marked as externally allocated. /// /// A call to [`Metrics::mark_external_allocation`] will increase this count, and a call to /// [`Metrics::mark_external_deallocation`] will decrease it. #[inline] pub fn total_external_allocation(&self) -> usize { self.0.total_external_bytes.get() } /// Returns the sum of `Metrics::total_gc_allocation()` and /// `Metrics::total_external_allocation()`. #[inline] pub fn total_allocation(&self) -> usize { self.0 .total_gc_bytes .get() .saturating_add(self.0.total_external_bytes.get()) } /// Call to mark that bytes have been externally allocated that are owned by an arena. /// /// This affects the GC pacing, marking external bytes as allocated will trigger allocation /// debt. #[inline] pub fn mark_external_allocation(&self, bytes: usize) { cell_update(&self.0.total_external_bytes, |b| b.saturating_add(bytes)); } /// Call to mark that bytes which have been marked as allocated with /// [`Metrics::mark_external_allocation`] have been since deallocated. /// /// This affects the GC pacing, marking external bytes as deallocated will reduce allocation /// debt. /// /// It is safe, but may result in unspecified behavior (such as very weird GC pacing), if the /// amount of bytes marked for deallocation is greater than the number of bytes marked for /// allocation. #[inline] pub fn mark_external_deallocation(&self, bytes: usize) { cell_update(&self.0.total_external_bytes, |b| b.saturating_sub(bytes)); } /// Add artificial debt equivalent to allocating the given number of bytes. /// /// This is different than marking external allocation because it will not show up in a call to /// [`Metrics::total_external_allocation`] or [`Metrics::total_allocation`] and instead *only* /// speeds up collection. #[inline] pub fn add_debt(&self, bytes: usize) { cell_update(&self.0.artificial_debt, |d| d + bytes as f64); } /// All arena allocation causes the arena to accumulate "allocation debt". This debt is then /// used to time incremental garbage collection based on the tuning parameters in the current /// `Pacing`. The allocation debt is measured in bytes, but will generally increase at a rate /// faster than that of allocation so that collection will always complete. #[inline] pub fn allocation_debt(&self) -> f64 { let total_gcs = self.0.total_gcs.get(); if total_gcs == 0 { // If we have no live `Gc`s, then there is no possible collection to do so always // return zero debt. return 0.0; } // Right now, we treat allocating an external byte as 1.0 units of debt and deallocating an // external byte as 1.0 units of work (we also treat freeing more external bytes than were // allocated in the current cycle as performing *no* work). The result is that the *total* // increase of externally allocated bytes (allocated minus freed) incurs debt exactly the // same as GC allocated bytes. let allocated_external_bytes = self .0 .total_external_bytes .get() .checked_sub(self.0.external_bytes_start.get()) .unwrap_or(0); let allocated_bytes = self.0.allocated_gc_bytes.get() as f64 + allocated_external_bytes as f64; // Every allocation after the `wakeup_amount` in a cycle is a debit. let cycle_debits = allocated_bytes - self.0.wakeup_amount.get() + self.0.artificial_debt.get(); // If our debits are not positive, then we know the total debt is not positive. if cycle_debits <= 0.0 { return 0.0; } let pacing = self.0.pacing.get(); let cycle_credits = self.0.marked_gc_bytes.get() as f64 * pacing.mark_factor + self.0.traced_gc_bytes.get() as f64 * pacing.trace_factor + self.0.remembered_gc_bytes.get() as f64 * pacing.keep_factor + self.0.dropped_gc_bytes.get() as f64 * pacing.drop_factor + self.0.freed_gc_bytes.get() as f64 * pacing.free_factor; (cycle_debits - cycle_credits).max(0.0) } pub(crate) fn finish_cycle(&self, reset_debt: bool) { let pacing = self.0.pacing.get(); let remembered_size = self.0.remembered_gc_bytes.get(); let wakeup_amount = (remembered_size as f64 * pacing.sleep_factor).max(pacing.min_sleep as f64); let artificial_debt = if reset_debt { 0.0 } else { self.allocation_debt() }; self.0.wakeup_amount.set(wakeup_amount); self.0.artificial_debt.set(artificial_debt); self.0 .external_bytes_start .set(self.0.total_external_bytes.get()); self.0.allocated_gc_bytes.set(0); self.0.dropped_gc_bytes.set(0); self.0.freed_gc_bytes.set(0); self.0.marked_gcs.set(0); self.0.marked_gc_bytes.set(0); self.0.traced_gcs.set(0); self.0.traced_gc_bytes.set(0); self.0.remembered_gcs.set(0); self.0.remembered_gc_bytes.set(0); } #[inline] pub(crate) fn mark_gc_allocated(&self, bytes: usize) { cell_update(&self.0.total_gcs, |c| c + 1); cell_update(&self.0.total_gc_bytes, |b| b + bytes); cell_update(&self.0.allocated_gc_bytes, |b| b.saturating_add(bytes)); } #[inline] pub(crate) fn mark_gc_dropped(&self, bytes: usize) { cell_update(&self.0.dropped_gc_bytes, |b| b.saturating_add(bytes)); } #[inline] pub(crate) fn mark_gc_freed(&self, bytes: usize) { cell_update(&self.0.total_gcs, |c| c - 1); cell_update(&self.0.total_gc_bytes, |b| b - bytes); cell_update(&self.0.freed_gc_bytes, |b| b.saturating_add(bytes)); } #[inline] pub(crate) fn mark_gc_marked(&self, bytes: usize) { cell_update(&self.0.marked_gcs, |c| c + 1); cell_update(&self.0.marked_gc_bytes, |b| b + bytes); } #[inline] pub(crate) fn mark_gc_traced(&self, bytes: usize) { cell_update(&self.0.traced_gcs, |c| c + 1); cell_update(&self.0.traced_gc_bytes, |b| b + bytes); } #[inline] pub(crate) fn mark_gc_untraced(&self, bytes: usize) { cell_update(&self.0.traced_gcs, |c| c - 1); cell_update(&self.0.traced_gc_bytes, |b| b - bytes); } #[inline] pub(crate) fn mark_gc_remembered(&self, bytes: usize) { cell_update(&self.0.remembered_gcs, |c| c + 1); cell_update(&self.0.remembered_gc_bytes, |b| b + bytes); } } // TODO: Use `Cell::update` when it is available, see: // https://github.com/rust-lang/rust/issues/50186 #[inline] fn cell_update<T: Copy>(c: &Cell<T>, f: impl FnOnce(T) -> T) { c.set(f(c.get())) }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/mod.rs
Rust
#![cfg_attr(miri, feature(strict_provenance))] pub mod arena; pub mod barrier; pub mod collect; mod collect_impl; mod context; pub mod dynamic_roots; mod gc; mod gc_weak; pub mod lock; pub mod metrics; mod no_drop; mod static_collect; mod types; mod unsize; pub mod allocator_api; mod hashbrown; #[doc(hidden)] pub use tcvm_derive::__unelide_lifetimes; #[doc(hidden)] pub use self::{arena::__DynRootable, no_drop::__MustNotImplDrop, unsize::__CoercePtrInternal}; pub use self::{ arena::{Arena, Rootable}, collect::Collect, context::{Finalization, Mutation}, dynamic_roots::{DynamicRoot, DynamicRootSet}, gc::Gc, gc_weak::GcWeak, lock::{GcLock, GcRefLock, Lock, RefLock}, static_collect::Static, };
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/no_drop.rs
Rust
// Trait that is automatically implemented for all types that implement `Drop`. // // Used to cause a conflicting trait impl if a type implements `Drop` to forbid implementing `Drop`. #[doc(hidden)] pub trait __MustNotImplDrop {} #[allow(drop_bounds)] impl<T: Drop> __MustNotImplDrop for T {}
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/static_collect.rs
Rust
use crate::dmm::Rootable; use crate::dmm::collect::Collect; use core::convert::{AsMut, AsRef}; use core::ops::{Deref, DerefMut}; use std::borrow::{Borrow, BorrowMut}; /// A wrapper type that implements Collect whenever the contained T is 'static, which is useful in /// generic contexts #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)] #[repr(transparent)] pub struct Static<T: ?Sized>(pub T); impl<'a, T: ?Sized + 'static> Rootable<'a> for Static<T> { type Root = Static<T>; } unsafe impl<'gc, T: ?Sized + 'static> Collect<'gc> for Static<T> { const NEEDS_TRACE: bool = false; } impl<T> From<T> for Static<T> { fn from(value: T) -> Self { Self(value) } } impl<T: ?Sized> AsRef<T> for Static<T> { fn as_ref(&self) -> &T { &self.0 } } impl<T: ?Sized> AsMut<T> for Static<T> { fn as_mut(&mut self) -> &mut T { &mut self.0 } } impl<T: ?Sized> Deref for Static<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl<T: ?Sized> DerefMut for Static<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<T: ?Sized> Borrow<T> for Static<T> { fn borrow(&self) -> &T { &self.0 } } impl<T: ?Sized> BorrowMut<T> for Static<T> { fn borrow_mut(&mut self) -> &mut T { &mut self.0 } }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/types.rs
Rust
use core::alloc::Layout; use core::cell::Cell; use core::marker::PhantomData; use core::ptr::NonNull; use core::{mem, ptr}; use crate::dmm::{collect::Collect, context::Context}; /// A thin-pointer-sized box containing a type-erased GC object. /// Stores the metadata required by the GC algorithm inline (see `GcBoxInner` /// for its typed counterpart). #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub(crate) struct GcBox(NonNull<GcBoxInner<()>>); impl GcBox { /// Erases a pointer to a typed GC object. /// /// **SAFETY:** The pointer must point to a valid `GcBoxInner` allocated /// in a `Box`. #[inline(always)] pub(crate) unsafe fn erase<T: ?Sized>(ptr: NonNull<GcBoxInner<T>>) -> Self { // This cast is sound because `GcBoxInner` is `repr(C)`. let erased = ptr.as_ptr() as *mut GcBoxInner<()>; unsafe { Self(NonNull::new_unchecked(erased)) } } /// Gets a pointer to the value stored inside this box. /// `T` must be the same type that was used with `erase`, so that /// we can correctly compute the field offset. #[inline(always)] fn unerased_value<T>(&self) -> *mut T { unsafe { let ptr = self.0.as_ptr() as *mut GcBoxInner<T>; // Don't create a reference, to keep the full provenance. // Also, this gives us interior mutability "for free". ptr::addr_of_mut!((*ptr).value) as *mut T } } #[inline(always)] pub(crate) fn header(&self) -> &GcBoxHeader { unsafe { &self.0.as_ref().header } } /// Traces the stored value. /// /// **SAFETY**: `Self::drop_in_place` must not have been called. #[inline(always)] pub(crate) unsafe fn trace_value(&self, cc: &mut Context) { unsafe { (self.header().vtable().trace_value)(*self, cc) } } /// Drops the stored value. /// /// **SAFETY**: once called, no GC pointers should access the stored value /// (but accessing the `GcBox` itself is still safe). #[inline(always)] pub(crate) unsafe fn drop_in_place(&mut self) { unsafe { (self.header().vtable().drop_value)(*self) } } /// Deallocates the box. Failing to call `Self::drop_in_place` beforehand /// will cause the stored value to be leaked. /// /// **SAFETY**: once called, this `GcBox` should never be accessed by any GC /// pointers again. #[inline(always)] pub(crate) unsafe fn dealloc(self) { unsafe { let layout = self.header().vtable().box_layout; let ptr = self.0.as_ptr() as *mut u8; // SAFETY: the pointer was `Box`-allocated with this layout. std::alloc::dealloc(ptr, layout); } } } pub(crate) struct GcBoxHeader { /// The next element in the global linked list of allocated objects. next: Cell<Option<GcBox>>, /// A custom virtual function table for handling type-specific operations. /// /// The lower bits of the pointer are used to store GC flags: /// - bits 0 & 1 for the current `GcColor`; /// - bit 2 for the `needs_trace` flag; /// - bit 3 for the `is_live` flag. tagged_vtable: Cell<*const CollectVtable>, } impl GcBoxHeader { #[inline(always)] pub fn new<'gc, T: Collect<'gc>>() -> Self { // Helper trait to materialize vtables in static memory. trait HasCollectVtable { const VTABLE: CollectVtable; } impl<'gc, T: Collect<'gc>> HasCollectVtable for T { const VTABLE: CollectVtable = CollectVtable::vtable_for::<T>(); } let vtable: &'static _ = &<T as HasCollectVtable>::VTABLE; Self { next: Cell::new(None), tagged_vtable: Cell::new(vtable as *const _), } } /// Gets a reference to the `CollectVtable` used by this box. #[inline(always)] fn vtable(&self) -> &'static CollectVtable { let ptr = tagged_ptr::untag(self.tagged_vtable.get()); // SAFETY: // - the pointer was properly untagged. // - the vtable is stored in static memory. unsafe { &*ptr } } /// Gets the next element in the global linked list of allocated objects. #[inline(always)] pub(crate) fn next(&self) -> Option<GcBox> { self.next.get() } /// Sets the next element in the global linked list of allocated objects. #[inline(always)] pub(crate) fn set_next(&self, next: Option<GcBox>) { self.next.set(next) } /// Returns the (shallow) size occupied by this box in memory. #[inline(always)] pub(crate) fn size_of_box(&self) -> usize { self.vtable().box_layout.size() } #[inline] pub(crate) fn color(&self) -> GcColor { match tagged_ptr::get::<0x3, _>(self.tagged_vtable.get()) { 0x0 => GcColor::White, 0x1 => GcColor::WhiteWeak, 0x2 => GcColor::Gray, _ => GcColor::Black, } } #[inline] pub(crate) fn set_color(&self, color: GcColor) { tagged_ptr::set::<0x3, _>( &self.tagged_vtable, match color { GcColor::White => 0x0, GcColor::WhiteWeak => 0x1, GcColor::Gray => 0x2, GcColor::Black => 0x3, }, ); } #[inline] pub(crate) fn needs_trace(&self) -> bool { tagged_ptr::get::<0x4, _>(self.tagged_vtable.get()) != 0x0 } /// Determines whether or not we've dropped the `dyn Collect` value /// stored in `GcBox.value` /// When we garbage-collect a `GcBox` that still has outstanding weak pointers, /// we set `alive` to false. When there are no more weak pointers remaining, /// we will deallocate the `GcBox`, but skip dropping the `dyn Collect` value /// (since we've already done it). #[inline] pub(crate) fn is_live(&self) -> bool { tagged_ptr::get::<0x8, _>(self.tagged_vtable.get()) != 0x0 } #[inline] pub(crate) fn set_needs_trace(&self, needs_trace: bool) { tagged_ptr::set_bool::<0x4, _>(&self.tagged_vtable, needs_trace); } #[inline] pub(crate) fn set_live(&self, alive: bool) { tagged_ptr::set_bool::<0x8, _>(&self.tagged_vtable, alive); } } /// Type-specific operations for GC'd values. /// /// We use a custom vtable instead of `dyn Collect` for extra flexibility. /// The type is over-aligned so that `GcBoxHeader` can store flags into the LSBs of the vtable pointer. #[repr(align(16))] struct CollectVtable { /// The layout of the `GcBox` the GC'd value is stored in. box_layout: Layout, /// Drops the value stored in the given `GcBox` (without deallocating the box). drop_value: unsafe fn(GcBox), /// Traces the value stored in the given `GcBox`. trace_value: unsafe fn(GcBox, &mut Context), } impl CollectVtable { /// Makes a vtable for a known, `Sized` type. /// Because `T: Sized`, we can recover a typed pointer /// directly from the erased `GcBox`. #[inline(always)] const fn vtable_for<'gc, T: Collect<'gc>>() -> Self { Self { box_layout: Layout::new::<GcBoxInner<T>>(), drop_value: |erased| unsafe { ptr::drop_in_place(erased.unerased_value::<T>()); }, trace_value: |erased, cc| unsafe { let val = &*(erased.unerased_value::<T>()); val.trace(cc) }, } } } /// A typed GC'd value, together with its metadata. /// This type is never manipulated directly by the GC algorithm, allowing /// user-facing `Gc`s to freely cast their pointer to it. #[repr(C)] pub(crate) struct GcBoxInner<T: ?Sized> { pub(crate) header: GcBoxHeader, /// The typed value stored in this `GcBox`. pub(crate) value: mem::ManuallyDrop<T>, } impl<'gc, T: Collect<'gc>> GcBoxInner<T> { #[inline(always)] pub(crate) fn new(header: GcBoxHeader, t: T) -> Self { Self { header, value: mem::ManuallyDrop::new(t), } } } #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub(crate) enum GcColor { /// An object that has not yet been reached by tracing (if we're in a tracing phase). /// /// During `Phase::Sweep`, we will free all white objects that existed *before* the start of the /// current `Phase::Sweep`. Objects allocated during `Phase::Sweep` will be white, but will not /// be freed. White, /// Like White, but for objects weakly reachable from a Black object. /// /// These objects may drop their contents during `Phase::Sweep`, but must stay allocated so that /// weak references can check the alive status. WhiteWeak, /// An object reachable from a Black object, but that has not yet been traced using /// `Collect::trace`. We also mark black objects as gray during `Phase::Mark` in response to /// a write barrier, so that we re-trace and find any objects newly reachable from the mutated /// object. Gray, /// An object that was reached during tracing. It will not be freed during `Phase::Sweep`. At /// the end of `Phase::Sweep`, all black objects will be reset to white. Black, } // Phantom type that holds a lifetime and ensures that it is invariant. pub(crate) type Invariant<'a> = PhantomData<Cell<&'a ()>>; /// Utility functions for tagging and untagging pointers. mod tagged_ptr { use core::cell::Cell; trait ValidMask<const MASK: usize> { const CHECK: (); } impl<T, const MASK: usize> ValidMask<MASK> for T { const CHECK: () = assert!(MASK < core::mem::align_of::<T>()); } /// Checks that `$mask` can be used to tag a pointer to `$type`. /// If this isn't true, this macro will cause a post-monomorphization error. macro_rules! check_mask { ($type:ty, $mask:expr) => { let _ = <$type as ValidMask<$mask>>::CHECK; }; } #[inline(always)] pub(super) fn untag<T>(tagged_ptr: *const T) -> *const T { let mask = core::mem::align_of::<T>() - 1; tagged_ptr.map_addr(|addr| addr & !mask) } #[inline(always)] pub(super) fn get<const MASK: usize, T>(tagged_ptr: *const T) -> usize { check_mask!(T, MASK); tagged_ptr.addr() & MASK } #[inline(always)] pub(super) fn set<const MASK: usize, T>(pcell: &Cell<*const T>, tag: usize) { check_mask!(T, MASK); let ptr = pcell.get(); let ptr = ptr.map_addr(|addr| (addr & !MASK) | (tag & MASK)); pcell.set(ptr) } #[inline(always)] pub(super) fn set_bool<const MASK: usize, T>(pcell: &Cell<*const T>, value: bool) { check_mask!(T, MASK); let ptr = pcell.get(); let ptr = ptr.map_addr(|addr| (addr & !MASK) | if value { MASK } else { 0 }); pcell.set(ptr) } }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/dmm/unsize.rs
Rust
use core::marker::PhantomData; use core::ptr::NonNull; use crate::dmm::{ types::GcBoxInner, {Gc, GcWeak}, }; /// Unsizes a [`Gc`] or [`GcWeak`] pointer. /// /// This macro is a `gc_arena`-specific replacement for the nightly-only `CoerceUnsized` trait. /// /// ## Usage /// /// ```rust /// # use std::fmt::Display; /// # use gc_arena::{Gc, unsize}; /// # fn main() { /// # gc_arena::arena::rootless_mutate(|mc| { /// // Unsizing arrays to slices. /// let mut slice; /// slice = unsize!(Gc::new(mc, [1, 2]) => [u8]); /// assert_eq!(slice.len(), 2); /// slice = unsize!(Gc::new(mc, [42; 4]) => [u8]); /// assert_eq!(slice.len(), 4); /// /// // Unsizing values to trait objects. /// let mut display; /// display = unsize!(Gc::new(mc, "Hello world!".to_owned()) => dyn Display); /// assert_eq!(display.to_string(), "Hello world!"); /// display = unsize!(Gc::new(mc, 123456) => dyn Display); /// assert_eq!(display.to_string(), "123456"); /// # }) /// # } /// ``` /// /// The `unsize` macro is safe, and will fail to compile when trying to coerce between /// incompatible types. /// ```rust,compile_fail /// # use std::error::Error; /// # use gc_arena::{Gc, unsize}; /// # fn main() { /// # gc_arena::arena::rootless_mutate(|mc| { /// // Error: `Option<char>` doesn't implement `Error`. /// let _ = unsize!(Gc::new(mc, Some('💥')) => dyn Error); /// # }) /// # } /// ``` #[macro_export] macro_rules! unsize { ($gc:expr => $ty:ty) => {{ let gc = $gc; // SAFETY: the closure has a trivial body and must be a valid pointer // coercion, if it compiles. Additionally, the `__CoercePtrInternal` trait // ensures that the resulting GC pointer has the correct `'gc` lifetime. unsafe { $crate::__CoercePtrInternal::__coerce_unchecked(gc, |p: *mut _| -> *mut $ty { p }) } }}; } // Not public API; implementation detail of the `unsize` macro. // // Maps a raw pointer coercion (`*mut FromPtr -> *mut ToPtr`) to // a smart pointer coercion (`Self -> Dst`). #[doc(hidden)] pub unsafe trait __CoercePtrInternal<Dst> { type FromPtr; type ToPtr: ?Sized; // SAFETY: `coerce` must be a valid pointer coercion; in particular, the coerced // pointer must have the same address and provenance as the original. unsafe fn __coerce_unchecked<F>(self, coerce: F) -> Dst where F: FnOnce(*mut Self::FromPtr) -> *mut Self::ToPtr; } unsafe impl<'gc, T, U: ?Sized> __CoercePtrInternal<Gc<'gc, U>> for Gc<'gc, T> { type FromPtr = T; type ToPtr = U; #[inline(always)] unsafe fn __coerce_unchecked<F>(self, coerce: F) -> Gc<'gc, U> where F: FnOnce(*mut T) -> *mut U, { let ptr = self.ptr.as_ptr() as *mut T; unsafe { Gc { ptr: NonNull::new_unchecked(coerce(ptr) as *mut GcBoxInner<U>), _invariant: PhantomData, } } } } unsafe impl<'gc, T, U: ?Sized> __CoercePtrInternal<GcWeak<'gc, U>> for GcWeak<'gc, T> { type FromPtr = T; type ToPtr = U; #[inline(always)] unsafe fn __coerce_unchecked<F>(self, coerce: F) -> GcWeak<'gc, U> where F: FnOnce(*mut T) -> *mut U, { unsafe { let inner = self.inner.__coerce_unchecked(coerce); GcWeak { inner } } } }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/instruction.rs
Rust
type Register = u8; type UpvalueIndex = u8; type ConstantIndex = u16; #[derive(Debug, Clone, Copy)] #[repr(u8)] #[repr(align(8))] pub enum Instruction { MOVE { dst: Register, src: Register, }, LOAD { dst: Register, idx: ConstantIndex, }, LFALSESKIP { src: Register, }, GETUPVAL { dst: Register, idx: UpvalueIndex, }, SETUPVAL { src: Register, idx: UpvalueIndex, }, GETTABUP { dst: Register, idx: UpvalueIndex, key: ConstantIndex, }, SETTABUP { src: Register, idx: UpvalueIndex, key: ConstantIndex, }, GETTABLE { dst: Register, table: Register, key: Register, }, SETTABLE { src: Register, table: Register, key: Register, }, NEWTABLE { dst: Register, }, ADD { dst: Register, lhs: Register, rhs: Register, }, SUB { dst: Register, lhs: Register, rhs: Register, }, MUL { dst: Register, lhs: Register, rhs: Register, }, MOD { dst: Register, lhs: Register, rhs: Register, }, POW { dst: Register, lhs: Register, rhs: Register, }, DIV { dst: Register, lhs: Register, rhs: Register, }, IDIV { dst: Register, lhs: Register, rhs: Register, }, BAND { dst: Register, lhs: Register, rhs: Register, }, BOR { dst: Register, lhs: Register, rhs: Register, }, BXOR { dst: Register, lhs: Register, rhs: Register, }, SHL { dst: Register, lhs: Register, rhs: Register, }, SHR { dst: Register, lhs: Register, rhs: Register, }, MMBIN { lhs: Register, rhs: Register, metamethod: MetaMethod, }, UNM { dst: Register, src: Register, }, BNOT { dst: Register, src: Register, }, NOT { dst: Register, src: Register, }, LEN { dst: Register, src: Register, }, CONCAT { dst: Register, lhs: Register, rhs: Register, }, CLOSE { start: Register, }, TBC { val: Register, }, JMP { offset: i32, }, EQ { lhs: Register, rhs: Register, inverted: bool, }, LT { lhs: Register, rhs: Register, inverted: bool, }, LE { lhs: Register, rhs: Register, inverted: bool, }, TEST { src: Register, inverted: bool, }, CALL { func: Register, args: u8, returns: u8, }, TAILCALL { func: Register, args: u8, }, RETURN { values: Register, count: u8, }, FORLOOP {}, FORPREP {}, TFORPREP {}, TFORCALL {}, TFORLOOP {}, SETLIST {}, CLOSURE {}, VARARG {}, VARARGPREP {}, NOP, STOP, } impl Instruction { pub fn discriminant(self) -> u8 { unsafe { *<*const _>::from(&self).cast::<u8>() } } } #[derive(Debug, Clone, Copy)] pub enum MetaMethod { INDEX, NEWINDEX, GC, MODE, LEN, EQ, ADD, SUB, MUL, MOD, POW, DIV, IDIV, BAND, BOR, BXOR, SHL, SHR, UNM, BNOT, LT, LE, CONCAT, CALL, CLOSE, }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/lib.rs
Rust
#![allow(incomplete_features)] #![feature(explicit_tail_calls)] #![feature(macro_metavar_expr)] #![feature(likely_unlikely)] #![feature(allocator_api)] pub mod dmm; mod instruction; mod parser; mod vm; pub mod env;
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/parser/lexer.rs
Rust
pub struct Lexer<'source> { source: &'source str, }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/parser/mod.rs
Rust
mod lexer; mod token;
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/parser/token.rs
Rust
pub enum Token { And, Break, Do, Else, ElseIf, End, False, For, Function, Global, Goto, If, In, Local, Nil, Not, Or, Repeat, Return, Then, True, Until, While, Add, Sub, Mul, Div, Mod, Pow, Len, BitAnd, BitNot, BitOr, Shl, Shr, IDiv, Eq, Neq, Lt, Gt, Le, Ge, Assign, LParen, RParen, LBrace, RBrace, LBracket, RBracket, DoubleColon, SemiColon, Colon, Comma, Dot, Concat, Dots, }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/vm/interp.rs
Rust
use crate::instruction::Instruction; use crate::vm::num::{self, op_arith, op_bit}; use crate::env::Value; const HANDLERS: &[Handler] = &[ op_move, op_load, op_lfalseskip, op_getupval, op_setupval, op_gettabup, op_settabup, op_gettable, op_settable, op_newtable, op_add, op_sub, op_mul, op_mod, op_pow, op_div, op_idiv, op_band, op_bor, op_bxor, op_shl, op_shr, op_mmbin, op_unm, op_bnot, op_not, op_len, op_concat, op_close, op_tbc, op_jmp, op_eq, op_lt, op_le, op_test, op_call, op_tailcall, op_return, op_forloop, op_forprep, op_tforcall, op_tforloop, op_setlist, op_closure, op_vararg, op_varargprep, op_nop, op_stop, ]; #[derive(Debug)] struct Error { pc: usize, } pub struct Thread { tape: Vec<Instruction>, } #[cfg(debug_assertions)] type Registers<'gc, 'a> = &'a mut [Value<'gc>]; #[cfg(not(debug_assertions))] type Registers<'gc, 'a> = *mut Value<'gc>; type Handler = fn( instruction: Instruction, thread: &mut Thread, registers: Registers<'_, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>>; macro_rules! helpers { ($instruction:expr, $thread:expr, $registers:expr, $ip:expr, $handlers:expr) => { macro_rules! dispatch { () => {{ unsafe { let _ = $instruction; debug_assert!($ip.offset_from_unsigned($thread.tape.as_ptr()) < $thread.tape.len()); let instruction = *$ip; let pos = instruction.discriminant() as usize; debug_assert!(pos < HANDLERS.len()); let handler = *$handlers.cast::<Handler>().add(pos); let ip = $ip.add(1); become handler(instruction, $thread, $registers, ip, $handlers); } }}; } macro_rules! args { ($$kind:path { $$($$field:ident),* }) => {{ match $instruction { $$kind { $$($$field),* } => ( $$($$field),* ), _ => unsafe { std::hint::unreachable_unchecked() }, } }}; } macro_rules! raise { () => {{ become impl_error($instruction, $thread, $registers, $ip, $handlers); }}; } macro_rules! check { ($$cond:expr) => {{ if std::hint::unlikely(!$$cond) { raise!(); } }}; } macro_rules! reg { ($$idx:expr) => {{ #[cfg(debug_assertions)] { $registers[$$idx as usize] } #[cfg(not(debug_assertions))] unsafe { $registers.add($$idx as usize).read() } }}; (mut $$idx:expr) => {{ #[cfg(debug_assertions)] { &mut $registers[$$idx as usize] } #[cfg(not(debug_assertions))] unsafe { &mut *$registers.add($$idx as usize) } }}; } }; } #[inline(never)] pub fn run(tape: &[Instruction], thread: &mut Thread) { let ip = tape.as_ptr(); let handlers = HANDLERS.as_ptr() as *const (); #[cfg(debug_assertions)] let registers = &mut []; #[cfg(not(debug_assertions))] let registers = std::ptr::null_mut(); op_nop(Instruction::NOP, thread, registers, ip, handlers).unwrap(); } #[cold] #[inline(never)] fn impl_error<'gc>( _instruction: Instruction, thread: &mut Thread, _registers: Registers<'gc, '_>, ip: *const Instruction, _handlers: *const (), ) -> Result<(), Box<Error>> { let pc = unsafe { ip.offset_from_unsigned(thread.tape.as_ptr()) }; let error = Error { pc }; Err(Box::new(error)) } #[inline(never)] fn op_move<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, src) = args!(Instruction::MOVE { dst, src }); *reg!(mut dst) = reg!(src); dispatch!(); } #[inline(never)] fn op_load<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, idx) = args!(Instruction::LOAD { dst, idx }); dispatch!(); } #[inline(never)] fn op_lfalseskip<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let src = args!(Instruction::LFALSESKIP { src }); dispatch!(); } #[inline(never)] fn op_getupval<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, idx) = args!(Instruction::GETUPVAL { dst, idx }); dispatch!(); } #[inline(never)] fn op_setupval<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (src, idx) = args!(Instruction::SETUPVAL { src, idx }); dispatch!(); } #[inline(never)] fn op_gettabup<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, idx, key) = args!(Instruction::GETTABUP { dst, idx, key }); dispatch!(); } #[inline(never)] fn op_settabup<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (src, idx, key) = args!(Instruction::SETTABUP { src, idx, key }); dispatch!(); } #[inline(never)] fn op_gettable<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, table, key) = args!(Instruction::GETTABLE { dst, table, key }); dispatch!(); } #[inline(never)] fn op_settable<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (src, table, key) = args!(Instruction::SETTABLE { src, table, key }); dispatch!(); } #[inline(never)] fn op_newtable<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let dst = args!(Instruction::NEWTABLE { dst }); dispatch!(); } #[inline(never)] fn op_add<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::ADD { dst, lhs, rhs }); let (lhs, rhs) = (reg!(lhs), reg!(rhs)); if let Some(v) = op_arith::<num::Add>(lhs, rhs) { *reg!(mut dst) = v; } dispatch!(); } #[inline(never)] fn op_sub<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::SUB { dst, lhs, rhs }); let (lhs, rhs) = (reg!(lhs), reg!(rhs)); if let Some(v) = op_arith::<num::Sub>(lhs, rhs) { *reg!(mut dst) = v; } dispatch!(); } #[inline(never)] fn op_mul<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::MUL { dst, lhs, rhs }); let (lhs, rhs) = (reg!(lhs), reg!(rhs)); if let Some(v) = op_arith::<num::Mul>(lhs, rhs) { *reg!(mut dst) = v; } dispatch!(); } #[inline(never)] fn op_mod<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::MOD { dst, lhs, rhs }); let (lhs, rhs) = (reg!(lhs), reg!(rhs)); if let Some(v) = op_arith::<num::Mod>(lhs, rhs) { *reg!(mut dst) = v; } dispatch!(); } #[inline(never)] fn op_pow<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::POW { dst, lhs, rhs }); let (lhs, rhs) = (reg!(lhs), reg!(rhs)); if let Some(v) = op_arith::<num::Pow>(lhs, rhs) { *reg!(mut dst) = v; } dispatch!(); } #[inline(never)] fn op_div<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::DIV { dst, lhs, rhs }); let (lhs, rhs) = (reg!(lhs), reg!(rhs)); if let Some(v) = op_arith::<num::Div>(lhs, rhs) { *reg!(mut dst) = v; } dispatch!(); } #[inline(never)] fn op_idiv<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::IDIV { dst, lhs, rhs }); let (lhs, rhs) = (reg!(lhs), reg!(rhs)); if let Some(v) = op_arith::<num::Sub>(lhs, rhs) { *reg!(mut dst) = v; } dispatch!(); } #[inline(never)] fn op_band<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::BAND { dst, lhs, rhs }); let (lhs, rhs) = (reg!(lhs), reg!(rhs)); if let Some(v) = op_bit::<num::BAnd>(lhs, rhs) { *reg!(mut dst) = v; } dispatch!(); } #[inline(never)] fn op_bor<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::BOR { dst, lhs, rhs }); let (lhs, rhs) = (reg!(lhs), reg!(rhs)); if let Some(v) = op_bit::<num::BOr>(lhs, rhs) { *reg!(mut dst) = v; } dispatch!(); } #[inline(never)] fn op_bxor<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::BXOR { dst, lhs, rhs }); let (lhs, rhs) = (reg!(lhs), reg!(rhs)); if let Some(v) = op_bit::<num::BXor>(lhs, rhs) { *reg!(mut dst) = v; } dispatch!(); } #[inline(never)] fn op_shl<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::SHL { dst, lhs, rhs }); let (lhs, rhs) = (reg!(lhs), reg!(rhs)); if let Some(v) = op_bit::<num::Shl>(lhs, rhs) { *reg!(mut dst) = v; } dispatch!(); } #[inline(never)] fn op_shr<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::SHR { dst, lhs, rhs }); let (lhs, rhs) = (reg!(lhs), reg!(rhs)); if let Some(v) = op_bit::<num::Shr>(lhs, rhs) { *reg!(mut dst) = v; } dispatch!(); } #[inline(never)] fn op_mmbin<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (lhs, rhs, metamethod) = args!(Instruction::MMBIN { lhs, rhs, metamethod }); dispatch!(); } #[inline(never)] fn op_unm<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, src) = args!(Instruction::UNM { dst, src }); dispatch!(); } #[inline(never)] fn op_bnot<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, src) = args!(Instruction::BNOT { dst, src }); dispatch!(); } #[inline(never)] fn op_not<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, src) = args!(Instruction::BNOT { dst, src }); dispatch!(); } #[inline(never)] fn op_len<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, src) = args!(Instruction::BNOT { dst, src }); dispatch!(); } #[inline(never)] fn op_concat<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (dst, lhs, rhs) = args!(Instruction::CONCAT { dst, lhs, rhs }); dispatch!(); } #[inline(never)] fn op_close<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let start = args!(Instruction::CLOSE { start }); dispatch!(); } #[inline(never)] fn op_tbc<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let val = args!(Instruction::TBC { val }); dispatch!(); } #[inline(never)] fn op_jmp<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let offset = args!(Instruction::JMP { offset }); dispatch!(); } #[inline(never)] fn op_eq<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (lhs, rhs, inverted) = args!(Instruction::EQ { lhs, rhs, inverted }); dispatch!(); } #[inline(never)] fn op_lt<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (lhs, rhs, inverted) = args!(Instruction::LT { lhs, rhs, inverted }); dispatch!(); } #[inline(never)] fn op_le<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (lhs, rhs, inverted) = args!(Instruction::LE { lhs, rhs, inverted }); dispatch!(); } #[inline(never)] fn op_test<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (src, inverted) = args!(Instruction::TEST { src, inverted }); dispatch!(); } #[inline(never)] fn op_call<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (func, args, returns) = args!(Instruction::CALL { func, args, returns }); dispatch!(); } #[inline(never)] fn op_tailcall<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (func, args) = args!(Instruction::TAILCALL { func, args }); dispatch!(); } #[inline(never)] fn op_return<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); let (values, count) = args!(Instruction::RETURN { values, count }); dispatch!(); } #[inline(never)] fn op_forloop<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); dispatch!(); } #[inline(never)] fn op_forprep<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); dispatch!(); } #[inline(never)] fn op_tforprep<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); dispatch!(); } #[inline(never)] fn op_tforcall<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); dispatch!(); } #[inline(never)] fn op_tforloop<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); dispatch!(); } #[inline(never)] fn op_setlist<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); dispatch!(); } #[inline(never)] fn op_closure<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); dispatch!(); } #[inline(never)] fn op_vararg<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); dispatch!(); } #[inline(never)] fn op_varargprep<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); dispatch!(); } #[inline(never)] fn op_nop<'gc>( instruction: Instruction, thread: &mut Thread, registers: Registers<'gc, '_>, ip: *const Instruction, handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, thread, registers, ip, handlers); args!(Instruction::NOP {}); dispatch!(); } #[inline(never)] fn op_stop<'gc>( instruction: Instruction, _thread: &mut Thread, _registers: Registers<'gc, '_>, _ip: *const Instruction, _handlers: *const (), ) -> Result<(), Box<Error>> { helpers!(instruction, _thread, _registers, _ip, _handlers); args!(Instruction::STOP {}); Ok(()) }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/vm/mod.rs
Rust
mod interp; mod num;
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
src/vm/num.rs
Rust
use crate::env::Value; fn exact_float_to_int(f: f64) -> Option<i64> { if !f.is_finite() { return None; } const MIN: i64 = -(2<<53 - 1); const MAX: i64 = 2<<53 - 1; if f < MIN as f64 || f > MAX as f64 { return None; } if f.trunc() != f { return None; } let i = unsafe { f.to_int_unchecked() }; Some(i) } #[inline(always)] pub fn op_arith<'gc, Op: ArithOp>(lhs: Value, rhs: Value) -> Option<Value<'gc>> { if let (Value::Integer(lhs), Value::Integer(rhs)) = (lhs, rhs) { return Some(Op::int(lhs, rhs)); } let lhs = match lhs { Value::Integer(v) => v as f64, Value::Float(v) => v, _ => return None, }; let rhs = match rhs { Value::Integer(v) => v as f64, Value::Float(v) => v, _ => return None, }; Some(Op::float(lhs, rhs)) } pub trait ArithOp { fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc>; fn float<'gc>(lhs: f64, rhs: f64) -> Value<'gc>; } pub struct Add; impl ArithOp for Add { #[inline(always)] fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc> { Value::Integer(lhs.wrapping_add(rhs)) } #[inline(always)] fn float<'gc>(lhs: f64, rhs: f64) -> Value<'gc> { Value::Float(lhs + rhs) } } pub struct Sub; impl ArithOp for Sub { #[inline(always)] fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc> { Value::Integer(lhs.wrapping_sub(rhs)) } #[inline(always)] fn float<'gc>(lhs: f64, rhs: f64) -> Value<'gc> { Value::Float(lhs - rhs) } } pub struct Mul; impl ArithOp for Mul { #[inline(always)] fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc> { Value::Integer(lhs.wrapping_mul(rhs)) } #[inline(always)] fn float<'gc>(lhs: f64, rhs: f64) -> Value<'gc> { Value::Float(lhs * rhs) } } pub struct Mod; impl ArithOp for Mod { #[inline(always)] fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc> { Value::Integer(lhs.wrapping_rem(rhs)) } #[inline(always)] fn float<'gc>(lhs: f64, rhs: f64) -> Value<'gc> { Value::Float(lhs % rhs) } } pub struct Pow; impl ArithOp for Pow { #[inline(always)] fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc> { Value::Float((lhs as f64).powf(rhs as f64)) } #[inline(always)] fn float<'gc>(lhs: f64, rhs: f64) -> Value<'gc> { Value::Float(lhs.powf(rhs)) } } pub struct Div; impl ArithOp for Div { #[inline(always)] fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc> { Value::Float((lhs as f64) / (rhs as f64)) } #[inline(always)] fn float<'gc>(lhs: f64, rhs: f64) -> Value<'gc> { Value::Float(lhs / rhs) } } pub struct IDiv; impl ArithOp for IDiv { #[inline(always)] fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc> { Value::Integer(lhs.wrapping_div(rhs)) } #[inline(always)] fn float<'gc>(lhs: f64, rhs: f64) -> Value<'gc> { Value::Integer((lhs / rhs).floor() as i64) } } #[inline(always)] pub fn op_bit<'gc, Op: BitOp>(lhs: Value, rhs: Value) -> Option<Value<'gc>> { let lhs = match lhs { Value::Integer(v) => v, Value::Float(v) => exact_float_to_int(v).unwrap(), _ => return None, }; let rhs = match rhs { Value::Integer(v) => v, Value::Float(v) => exact_float_to_int(v).unwrap(), _ => return None, }; Some(Op::int(lhs, rhs)) } pub trait BitOp { fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc>; } pub struct BAnd; impl BitOp for BAnd { #[inline(always)] fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc> { Value::Integer(lhs & rhs) } } pub struct BOr; impl BitOp for BOr { #[inline(always)] fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc> { Value::Integer(lhs | rhs) } } pub struct BXor; impl BitOp for BXor { #[inline(always)] fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc> { Value::Integer(lhs ^ rhs) } } pub struct Shl; impl BitOp for Shl { #[inline(always)] fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc> { Value::Integer(lhs.wrapping_shl(rhs as u32)) } } pub struct Shr; impl BitOp for Shr { #[inline(always)] fn int<'gc>(lhs: i64, rhs: i64) -> Value<'gc> { Value::Integer(lhs.wrapping_shr(rhs as u32)) } }
xacrimon/tcvm
7
Rust
xacrimon
Joel Wejdenstål
linköping university
checkstyle.py
Python
#!/usr/bin/python import fnmatch import sys import subprocess def git_get_staged_files(): files = str(subprocess.check_output(['git', 'diff', '--name-only', '--cached'])) return [line for line in files.splitlines() if line != ''] def git_get_all_files(): files = str(subprocess.check_output(['git', 'ls-files'])) return [line for line in files.splitlines() if line != ''] def get_src_files(): files = git_get_all_files() extensions = ('c', 'cpp', 'h', 'hpp') return [file for file in files if (file.startswith('src/') or file.startswith('inc')) and file.endswith(extensions)] def get_staged_src_files(): files = git_get_staged_files() extensions = ('c', 'cpp', 'h', 'hpp') return [file for file in files if file.startswith('src/') and file.endswith(extensions)] def get_blacklisted_files(): with open('blacklist', 'r') as blacklist: return [line.rstrip() for line in blacklist if line != '' and line.lstrip()[0] != '#'] def cpplint_check_file(filename): try: filters = '--filter=-readability/check,-build/include_order,-build/header_guard' subprocess.check_call(['python', 'cpplint.py', '--root=src', filters, filename]) except subprocess.CalledProcessError as error: return False return True def main(): src_files = get_staged_src_files() if len(sys.argv) == 2 and sys.argv[1] == 'all': src_files = get_src_files() blacklisted_files = get_blacklisted_files() files_to_check = [file for file in src_files if file not in blacklisted_files] bad_files_count = 0 for file in files_to_check: if not cpplint_check_file(file): bad_files_count += 1 sys.exit(bad_files_count) if __name__ == '__main__': main()
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
client.sh
Shell
#!/bin/sh cd bin export LD_LIBRARY_PATH=`pwd` cd .. ./bin/sample-client
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
cpplint.py
Python
#!/usr/bin/python # # Copyright (c) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Here are some issues that I've had people identify in my code during reviews, # that I think are possible to flag automatically in a lint tool. If these were # caught by lint, it would save time both for myself and that of my reviewers. # Most likely, some of these are beyond the scope of the current lint framework, # but I think it is valuable to retain these wish-list items even if they cannot # be immediately implemented. # # Suggestions # ----------- # - Check for no 'explicit' for multi-arg ctor # - Check for boolean assign RHS in parens # - Check for ctor initializer-list colon position and spacing # - Check that if there's a ctor, there should be a dtor # - Check accessors that return non-pointer member variables are # declared const # - Check accessors that return non-const pointer member vars are # *not* declared const # - Check for using public includes for testing # - Check for spaces between brackets in one-line inline method # - Check for no assert() # - Check for spaces surrounding operators # - Check for 0 in pointer context (should be NULL) # - Check for 0 in char context (should be '\0') # - Check for camel-case method name conventions for methods # that are not simple inline getters and setters # - Do not indent namespace contents # - Avoid inlining non-trivial constructors in header files # - Check for old-school (void) cast for call-sites of functions # ignored return value # - Check gUnit usage of anonymous namespace # - Check for class declaration order (typedefs, consts, enums, # ctor(s?), dtor, friend declarations, methods, member vars) # """Does google-lint on c++ files. The goal of this script is to identify places in the code that *may* be in non-compliance with google style. It does not attempt to fix up these problems -- the point is to educate. It does also not attempt to find all problems, or to ensure that everything it does find is legitimately a problem. In particular, we can get very confused by /* and // inside strings! We do a small hack, which is to ignore //'s with "'s after them on the same line, but it is far from perfect (in either direction). """ import codecs import copy import getopt import math # for log import os import re import sre_compile import string import sys import unicodedata _USAGE = """ Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...] [--counting=total|toplevel|detailed] <file> [file] ... The style guidelines this tries to follow are those in http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml Every problem is given a confidence score from 1-5, with 5 meaning we are certain of the problem, and 1 meaning it could be a legitimate construct. This will miss some errors, and is not a substitute for a code review. To suppress false-positive errors of a certain category, add a 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*) suppresses errors of all categories on that line. The files passed in will be linted; at least one file must be provided. Linted extensions are .cc, .cpp, and .h. Other file types will be ignored. Flags: output=vs7 By default, the output is formatted to ease emacs parsing. Visual Studio compatible output (vs7) may also be used. Other formats are unsupported. verbose=# Specify a number 0-5 to restrict errors to certain verbosity levels. filter=-x,+y,... Specify a comma-separated list of category-filters to apply: only error messages whose category names pass the filters will be printed. (Category names are printed with the message and look like "[whitespace/indent]".) Filters are evaluated left to right. "-FOO" and "FOO" means "do not print categories that start with FOO". "+FOO" means "do print categories that start with FOO". Examples: --filter=-whitespace,+whitespace/braces --filter=whitespace,runtime/printf,+runtime/printf_format --filter=-,+build/include_what_you_use To see a list of all the categories used in cpplint, pass no arg: --filter= counting=total|toplevel|detailed The total number of errors found is always printed. If 'toplevel' is provided, then the count of errors in each of the top-level categories like 'build' and 'whitespace' will also be printed. If 'detailed' is provided, then a count is provided for each category like 'build/class'. root=subdir The root directory used for deriving header guard CPP variable. By default, the header guard CPP variable is calculated as the relative path to the directory that contains .git, .hg, or .svn. When this flag is specified, the relative path is calculated from the specified directory. If the specified directory does not exist, this flag is ignored. Examples: Assuing that src/.git exists, the header guard CPP variables for src/chrome/browser/ui/browser.h are: No flag => CHROME_BROWSER_UI_BROWSER_H_ --root=chrome => BROWSER_UI_BROWSER_H_ --root=chrome/browser => UI_BROWSER_H_ """ # We categorize each error message we print. Here are the categories. # We want an explicit list so we can list them all in cpplint --filter=. # If you add a new error message with a new category, add it to the list # here! cpplint_unittest.py should tell you if you forget to do this. # \ used for clearer layout -- pylint: disable-msg=C6013 _ERROR_CATEGORIES = [ 'build/class', 'build/deprecated', 'build/endif_comment', 'build/explicit_make_pair', 'build/forward_decl', 'build/header_guard', 'build/include', 'build/include_alpha', 'build/include_order', 'build/include_what_you_use', 'build/namespaces', 'build/printf_format', 'build/storage_class', 'legal/copyright', 'readability/alt_tokens', 'readability/braces', 'readability/casting', 'readability/check', 'readability/constructors', 'readability/fn_size', 'readability/function', 'readability/multiline_comment', 'readability/multiline_string', 'readability/namespace', 'readability/nolint', 'readability/streams', 'readability/todo', 'readability/utf8', 'runtime/arrays', 'runtime/casting', 'runtime/explicit', 'runtime/int', 'runtime/init', 'runtime/invalid_increment', 'runtime/member_string_references', 'runtime/memset', 'runtime/operator', 'runtime/printf', 'runtime/printf_format', 'runtime/references', 'runtime/rtti', 'runtime/sizeof', 'runtime/string', 'runtime/threadsafe_fn', 'whitespace/blank_line', 'whitespace/braces', 'whitespace/comma', 'whitespace/comments', 'whitespace/empty_loop_body', 'whitespace/end_of_line', 'whitespace/ending_newline', 'whitespace/forcolon', 'whitespace/indent', 'whitespace/labels', 'whitespace/line_length', 'whitespace/newline', 'whitespace/operators', 'whitespace/parens', 'whitespace/semicolon', 'whitespace/tab', 'whitespace/todo' ] # The default state of the category filter. This is overrided by the --filter= # flag. By default all errors are on, so only add here categories that should be # off by default (i.e., categories that must be enabled by the --filter= flags). # All entries here should start with a '-' or '+', as in the --filter= flag. _DEFAULT_FILTERS = ['-build/include_alpha'] # We used to check for high-bit characters, but after much discussion we # decided those were OK, as long as they were in UTF-8 and didn't represent # hard-coded international strings, which belong in a separate i18n file. # Headers that we consider STL headers. _STL_HEADERS = frozenset([ 'algobase.h', 'algorithm', 'alloc.h', 'bitset', 'deque', 'exception', 'function.h', 'functional', 'hash_map', 'hash_map.h', 'hash_set', 'hash_set.h', 'iterator', 'list', 'list.h', 'map', 'memory', 'new', 'pair.h', 'pthread_alloc', 'queue', 'set', 'set.h', 'sstream', 'stack', 'stl_alloc.h', 'stl_relops.h', 'type_traits.h', 'utility', 'vector', 'vector.h', ]) # Non-STL C++ system headers. _CPP_HEADERS = frozenset([ 'algo.h', 'builtinbuf.h', 'bvector.h', 'cassert', 'cctype', 'cerrno', 'cfloat', 'ciso646', 'climits', 'clocale', 'cmath', 'complex', 'complex.h', 'csetjmp', 'csignal', 'cstdarg', 'cstddef', 'cstdio', 'cstdlib', 'cstring', 'ctime', 'cwchar', 'cwctype', 'defalloc.h', 'deque.h', 'editbuf.h', 'exception', 'fstream', 'fstream.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip', 'iomanip.h', 'ios', 'iosfwd', 'iostream', 'iostream.h', 'istream', 'istream.h', 'iterator.h', 'limits', 'map.h', 'multimap.h', 'multiset.h', 'numeric', 'ostream', 'ostream.h', 'parsestream.h', 'pfstream.h', 'PlotFile.h', 'procbuf.h', 'pthread_alloc.h', 'rope', 'rope.h', 'ropeimpl.h', 'SFile.h', 'slist', 'slist.h', 'stack.h', 'stdexcept', 'stdiostream.h', 'streambuf', 'streambuf.h', 'stream.h', 'strfile.h', 'string', 'strstream', 'strstream.h', 'tempbuf.h', 'tree.h', 'typeinfo', 'valarray', ]) # Assertion macros. These are defined in base/logging.h and # testing/base/gunit.h. Note that the _M versions need to come first # for substring matching to work. _CHECK_MACROS = [ 'DCHECK', 'CHECK', 'EXPECT_TRUE_M', 'EXPECT_TRUE', 'ASSERT_TRUE_M', 'ASSERT_TRUE', 'EXPECT_FALSE_M', 'EXPECT_FALSE', 'ASSERT_FALSE_M', 'ASSERT_FALSE', ] # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS]) for op, replacement in [('==', 'EQ'), ('!=', 'NE'), ('>=', 'GE'), ('>', 'GT'), ('<=', 'LE'), ('<', 'LT')]: _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), ('>=', 'LT'), ('>', 'LE'), ('<=', 'GT'), ('<', 'GE')]: _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement # Alternative tokens and their replacements. For full list, see section 2.5 # Alternative tokens [lex.digraph] in the C++ standard. # # Digraphs (such as '%:') are not included here since it's a mess to # match those on a word boundary. _ALT_TOKEN_REPLACEMENT = { 'and': '&&', 'bitor': '|', 'or': '||', 'xor': '^', 'compl': '~', 'bitand': '&', 'and_eq': '&=', 'or_eq': '|=', 'xor_eq': '^=', 'not': '!', 'not_eq': '!=' } # Compile regular expression that matches all the above keywords. The "[ =()]" # bit is meant to avoid matching these keywords outside of boolean expressions. # # False positives include C-style multi-line comments (http://go/nsiut ) # and multi-line strings (http://go/beujw ), but those have always been # troublesome for cpplint. _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') # These constants define types of headers for use with # _IncludeState.CheckNextIncludeOrder(). _C_SYS_HEADER = 1 _CPP_SYS_HEADER = 2 _LIKELY_MY_HEADER = 3 _POSSIBLE_MY_HEADER = 4 _OTHER_HEADER = 5 # These constants define the current inline assembly state _NO_ASM = 0 # Outside of inline assembly block _INSIDE_ASM = 1 # Inside inline assembly block _END_ASM = 2 # Last line of inline assembly block _BLOCK_ASM = 3 # The whole block is an inline assembly block # Match start of assembly blocks _MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)' r'(?:\s+(volatile|__volatile__))?' r'\s*[{(]') _regexp_compile_cache = {} # Finds occurrences of NOLINT or NOLINT(...). _RE_SUPPRESSION = re.compile(r'\bNOLINT\b(\([^)]*\))?') # {str, set(int)}: a map from error categories to sets of linenumbers # on which those errors are expected and should be suppressed. _error_suppressions = {} # The root directory used for deriving header guard CPP variable. # This is set by --root flag. _root = None def ParseNolintSuppressions(filename, raw_line, linenum, error): """Updates the global list of error-suppressions. Parses any NOLINT comments on the current line, updating the global error_suppressions store. Reports an error if the NOLINT comment was malformed. Args: filename: str, the name of the input file. raw_line: str, the line of input text, with comments. linenum: int, the number of the current line. error: function, an error handler. """ # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*). matched = _RE_SUPPRESSION.search(raw_line) if matched: category = matched.group(1) if category in (None, '(*)'): # => "suppress all" _error_suppressions.setdefault(None, set()).add(linenum) else: if category.startswith('(') and category.endswith(')'): category = category[1:-1] if category in _ERROR_CATEGORIES: _error_suppressions.setdefault(category, set()).add(linenum) else: error(filename, linenum, 'readability/nolint', 5, 'Unknown NOLINT error category: %s' % category) def ResetNolintSuppressions(): "Resets the set of NOLINT suppressions to empty." _error_suppressions.clear() def IsErrorSuppressedByNolint(category, linenum): """Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment. """ return (linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set())) def Match(pattern, s): """Matches the string with the pattern, caching the compiled regexp.""" # The regexp compilation caching is inlined in both Match and Search for # performance reasons; factoring it out into a separate function turns out # to be noticeably expensive. if not pattern in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].match(s) def Search(pattern, s): """Searches the string for the pattern, caching the compiled regexp.""" if not pattern in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].search(s) class _IncludeState(dict): """Tracks line numbers for includes, and the order in which includes appear. As a dict, an _IncludeState object serves as a mapping between include filename and line number on which that file was included. Call CheckNextIncludeOrder() once for each header in the file, passing in the type constants defined above. Calls in an illegal order will raise an _IncludeError with an appropriate error message. """ # self._section will move monotonically through this set. If it ever # needs to move backwards, CheckNextIncludeOrder will raise an error. _INITIAL_SECTION = 0 _MY_H_SECTION = 1 _C_SECTION = 2 _CPP_SECTION = 3 _OTHER_H_SECTION = 4 _TYPE_NAMES = { _C_SYS_HEADER: 'C system header', _CPP_SYS_HEADER: 'C++ system header', _LIKELY_MY_HEADER: 'header this file implements', _POSSIBLE_MY_HEADER: 'header this file may implement', _OTHER_HEADER: 'other header', } _SECTION_NAMES = { _INITIAL_SECTION: "... nothing. (This can't be an error.)", _MY_H_SECTION: 'a header this file implements', _C_SECTION: 'C system header', _CPP_SECTION: 'C++ system header', _OTHER_H_SECTION: 'other header', } def __init__(self): dict.__init__(self) # The name of the current section. self._section = self._INITIAL_SECTION # The path of last found header. self._last_header = '' def CanonicalizeAlphabeticalOrder(self, header_path): """Returns a path canonicalized for alphabetical comparison. - replaces "-" with "_" so they both cmp the same. - removes '-inl' since we don't require them to be after the main header. - lowercase everything, just in case. Args: header_path: Path to be canonicalized. Returns: Canonicalized path. """ return header_path.replace('-inl.h', '.h').replace('-', '_').lower() def IsInAlphabeticalOrder(self, header_path): """Check if a header is in alphabetical order with the previous header. Args: header_path: Header to be checked. Returns: Returns true if the header is in alphabetical order. """ canonical_header = self.CanonicalizeAlphabeticalOrder(header_path) if self._last_header > canonical_header: return False self._last_header = canonical_header return True def CheckNextIncludeOrder(self, header_type): """Returns a non-empty error message if the next header is out of order. This function also updates the internal state to be ready to check the next include. Args: header_type: One of the _XXX_HEADER constants defined above. Returns: The empty string if the header is in the right order, or an error message describing what's wrong. """ error_message = ('Found %s after %s' % (self._TYPE_NAMES[header_type], self._SECTION_NAMES[self._section])) last_section = self._section if header_type == _C_SYS_HEADER: if self._section <= self._C_SECTION: self._section = self._C_SECTION else: self._last_header = '' return error_message elif header_type == _CPP_SYS_HEADER: if self._section <= self._CPP_SECTION: self._section = self._CPP_SECTION else: self._last_header = '' return error_message elif header_type == _LIKELY_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: self._section = self._OTHER_H_SECTION elif header_type == _POSSIBLE_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: # This will always be the fallback because we're not sure # enough that the header is associated with this file. self._section = self._OTHER_H_SECTION else: assert header_type == _OTHER_HEADER self._section = self._OTHER_H_SECTION if last_section != self._section: self._last_header = '' return '' class _CppLintState(object): """Maintains module-wide state..""" def __init__(self): self.verbose_level = 1 # global setting. self.error_count = 0 # global count of reported errors # filters to apply when emitting error messages self.filters = _DEFAULT_FILTERS[:] self.counting = 'total' # In what way are we counting errors? self.errors_by_category = {} # string to int dict storing error counts # output format: # "emacs" - format that emacs can parse (default) # "vs7" - format that Microsoft Visual Studio 7 can parse self.output_format = 'emacs' def SetOutputFormat(self, output_format): """Sets the output format for errors.""" self.output_format = output_format def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level def SetCountingStyle(self, counting_style): """Sets the module's counting options.""" self.counting = counting_style def SetFilters(self, filters): """Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" """ # Default filters always have less priority than the flag ones. self.filters = _DEFAULT_FILTERS[:] for filt in filters.split(','): clean_filt = filt.strip() if clean_filt: self.filters.append(clean_filt) for filt in self.filters: if not (filt.startswith('+') or filt.startswith('-')): raise ValueError('Every filter in --filters must start with + or -' ' (%s does not)' % filt) def ResetErrorCounts(self): """Sets the module's error statistic back to zero.""" self.error_count = 0 self.errors_by_category = {} def IncrementErrorCount(self, category): """Bumps the module's error statistic.""" self.error_count += 1 if self.counting in ('toplevel', 'detailed'): if self.counting != 'detailed': category = category.split('/')[0] if category not in self.errors_by_category: self.errors_by_category[category] = 0 self.errors_by_category[category] += 1 def PrintErrorCounts(self): """Print a summary of errors by category, and the total.""" for category, count in self.errors_by_category.iteritems(): sys.stderr.write('Category \'%s\' errors found: %d\n' % (category, count)) sys.stderr.write('Total errors found: %d\n' % self.error_count) _cpplint_state = _CppLintState() def _OutputFormat(): """Gets the module's output format.""" return _cpplint_state.output_format def _SetOutputFormat(output_format): """Sets the module's output format.""" _cpplint_state.SetOutputFormat(output_format) def _VerboseLevel(): """Returns the module's verbosity setting.""" return _cpplint_state.verbose_level def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level) def _SetCountingStyle(level): """Sets the module's counting options.""" _cpplint_state.SetCountingStyle(level) def _Filters(): """Returns the module's list of output filters, as a list.""" return _cpplint_state.filters def _SetFilters(filters): """Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.SetFilters(filters) class _FunctionState(object): """Tracks current function name and the number of lines in its body.""" _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. def __init__(self): self.in_a_function = False self.lines_in_function = 0 self.current_function = '' def Begin(self, function_name): """Start analyzing function body. Args: function_name: The name of the function being tracked. """ self.in_a_function = True self.lines_in_function = 0 self.current_function = function_name def Count(self): """Count line in current function body.""" if self.in_a_function: self.lines_in_function += 1 def Check(self, error, filename, linenum): """Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check. """ if Match(r'T(EST|est)', self.current_function): base_trigger = self._TEST_TRIGGER else: base_trigger = self._NORMAL_TRIGGER trigger = base_trigger * 2**_VerboseLevel() if self.lines_in_function > trigger: error_level = int(math.log(self.lines_in_function / base_trigger, 2)) # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... if error_level > 5: error_level = 5 error(filename, linenum, 'readability/fn_size', error_level, 'Small and focused functions are preferred:' ' %s has %d non-comment lines' ' (error triggered by exceeding %d lines).' % ( self.current_function, self.lines_in_function, trigger)) def End(self): """Stop analyzing function body.""" self.in_a_function = False class _IncludeError(Exception): """Indicates a problem with the include order in a file.""" pass class FileInfo: """Provides utility functions for filenames. FileInfo provides easy access to the components of a file's path relative to the project root. """ def __init__(self, filename): self._filename = filename def FullName(self): """Make Windows paths like Unix.""" return os.path.abspath(self._filename).replace('\\', '/') def RepositoryName(self): """FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors. """ fullname = self.FullName() if os.path.exists(fullname): project_dir = os.path.dirname(fullname) if os.path.exists(os.path.join(project_dir, ".svn")): # If there's a .svn file in the current directory, we recursively look # up the directory tree for the top of the SVN checkout root_dir = project_dir one_up_dir = os.path.dirname(root_dir) while os.path.exists(os.path.join(one_up_dir, ".svn")): root_dir = os.path.dirname(root_dir) one_up_dir = os.path.dirname(one_up_dir) prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by # searching up from the current path. root_dir = os.path.dirname(fullname) while (root_dir != os.path.dirname(root_dir) and not os.path.exists(os.path.join(root_dir, ".git")) and not os.path.exists(os.path.join(root_dir, ".hg")) and not os.path.exists(os.path.join(root_dir, ".svn"))): root_dir = os.path.dirname(root_dir) if (os.path.exists(os.path.join(root_dir, ".git")) or os.path.exists(os.path.join(root_dir, ".hg")) or os.path.exists(os.path.join(root_dir, ".svn"))): prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Don't know what to do; header guard warnings may be wrong... return fullname def Split(self): """Splits the file into the directory, basename, and extension. For 'chrome/browser/browser.cc', Split() would return ('chrome/browser', 'browser', '.cc') Returns: A tuple of (directory, basename, extension). """ googlename = self.RepositoryName() project, rest = os.path.split(googlename) return (project,) + os.path.splitext(rest) def BaseName(self): """File base name - text after the final slash, before the final period.""" return self.Split()[1] def Extension(self): """File extension - text following the final period.""" return self.Split()[2] def NoExtension(self): """File has no source file extension.""" return '/'.join(self.Split()[0:2]) def IsSource(self): """File has a source file extension.""" return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') def _ShouldPrintError(category, confidence, linenum): """If confidence >= verbose, category passes filter and is not suppressed.""" # There are three ways we might decide not to print an error message: # a "NOLINT(category)" comment appears in the source, # the verbosity level isn't high enough, or the filters filter it out. if IsErrorSuppressedByNolint(category, linenum): return False if confidence < _cpplint_state.verbose_level: return False is_filtered = False for one_filter in _Filters(): if one_filter.startswith('-'): if category.startswith(one_filter[1:]): is_filtered = True elif one_filter.startswith('+'): if category.startswith(one_filter[1:]): is_filtered = False else: assert False # should have been checked for in SetFilter. if is_filtered: return False return True def Error(filename, linenum, category, confidence, message): """Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message. """ if _ShouldPrintError(category, confidence, linenum): _cpplint_state.IncrementErrorCount(category) if _cpplint_state.output_format == 'vs7': sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) elif _cpplint_state.output_format == 'eclipse': sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) else: sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) # Matches standard C++ escape esequences per 2.13.2.3 of the C++ standard. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') # Matches strings. Escape codes should already be removed by ESCAPES. _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"') # Matches characters. Escape codes should already be removed by ESCAPES. _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'") # Matches multi-line C++ comments. # This RE is a little bit more complicated than one might expect, because we # have to take care of space removals tools so we can handle comments inside # statements better. # The current rule is: We only clear spaces from both sides when we're at the # end of the line. Otherwise, we try to remove spaces from the right side, # if this doesn't work we try on left side but only if there's a non-character # on the right. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile( r"""(\s*/\*.*\*/\s*$| /\*.*\*/\s+| \s+/\*.*\*/(?=\W)| /\*.*\*/)""", re.VERBOSE) def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) < 0: return lineix lineix += 1 return len(lines) def FindNextMultiLineCommentEnd(lines, lineix): """We are inside a comment, find the end marker.""" while lineix < len(lines): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines) def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '// dummy' def RemoveMultiLineComments(filename, lines, error): """Removes multiline (c-style) comments from lines.""" lineix = 0 while lineix < len(lines): lineix_begin = FindNextMultiLineCommentStart(lines, lineix) if lineix_begin >= len(lines): return lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) if lineix_end >= len(lines): error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, 'Could not find end of multi-line comment') return RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) lineix = lineix_end + 1 def CleanseComments(line): """Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed. """ commentpos = line.find('//') if commentpos != -1 and not IsCppString(line[:commentpos]): line = line[:commentpos].rstrip() # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) class CleansedLines(object): """Holds 3 copies of all lines with different preprocessing applied to them. 1) elided member contains lines without strings and comments, 2) lines member contains lines without comments, and 3) raw_lines member contains all the lines without processing. All these three members are of <type 'list'>, and of the same length. """ def __init__(self, lines): self.elided = [] self.lines = [] self.raw_lines = lines self.num_lines = len(lines) for linenum in range(len(lines)): self.lines.append(CleanseComments(lines[linenum])) elided = self._CollapseStrings(lines[linenum]) self.elided.append(CleanseComments(elided)) def NumLines(self): """Returns the number of lines represented.""" return self.num_lines @staticmethod def _CollapseStrings(elided): """Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings. """ if not _RE_PATTERN_INCLUDE.match(elided): # Remove escaped characters first to make quote/single quote collapsing # basic. Things that look like escaped characters shouldn't occur # outside of strings and chars. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided) elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided) return elided def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar): """Find the position just after the matching endchar. Args: line: a CleansedLines line. startpos: start searching at this position. depth: nesting level at startpos. startchar: expression opening character. endchar: expression closing character. Returns: Index just after endchar. """ for i in xrange(startpos, len(line)): if line[i] == startchar: depth += 1 elif line[i] == endchar: depth -= 1 if depth == 0: return i + 1 return -1 def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[', finds the linenum/pos that correspond to the closing of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] startchar = line[pos] if startchar not in '({[': return (line, clean_lines.NumLines(), -1) if startchar == '(': endchar = ')' if startchar == '[': endchar = ']' if startchar == '{': endchar = '}' # Check first line end_pos = FindEndOfExpressionInLine(line, pos, 0, startchar, endchar) if end_pos > -1: return (line, linenum, end_pos) tail = line[pos:] num_open = tail.count(startchar) - tail.count(endchar) while linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] delta = line.count(startchar) - line.count(endchar) if num_open + delta <= 0: return (line, linenum, FindEndOfExpressionInLine(line, 0, num_open, startchar, endchar)) num_open += delta # Did not find endchar before end of file, give up return (line, clean_lines.NumLines(), -1) def CheckForCopyright(filename, lines, error): """Logs an error if no Copyright message appears at the top of the file.""" # We'll say it should occur by line 10. Don't forget there's a # dummy line at the front. for line in xrange(1, min(len(lines), 11)): if re.search(r'Copyright', lines[line], re.I): break else: # means no copyright line was found error(filename, 0, 'legal/copyright', 5, 'No copyright message found. ' 'You should have a line: "Copyright [year] <Copyright Owner>"') def GetHeaderGuardCPPVariable(filename): """Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file. """ # Restores original filename in case that cpplint is invoked from Emacs's # flymake. filename = re.sub(r'_flymake\.h$', '.h', filename) filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) fileinfo = FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() if _root: file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root) return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' def CheckForHeaderGuard(filename, lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ cppvar = GetHeaderGuardCPPVariable(filename) ifndef = None ifndef_linenum = 0 define = None endif = None endif_linenum = 0 for linenum, line in enumerate(lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return if not define: error(filename, 0, 'build/header_guard', 5, 'No #define header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) if define != ifndef: error(filename, 0, 'build/header_guard', 5, '#ifndef and #define don\'t match, suggested CPP variable is: %s' % cppvar) return if endif != ('#endif // %s' % cppvar): error_level = 0 if endif != ('#endif // %s' % (cppvar + '_')): error_level = 5 ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum, error) error(filename, endif_linenum, 'build/header_guard', error_level, '#endif line should be "#endif // %s"' % cppvar) def CheckForUnicodeReplacementCharacters(filename, lines, error): """Logs an error for each line containing Unicode replacement characters. These indicate that either the file contained invalid UTF-8 (likely) or Unicode replacement characters (which it shouldn't). Note that it's possible for this to throw off line numbering if the invalid UTF-8 occurred adjacent to a newline. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ for linenum, line in enumerate(lines): if u'\ufffd' in line: error(filename, linenum, 'readability/utf8', 5, 'Line contains invalid UTF-8 (or Unicode replacement character).') def CheckForNewlineAtEOF(filename, lines, error): """Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ # The array lines() was created by adding two newlines to the # original file (go figure), then splitting on \n. # To verify that the file ends in \n, we just have to make sure the # last-but-two element of lines() exists and is empty. if len(lines) < 3 or lines[-2]: error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, 'Could not find a newline character at the end of the file.') def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. They\'re ' 'ugly and unnecessary, and you should use concatenation instead".') threading_list = ( ('asctime(', 'asctime_r('), ('ctime(', 'ctime_r('), ('getgrgid(', 'getgrgid_r('), ('getgrnam(', 'getgrnam_r('), ('getlogin(', 'getlogin_r('), ('getpwnam(', 'getpwnam_r('), ('getpwuid(', 'getpwuid_r('), ('gmtime(', 'gmtime_r('), ('localtime(', 'localtime_r('), ('rand(', 'rand_r('), ('readdir(', 'readdir_r('), ('strtok(', 'strtok_r('), ('ttyname(', 'ttyname_r('), ) def CheckPosixThreading(filename, clean_lines, linenum, error): """Checks for calls to thread-unsafe functions. Much code has been originally written without consideration of multi-threading. Also, engineers are relying on their old experience; they have learned posix before threading extensions were added. These tests guide the engineers to use thread-safe functions (when using posix directly). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] for single_thread_function, multithread_safe_function in threading_list: ix = line.find(single_thread_function) # Comparisons made explicit for clarity -- pylint: disable-msg=C6403 if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and line[ix - 1] not in ('_', '.', '>'))): error(filename, linenum, 'runtime/threadsafe_fn', 2, 'Consider using ' + multithread_safe_function + '...) instead of ' + single_thread_function + '...) for improved thread safety.') # Matches invalid increment: *count++, which moves pointer instead of # incrementing a value. _RE_PATTERN_INVALID_INCREMENT = re.compile( r'^\s*\*\w+(\+\+|--);') def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).') class _BlockInfo(object): """Stores information about a generic block of code.""" def __init__(self, seen_open_brace): self.seen_open_brace = seen_open_brace self.open_parentheses = 0 self.inline_asm = _NO_ASM def CheckBegin(self, filename, clean_lines, linenum, error): """Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass def CheckEnd(self, filename, clean_lines, linenum, error): """Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass class _ClassInfo(_BlockInfo): """Stores information about a class.""" def __init__(self, name, class_or_struct, clean_lines, linenum): _BlockInfo.__init__(self, False) self.name = name self.starting_linenum = linenum self.is_derived = False if class_or_struct == 'struct': self.access = 'public' else: self.access = 'private' # Try to find the end of the class. This will be confused by things like: # class A { # } *x = { ... # # But it's still good enough for CheckSectionSpacing. self.last_line = 0 depth = 0 for i in range(linenum, clean_lines.NumLines()): line = clean_lines.elided[i] depth += line.count('{') - line.count('}') if not depth: self.last_line = i break def CheckBegin(self, filename, clean_lines, linenum, error): # Look for a bare ':' if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]): self.is_derived = True class _NamespaceInfo(_BlockInfo): """Stores information about a namespace.""" def __init__(self, name, linenum): _BlockInfo.__init__(self, False) self.name = name or '' self.starting_linenum = linenum def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply checks if there is already an end of # namespace comment and it's incorrect. # # TODO(unknown): We always want to check end of namespace comments # if a namespace is large, but sometimes we also want to apply the # check if a short namespace contained nontrivial things (something # other than forward declarations). There is currently no logic on # deciding what these nontrivial things are, so this check is # triggered by namespace size only, which works most of the time. if (linenum - self.starting_linenum < 10 and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)): return # Look for matching comment at end of namespace. # # Note that we accept C style "/* */" comments for terminating # namespaces, so that code that terminate namespaces inside # preprocessor macros can be cpplint clean. Example: http://go/nxpiz # # We also accept stuff like "// end of namespace <name>." with the # period at the end. # # Besides these, we don't accept anything else, otherwise we might # get false negatives when existing comment is a substring of the # expected namespace. Example: http://go/ldkdc, http://cl/23548205 if self.name: # Named namespace if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + r'[\*/\.\\\s]*$'), line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace %s"' % self.name) else: # Anonymous namespace if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace"') class _PreprocessorInfo(object): """Stores checkpoints of nesting stacks when #if/#else is seen.""" def __init__(self, stack_before_if): # The entire nesting stack before #if self.stack_before_if = stack_before_if # The entire nesting stack up to #else self.stack_before_else = [] # Whether we have already seen #else or #elif self.seen_else = False class _NestingState(object): """Holds states related to parsing braces.""" def __init__(self): # Stack for tracking all braces. An object is pushed whenever we # see a "{", and popped when we see a "}". Only 3 types of # objects are possible: # - _ClassInfo: a class or struct. # - _NamespaceInfo: a namespace. # - _BlockInfo: some other type of block. self.stack = [] # Stack of _PreprocessorInfo objects. self.pp_stack = [] def SeenOpenBrace(self): """Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace. """ return (not self.stack) or self.stack[-1].seen_open_brace def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo) def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif (see http://go/qwddn for original example) We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass def Update(self, filename, clean_lines, linenum, error): """Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Update pp_stack first self.UpdatePreprocessor(line) # Count parentheses. This is to avoid adding struct arguments to # the nesting stack. if self.stack: inner_block = self.stack[-1] depth_change = line.count('(') - line.count(')') inner_block.open_parentheses += depth_change # Also check if we are starting or ending an inline assembly block. if inner_block.inline_asm in (_NO_ASM, _END_ASM): if (depth_change != 0 and inner_block.open_parentheses == 1 and _MATCH_ASM.match(line)): # Enter assembly block inner_block.inline_asm = _INSIDE_ASM else: # Not entering assembly block. If previous line was _END_ASM, # we will now shift to _NO_ASM state. inner_block.inline_asm = _NO_ASM elif (inner_block.inline_asm == _INSIDE_ASM and inner_block.open_parentheses == 0): # Exit assembly block inner_block.inline_asm = _END_ASM # Consume namespace declaration at the beginning of the line. Do # this in a loop so that we catch same line declarations like this: # namespace proto2 { namespace bridge { class MessageSet; } } while True: # Match start of namespace. The "\b\s*" below catches namespace # declarations even if it weren't followed by a whitespace, this # is so that we don't confuse our namespace checker. The # missing spaces will be flagged by CheckSpacing. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) if not namespace_decl_match: break new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) self.stack.append(new_namespace) line = namespace_decl_match.group(2) if line.find('{') != -1: new_namespace.seen_open_brace = True line = line[line.find('{') + 1:] # Look for a class declaration in whatever is left of the line # after parsing namespaces. The regexp accounts for decorated classes # such as in: # class LOCKABLE API Object { # }; # # Templates with class arguments may confuse the parser, for example: # template <class T # class Comparator = less<T>, # class Vector = vector<T> > # class HeapQueue { # # Because this parser has no nesting state about templates, by the # time it saw "class Comparator", it may think that it's a new class. # Nested templates have a similar problem: # template < # typename ExportedType, # typename TupleType, # template <typename, typename> class ImplTemplate> # # To avoid these cases, we ignore classes that are followed by '=' or '>' class_decl_match = Match( r'\s*(template\s*<[\w\s<>,:]*>\s*)?' '(class|struct)\s+([A-Z_]+\s+)*(\w+(?:::\w+)*)' '(([^=>]|<[^<>]*>)*)$', line) if (class_decl_match and (not self.stack or self.stack[-1].open_parentheses == 0)): self.stack.append(_ClassInfo( class_decl_match.group(4), class_decl_match.group(2), clean_lines, linenum)) line = class_decl_match.group(5) # If we have not yet seen the opening brace for the innermost block, # run checks here. if not self.SeenOpenBrace(): self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) # Update access control if we are inside a class/struct if self.stack and isinstance(self.stack[-1], _ClassInfo): access_match = Match(r'\s*(public|private|protected)\s*:', line) if access_match: self.stack[-1].access = access_match.group(1) # Consume braces or semicolons from what's left of the line while True: # Match first brace, semicolon, or closed parenthesis. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) if not matched: break token = matched.group(1) if token == '{': # If namespace or class hasn't seen a opening brace yet, mark # namespace/class head as complete. Push a new block onto the # stack otherwise. if not self.SeenOpenBrace(): self.stack[-1].seen_open_brace = True else: self.stack.append(_BlockInfo(True)) if _MATCH_ASM.match(line): self.stack[-1].inline_asm = _BLOCK_ASM elif token == ';' or token == ')': # If we haven't seen an opening brace yet, but we already saw # a semicolon, this is probably a forward declaration. Pop # the stack for these. # # Similarly, if we haven't seen an opening brace yet, but we # already saw a closing parenthesis, then these are probably # function arguments with extra "class" or "struct" keywords. # Also pop these stack for these. if not self.SeenOpenBrace(): self.stack.pop() else: # token == '}' # Perform end of block checks and pop the stack. if self.stack: self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) self.stack.pop() line = matched.group(2) def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None def CheckClassFinished(self, filename, error): """Checks that all classes have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % obj.name) def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): """Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message """ # Remove comments from the line, but leave in strings for now. line = clean_lines.lines[linenum] if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): error(filename, linenum, 'runtime/printf_format', 3, '%q in format strings is deprecated. Use %ll instead.') if Search(r'printf\s*\(.*".*%\d+\$', line): error(filename, linenum, 'runtime/printf_format', 2, '%N$ formats are unconventional. Try rewriting to avoid them.') # Remove escaped backslashes before looking for undefined escapes. line = line.replace('\\\\', '') if Search(r'("|\').*\\(%|\[|\(|{)', line): error(filename, linenum, 'build/printf_format', 3, '%, [, (, and { are undefined character escapes. Unescape them.') # For the rest, work with both comments and strings removed. line = clean_lines.elided[linenum] if Search(r'\b(const|volatile|void|char|short|int|long' r'|float|double|signed|unsigned' r'|schar|u?int8|u?int16|u?int32|u?int64)' r'\s+(register|static|extern|typedef)\b', line): error(filename, linenum, 'build/storage_class', 5, 'Storage class (static, extern, typedef, etc) should be first.') if Match(r'\s*#\s*endif\s*[^/\s]+', line): error(filename, linenum, 'build/endif_comment', 5, 'Uncommented text after #endif is non-standard. Use a comment.') if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): error(filename, linenum, 'build/forward_decl', 5, 'Inner-style forward declarations are invalid. Remove this line.') if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line): error(filename, linenum, 'build/deprecated', 3, '>? and <? (max and min) operators are non-standard and deprecated.') if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): # TODO(unknown): Could it be expanded safely to arbitrary references, # without triggering too many false positives? The first # attempt triggered 5 warnings for mostly benign code in the regtest, hence # the restriction. # Here's the original regexp, for the reference: # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' error(filename, linenum, 'runtime/member_string_references', 2, 'const string& members are dangerous. It is much better to use ' 'alternatives, such as pointers or simple constants.') # Everything else in this function operates on class declarations. # Return early if the top of the nesting stack is not a class, or if # the class head is not completed yet. classinfo = nesting_state.InnermostClass() if not classinfo or not classinfo.seen_open_brace: return # The class may have been declared with namespace or classname qualifiers. # The constructor and destructor will not have those qualifiers. base_classname = classinfo.name.split('::')[-1] # Look for single-argument constructors that aren't marked explicit. # Technically a valid construct, but against style. args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)' % re.escape(base_classname), line) if (args and args.group(1) != 'void' and not Match(r'(const\s+)?%s\s*(?:<\w+>\s*)?&' % re.escape(base_classname), args.group(1).strip())): error(filename, linenum, 'runtime/explicit', 5, 'Single-argument constructors should be marked explicit.') def CheckSpacingForFunctionCall(filename, line, linenum, error): """Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. line: The text of the line to check. linenum: The number of the line to check. error: The function to call with any errors found. """ # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|delete)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'#\s*define|typedef', fncall) and not Search(r'\w\s+\((\w+::)?\*\w+\)\(', fncall)): error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )') def IsBlankLine(line): """Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank. """ return not line or line.isspace() def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error): """Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found. """ lines = clean_lines.lines line = lines[linenum] raw = clean_lines.raw_lines raw_line = raw[linenum] joined_line = '' starting_func = False regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... match_result = Match(regexp, line) if match_result: # If the name is all caps and underscores, figure it's a macro and # ignore it, unless it's TEST or TEST_F. function_name = match_result.group(1).split()[-1] if function_name == 'TEST' or function_name == 'TEST_F' or ( not Match(r'[A-Z_]+$', function_name)): starting_func = True if starting_func: body_found = False for start_linenum in xrange(linenum, clean_lines.NumLines()): start_line = lines[start_linenum] joined_line += ' ' + start_line.lstrip() if Search(r'(;|})', start_line): # Declarations and trivial functions body_found = True break # ... ignore elif Search(r'{', start_line): body_found = True function = Search(r'((\w|:)*)\(', line).group(1) if Match(r'TEST', function): # Handle TEST... macros parameter_regexp = Search(r'(\(.*\))', joined_line) if parameter_regexp: # Ignore bad syntax function += parameter_regexp.group(1) else: function += '()' function_state.Begin(function) break if not body_found: # No body for the function (or evidence of a non-function) was found. error(filename, linenum, 'readability/fn_size', 5, 'Lint failed to find start of function body.') elif Match(r'^\}\s*$', line): # function end function_state.Check(error, filename, linenum) function_state.End() elif not Match(r'^\s*$', line): function_state.Count() # Count non-blank/non-comment lines. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?') def CheckComment(comment, filename, linenum, error): """Checks for common mistakes in TODO comments. Args: comment: The text of the comment from the line in question. filename: The name of the current file. linenum: The number of the line to check. error: The function to call with any errors found. """ match = _RE_PATTERN_TODO.match(comment) if match: # One whitespace is correct; zero whitespace is handled elsewhere. leading_whitespace = match.group(1) if len(leading_whitespace) > 1: error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO') username = match.group(2) if not username: error(filename, linenum, 'readability/todo', 2, 'Missing username in TODO; it should look like ' '"// TODO(my_username): Stuff."') middle_whitespace = match.group(3) # Comparisons made explicit for correctness -- pylint: disable-msg=C6403 if middle_whitespace != ' ' and middle_whitespace != '': error(filename, linenum, 'whitespace/todo', 2, 'TODO(my_username) should be followed by a space') def CheckAccess(filename, clean_lines, linenum, nesting_state, error): """Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' r'DISALLOW_EVIL_CONSTRUCTORS|' r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) if not matched: return if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): if nesting_state.stack[-1].access != 'private': error(filename, linenum, 'readability/constructors', 3, '%s must be in the private: section' % matched.group(1)) else: # Found DISALLOW* macro outside a class declaration, or perhaps it # was used inside a function when it should have been part of the # class declaration. We could issue a warning here, but it # probably resulted in a compiler error already. pass def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix): """Find the corresponding > to close a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_suffix: Remainder of the current line after the initial <. Returns: True if a matching bracket exists. """ line = init_suffix nesting_stack = ['<'] while True: # Find the next operator that can tell us whether < is used as an # opening bracket or as a less-than operator. We only want to # warn on the latter case. # # We could also check all other operators and terminate the search # early, e.g. if we got something like this "a<b+c", the "<" is # most likely a less-than operator, but then we will get false # positives for default arguments (e.g. http://go/prccd) and # other template expressions (e.g. http://go/oxcjq). match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line) if match: # Found an operator, update nesting stack operator = match.group(1) line = match.group(2) if nesting_stack[-1] == '<': # Expecting closing angle bracket if operator in ('<', '(', '['): nesting_stack.append(operator) elif operator == '>': nesting_stack.pop() if not nesting_stack: # Found matching angle bracket return True elif operator == ',': # Got a comma after a bracket, this is most likely a template # argument. We have not seen a closing angle bracket yet, but # it's probably a few lines later if we look for it, so just # return early here. return True else: # Got some other operator. return False else: # Expecting closing parenthesis or closing bracket if operator in ('<', '(', '['): nesting_stack.append(operator) elif operator in (')', ']'): # We don't bother checking for matching () or []. If we got # something like (] or [), it would have been a syntax error. nesting_stack.pop() else: # Scan the next line linenum += 1 if linenum >= len(clean_lines.elided): break line = clean_lines.elided[linenum] # Exhausted all remaining lines and still no matching angle bracket. # Most likely the input was incomplete, otherwise we should have # seen a semicolon and returned early. return True def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix): """Find the corresponding < that started a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_prefix: Part of the current line before the initial >. Returns: True if a matching bracket exists. """ line = init_prefix nesting_stack = ['>'] while True: # Find the previous operator match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line) if match: # Found an operator, update nesting stack operator = match.group(2) line = match.group(1) if nesting_stack[-1] == '>': # Expecting opening angle bracket if operator in ('>', ')', ']'): nesting_stack.append(operator) elif operator == '<': nesting_stack.pop() if not nesting_stack: # Found matching angle bracket return True elif operator == ',': # Got a comma before a bracket, this is most likely a # template argument. The opening angle bracket is probably # there if we look for it, so just return early here. return True else: # Got some other operator. return False else: # Expecting opening parenthesis or opening bracket if operator in ('>', ')', ']'): nesting_stack.append(operator) elif operator in ('(', '['): nesting_stack.pop() else: # Scan the previous line linenum -= 1 if linenum < 0: break line = clean_lines.elided[linenum] # Exhausted all earlier lines and still no matching angle bracket. return False def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): """Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ raw = clean_lines.raw_lines line = raw[linenum] # Before nixing comments, check if the line is blank for no good # reason. This includes the first line after a block is opened, and # blank lines at the end of a function (ie, right before a line like '}' # # Skip all the blank line checks if we are immediately inside a # namespace body. In other words, don't issue blank line warnings # for this block: # namespace { # # } # # A warning about missing end of namespace comments will be issued instead. if IsBlankLine(line) and not nesting_state.InNamespaceBody(): elided = clean_lines.elided prev_line = elided[linenum - 1] prevbrace = prev_line.rfind('{') # TODO(unknown): Don't complain if line before blank line, and line after, # both start with alnums and are indented the same amount. # This ignores whitespace at the start of a namespace block # because those are not usually indented. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: # OK, we have a blank line at the start of a code block. Before we # complain, we check if it is an exception to the rule: The previous # non-empty line has the parameters of a function header that are indented # 4 spaces (because they did not fit in a 80 column line when placed on # the same line as the function name). We also check for the case where # the previous line is indented 6 spaces, which may happen when the # initializers of a constructor do not fit into a 80 column line. exception = False if Match(r' {6}\w', prev_line): # Initializer list? # We are looking for the opening column of initializer list, which # should be indented 4 spaces to cause 6 space indentation afterwards. search_position = linenum-2 while (search_position >= 0 and Match(r' {6}\w', elided[search_position])): search_position -= 1 exception = (search_position >= 0 and elided[search_position][:5] == ' :') else: # Search for the function arguments or an initializer list. We use a # simple heuristic here: If the line is indented 4 spaces; and we have a # closing paren, without the opening paren, followed by an opening brace # or colon (for initializer lists) we assume that it is the last line of # a function header. If we have a colon indented 4 spaces, it is an # initializer list. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', prev_line) or Match(r' {4}:', prev_line)) if not exception: error(filename, linenum, 'whitespace/blank_line', 2, 'Blank line at the start of a code block. Is this needed?') # Ignore blank lines at the end of a block in a long if-else # chain, like this: # if (condition1) { # // Something followed by a blank line # # } else if (condition2) { # // Something else # } if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] if (next_line and Match(r'\s*}', next_line) and next_line.find('} else ') == -1): error(filename, linenum, 'whitespace/blank_line', 3, 'Blank line at the end of a code block. Is this needed?') matched = Match(r'\s*(public|protected|private):', prev_line) if matched: error(filename, linenum, 'whitespace/blank_line', 3, 'Do not leave a blank line after "%s:"' % matched.group(1)) # Next, we complain if there's a comment too near the text commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it # Comparisons made explicit for clarity -- pylint: disable-msg=C6403 if (line.count('"', 0, commentpos) - line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes # Allow one space for new scopes, two spaces otherwise: if (not Match(r'^\s*{ //', line) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # There should always be a space between the // and the comment commentend = commentpos + 2 if commentend < len(line) and not line[commentend] == ' ': # but some lines are exceptions -- e.g. if they're big # comment delimiters like: # //---------------------------------------------------------- # or are an empty C++ style Doxygen comment, like: # /// # or they begin with multiple slashes followed by a space: # //////// Header comment match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or Search(r'^/$', line[commentend:]) or Search(r'^/+ ', line[commentend:])) if not match: error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment') CheckComment(line[commentpos:], filename, linenum, error) line = clean_lines.elided[linenum] # get rid of comments and strings # Don't try to do spacing checks for operator methods line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line) # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". # Otherwise not. Note we only check for non-spaces on *both* sides; # sometimes people put non-spaces on one side when aligning ='s among # many lines (not that this is behavior that I approve of...) if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line): error(filename, linenum, 'whitespace/operators', 4, 'Missing spaces around =') # It's ok not to have spaces around binary operators like + - * /, but if # there's too little whitespace, we get concerned. It's hard to tell, # though, so we punt on this one for now. TODO. # You should always have whitespace around binary operators. # # Check <= and >= first to avoid false positives with < and >, then # check non-include lines for spacing around < and >. match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around %s' % match.group(1)) # We allow no-spaces around << when used like this: 10<<20, but # not otherwise (particularly, not when used as streams) match = Search(r'(\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line) if match and not (match.group(1).isdigit() and match.group(2).isdigit()): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <<') elif not Match(r'#.*include', line): # Avoid false positives on -> reduced_line = line.replace('->', '') # Look for < that is not surrounded by spaces. This is only # triggered if both sides are missing spaces, even though # technically should should flag if at least one side is missing a # space. This is done to avoid some false positives with shifts. match = Search(r'[^\s<]<([^\s=<].*)', reduced_line) if (match and not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <') # Look for > that is not surrounded by spaces. Similar to the # above, we only trigger if both sides are missing spaces to avoid # false positives with shifts. match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line) if (match and not FindPreviousMatchingAngleBracket(clean_lines, linenum, match.group(1))): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >') # We allow no-spaces around >> for almost anything. This is because # C++11 allows ">>" to close nested templates, which accounts for # most cases when ">>" is not followed by a space. # # We still warn on ">>" followed by alpha character, because that is # likely due to ">>" being used for right shifts, e.g.: # value >> alpha # # When ">>" is used to close templates, the alphanumeric letter that # follows would be part of an identifier, and there should still be # a space separating the template type and the identifier. # type<type<type>> alpha match = Search(r'>>[a-zA-Z_]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >>') # There shouldn't be space around unary operators match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) if match: error(filename, linenum, 'whitespace/operators', 4, 'Extra space for operator %s' % match.group(1)) # A pet peeve of mine: no spaces after an if, while, switch, or for match = Search(r' (if\(|for\(|while\(|switch\()', line) if match: error(filename, linenum, 'whitespace/parens', 5, 'Missing space before ( in %s' % match.group(1)) # For if/for/while/switch, the left and right parens should be # consistent about how many spaces are inside the parens, and # there should either be zero or one spaces inside the parens. # We don't want: "if ( foo)" or "if ( foo )". # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. match = Search(r'\b(if|for|while|switch)\s*' r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', line) if match: if len(match.group(2)) != len(match.group(4)): if not (match.group(3) == ';' and len(match.group(2)) == 1 + len(match.group(4)) or not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): error(filename, linenum, 'whitespace/parens', 5, 'Mismatching spaces inside () in %s' % match.group(1)) if not len(match.group(2)) in [0, 1]: error(filename, linenum, 'whitespace/parens', 5, 'Should have zero or one spaces inside ( and ) in %s' % match.group(1)) # You should always have a space after a comma (either as fn arg or operator) if Search(r',[^\s]', line): error(filename, linenum, 'whitespace/comma', 3, 'Missing space after ,') # You should always have a space after a semicolon # except for few corner cases # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more # space after ; if Search(r';[^\s};\\)/]', line): error(filename, linenum, 'whitespace/semicolon', 3, 'Missing space after ;') # Next we will look for issues with function calls. CheckSpacingForFunctionCall(filename, line, linenum, error) # Except after an opening paren, or after another opening brace (in case of # an initializer list, for instance), you should have spaces before your # braces. And since you should never have braces at the beginning of a line, # this is an easy test. if Search(r'[^ ({]{', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before {') # Make sure '} else {' has spaces. if Search(r'}else', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before else') # You shouldn't have spaces before your brackets, except maybe after # 'delete []' or 'new char * []'. if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line): error(filename, linenum, 'whitespace/braces', 5, 'Extra space before [') # You shouldn't have a space before a semicolon at the end of the line. # There's a special case for "for" since the style guide allows space before # the semicolon there. if Search(r':\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Semicolon defining empty statement. Use {} instead.') elif Search(r'^\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Line contains only semicolon. If this should be an empty statement, ' 'use {} instead.') elif (Search(r'\s+;\s*$', line) and not Search(r'\bfor\b', line)): error(filename, linenum, 'whitespace/semicolon', 5, 'Extra space before last semicolon. If this should be an empty ' 'statement, use {} instead.') # In range-based for, we wanted spaces before and after the colon, but # not around "::" tokens that might appear. if (Search('for *\(.*[^:]:[^: ]', line) or Search('for *\(.*[^: ]:[^:]', line)): error(filename, linenum, 'whitespace/forcolon', 2, 'Missing space around colon in range-based for loop') def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): """Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found. """ # Skip checks if the class is small, where small means 25 lines or less. # 25 lines seems like a good cutoff since that's the usual height of # terminals, and any class that can't fit in one screen can't really # be considered "small". # # Also skip checks if we are on the first line. This accounts for # classes that look like # class Foo { public: ... }; # # If we didn't find the end of the class, last_line would be zero, # and the check will be skipped by the first condition. if (class_info.last_line - class_info.starting_linenum <= 24 or linenum <= class_info.starting_linenum): return matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) if matched: # Issue warning if the line before public/protected/private was # not a blank line, but don't do this if the previous line contains # "class" or "struct". This can happen two ways: # - We are at the beginning of the class. # - We are forward-declaring an inner class that is semantically # private, but needed to be public for implementation reasons. # Also ignores cases where the previous line ends with a backslash as can be # common when defining classes in C macros. prev_line = clean_lines.lines[linenum - 1] if (not IsBlankLine(prev_line) and not Search(r'\b(class|struct)\b', prev_line) and not Search(r'\\$', prev_line)): # Try a bit harder to find the beginning of the class. This is to # account for multi-line base-specifier lists, e.g.: # class Derived # : public Base { end_class_head = class_info.starting_linenum for i in range(class_info.starting_linenum, linenum): if Search(r'\{\s*$', clean_lines.lines[i]): end_class_head = i break if end_class_head < linenum - 1: error(filename, linenum, 'whitespace/blank_line', 3, '"%s:" should be preceded by a blank line' % matched.group(1)) def GetPreviousNonBlankLine(clean_lines, linenum): """Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line. """ prevlinenum = linenum - 1 while prevlinenum >= 0: prevline = clean_lines.elided[prevlinenum] if not IsBlankLine(prevline): # if not a blank line... return (prevline, prevlinenum) prevlinenum -= 1 return ('', -1) def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone # is using braces in a block to explicitly create a new scope, # which is commonly used to control the lifetime of # stack-allocated variables. We don't detect this perfectly: we # just don't complain if the last non-whitespace character on the # previous non-blank line is ';', ':', '{', or '}', or if the previous # line starts a preprocessor block. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (not Search(r'[;:}{]\s*$', prevline) and not Match(r'\s*#', prevline)): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\s*', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) if endline[endpos:].find('{') == -1: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') else: # common case: else not followed by a multi-line if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Braces shouldn't be followed by a ; unless they're defining a struct # or initializing an array. # We can't tell in general, but we can for some common cases. prevlinenum = linenum while True: (prevline, prevlinenum) = GetPreviousNonBlankLine(clean_lines, prevlinenum) if Match(r'\s+{.*}\s*;', line) and not prevline.count(';'): line = prevline + line else: break if (Search(r'{.*}\s*;', line) and line.count('{') == line.count('}') and not Search(r'struct|class|enum|\s*=\s*{', line)): error(filename, linenum, 'readability/braces', 4, "You don't need a ; after a }") def CheckEmptyLoopBody(filename, clean_lines, linenum, error): """Loop for empty loop body with only a single semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Search for loop keywords at the beginning of the line. Because only # whitespaces are allowed before the keywords, this will also ignore most # do-while-loops, since those lines should start with closing brace. line = clean_lines.elided[linenum] if Match(r'\s*(for|while)\s*\(', line): # Find the end of the conditional expression (end_line, end_linenum, end_pos) = CloseExpression( clean_lines, linenum, line.find('(')) # Output warning if what follows the condition expression is a semicolon. # No warning for all other cases, including whitespace or newline, since we # have a separate check for semicolons preceded by whitespace. if end_pos >= 0 and Match(r';', end_line[end_pos:]): error(filename, end_linenum, 'whitespace/empty_loop_body', 5, 'Empty loop bodies should use {} or continue') def ReplaceableCheck(operator, macro, line): """Determine whether a basic CHECK can be replaced with a more specific one. For example suggest using CHECK_EQ instead of CHECK(a == b) and similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE. Args: operator: The C++ operator used in the CHECK. macro: The CHECK or EXPECT macro being called. line: The current source line. Returns: True if the CHECK can be replaced with a more specific one. """ # This matches decimal and hex integers, strings, and chars (in that order). match_constant = r'([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')' # Expression to match two sides of the operator with something that # looks like a literal, since CHECK(x == iterator) won't compile. # This means we can't catch all the cases where a more specific # CHECK is possible, but it's less annoying than dealing with # extraneous warnings. match_this = (r'\s*' + macro + r'\((\s*' + match_constant + r'\s*' + operator + r'[^<>].*|' r'.*[^<>]' + operator + r'\s*' + match_constant + r'\s*\))') # Don't complain about CHECK(x == NULL) or similar because # CHECK_EQ(x, NULL) won't compile (requires a cast). # Also, don't complain about more complex boolean expressions # involving && or || such as CHECK(a == b || c == d). return Match(match_this, line) and not Search(r'NULL|&&|\|\|', line) def CheckCheck(filename, clean_lines, linenum, error): """Checks the use of CHECK and EXPECT macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Decide the set of replacement macros that should be suggested raw_lines = clean_lines.raw_lines current_macro = '' for macro in _CHECK_MACROS: if raw_lines[linenum].find(macro) >= 0: current_macro = macro break if not current_macro: # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT' return line = clean_lines.elided[linenum] # get rid of comments and strings # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc. for operator in ['==', '!=', '>=', '>', '<=', '<']: if ReplaceableCheck(operator, current_macro, line): error(filename, linenum, 'readability/check', 2, 'Consider using %s instead of %s(a %s b)' % ( _CHECK_REPLACEMENT[current_macro][operator], current_macro, operator)) break def CheckAltTokens(filename, clean_lines, linenum, error): """Check alternative keywords being used in boolean expressions. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Avoid preprocessor lines if Match(r'^\s*#', line): return # Last ditch effort to avoid multi-line comments. This will not help # if the comment started before the current line or ended after the # current line, but it catches most of the false positives. At least, # it provides a way to workaround this warning for people who use # multi-line comments in preprocessor macros. # # TODO(unknown): remove this once cpplint has better support for # multi-line comments. if line.find('/*') >= 0 or line.find('*/') >= 0: return for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): error(filename, linenum, 'readability/alt_tokens', 2, 'Use operator %s instead of %s' % ( _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) def GetLineWidth(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width else: return len(line) def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, error): """Checks rules from the 'C++ style rules' section of cppguide.html. Most of these rules are hard to test (naming, comment style), but we do what we can. In particular we check for 2-space indents, line lengths, tab usage, spaces inside code, etc. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ raw_lines = clean_lines.raw_lines line = raw_lines[linenum] if line.find('\t') != -1: error(filename, linenum, 'whitespace/tab', 1, 'Tab found; better to use spaces') # One or three blank spaces at the beginning of the line is weird; it's # hard to reconcile that with 2-space indents. # NOTE: here are the conditions rob pike used for his tests. Mine aren't # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces # if(RLENGTH > 20) complain = 0; # if(match($0, " +(error|private|public|protected):")) complain = 0; # if(match(prev, "&& *$")) complain = 0; # if(match(prev, "\\|\\| *$")) complain = 0; # if(match(prev, "[\",=><] *$")) complain = 0; # if(match($0, " <<")) complain = 0; # if(match(prev, " +for \\(")) complain = 0; # if(prevodd && match(prevprev, " +for \\(")) complain = 0; initial_spaces = 0 cleansed_line = clean_lines.elided[linenum] while initial_spaces < len(line) and line[initial_spaces] == ' ': initial_spaces += 1 if line and line[-1].isspace(): error(filename, linenum, 'whitespace/end_of_line', 4, 'Line ends in whitespace. Consider deleting these extra spaces.') # There are certain situations we allow one space, notably for labels elif ((initial_spaces == 1 or initial_spaces == 3) and not Match(r'\s*\w+\s*:\s*$', cleansed_line)): error(filename, linenum, 'whitespace/indent', 3, 'Weird number of spaces at line-start. ' 'Are you using a 2-space indent?') # Labels should always be indented at least one space. elif not initial_spaces and line[:2] != '//' and Search(r'[^:]:\s*$', line): error(filename, linenum, 'whitespace/labels', 4, 'Labels should always be indented at least one space. ' 'If this is a member-initializer list in a constructor or ' 'the base class list in a class definition, the colon should ' 'be on the following line.') # Check if the line is a header guard. is_header_guard = False if file_extension == 'h': cppvar = GetHeaderGuardCPPVariable(filename) if (line.startswith('#ifndef %s' % cppvar) or line.startswith('#define %s' % cppvar) or line.startswith('#endif // %s' % cppvar)): is_header_guard = True # #include lines and header guards can be long, since there's no clean way to # split them. # # URLs can be long too. It's possible to split these, but it makes them # harder to cut&paste. # # The "$Id:...$" comment may also get very long without it being the # developers fault. if (not line.startswith('#include') and not is_header_guard and not Match(r'^\s*//.*http(s?)://\S*$', line) and not Match(r'^// \$Id:.*#[0-9]+ \$$', line)): line_width = GetLineWidth(line) if line_width > 100: error(filename, linenum, 'whitespace/line_length', 4, 'Lines should very rarely be longer than 100 characters') elif line_width > 80: error(filename, linenum, 'whitespace/line_length', 2, 'Lines should be <= 80 characters long') if (cleansed_line.count(';') > 1 and # for loops are allowed two ;'s (and may run over two lines). cleansed_line.find('for') == -1 and (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and # It's ok to have many commands in a switch case that fits in 1 line not ((cleansed_line.find('case ') != -1 or cleansed_line.find('default:') != -1) and cleansed_line.find('break;') != -1)): error(filename, linenum, 'whitespace/newline', 0, 'More than one command on the same line') # Some more style checks CheckBraces(filename, clean_lines, linenum, error) CheckEmptyLoopBody(filename, clean_lines, linenum, error) CheckAccess(filename, clean_lines, linenum, nesting_state, error) CheckSpacing(filename, clean_lines, linenum, nesting_state, error) CheckCheck(filename, clean_lines, linenum, error) CheckAltTokens(filename, clean_lines, linenum, error) classinfo = nesting_state.InnermostClass() if classinfo: CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"') _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') # Matches the first component of a filename delimited by -s and _s. That is: # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') def _DropCommonSuffixes(filename): """Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed. """ for suffix in ('test.cc', 'regtest.cc', 'unittest.cc', 'inl.h', 'impl.h', 'internal.h'): if (filename.endswith(suffix) and len(filename) > len(suffix) and filename[-len(suffix) - 1] in ('-', '_')): return filename[:-len(suffix) - 1] return os.path.splitext(filename)[0] def _IsTestFilename(filename): """Determines if the given filename has a suffix that identifies it as a test. Args: filename: The input filename. Returns: True if 'filename' looks like a test, False otherwise. """ if (filename.endswith('_test.cc') or filename.endswith('_unittest.cc') or filename.endswith('_regtest.cc')): return True else: return False def _ClassifyInclude(fileinfo, include, is_system): """Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _XXX_HEADER constants. For example: >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) _C_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) _CPP_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) _LIKELY_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), ... 'bar/foo_other_ext.h', False) _POSSIBLE_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) _OTHER_HEADER """ # This is a list of all standard c++ header files, except # those already checked for above. is_stl_h = include in _STL_HEADERS is_cpp_h = is_stl_h or include in _CPP_HEADERS if is_system: if is_cpp_h: return _CPP_SYS_HEADER else: return _C_SYS_HEADER # If the target file and the include we're checking share a # basename when we drop common extensions, and the include # lives in . , then it's likely to be owned by the target file. target_dir, target_base = ( os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) if target_base == include_base and ( include_dir == target_dir or include_dir == os.path.normpath(target_dir + '/../public')): return _LIKELY_MY_HEADER # If the target and include share some initial basename # component, it's possible the target is implementing the # include, so it's allowed to be first, but we'll never # complain if it's not there. target_first_component = _RE_FIRST_COMPONENT.match(target_base) include_first_component = _RE_FIRST_COMPONENT.match(include_base) if (target_first_component and include_first_component and target_first_component.group(0) == include_first_component.group(0)): return _POSSIBLE_MY_HEADER return _OTHER_HEADER def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): """Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found. """ fileinfo = FileInfo(filename) line = clean_lines.lines[linenum] # "include" should use the new style "foo/bar.h" instead of just "bar.h" if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line): error(filename, linenum, 'build/include', 4, 'Include the directory when naming .h files') # we shouldn't include a file more than once. actually, there are a # handful of instances where doing so is okay, but in general it's # not. match = _RE_PATTERN_INCLUDE.search(line) if match: include = match.group(2) is_system = (match.group(1) == '<') if include in include_state: error(filename, linenum, 'build/include', 4, '"%s" already included at %s:%s' % (include, filename, include_state[include])) else: include_state[include] = linenum # We want to ensure that headers appear in the right order: # 1) for foo.cc, foo.h (preferred location) # 2) c system files # 3) cpp system files # 4) for foo.cc, foo.h (deprecated location) # 5) other google headers # # We classify each include statement as one of those 5 types # using a number of techniques. The include_state object keeps # track of the highest type seen, and complains if we see a # lower type after that. error_message = include_state.CheckNextIncludeOrder( _ClassifyInclude(fileinfo, include, is_system)) if error_message: error(filename, linenum, 'build/include_order', 4, '%s. Should be: %s.h, c system, c++ system, other.' % (error_message, fileinfo.BaseName())) if not include_state.IsInAlphabeticalOrder(include): error(filename, linenum, 'build/include_alpha', 4, 'Include "%s" not in alphabetical order' % include) # Look for any of the stream classes that are part of standard C++. match = _RE_PATTERN_INCLUDE.match(line) if match: include = match.group(2) if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include): # Many unit tests use cout, so we exempt them. if not _IsTestFilename(filename): error(filename, linenum, 'readability/streams', 3, 'Streams are highly discouraged.') def _GetTextInside(text, start_pattern): """Retrieves all the text between matching open and close parentheses. Given a string of lines and a regular expression string, retrieve all the text following the expression and between opening punctuation symbols like (, [, or {, and the matching close-punctuation symbol. This properly nested occurrences of the punctuations, so for the text like printf(a(), b(c())); a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. start_pattern must match string having an open punctuation symbol at the end. Args: text: The lines to extract text. Its comments and strings must be elided. It can be single line and can span multiple lines. start_pattern: The regexp string indicating where to start extracting the text. Returns: The extracted text. None if either the opening string or ending punctuation could not be found. """ # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably # rewritten to use _GetTextInside (and use inferior regexp matching today). # Give opening punctuations to get the matching close-punctuations. matching_punctuation = {'(': ')', '{': '}', '[': ']'} closing_punctuation = set(matching_punctuation.itervalues()) # Find the position to start extracting text. match = re.search(start_pattern, text, re.M) if not match: # start_pattern not found in text. return None start_position = match.end(0) assert start_position > 0, ( 'start_pattern must ends with an opening punctuation.') assert text[start_position - 1] in matching_punctuation, ( 'start_pattern must ends with an opening punctuation.') # Stack of closing punctuations we expect to have in text after position. punctuation_stack = [matching_punctuation[text[start_position - 1]]] position = start_position while punctuation_stack and position < len(text): if text[position] == punctuation_stack[-1]: punctuation_stack.pop() elif text[position] in closing_punctuation: # A closing punctuation without matching opening punctuations. return None elif text[position] in matching_punctuation: punctuation_stack.append(matching_punctuation[text[position]]) position += 1 if punctuation_stack: # Opening punctuations left without matching close-punctuations. return None # punctuations match. return text[start_position:position - 1] def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state, error): """Checks rules from the 'C++ language rules' section of cppguide.html. Some of these rules are hard to test (function overloading, using uint32 inappropriately), but we do the best we can. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found. """ # If the line is empty or consists of entirely a comment, no need to # check it. line = clean_lines.elided[linenum] if not line: return match = _RE_PATTERN_INCLUDE.search(line) if match: CheckIncludeLine(filename, clean_lines, linenum, include_state, error) return # Create an extended_line, which is the concatenation of the current and # next lines, for more effective checking of code that may span more than one # line. if linenum + 1 < clean_lines.NumLines(): extended_line = line + clean_lines.elided[linenum + 1] else: extended_line = line # Make Windows paths like Unix. fullname = os.path.abspath(filename).replace('\\', '/') # TODO(unknown): figure out if they're using default arguments in fn proto. # Check for non-const references in functions. This is tricky because & # is also used to take the address of something. We allow <> for templates, # (ignoring whatever is between the braces) and : for classes. # These are complicated re's. They try to capture the following: # paren (for fn-prototype start), typename, &, varname. For the const # version, we're willing for const to be before typename or after # Don't check the implementation on same line. fnline = line.split('{', 1)[0] if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) > len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?' r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) + len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+', fnline))): # We allow non-const references in a few standard places, like functions # called "swap()" or iostream operators like "<<" or ">>". We also filter # out for loops, which lint otherwise mistakenly thinks are functions. if not Search( r'(for|swap|Swap|operator[<>][<>])\s*\(\s*' r'(?:(?:typename\s*)?[\w:]|<.*>)+\s*&', fnline): error(filename, linenum, 'runtime/references', 2, 'Is this a non-const reference? ' 'If so, make const or use a pointer.') # Check to see if they're using an conversion function cast. # I just try to capture the most common basic types, though there are more. # Parameterless conversion functions, such as bool(), are allowed as they are # probably a member operator declaration or default constructor. match = Search( r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there r'(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line) if match: # gMock methods are defined using some variant of MOCK_METHODx(name, type) # where type may be float(), int(string), etc. Without context they are # virtually indistinguishable from int(x) casts. Likewise, gMock's # MockCallback takes a template parameter of the form return_type(arg_type), # which looks much like the cast we're trying to detect. if (match.group(1) is None and # If new operator, then this isn't a cast not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or Match(r'^\s*MockCallback<.*>', line))): # Try a bit harder to catch gmock lines: the only place where # something looks like an old-style cast is where we declare the # return type of the mocked method, and the only time when we # are missing context is if MOCK_METHOD was split across # multiple lines (for example http://go/hrfhr ), so we only need # to check the previous line for MOCK_METHOD. if (linenum == 0 or not Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(\S+,\s*$', clean_lines.elided[linenum - 1])): error(filename, linenum, 'readability/casting', 4, 'Using deprecated casting style. ' 'Use static_cast<%s>(...) instead' % match.group(2)) CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], 'static_cast', r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) # This doesn't catch all cases. Consider (const char * const)"hello". # # (char *) "foo" should always be a const_cast (reinterpret_cast won't # compile). if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error): pass else: # Check pointer casts for other than string constants CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error) # In addition, we look for people taking the address of a cast. This # is dangerous -- casts can assign to temporaries, so the pointer doesn't # point where you think. if Search( r'(&\([^)]+\)[\w(])|(&(static|dynamic|reinterpret)_cast\b)', line): error(filename, linenum, 'runtime/casting', 4, ('Are you taking an address of a cast? ' 'This is dangerous: could be a temp var. ' 'Take the address before doing the cast, rather than after')) # Check for people declaring static/global STL strings at the top level. # This is dangerous because the C++ language does not guarantee that # globals with constructors are initialized before the first access. match = Match( r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)', line) # Make sure it's not a function. # Function template specialization looks like: "string foo<Type>(...". # Class template definitions look like: "string Foo<Type>::Method(...". if match and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)', match.group(3)): error(filename, linenum, 'runtime/string', 4, 'For a static/global string constant, use a C style string instead: ' '"%schar %s[]".' % (match.group(1), match.group(2))) # Check that we're not using RTTI outside of testing code. if Search(r'\bdynamic_cast<', line) and not _IsTestFilename(filename): error(filename, linenum, 'runtime/rtti', 5, 'Do not use dynamic_cast<>. If you need to cast within a class ' "hierarchy, use static_cast<> to upcast. Google doesn't support " 'RTTI.') if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line): error(filename, linenum, 'runtime/init', 4, 'You seem to be initializing a member variable with itself.') if file_extension == 'h': # TODO(unknown): check that 1-arg constructors are explicit. # How to tell it's a constructor? # (handled in CheckForNonStandardConstructs for now) # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS # (level 1 error) pass # Check if people are using the verboten C basic types. The only exception # we regularly allow is "unsigned short port" for port. if Search(r'\bshort port\b', line): if not Search(r'\bunsigned short port\b', line): error(filename, linenum, 'runtime/int', 4, 'Use "unsigned short" for ports, not "short"') else: match = Search(r'\b(short|long(?! +double)|long long)\b', line) if match: error(filename, linenum, 'runtime/int', 4, 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) # When snprintf is used, the second argument shouldn't be a literal. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) if match and match.group(2) != '0': # If 2nd arg is zero, snprintf is used to calculate size. error(filename, linenum, 'runtime/printf', 3, 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' 'to snprintf.' % (match.group(1), match.group(2))) # Check if some verboten C functions are being used. if Search(r'\bsprintf\b', line): error(filename, linenum, 'runtime/printf', 5, 'Never use sprintf. Use snprintf instead.') match = Search(r'\b(strcpy|strcat)\b', line) if match: error(filename, linenum, 'runtime/printf', 4, 'Almost always, snprintf is better than %s' % match.group(1)) if Search(r'\bsscanf\b', line): error(filename, linenum, 'runtime/printf', 1, 'sscanf can be ok, but is slow and can overflow buffers.') # Check if some verboten operator overloading is going on # TODO(unknown): catch out-of-line unary operator&: # class X {}; # int operator&(const X& x) { return 42; } // unary operator& # The trick is it's hard to tell apart from binary operator&: # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& if Search(r'\boperator\s*&\s*\(\s*\)', line): error(filename, linenum, 'runtime/operator', 4, 'Unary operator& is dangerous. Do not use it.') # Check for suspicious usage of "if" like # } if (a == b) { if Search(r'\}\s*if\s*\(', line): error(filename, linenum, 'readability/braces', 4, 'Did you mean "else if"? If not, start a new line for "if".') # Check for potential format string bugs like printf(foo). # We constrain the pattern not to pick things like DocidForPrintf(foo). # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) # TODO(sugawarayu): Catch the following case. Need to change the calling # convention of the whole function to process multiple line to handle it. # printf( # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') if printf_args: match = Match(r'([\w.\->()]+)$', printf_args) if match and match.group(1) != '__VA_ARGS__': function_name = re.search(r'\b((?:string)?printf)\s*\(', line, re.I).group(1) error(filename, linenum, 'runtime/printf', 4, 'Potential format string bug. Do %s("%%s", %s) instead.' % (function_name, match.group(1))) # Check for potential memset bugs like memset(buf, sizeof(buf), 0). match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): error(filename, linenum, 'runtime/memset', 4, 'Did you mean "memset(%s, 0, %s)"?' % (match.group(1), match.group(2))) if Search(r'\busing namespace\b', line): error(filename, linenum, 'build/namespaces', 5, 'Do not use namespace using-directives. ' 'Use using-declarations instead.') # Detect variable-length arrays. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) if (match and match.group(2) != 'return' and match.group(2) != 'delete' and match.group(3).find(']') == -1): # Split the size using space and arithmetic operators as delimiters. # If any of the resulting tokens are not compile time constants then # report the error. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) is_const = True skip_next = False for tok in tokens: if skip_next: skip_next = False continue if Search(r'sizeof\(.+\)', tok): continue if Search(r'arraysize\(\w+\)', tok): continue tok = tok.lstrip('(') tok = tok.rstrip(')') if not tok: continue if Match(r'\d+', tok): continue if Match(r'0[xX][0-9a-fA-F]+', tok): continue if Match(r'k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue # A catch all for tricky sizeof cases, including 'sizeof expression', # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' # requires skipping the next token because we split on ' ' and '*'. if tok.startswith('sizeof'): skip_next = True continue is_const = False break if not is_const: error(filename, linenum, 'runtime/arrays', 1, 'Do not use variable-length arrays. Use an appropriately named ' "('k' followed by CamelCase) compile-time constant for the size.") # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing # in the class declaration. match = Match( (r'\s*' r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))' r'\(.*\);$'), line) if match and linenum + 1 < clean_lines.NumLines(): next_line = clean_lines.elided[linenum + 1] # We allow some, but not all, declarations of variables to be present # in the statement that defines the class. The [\w\*,\s]* fragment of # the regular expression below allows users to declare instances of # the class or pointers to instances, but not less common types such # as function pointers or arrays. It's a tradeoff between allowing # reasonable code and avoiding trying to parse more C++ using regexps. if not Search(r'^\s*}[\w\*,\s]*;', next_line): error(filename, linenum, 'readability/constructors', 3, match.group(1) + ' should be the last thing in the class') # Check for use of unnamed namespaces in header files. Registration # macros are typically OK, so we allow use of "namespace {" on lines # that end with backslashes. if (file_extension == 'h' and Search(r'\bnamespace\s*{', line) and line[-1] != '\\'): error(filename, linenum, 'build/namespaces', 4, 'Do not use unnamed namespaces in header files. See ' 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' ' for more information.') def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. This also handles sizeof(type) warnings, due to similarity of content. Args: filename: The name of the current file. linenum: The number of the line to check. line: The line of code to check. raw_line: The raw line of code to check, with comments. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ match = Search(pattern, line) if not match: return False # e.g., sizeof(int) sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1]) if sizeof_match: error(filename, linenum, 'runtime/sizeof', 1, 'Using sizeof(type). Use sizeof(varname) instead if possible') return True # operator++(int) and operator--(int) if (line[0:match.start(1) - 1].endswith(' operator++') or line[0:match.start(1) - 1].endswith(' operator--')): return False remainder = line[match.end(0):] # The close paren is for function pointers as arguments to a function. # eg, void foo(void (*bar)(int)); # The semicolon check is a more basic function check; also possibly a # function pointer typedef. # eg, void foo(int); or void foo(int) const; # The equals check is for function pointer assignment. # eg, void *(*foo)(int) = ... # The > is for MockCallback<...> ... # # Right now, this will only catch cases where there's a single argument, and # it's unnamed. It should probably be expanded to check for multiple # arguments with some unnamed. function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)|>))', remainder) if function_match: if (not function_match.group(3) or function_match.group(3) == ';' or ('MockCallback<' not in raw_line and '/*' not in raw_line)): error(filename, linenum, 'readability/function', 3, 'All parameters should be named in a function') return True # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True _HEADERS_CONTAINING_TEMPLATES = ( ('<deque>', ('deque',)), ('<functional>', ('unary_function', 'binary_function', 'plus', 'minus', 'multiplies', 'divides', 'modulus', 'negate', 'equal_to', 'not_equal_to', 'greater', 'less', 'greater_equal', 'less_equal', 'logical_and', 'logical_or', 'logical_not', 'unary_negate', 'not1', 'binary_negate', 'not2', 'bind1st', 'bind2nd', 'pointer_to_unary_function', 'pointer_to_binary_function', 'ptr_fun', 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t', 'mem_fun_ref_t', 'const_mem_fun_t', 'const_mem_fun1_t', 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t', 'mem_fun_ref', )), ('<limits>', ('numeric_limits',)), ('<list>', ('list',)), ('<map>', ('map', 'multimap',)), ('<memory>', ('allocator',)), ('<queue>', ('queue', 'priority_queue',)), ('<set>', ('set', 'multiset',)), ('<stack>', ('stack',)), ('<string>', ('char_traits', 'basic_string',)), ('<utility>', ('pair',)), ('<vector>', ('vector',)), # gcc extensions. # Note: std::hash is their hash, ::hash is our hash ('<hash_map>', ('hash_map', 'hash_multimap',)), ('<hash_set>', ('hash_set', 'hash_multiset',)), ('<slist>', ('slist',)), ) _RE_PATTERN_STRING = re.compile(r'\bstring\b') _re_pattern_algorithm_header = [] for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap', 'transform'): # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or # type::max(). _re_pattern_algorithm_header.append( (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'), _template, '<algorithm>')) _re_pattern_templates = [] for _header, _templates in _HEADERS_CONTAINING_TEMPLATES: for _template in _templates: _re_pattern_templates.append( (re.compile(r'(\<|\b)' + _template + r'\s*\<'), _template + '<>', _header)) def FilesBelongToSameModule(filename_cc, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the .cc file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file. """ if not filename_cc.endswith('.cc'): return (False, '') filename_cc = filename_cc[:-len('.cc')] if filename_cc.endswith('_unittest'): filename_cc = filename_cc[:-len('_unittest')] elif filename_cc.endswith('_test'): filename_cc = filename_cc[:-len('_test')] filename_cc = filename_cc.replace('/public/', '/') filename_cc = filename_cc.replace('/internal/', '/') if not filename_h.endswith('.h'): return (False, '') filename_h = filename_h[:-len('.h')] if filename_h.endswith('-inl'): filename_h = filename_h[:-len('-inl')] filename_h = filename_h.replace('/public/', '/') filename_h = filename_h.replace('/internal/', '/') files_belong_to_same_module = filename_cc.endswith(filename_h) common_path = '' if files_belong_to_same_module: common_path = filename_cc[:-len(filename_h)] return files_belong_to_same_module, common_path def UpdateIncludeState(filename, include_state, io=codecs): """Fill up the include_state with new includes found from the file. Args: filename: the name of the header to read. include_state: an _IncludeState instance in which the headers are inserted. io: The io factory to use to read the file. Provided for testability. Returns: True if a header was succesfully added. False otherwise. """ headerfile = None try: headerfile = io.open(filename, 'r', 'utf8', 'replace') except IOError: return False linenum = 0 for line in headerfile: linenum += 1 clean_line = CleanseComments(line) match = _RE_PATTERN_INCLUDE.search(clean_line) if match: include = match.group(2) # The value formatting is cute, but not really used right now. # What matters here is that the key is in include_state. include_state.setdefault(include, '%s:%d' % (filename, linenum)) return True def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs): """Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection. """ required = {} # A map of header name to linenumber and the template entity. # Example of required: { '<functional>': (1219, 'less<>') } for linenum in xrange(clean_lines.NumLines()): line = clean_lines.elided[linenum] if not line or line[0] == '#': continue # String is special -- it is a non-templatized type in STL. matched = _RE_PATTERN_STRING.search(line) if matched: # Don't warn about strings in non-STL namespaces: # (We check only the first match per line; good enough.) prefix = line[:matched.start()] if prefix.endswith('std::') or not prefix.endswith('::'): required['<string>'] = (linenum, 'string') for pattern, template, header in _re_pattern_algorithm_header: if pattern.search(line): required[header] = (linenum, template) # The following function is just a speed up, no semantics are changed. if not '<' in line: # Reduces the cpu time usage by skipping lines. continue for pattern, template, header in _re_pattern_templates: if pattern.search(line): required[header] = (linenum, template) # The policy is that if you #include something in foo.h you don't need to # include it again in foo.cc. Here, we will look at possible includes. # Let's copy the include_state so it is only messed up within this function. include_state = include_state.copy() # Did we find the header for this file (if any) and succesfully load it? header_found = False # Use the absolute path so that matching works properly. abs_filename = FileInfo(filename).FullName() # For Emacs's flymake. # If cpplint is invoked from Emacs's flymake, a temporary file is generated # by flymake and that file name might end with '_flymake.cc'. In that case, # restore original file name here so that the corresponding header file can be # found. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' # instead of 'foo_flymake.h' abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) # include_state is modified during iteration, so we iterate over a copy of # the keys. header_keys = include_state.keys() for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header if same_module and UpdateIncludeState(fullpath, include_state, io): header_found = True # If we can't find the header file for a .cc, assume it's because we don't # know where to look. In that case we'll give up as we're not sure they # didn't include it in the .h file. # TODO(unknown): Do a better job of finding .h files so we are confident that # not having the .h file means there isn't one. if filename.endswith('.cc') and not header_found: return # All the lines have been processed, report the errors found. for required_header_unstripped in required: template = required[required_header_unstripped][1] if required_header_unstripped.strip('<>"') not in include_state: error(filename, required[required_header_unstripped][0], 'build/include_what_you_use', 4, 'Add #include ' + required_header_unstripped + ' for ' + template) _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<') def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): """Check that make_pair's template arguments are deduced. G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ raw = clean_lines.raw_lines line = raw[linenum] match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) if match: error(filename, linenum, 'build/explicit_make_pair', 4, # 4 = high confidence 'For C++11-compatibility, omit template arguments from make_pair' ' OR use pair directly OR if appropriate, construct a pair directly') def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[]): """Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) nesting_state.Update(filename, clean_lines, line, error) if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM: return CheckForFunctionLengths(filename, clean_lines, line, function_state, error) CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) CheckLanguage(filename, clean_lines, line, file_extension, include_state, error) CheckForNonStandardConstructs(filename, clean_lines, line, nesting_state, error) CheckPosixThreading(filename, clean_lines, line, error) CheckInvalidIncrement(filename, clean_lines, line, error) CheckMakePairUsesDeduction(filename, clean_lines, line, error) for check_fn in extra_check_functions: check_fn(filename, clean_lines, line, error) def ProcessFileData(filename, file_extension, lines, error, extra_check_functions=[]): """Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. lines: An array of strings, each representing a line of the file, with the last element being empty if the file is terminated with a newline. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ lines = (['// marker so line numbers and indices both start at 1'] + lines + ['// marker so line numbers end in a known way']) include_state = _IncludeState() function_state = _FunctionState() nesting_state = _NestingState() ResetNolintSuppressions() CheckForCopyright(filename, lines, error) if file_extension == 'h': CheckForHeaderGuard(filename, lines, error) RemoveMultiLineComments(filename, lines, error) clean_lines = CleansedLines(lines) for line in xrange(clean_lines.NumLines()): ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions) nesting_state.CheckClassFinished(filename, error) CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) # We check here rather than inside ProcessLine so that we see raw # lines rather than "cleaned" lines. CheckForUnicodeReplacementCharacters(filename, lines, error) CheckForNewlineAtEOF(filename, lines, error) def ProcessFile(filename, vlevel, extra_check_functions=[]): """Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ _SetVerboseLevel(vlevel) try: # Support the UNIX convention of using "-" for stdin. Note that # we are not opening the file with universal newline support # (which codecs doesn't support anyway), so the resulting lines do # contain trailing '\r' characters if we are reading a file that # has CRLF endings. # If after the split a trailing '\r' is present, it is removed # below. If it is not expected to be present (i.e. os.linesep != # '\r\n' as in Windows), a warning is issued below if this file # is processed. if filename == '-': lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n') else: lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') carriage_return_found = False # Remove trailing '\r'. for linenum in range(len(lines)): if lines[linenum].endswith('\r'): lines[linenum] = lines[linenum].rstrip('\r') carriage_return_found = True except IOError: sys.stderr.write( "Skipping input '%s': Can't open for reading\n" % filename) return # Note, if no dot is found, this will give the entire filename as the ext. file_extension = filename[filename.rfind('.') + 1:] # When reading from stdin, the extension is unknown, so no cpplint tests # should rely on the extension. if (filename != '-' and file_extension != 'cc' and file_extension != 'h' and file_extension != 'cpp'): sys.stderr.write('Ignoring %s; not a .cc or .h file\n' % filename) else: ProcessFileData(filename, file_extension, lines, Error, extra_check_functions) if carriage_return_found and os.linesep != '\r\n': # Use 0 for linenum since outputting only one error for potentially # several lines. Error(filename, 0, 'whitespace/newline', 1, 'One or more unexpected \\r (^M) found;' 'better to use only a \\n') sys.stderr.write('Done processing %s\n' % filename) def PrintUsage(message): """Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message. """ sys.stderr.write(_USAGE) if message: sys.exit('\nFATAL ERROR: ' + message) else: sys.exit(1) def PrintCategories(): """Prints a list of all the error-categories used by error messages. These are the categories used to filter messages via --filter. """ sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) sys.exit(0) def ParseArguments(args): """Parses the command line arguments. This may set the output format and verbosity level as side-effects. Args: args: The command line arguments: Returns: The list of filenames to lint. """ try: (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', 'counting=', 'filter=', 'root=']) except getopt.GetoptError: PrintUsage('Invalid arguments.') verbosity = _VerboseLevel() output_format = _OutputFormat() filters = '' counting_style = '' for (opt, val) in opts: if opt == '--help': PrintUsage(None) elif opt == '--output': if not val in ('emacs', 'vs7', 'eclipse'): PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.') output_format = val elif opt == '--verbose': verbosity = int(val) elif opt == '--filter': filters = val if not filters: PrintCategories() elif opt == '--counting': if val not in ('total', 'toplevel', 'detailed'): PrintUsage('Valid counting options are total, toplevel, and detailed') counting_style = val elif opt == '--root': global _root _root = val if not filenames: PrintUsage('No files were specified.') _SetOutputFormat(output_format) _SetVerboseLevel(verbosity) _SetFilters(filters) _SetCountingStyle(counting_style) return filenames def main(): filenames = ParseArguments(sys.argv[1:]) # Change stderr to write with replacement characters so we don't die # if we try to print something containing non-ASCII characters. sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') _cpplint_state.ResetErrorCounts() for filename in filenames: ProcessFile(filename, _cpplint_state.verbose_level) _cpplint_state.PrintErrorCounts() sys.exit(_cpplint_state.error_count > 0) if __name__ == '__main__': main()
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
include/enet-plus/base/macros.h
C/C++ Header
// Copyright (c) 2013 Andrey Konovalov #ifndef ENET_PLUS_BASE_MACROS_HPP_ #define ENET_PLUS_BASE_MACROS_HPP_ #include <cstdio> #include <cstdlib> // The CHECK() macro is used for checking assertions, and will cause // an immediate crash if its assertion is not met. DCHECK() is like // CHECK() but is only compiled in on debug builds. #ifndef CHECK #define CHECK(x) \ do { \ if (!(x)) { \ fprintf(stderr, "Assertion failed: %s, file %s, line %u\n", \ #x, __FILE__, __LINE__); \ abort(); \ } \ } while (0) #endif #ifndef DCHECK #ifdef NDEBUG #define DCHECK(x) #else #define DCHECK(x) CHECK(x) #endif #endif // The SCHECK() macro is used for checking compile-time assertions, // and will cause a compilation error if its assertion is not met. #ifndef SCHECK template<bool x> struct __SCHECK_F; template< > struct __SCHECK_F <true> {}; template<int x> struct __SCHECK_P {}; #define SCHECK(B) \ typedef __SCHECK_P<sizeof(__SCHECK_F<((B)? true : false)>)> \ __SCHECK_ASSERT##__LINE__ #endif // A macro to disallow the copy constructor and operator= functions. // This should be used in the private: declarations for a class. #ifndef DISALLOW_COPY_AND_ASSIGN #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) #endif // A macro to disallow all the implicit constructors, namely the // default constructor, copy constructor and operator= functions. // // This should be used in the private: declarations for a class // that wants to prevent anyone from instantiating it. This is // especially useful for classes containing only static methods. #ifndef DISALLOW_IMPLICIT_CONSTRUCTORS #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ TypeName(); \ DISALLOW_COPY_AND_ASSIGN(TypeName) #endif #endif // ENET_PLUS_BASE_MACROS_HPP_
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
include/enet-plus/base/pstdint.h
C/C++ Header
// Copyright (c) 2013 Andrey Konovalov #ifndef ENET_PLUS_BASE_PSTDINT_HPP_ #define ENET_PLUS_BASE_PSTDINT_HPP_ #include "enet-plus/base/macros.h" #define __STDC_LIMIT_MACROS #include <stdint.h> typedef float float32_t; typedef double float64_t; SCHECK(sizeof(uint8_t) == 1); SCHECK(sizeof(uint16_t) == 2); SCHECK(sizeof(uint32_t) == 4); SCHECK(sizeof(uint64_t) == 8); SCHECK(sizeof(int8_t) == 1); SCHECK(sizeof(int16_t) == 2); SCHECK(sizeof(int32_t) == 4); SCHECK(sizeof(int64_t) == 8); SCHECK(sizeof(float32_t) == 4); SCHECK(sizeof(float64_t) == 8); // Unicode character. typedef uint32_t uchar_t; #endif // ENET_PLUS_BASE_PSTDINT_HPP_
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
include/enet-plus/client_host.h
C/C++ Header
// Copyright (c) 2013 Andrey Konovalov #ifndef ENET_PLUS_CLIENT_HOST_HPP_ #define ENET_PLUS_CLIENT_HOST_HPP_ #include <string> #include "enet-plus/base/macros.h" #include "enet-plus/base/pstdint.h" #include "enet-plus/host.h" #include "enet-plus/dll.h" struct _ENetHost; namespace enet { class Enet; class Event; class Peer; // A client host for communicating with a server host. // You can create a 'ClientHost' using 'Enet::CreateClientHost'. class ClientHost : public Host { friend class Enet; public: ENET_PLUS_DECL ~ClientHost(); // Initializes 'ClientHost'. // You may specify 'channel_count' - number of channels to be used. // You may specify incoming and outgoing bandwidth of the server in bytes // per second. Specifying '0' for these two options will cause ENet to rely // entirely upon its dynamic throttling algorithm to manage bandwidth. ENET_PLUS_DECL bool Initialize( size_t channel_count = 1, uint32_t incoming_bandwidth = 0, uint32_t outgoing_bandwidth = 0); // Cleans up. Automatically called in the destructor. ENET_PLUS_DECL void Finalize(); // Initiates connection procedure to another host. To complete connection, an // event 'EVENT_CONNECT' should be dispatched using 'ClientHost::Service()'. // You may specify 'channel_count' - number of channels to be used. // Returns 'Peer' on success, returns 'NULL' on error. // Returned 'Peer' will be deallocated automatically. ENET_PLUS_DECL Peer* Connect( std::string server_ip, uint16_t port, size_t channel_count = 1); // Look in 'host.hpp' for the description. // ENET_PLUS_DECL virtual bool Service(Event* event, uint32_t timeout); // Look in 'host.hpp' for the description. // ENET_PLUS_DECL virtual void Flush(); private: // Creates an uninitialized 'ClientHost'. ClientHost(); enum { STATE_FINALIZED, STATE_INITIALIZED, } _state; DISALLOW_COPY_AND_ASSIGN(ClientHost); }; } // namespace enet #endif // ENET_PLUS_CLIENT_HOST_HPP_
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
include/enet-plus/dll.h
C/C++ Header
// Copyright (c) 2013 Andrey Konovalov #ifndef ENET_PLUS_DLL_HPP_ #define ENET_PLUS_DLL_HPP_ #ifdef _MSC_VER #ifdef ENET_PLUS_DLL #define ENET_PLUS_DECL __declspec(dllexport) #else #define ENET_PLUS_DECL __declspec(dllimport) #endif #else #define ENET_PLUS_DECL #endif #endif // ENET_PLUS_DLL_HPP_
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
include/enet-plus/enet.h
C/C++ Header
// Copyright (c) 2013 Andrey Konovalov #ifndef ENET_PLUS_ENET_HPP_ #define ENET_PLUS_ENET_HPP_ #include "enet-plus/base/macros.h" #include "enet-plus/base/pstdint.h" #include "enet-plus/host.h" #include "enet-plus/server_host.h" #include "enet-plus/client_host.h" #include "enet-plus/event.h" #include "enet-plus/peer.h" #include "enet-plus/dll.h" namespace enet { // You need to create and 'Initialize()' a 'Enet' instance to work with ENet. class Enet { public: ENET_PLUS_DECL Enet(); ENET_PLUS_DECL ~Enet(); // Initializes ENet. // Returns 'true' on success, returns 'false' on error. ENET_PLUS_DECL bool Initialize(); // Cleans up. // Automatically called in the destructor. ENET_PLUS_DECL void Finalize(); // Creates 'ServerHost' bound to 'port'. // You may specify 'channel_count' - number of channels to be used. // You may specify incoming and outgoing bandwidth of the server in bytes // per second. Specifying '0' for these two options will cause ENet to rely // entirely upon its dynamic throttling algorithm to manage bandwidth. // Returned 'ServerHost' should be deallocated manually using 'delete'. // Returns 'NULL' on error. ENET_PLUS_DECL ServerHost* CreateServerHost( uint16_t port, size_t peer_count = 32, size_t channel_count = 1, uint32_t incoming_bandwith = 0, uint32_t outgoing_bandwith = 0); // Creates 'ClientHost'. // You may specify 'channel_count' - number of channels to be used. // You may specify incoming and outgoing bandwidth of the server in bytes // per second. Specifying '0' for these two options will cause ENet to rely // entirely upon its dynamic throttling algorithm to manage bandwidth. // Returned 'ClientHost' should be deallocated manually using 'delete'. // Returns 'NULL' on error. ENET_PLUS_DECL ClientHost* CreateClientHost( size_t channel_count = 1, uint32_t incoming_bandwith = 0, uint32_t outgoing_bandwith = 0); // Creates an empty Event. // Returned 'Event' should be deallocated manually using 'delete'. ENET_PLUS_DECL Event* CreateEvent(); private: enum { STATE_FINALIZED, STATE_INITIALIZED, } _state; DISALLOW_COPY_AND_ASSIGN(Enet); }; } // namespace enet #endif // ENET_PLUS_ENET_HPP_
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
include/enet-plus/event.h
C/C++ Header
// Copyright (c) 2013 Andrey Konovalov #ifndef ENET_PLUS_EVENT_HPP_ #define ENET_PLUS_EVENT_HPP_ #include <string> #include <vector> #include "enet-plus/base/macros.h" #include "enet-plus/base/pstdint.h" #include "enet-plus/dll.h" struct _ENetEvent; namespace enet { class Enet; class Host; class Peer; // 'Event' class represents an event that can be delivered by // 'ClientHost::Service()' and 'ServerHost::Service()' methods. // You can create an empty 'Event' by using 'Enet::CreateEvent()'. class Event { friend class Host; friend class Enet; public: enum EventType { // No event occurred within the specified time limit. TYPE_NONE, // A connection request initiated by 'ClientHost::Connect()' has completed. // You can use 'GetPeer()' to get information about the connected peer. TYPE_CONNECT, // A peer has disconnected. This event is generated on a successful // completion of a disconnect initiated by 'Peer::Disconnect()'. // You can use 'GetPeer()' to get information about the disconnected peer. TYPE_DISCONNECT, // A packet has been received from a peer. You can use 'GetPeer()' to get // information about peer which sent the packet, 'GetChannelId()' to get // the channel number upon which the packet was received, 'GetData()' to // get the data from the received packet. TYPE_RECEIVE }; ENET_PLUS_DECL ~Event(); // Returns the type of the event. ENET_PLUS_DECL EventType GetType() const; // Returns the channel on which the received packet was sent. // Event type should not be 'TYPE_NONE' to use this method. ENET_PLUS_DECL uint8_t GetChannelId() const; // Returns the data associated with the event. Data will be lost if // another event is delivered using 'ClientHost::Service()' or // 'ServerHost::Service()' using this instance of 'Event' class. // Event type should be 'TYPE_RECEIVE' to use this method. ENET_PLUS_DECL void GetData(std::vector<char>* output) const; // Returns 'Peer', which caused the event. Returned 'Peer' will be // deallocated automatically. // Event type should not be 'TYPE_NONE' to use this method. ENET_PLUS_DECL Peer* GetPeer(); private: // Creates an uninitialized 'Event'. Don't use it yourself. // You can create an 'Event' by using 'Enet::CreateEvent()'. Event(); // Destroys the packet that is hold by '_event'. If it hasn't been // received yet or has been destroyed already - nothing happens. void _DestroyPacket(); _ENetEvent* _event; // 'False' if a packet received using 'ClientHost::Service()' or // 'ServerHost::Service()' hasn't been deallocated yet. bool _is_packet_destroyed; // 'Host' that generated the event. Host* _host; DISALLOW_COPY_AND_ASSIGN(Event); }; } // namespace enet #endif // ENET_PLUS_EVENT_HPP_
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
include/enet-plus/host.h
C/C++ Header
// Copyright (c) 2013 Andrey Konovalov #ifndef ENET_PLUS_HOST_HPP_ #define ENET_PLUS_HOST_HPP_ #include <map> #include <string> #include "enet-plus/base/macros.h" #include "enet-plus/base/pstdint.h" #include "enet-plus/dll.h" struct _ENetHost; struct _ENetPeer; namespace enet { class Enet; class Event; class Peer; // Internally used class. Use 'ServerHost' and 'ClientHost' instead. class Host { friend class Event; public: ENET_PLUS_DECL virtual ~Host(); // Initializes 'Host'. // 'ip' and 'port' are the address at which other peers may connect to this // host. If 'ip' is an empty string and 'port' is '0', then no peers may // connect to the host. // 'peer_count' is the maximum number of peers that should be allocated for // the host. 'channel_count' is the maximum number of channels allowed. If // '0', then this is equivalent to 'ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT'. // 'incoming_bandwidth' and 'outgoing_bandwidth' are incoming and outgoing // bandwidth of the server in bytes per second. Specifying '0' for these two // options will cause ENet to rely entirely upon its dynamic throttling // algorithm to manage bandwidth. ENET_PLUS_DECL bool Initialize( const std::string& ip, uint16_t port, size_t peer_count, size_t channel_count, uint32_t incoming_bandwidth, uint32_t outgoing_bandwidth); // Cleans up. Automatically called in the destructor. ENET_PLUS_DECL void Finalize(); // Checks for events with a timeout. Should be called to send all queued // with 'Peer::Send()' packets. 'event' is an 'Event' class where event // details will be placed if one occurs. // If a timeout of '0' is specified, 'Service()' will return immediately // if there are no events to dispatch. If 'event' is 'NULL' then no events // will be delivered. // An 'Event' with type 'EVENT_NONE' will be placed in 'event' if no event // occured within the specified time limit. // Returns 'true' on success, returns 'false' on error. ENET_PLUS_DECL virtual bool Service(Event* event, uint32_t timeout); // This function need only be used in circumstances where one wishes to send // queued packets earlier than in a call to 'Service()'. ENET_PLUS_DECL virtual void Flush(); protected: // Creates an uninitialized 'Host'. Host(); // Returns 'Peer' associated with ENet's peer 'enet_peer'. Peer* _GetPeer(_ENetPeer* enet_peer); enum { STATE_FINALIZED, STATE_INITIALIZED } _state; _ENetHost* _host; std::map<_ENetPeer*, Peer*> _peers; private: DISALLOW_COPY_AND_ASSIGN(Host); }; } // namespace enet #endif // ENET_PLUS_HOST_HPP_
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
include/enet-plus/peer.h
C/C++ Header
// Copyright (c) 2013 Andrey Konovalov #ifndef ENET_PLUS_PEER_HPP_ #define ENET_PLUS_PEER_HPP_ #include <string> #include "enet-plus/base/macros.h" #include "enet-plus/base/pstdint.h" #include "enet-plus/dll.h" struct _ENetPeer; namespace enet { class Enet; class ClientHost; // 'Peer' represents a remote transmission point which data packets // may be sent or received from. class Peer { friend class Event; friend class Host; public: // Queues a packet to be sent. 'data' is the allocated data for the packet. // 'length' is the length of the data. 'reliable' is the reliability flag. // 'channel_id' is the id of the channel the packet will be sent through. // The packet will be sent after calling 'ServerHost::Service()' or // 'ClientHost::Service()' methods. // Returns 'true' on success, returns 'false' on error. ENET_PLUS_DECL bool Send( const char* data, size_t length, bool reliable = true, uint8_t channel_id = 0); // Returns the ip of the remote peer. // An empty string will be returned in case of an error. ENET_PLUS_DECL std::string GetIp() const; // Returns the port of the remote peer. ENET_PLUS_DECL uint16_t GetPort() const; // Request a disconnection from a peer. // An 'Event::TYPE_DISCONNECT' event will be generated by // 'ServerHost::Service()' or 'ClientHost::Service()' once // the disconnection is complete. ENET_PLUS_DECL void Disconnect(); // Force an immediate disconnection from a peer. // No 'Event::TYPE_DISCONNECT' event will be generated. The foreign peer // is not guarenteed to receive the disconnect notification, and is reset // immediately upon return from this function. ENET_PLUS_DECL void DisconnectNow(); // Request a disconnection from a peer, but only after all queued outgoing // packets are sent. // An 'Event::TYPE_DISCONNECT' event will be generated by // 'ServerHost::Service()' or 'ClientHost::Service()' once // the disconnection is complete. ENET_PLUS_DECL void DisconnectLater(); // Forcefully disconnects a peer. The foreign host represented by the peer // is not notified of the disconnection and will timeout on its connection // to the local host. ENET_PLUS_DECL void Reset(); // Sets the 'Peer''s internal data, that can be freely modified. // If you have two intances of 'Peer' associated with the same '_peer', both // of them will have the same internal data. ENET_PLUS_DECL void SetData(void* data); // Returns the 'Peer's internal data. ENET_PLUS_DECL void* GetData() const; private: // Creates a 'Peer' associated with the ENet peer 'peer'. explicit Peer(_ENetPeer* peer); _ENetPeer* _peer; DISALLOW_COPY_AND_ASSIGN(Peer); }; } // namespace enet #endif // ENET_PLUS_PEER_HPP_
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov