diff --git a/Cargo.toml b/Cargo.toml index d81b58195..9411533cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ documentation = "https://docs.rs/scrap" keywords = ["screen", "capture", "record"] license = "MIT" authors = ["Ram "] +edition = "2018" [dependencies] block = "0.1" diff --git a/src/common/dxgi.rs b/src/common/dxgi.rs index 12b8f9aa1..f7893fb71 100644 --- a/src/common/dxgi.rs +++ b/src/common/dxgi.rs @@ -1,11 +1,12 @@ -use dxgi; +use crate::dxgi; + +use std::io::ErrorKind::{NotFound, TimedOut, WouldBlock}; use std::{io, ops}; -use std::io::ErrorKind::{WouldBlock, TimedOut, NotFound}; pub struct Capturer { inner: dxgi::Capturer, width: usize, - height: usize + height: usize, } impl Capturer { @@ -13,7 +14,11 @@ impl Capturer { let width = display.width(); let height = display.height(); let inner = dxgi::Capturer::new(&display.0)?; - Ok(Capturer { inner, width, height }) + Ok(Capturer { + inner, + width, + height, + }) } pub fn width(&self) -> usize { @@ -28,10 +33,8 @@ impl Capturer { const MILLISECONDS_PER_FRAME: u32 = 0; match self.inner.frame(MILLISECONDS_PER_FRAME) { Ok(frame) => Ok(Frame(frame)), - Err(ref error) if error.kind() == TimedOut => { - Err(WouldBlock.into()) - }, - Err(error) => Err(error) + Err(ref error) if error.kind() == TimedOut => Err(WouldBlock.into()), + Err(error) => Err(error), } } } @@ -51,14 +54,12 @@ impl Display { pub fn primary() -> io::Result { match dxgi::Displays::new()?.next() { Some(inner) => Ok(Display(inner)), - None => Err(NotFound.into()) + None => Err(NotFound.into()), } } pub fn all() -> io::Result> { - Ok(dxgi::Displays::new()? - .map(Display) - .collect::>()) + Ok(dxgi::Displays::new()?.map(Display).collect::>()) } pub fn width(&self) -> usize { diff --git a/src/common/mod.rs b/src/common/mod.rs index 210793326..cf1ff1bf3 100644 --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -1,4 +1,4 @@ -cfg_if! { +cfg_if::cfg_if! { if #[cfg(quartz)] { mod quartz; pub use self::quartz::*; diff --git a/src/common/quartz.rs b/src/common/quartz.rs index 8a115f831..58e2a2318 100644 --- a/src/common/quartz.rs +++ b/src/common/quartz.rs @@ -1,11 +1,12 @@ -use quartz; -use std::{io, ops, mem}; +use crate::quartz; + use std::marker::PhantomData; use std::sync::{Arc, Mutex, TryLockError}; +use std::{io, mem, ops}; pub struct Capturer { inner: quartz::Capturer, - frame: Arc>> + frame: Arc>>, } impl Capturer { @@ -23,8 +24,9 @@ impl Capturer { if let Ok(mut f) = f.lock() { *f = Some(inner); } - } - ).map_err(|_| io::Error::from(io::ErrorKind::Other))?; + }, + ) + .map_err(|_| io::Error::from(io::ErrorKind::Other))?; Ok(Capturer { inner, frame }) } @@ -44,27 +46,20 @@ impl Capturer { mem::swap(&mut frame, &mut handle); match frame { - Some(frame) => - Ok(Frame(frame, PhantomData)), + Some(frame) => Ok(Frame(frame, PhantomData)), - None => - Err(io::ErrorKind::WouldBlock.into()) + None => Err(io::ErrorKind::WouldBlock.into()), } } - Err(TryLockError::WouldBlock) => - Err(io::ErrorKind::WouldBlock.into()), + Err(TryLockError::WouldBlock) => Err(io::ErrorKind::WouldBlock.into()), - Err(TryLockError::Poisoned(..)) => - Err(io::ErrorKind::Other.into()) + Err(TryLockError::Poisoned(..)) => Err(io::ErrorKind::Other.into()), } } } -pub struct Frame<'a>( - quartz::Frame, - PhantomData<&'a [u8]> -); +pub struct Frame<'a>(quartz::Frame, PhantomData<&'a [u8]>); impl<'a> ops::Deref for Frame<'a> { type Target = [u8]; @@ -81,13 +76,11 @@ impl Display { } pub fn all() -> io::Result> { - Ok( - quartz::Display::online() - .map_err(|_| io::Error::from(io::ErrorKind::Other))? - .into_iter() - .map(Display) - .collect() - ) + Ok(quartz::Display::online() + .map_err(|_| io::Error::from(io::ErrorKind::Other))? + .into_iter() + .map(Display) + .collect()) } pub fn width(&self) -> usize { diff --git a/src/common/x11.rs b/src/common/x11.rs index 342a171cd..4736eee5a 100644 --- a/src/common/x11.rs +++ b/src/common/x11.rs @@ -1,6 +1,7 @@ -use x11; -use std::{io, ops}; +use crate::x11; + use std::rc::Rc; +use std::{io, ops}; pub struct Capturer(x11::Capturer); @@ -37,7 +38,7 @@ impl Display { pub fn primary() -> io::Result { let server = Rc::new(match x11::Server::default() { Ok(server) => server, - Err(_) => return Err(io::ErrorKind::ConnectionRefused.into()) + Err(_) => return Err(io::ErrorKind::ConnectionRefused.into()), }); let mut displays = x11::Server::displays(server); @@ -48,14 +49,14 @@ impl Display { match best { Some(best) => Ok(Display(best)), - None => Err(io::ErrorKind::NotFound.into()) + None => Err(io::ErrorKind::NotFound.into()), } } pub fn all() -> io::Result> { let server = Rc::new(match x11::Server::default() { Ok(server) => server, - Err(_) => return Err(io::ErrorKind::ConnectionRefused.into()) + Err(_) => return Err(io::ErrorKind::ConnectionRefused.into()), }); Ok(x11::Server::displays(server).map(Display).collect()) diff --git a/src/dxgi/ffi.rs b/src/dxgi/ffi.rs index 5bfe317d0..563be1f74 100644 --- a/src/dxgi/ffi.rs +++ b/src/dxgi/ffi.rs @@ -1,15 +1,6 @@ use winapi::{ - GUID, - HRESULT, - REFIID, - IDXGIFactory1, - IDXGIAdapter, - D3D_DRIVER_TYPE, - HMODULE, - UINT, - ID3D11Device, - D3D_FEATURE_LEVEL, - ID3D11DeviceContext + ID3D11Device, ID3D11DeviceContext, IDXGIAdapter, IDXGIFactory1, D3D_DRIVER_TYPE, + D3D_FEATURE_LEVEL, GUID, HMODULE, HRESULT, REFIID, UINT, }; pub const DXGI_MAP_READ: UINT = 1; @@ -18,37 +9,34 @@ pub const IID_IDXGIFACTORY1: GUID = GUID { Data1: 0x770aae78, Data2: 0xf26f, Data3: 0x4dba, - Data4: [0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87] + Data4: [0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87], }; pub const IID_IDXGIOUTPUT1: GUID = GUID { Data1: 0x00cddea8, Data2: 0x939b, Data3: 0x4b83, - Data4: [0xa3, 0x40, 0xa6, 0x85, 0x22, 0x66, 0x66, 0xcc] + Data4: [0xa3, 0x40, 0xa6, 0x85, 0x22, 0x66, 0x66, 0xcc], }; pub const IID_IDXGISURFACE: GUID = GUID { Data1: 3405559148, Data2: 27331, Data3: 18569, - Data4: [191, 71, 158, 35, 187, 210, 96, 236] + Data4: [191, 71, 158, 35, 187, 210, 96, 236], }; pub const IID_ID3D11TEXTURE2D: GUID = GUID { Data1: 1863690994, Data2: 53768, Data3: 20105, - Data4: [154, 180, 72, 149, 53, 211, 79, 156] + Data4: [154, 180, 72, 149, 53, 211, 79, 156], }; -#[link(name="dxgi")] -#[link(name="d3d11")] +#[link(name = "dxgi")] +#[link(name = "d3d11")] extern "system" { - pub fn CreateDXGIFactory1( - id: REFIID, - pp_factory: *mut *mut IDXGIFactory1 - ) -> HRESULT; + pub fn CreateDXGIFactory1(id: REFIID, pp_factory: *mut *mut IDXGIFactory1) -> HRESULT; pub fn D3D11CreateDevice( pAdapter: *mut IDXGIAdapter, @@ -60,6 +48,6 @@ extern "system" { SDKVersion: UINT, ppDevice: *mut *mut ID3D11Device, pFeatureLevel: *mut D3D_FEATURE_LEVEL, - ppImmediateContext: *mut *mut ID3D11DeviceContext + ppImmediateContext: *mut *mut ID3D11DeviceContext, ) -> HRESULT; } diff --git a/src/dxgi/mod.rs b/src/dxgi/mod.rs index b2ad8a116..113a82eeb 100644 --- a/src/dxgi/mod.rs +++ b/src/dxgi/mod.rs @@ -1,37 +1,16 @@ use self::ffi::*; -use std::{io, mem, ptr, slice}; + use winapi::{ - HRESULT, - IDXGIAdapter1, - IDXGIFactory1, - IDXGIOutput1, - S_OK, - UINT, - DXGI_OUTPUT_DESC, - LONG, - DXGI_MODE_ROTATION, - ID3D11Device, - ID3D11DeviceContext, - IDXGIOutputDuplication, - D3D11_SDK_VERSION, - D3D_DRIVER_TYPE_UNKNOWN, - D3D_FEATURE_LEVEL_9_1, - DXGI_ERROR_ACCESS_LOST, - DXGI_ERROR_WAIT_TIMEOUT, - DXGI_ERROR_INVALID_CALL, - E_ACCESSDENIED, - DXGI_ERROR_UNSUPPORTED, - ID3D11Texture2D, - DXGI_ERROR_NOT_CURRENTLY_AVAILABLE, - DXGI_ERROR_SESSION_DISCONNECTED, - TRUE, - IDXGISurface, - IDXGIResource, - DXGI_RESOURCE_PRIORITY_MAXIMUM, - D3D11_CPU_ACCESS_READ, - D3D11_USAGE_STAGING + ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D, IDXGIAdapter1, IDXGIFactory1, IDXGIOutput1, + IDXGIOutputDuplication, IDXGIResource, IDXGISurface, D3D11_CPU_ACCESS_READ, D3D11_SDK_VERSION, + D3D11_USAGE_STAGING, D3D_DRIVER_TYPE_UNKNOWN, D3D_FEATURE_LEVEL_9_1, DXGI_ERROR_ACCESS_LOST, + DXGI_ERROR_INVALID_CALL, DXGI_ERROR_NOT_CURRENTLY_AVAILABLE, DXGI_ERROR_SESSION_DISCONNECTED, + DXGI_ERROR_UNSUPPORTED, DXGI_ERROR_WAIT_TIMEOUT, DXGI_MODE_ROTATION, DXGI_OUTPUT_DESC, + DXGI_RESOURCE_PRIORITY_MAXIMUM, E_ACCESSDENIED, HRESULT, LONG, S_OK, TRUE, UINT, }; +use std::{io, mem, ptr, slice}; + mod ffi; //TODO: Split up into files. @@ -40,8 +19,10 @@ pub struct Capturer { device: *mut ID3D11Device, context: *mut ID3D11DeviceContext, duplication: *mut IDXGIOutputDuplication, - fastlane: bool, surface: *mut IDXGISurface, - data: *mut u8, len: usize, + fastlane: bool, + surface: *mut IDXGISurface, + data: *mut u8, + len: usize, height: usize, } @@ -57,24 +38,22 @@ impl Capturer { &mut **display.adapter, D3D_DRIVER_TYPE_UNKNOWN, ptr::null_mut(), // No software rasterizer. - 0, // No device flags. + 0, // No device flags. ptr::null_mut(), // Feature levels. - 0, // Feature levels' length. + 0, // Feature levels' length. D3D11_SDK_VERSION, &mut device, &mut D3D_FEATURE_LEVEL_9_1, - &mut context + &mut context, ) - } != S_OK { + } != S_OK + { // Unknown error. return Err(io::ErrorKind::Other.into()); } let res = wrap_hresult(unsafe { - (*display.inner).DuplicateOutput( - &mut **device, - &mut duplication - ) + (*display.inner).DuplicateOutput(&mut **device, &mut duplication) }); if let Err(err) = res { @@ -91,12 +70,14 @@ impl Capturer { Ok(unsafe { let mut capturer = Capturer { - device, context, duplication, + device, + context, + duplication, fastlane: desc.DesktopImageInSystemMemory == TRUE, surface: ptr::null_mut(), height: display.height() as usize, data: ptr::null_mut(), - len: 0 + len: 0, }; let _ = capturer.load_frame(0); capturer @@ -108,17 +89,11 @@ impl Capturer { let mut info = mem::uninitialized(); self.data = ptr::null_mut(); - wrap_hresult((*self.duplication).AcquireNextFrame( - timeout, - &mut info, - &mut frame - ))?; + wrap_hresult((*self.duplication).AcquireNextFrame(timeout, &mut info, &mut frame))?; if self.fastlane { let mut rect = mem::uninitialized(); - let res = wrap_hresult( - (*self.duplication).MapDesktopSurface(&mut rect) - ); + let res = wrap_hresult((*self.duplication).MapDesktopSurface(&mut rect)); (*frame).Release(); @@ -134,10 +109,7 @@ impl Capturer { self.surface = self.ohgodwhat(frame)?; let mut rect = mem::uninitialized(); - wrap_hresult((*self.surface).Map( - &mut rect, - DXGI_MAP_READ - ))?; + wrap_hresult((*self.surface).Map(&mut rect, DXGI_MAP_READ))?; self.data = rect.pBits; self.len = self.height * rect.Pitch as usize; @@ -145,14 +117,11 @@ impl Capturer { } } - unsafe fn ohgodwhat( - &mut self, - frame: *mut IDXGIResource - ) -> io::Result<*mut IDXGISurface> { + unsafe fn ohgodwhat(&mut self, frame: *mut IDXGIResource) -> io::Result<*mut IDXGISurface> { let mut texture: *mut ID3D11Texture2D = ptr::null_mut(); (*frame).QueryInterface( &IID_ID3D11TEXTURE2D, - &mut texture as *mut *mut _ as *mut *mut _ + &mut texture as *mut *mut _ as *mut *mut _, ); let mut texture_desc = mem::uninitialized(); @@ -167,7 +136,7 @@ impl Capturer { let res = wrap_hresult((*self.device).CreateTexture2D( &mut texture_desc, ptr::null(), - &mut readable + &mut readable, )); if let Err(err) = res { @@ -181,13 +150,10 @@ impl Capturer { let mut surface = ptr::null_mut(); (*readable).QueryInterface( &IID_IDXGISURFACE, - &mut surface as *mut *mut _ as *mut *mut _ + &mut surface as *mut *mut _ as *mut *mut _, ); - (*self.context).CopyResource( - &mut **readable, - &mut **texture - ); + (*self.context).CopyResource(&mut **readable, &mut **texture); (*frame).Release(); (*texture).Release(); @@ -242,15 +208,13 @@ pub struct Displays { /// Index of the CURRENT adapter. nadapter: UINT, /// Index of the NEXT display to fetch. - ndisplay: UINT + ndisplay: UINT, } impl Displays { pub fn new() -> io::Result { let mut factory = ptr::null_mut(); - wrap_hresult(unsafe { - CreateDXGIFactory1(&IID_IDXGIFACTORY1, &mut factory) - })?; + wrap_hresult(unsafe { CreateDXGIFactory1(&IID_IDXGIFACTORY1, &mut factory) })?; let mut adapter = ptr::null_mut(); unsafe { @@ -262,7 +226,7 @@ impl Displays { factory, adapter, nadapter: 0, - ndisplay: 0 + ndisplay: 0, }) } @@ -311,10 +275,7 @@ impl Displays { let mut inner = ptr::null_mut(); unsafe { - (*output).QueryInterface( - &IID_IDXGIOUTPUT1, - &mut inner as *mut *mut _ as *mut *mut _ - ); + (*output).QueryInterface(&IID_IDXGIOUTPUT1, &mut inner as *mut *mut _ as *mut *mut _); (*output).Release(); } @@ -333,7 +294,11 @@ impl Displays { (*self.adapter).AddRef(); } - Some(Some(Display { inner, adapter: self.adapter, desc })) + Some(Some(Display { + inner, + adapter: self.adapter, + desc, + })) } } @@ -350,10 +315,7 @@ impl Iterator for Displays { self.adapter = unsafe { let mut adapter = ptr::null_mut(); - (*self.factory).EnumAdapters1( - self.nadapter, - &mut adapter - ); + (*self.factory).EnumAdapters1(self.nadapter, &mut adapter); adapter }; @@ -381,18 +343,16 @@ impl Drop for Displays { pub struct Display { inner: *mut IDXGIOutput1, adapter: *mut IDXGIAdapter1, - desc: DXGI_OUTPUT_DESC + desc: DXGI_OUTPUT_DESC, } impl Display { pub fn width(&self) -> LONG { - self.desc.DesktopCoordinates.right - - self.desc.DesktopCoordinates.left + self.desc.DesktopCoordinates.right - self.desc.DesktopCoordinates.left } pub fn height(&self) -> LONG { - self.desc.DesktopCoordinates.bottom - - self.desc.DesktopCoordinates.top + self.desc.DesktopCoordinates.bottom - self.desc.DesktopCoordinates.top } pub fn rotation(&self) -> DXGI_MODE_ROTATION { @@ -401,9 +361,7 @@ impl Display { pub fn name(&self) -> &[u16] { let s = &self.desc.DeviceName; - let i = s.iter() - .position(|&x| x == 0) - .unwrap_or(s.len()); + let i = s.iter().position(|&x| x == 0).unwrap_or(s.len()); &s[..i] } } @@ -428,6 +386,7 @@ fn wrap_hresult(x: HRESULT) -> io::Result<()> { DXGI_ERROR_UNSUPPORTED => ConnectionRefused, DXGI_ERROR_NOT_CURRENTLY_AVAILABLE => Interrupted, DXGI_ERROR_SESSION_DISCONNECTED => ConnectionAborted, - _ => Other - }).into()) + _ => Other, + }) + .into()) } diff --git a/src/lib.rs b/src/lib.rs index a81852638..7d73e29c4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,14 +1,15 @@ -#[macro_use] -extern crate cfg_if; -extern crate libc; - -#[cfg(quartz)] extern crate block; -#[cfg(quartz)] pub mod quartz; - -#[cfg(x11)] pub mod x11; - -#[cfg(dxgi)] extern crate winapi; -#[cfg(dxgi)] pub mod dxgi; +#[cfg(quartz)] +use block; +#[cfg(quartz)] +pub mod quartz; + +#[cfg(x11)] +pub mod x11; + +#[cfg(dxgi)] +use winapi; +#[cfg(dxgi)] +pub mod dxgi; mod common; pub use common::*; diff --git a/src/quartz/capturer.rs b/src/quartz/capturer.rs index 61330b9c1..992ce0c3b 100644 --- a/src/quartz/capturer.rs +++ b/src/quartz/capturer.rs @@ -1,9 +1,11 @@ -use block::{Block, ConcreteBlock}; -use libc::c_void; -use super::ffi::*; use super::config::Config; use super::display::Display; +use super::ffi::*; use super::frame::Frame; + +use block::{Block, ConcreteBlock}; +use libc::c_void; + use std::ptr; pub struct Capturer { @@ -13,7 +15,7 @@ pub struct Capturer { width: usize, height: usize, format: PixelFormat, - display: Display + display: Display, } impl Capturer { @@ -23,20 +25,20 @@ impl Capturer { height: usize, format: PixelFormat, config: Config, - handler: F + handler: F, ) -> Result { - let handler: FrameAvailableHandler = - ConcreteBlock::new(move |status, _, surface, _| { - use self::CGDisplayStreamFrameStatus::*; - if status == FrameComplete { - handler(unsafe { Frame::new(surface) }); - } - }).copy(); + let handler: FrameAvailableHandler = ConcreteBlock::new(move |status, _, surface, _| { + use self::CGDisplayStreamFrameStatus::*; + if status == FrameComplete { + handler(unsafe { Frame::new(surface) }); + } + }) + .copy(); let queue = unsafe { dispatch_queue_create( b"quadrupleslap.scrap\0".as_ptr() as *const i8, - ptr::null_mut() + ptr::null_mut(), ) }; @@ -49,7 +51,7 @@ impl Capturer { format, config, queue, - &*handler as *const Block<_, _> as *const c_void + &*handler as *const Block<_, _> as *const c_void, ); CFRelease(config); stream @@ -57,16 +59,29 @@ impl Capturer { match unsafe { CGDisplayStreamStart(stream) } { CGError::Success => Ok(Capturer { - stream, queue, width, height, format, display + stream, + queue, + width, + height, + format, + display, }), - x => Err(x) + x => Err(x), } } - pub fn width(&self) -> usize { self.width } - pub fn height(&self) -> usize { self.height } - pub fn format(&self) -> PixelFormat { self.format } - pub fn display(&self) -> Display { self.display } + pub fn width(&self) -> usize { + self.width + } + pub fn height(&self) -> usize { + self.height + } + pub fn format(&self) -> PixelFormat { + self.format + } + pub fn display(&self) -> Display { + self.display + } } impl Drop for Capturer { diff --git a/src/quartz/config.rs b/src/quartz/config.rs index 3ffea14a0..9d49a9911 100644 --- a/src/quartz/config.rs +++ b/src/quartz/config.rs @@ -1,5 +1,7 @@ use super::ffi::*; + use libc::c_void; + use std::ptr; //TODO: Color space, YCbCr matrix. @@ -13,7 +15,7 @@ pub struct Config { /// How many frames are allocated. /// 3 is the recommended value. /// 8 is the maximum value. - pub queue_length: i8 + pub queue_length: i8, } impl Config { @@ -23,25 +25,25 @@ impl Config { let throttle = CFNumberCreate( ptr::null_mut(), CFNumberType::Float64, - &self.throttle as *const _ as *const c_void + &self.throttle as *const _ as *const c_void, ); let queue_length = CFNumberCreate( ptr::null_mut(), CFNumberType::SInt8, - &self.queue_length as *const _ as *const c_void + &self.queue_length as *const _ as *const c_void, ); let keys: [CFStringRef; 4] = [ kCGDisplayStreamShowCursor, kCGDisplayStreamPreserveAspectRatio, kCGDisplayStreamMinimumFrameTime, - kCGDisplayStreamQueueDepth + kCGDisplayStreamQueueDepth, ]; let values: [*mut c_void; 4] = [ cfbool(self.cursor), cfbool(self.letterbox), throttle, - queue_length + queue_length, ]; let res = CFDictionaryCreate( @@ -50,7 +52,7 @@ impl Config { values.as_ptr(), 4, &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks + &kCFTypeDictionaryValueCallBacks, ); CFRelease(throttle); @@ -67,7 +69,7 @@ impl Default for Config { cursor: false, letterbox: true, throttle: 0.0, - queue_length: 3 + queue_length: 3, } } } diff --git a/src/quartz/display.rs b/src/quartz/display.rs index 5944f5a94..91675bad0 100644 --- a/src/quartz/display.rs +++ b/src/quartz/display.rs @@ -1,4 +1,5 @@ use super::ffi::*; + use std::mem; #[derive(PartialEq, Eq, Debug, Clone, Copy)] @@ -17,7 +18,7 @@ impl Display { match CGGetOnlineDisplayList(16, arr.as_mut_ptr(), &mut len) { CGError::Success => (), - x => return Err(x) + x => return Err(x), } let mut res = Vec::with_capacity(16); diff --git a/src/quartz/ffi.rs b/src/quartz/ffi.rs index 7653fec39..cc5be2c09 100644 --- a/src/quartz/ffi.rs +++ b/src/quartz/ffi.rs @@ -17,30 +17,31 @@ pub type CFAllocatorRef = *mut c_void; #[repr(C)] pub struct CFDictionaryKeyCallBacks { callbacks: [usize; 5], - version: i32 + version: i32, } #[repr(C)] pub struct CFDictionaryValueCallBacks { callbacks: [usize; 4], - version: i32 + version: i32, } macro_rules! pixel_format { ($a:expr, $b:expr, $c:expr, $d:expr) => { - ($a as i32) << 24 - | ($b as i32) << 16 - | ($c as i32) << 8 - | ($d as i32) - } + ($a as i32) << 24 | ($b as i32) << 16 | ($c as i32) << 8 | ($d as i32) + }; } -pub const SURFACE_LOCK_READ_ONLY: u32 = 0x0000_0001; +pub const SURFACE_LOCK_READ_ONLY: u32 = 0x0000_0001; pub const SURFACE_LOCK_AVOID_SYNC: u32 = 0x0000_0002; pub fn cfbool(x: bool) -> CFBooleanRef { unsafe { - if x { kCFBooleanTrue } else { kCFBooleanFalse } + if x { + kCFBooleanTrue + } else { + kCFBooleanFalse + } } } @@ -56,7 +57,7 @@ pub enum CGDisplayStreamFrameStatus { /// The display stream was stopped. Stopped = 3, #[doc(hidden)] - __Nonexhaustive + __Nonexhaustive, } #[repr(i32)] @@ -68,7 +69,7 @@ pub enum CFNumberType { SInt32 = 3, SInt64 = 4, Float32 = 5, - Float64 = 6, /* 64-bit IEEE 754 */ + Float64 = 6, /* 64-bit IEEE 754 */ /* Basic C types */ Char = 7, Short = 8, @@ -80,7 +81,7 @@ pub enum CFNumberType { /* Other */ CFIndex = 14, NSInteger = 15, - CGFloat = 16 + CGFloat = 16, } #[repr(i32)] @@ -99,38 +100,41 @@ pub enum CGError { InvalidOperation = 1010, NoneAvailable = 1011, #[doc(hidden)] - __Nonexhaustive + __Nonexhaustive, } #[repr(i32)] #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enum PixelFormat { /// Packed Little Endian ARGB8888 - Argb8888 = pixel_format!('B','G','R','A'), + Argb8888 = pixel_format!('B', 'G', 'R', 'A'), /// Packed Little Endian ARGB2101010 - Argb2101010 = pixel_format!('l','1','0','r'), + Argb2101010 = pixel_format!('l', '1', '0', 'r'), /// 2-plane "video" range YCbCr 4:2:0 - YCbCr420Video = pixel_format!('4','2','0','v'), + YCbCr420Video = pixel_format!('4', '2', '0', 'v'), /// 2-plane "full" range YCbCr 4:2:0 - YCbCr420Full = pixel_format!('4','2','0','f'), + YCbCr420Full = pixel_format!('4', '2', '0', 'f'), #[doc(hidden)] - __Nonexhaustive + __Nonexhaustive, } pub type CGDisplayStreamFrameAvailableHandler = *const c_void; -pub type FrameAvailableHandler = RcBlock<( - CGDisplayStreamFrameStatus, // status - u64, // displayTime - IOSurfaceRef, // frameSurface - CGDisplayStreamUpdateRef // updateRef -), ()>; - -#[link(name="System", kind="dylib")] -#[link(name="CoreGraphics", kind="framework")] -#[link(name="CoreFoundation", kind="framework")] -#[link(name="IOSurface", kind="framework")] -extern { +pub type FrameAvailableHandler = RcBlock< + ( + CGDisplayStreamFrameStatus, // status + u64, // displayTime + IOSurfaceRef, // frameSurface + CGDisplayStreamUpdateRef, // updateRef + ), + (), +>; + +#[link(name = "System", kind = "dylib")] +#[link(name = "CoreGraphics", kind = "framework")] +#[link(name = "CoreFoundation", kind = "framework")] +#[link(name = "IOSurface", kind = "framework")] +extern "C" { // CoreGraphics pub static kCGDisplayStreamShowCursor: CFStringRef; @@ -145,16 +149,12 @@ extern { pixel_format: PixelFormat, properties: CFDictionaryRef, queue: DispatchQueue, - handler: CGDisplayStreamFrameAvailableHandler + handler: CGDisplayStreamFrameAvailableHandler, ) -> CGDisplayStreamRef; - pub fn CGDisplayStreamStart( - displayStream: CGDisplayStreamRef - ) -> CGError; + pub fn CGDisplayStreamStart(displayStream: CGDisplayStreamRef) -> CGError; - pub fn CGDisplayStreamStop( - displayStream: CGDisplayStreamRef - ) -> CGError; + pub fn CGDisplayStreamStop(displayStream: CGDisplayStreamRef) -> CGError; pub fn CGMainDisplayID() -> u32; pub fn CGDisplayPixelsWide(display: u32) -> usize; @@ -163,7 +163,7 @@ extern { pub fn CGGetOnlineDisplayList( max_displays: u32, online_displays: *mut u32, - display_count: *mut u32 + display_count: *mut u32, ) -> CGError; pub fn CGDisplayIsBuiltin(display: u32) -> i32; @@ -177,27 +177,14 @@ extern { pub fn IOSurfaceGetBaseAddress(buffer: IOSurfaceRef) -> *mut c_void; pub fn IOSurfaceIncrementUseCount(buffer: IOSurfaceRef); pub fn IOSurfaceDecrementUseCount(buffer: IOSurfaceRef); - pub fn IOSurfaceLock( - buffer: IOSurfaceRef, - options: u32, - seed: *mut u32 - ) -> i32; - pub fn IOSurfaceUnlock( - buffer: IOSurfaceRef, - options: u32, - seed: *mut u32 - ) -> i32; + pub fn IOSurfaceLock(buffer: IOSurfaceRef, options: u32, seed: *mut u32) -> i32; + pub fn IOSurfaceUnlock(buffer: IOSurfaceRef, options: u32, seed: *mut u32) -> i32; // Dispatch - pub fn dispatch_queue_create( - label: *const i8, - attr: DispatchQueueAttr - ) -> DispatchQueue; + pub fn dispatch_queue_create(label: *const i8, attr: DispatchQueueAttr) -> DispatchQueue; - pub fn dispatch_release( - object: DispatchQueue - ); + pub fn dispatch_release(object: DispatchQueue); // Core Foundation @@ -211,7 +198,7 @@ extern { pub fn CFNumberCreate( allocator: CFAllocatorRef, theType: CFNumberType, - valuePtr: *const c_void + valuePtr: *const c_void, ) -> CFNumberRef; pub fn CFDictionaryCreate( @@ -220,7 +207,7 @@ extern { values: *const *mut c_void, numValues: i64, keyCallBacks: *const CFDictionaryKeyCallBacks, - valueCallBacks: *const CFDictionaryValueCallBacks + valueCallBacks: *const CFDictionaryValueCallBacks, ) -> CFDictionaryRef; pub fn CFRetain(cf: *const c_void); diff --git a/src/quartz/frame.rs b/src/quartz/frame.rs index 3b6b0496d..8d53b073e 100644 --- a/src/quartz/frame.rs +++ b/src/quartz/frame.rs @@ -1,9 +1,10 @@ use super::ffi::*; + use std::{ops, ptr, slice}; pub struct Frame { surface: IOSurfaceRef, - inner: &'static [u8] + inner: &'static [u8], } impl Frame { @@ -11,15 +12,11 @@ impl Frame { CFRetain(surface); IOSurfaceIncrementUseCount(surface); - IOSurfaceLock( - surface, - SURFACE_LOCK_READ_ONLY, - ptr::null_mut() - ); + IOSurfaceLock(surface, SURFACE_LOCK_READ_ONLY, ptr::null_mut()); let inner = slice::from_raw_parts( IOSurfaceGetBaseAddress(surface) as *const u8, - IOSurfaceGetAllocSize(surface) + IOSurfaceGetAllocSize(surface), ); Frame { surface, inner } @@ -36,11 +33,7 @@ impl ops::Deref for Frame { impl Drop for Frame { fn drop(&mut self) { unsafe { - IOSurfaceUnlock( - self.surface, - SURFACE_LOCK_READ_ONLY, - ptr::null_mut() - ); + IOSurfaceUnlock(self.surface, SURFACE_LOCK_READ_ONLY, ptr::null_mut()); IOSurfaceDecrementUseCount(self.surface); CFRelease(self.surface); diff --git a/src/x11/capturer.rs b/src/x11/capturer.rs index 7f3f3ad57..08c34c97d 100644 --- a/src/x11/capturer.rs +++ b/src/x11/capturer.rs @@ -1,7 +1,7 @@ -use libc; -use std::{io, ptr, slice}; -use super::Display; use super::ffi::*; +use super::Display; + +use std::{io, ptr, slice}; pub struct Capturer { display: Display, @@ -11,13 +11,11 @@ pub struct Capturer { request: xcb_shm_get_image_cookie_t, loading: usize, - size: usize + size: usize, } impl Capturer { - pub fn new( - display: Display - ) -> io::Result { + pub fn new(display: Display) -> io::Result { // Calculate dimensions. let pixel_width = 4; @@ -31,7 +29,7 @@ impl Capturer { libc::IPC_PRIVATE, size * 2, // Everyone can do anything. - libc::IPC_CREAT | 0o777 + libc::IPC_CREAT | 0o777, ) }; @@ -41,13 +39,7 @@ impl Capturer { // Attach the segment to a readable address. - let buffer = unsafe { - libc::shmat( - shmid, - ptr::null(), - libc::SHM_RDONLY - ) - } as *mut u8; + let buffer = unsafe { libc::shmat(shmid, ptr::null(), libc::SHM_RDONLY) } as *mut u8; if buffer as isize == -1 { return Err(io::Error::last_os_error()); @@ -62,7 +54,7 @@ impl Capturer { server, xcbid, shmid as u32, - 0 // False, i.e. not read-only. + 0, // False, i.e. not read-only. ); } @@ -72,20 +64,27 @@ impl Capturer { xcb_shm_get_image_unchecked( server, display.root(), - rect.x, rect.y, - rect.w, rect.h, + rect.x, + rect.y, + rect.w, + rect.h, !0, // Plane mask. XCB_IMAGE_FORMAT_Z_PIXMAP, xcbid, - 0 // Byte offset. + 0, // Byte offset. ) }; // Return! Ok(Capturer { - display, shmid, xcbid, buffer, - request, loading: 0, size + display, + shmid, + xcbid, + buffer, + request, + loading: 0, + size, }) } @@ -93,15 +92,11 @@ impl Capturer { &self.display } - pub fn frame<'b>(&'b mut self) -> &'b [u8] { + pub fn frame(&mut self) -> &[u8] { // Get the return value. - let result = unsafe { let off = self.loading & self.size; - slice::from_raw_parts( - self.buffer.offset(off as isize), - self.size - ) + slice::from_raw_parts(self.buffer.add(off), self.size) }; // Block for response. @@ -119,12 +114,14 @@ impl Capturer { xcb_shm_get_image_unchecked( self.display.server().raw(), self.display.root(), - rect.x, rect.y, - rect.w, rect.h, + rect.x, + rect.y, + rect.w, + rect.h, !0, XCB_IMAGE_FORMAT_Z_PIXMAP, self.xcbid, - (self.loading & self.size) as u32 + (self.loading & self.size) as u32, ) }; @@ -134,11 +131,8 @@ impl Capturer { } unsafe fn handle_response(&self) { - let response = xcb_shm_get_image_reply( - self.display.server().raw(), - self.request, - ptr::null_mut() - ); + let response = + xcb_shm_get_image_reply(self.display.server().raw(), self.request, ptr::null_mut()); libc::free(response as *mut _); } diff --git a/src/x11/display.rs b/src/x11/display.rs index e71a6df1f..a98863798 100644 --- a/src/x11/display.rs +++ b/src/x11/display.rs @@ -1,6 +1,7 @@ -use std::rc::Rc; -use super::Server; use super::ffi::*; +use super::Server; + +use std::rc::Rc; #[derive(Debug)] pub struct Display { @@ -19,17 +20,32 @@ pub struct Rect { } impl Display { + /// + /// # Safety pub unsafe fn new( server: Rc, default: bool, rect: Rect, - root: xcb_window_t + root: xcb_window_t, ) -> Display { - Display { server, default, rect, root } + Display { + server, + default, + rect, + root, + } } - pub fn server(&self) -> &Rc { &self.server } - pub fn is_default(&self) -> bool { self.default } - pub fn rect(&self) -> Rect { self.rect } - pub fn root(&self) -> xcb_window_t { self.root } + pub fn server(&self) -> &Rc { + &self.server + } + pub fn is_default(&self) -> bool { + self.default + } + pub fn rect(&self) -> Rect { + self.rect + } + pub fn root(&self) -> xcb_window_t { + self.root + } } diff --git a/src/x11/iter.rs b/src/x11/iter.rs index f705294bd..27a1da2fa 100644 --- a/src/x11/iter.rs +++ b/src/x11/iter.rs @@ -1,8 +1,8 @@ -use libc; +use super::ffi::*; +use super::{Display, Rect, Server}; + use std::ptr; use std::rc::Rc; -use super::{Display, Rect, Server}; -use super::ffi::*; //TODO: Do I have to free the displays? @@ -13,15 +13,21 @@ pub struct DisplayIter { } impl DisplayIter { + /// + /// # Safety pub unsafe fn new(server: Rc) -> DisplayIter { let mut outer = xcb_setup_roots_iterator(server.setup()); let inner = Self::next_screen(&mut outer, &server); - DisplayIter { outer, inner, server } + DisplayIter { + outer, + inner, + server, + } } fn next_screen( outer: &mut xcb_screen_iterator_t, - server: &Server + server: &Server, ) -> Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)> { if outer.rem == 0 { return None; @@ -36,11 +42,7 @@ impl DisplayIter { 1, //TODO: I don't know if this should be true or false. ); - let response = xcb_randr_get_monitors_reply( - server.raw(), - cookie, - ptr::null_mut(), - ); + let response = xcb_randr_get_monitors_reply(server.raw(), cookie, ptr::null_mut()); let inner = xcb_randr_get_monitors_monitors_iterator(response); @@ -59,24 +61,26 @@ impl Iterator for DisplayIter { loop { if let Some((ref mut inner, root)) = self.inner { // If there is something in the current screen, return that. - if inner.rem != 0 {unsafe { - let data = &*inner.data; - - let display = Display::new( - self.server.clone(), - data.primary != 0, - Rect { - x: data.x, - y: data.y, - w: data.width, - h: data.height, - }, - root - ); - - xcb_randr_monitor_info_next(inner); - return Some(display); - }} + if inner.rem != 0 { + unsafe { + let data = &*inner.data; + + let display = Display::new( + self.server.clone(), + data.primary != 0, + Rect { + x: data.x, + y: data.y, + w: data.width, + h: data.height, + }, + root, + ); + + xcb_randr_monitor_info_next(inner); + return Some(display); + } + } } else { // If there is no current screen, the screen iterator is empty. return None; diff --git a/src/x11/server.rs b/src/x11/server.rs index 16461a646..73fc068fe 100644 --- a/src/x11/server.rs +++ b/src/x11/server.rs @@ -1,45 +1,54 @@ +use super::ffi::*; +use super::DisplayIter; + use std::ptr; use std::rc::Rc; -use super::DisplayIter; -use super::ffi::*; #[derive(Debug)] pub struct Server { raw: *mut xcb_connection_t, screenp: i32, - setup: *const xcb_setup_t + setup: *const xcb_setup_t, } impl Server { pub fn displays(slf: Rc) -> DisplayIter { - unsafe { - DisplayIter::new(slf) - } + unsafe { DisplayIter::new(slf) } } pub fn default() -> Result { - Server::connect(ptr::null()) + unsafe { Server::connect(ptr::null()) } } - pub fn connect(addr: *const i8) -> Result { - unsafe { - let mut screenp = 0; - let raw = xcb_connect(addr, &mut screenp); + /// + /// # Safety + pub unsafe fn connect(addr: *const i8) -> Result { + let mut screenp = 0; + let raw = xcb_connect(addr, &mut screenp); - let error = xcb_connection_has_error(raw); - if error != 0 { - xcb_disconnect(raw); - Err(Error::from(error)) - } else { - let setup = xcb_get_setup(raw); - Ok(Server { raw, screenp, setup }) - } + let error = xcb_connection_has_error(raw); + if error != 0 { + xcb_disconnect(raw); + Err(Error::from(error)) + } else { + let setup = xcb_get_setup(raw); + Ok(Server { + raw, + screenp, + setup, + }) } } - pub fn raw(&self) -> *mut xcb_connection_t { self.raw } - pub fn screenp(&self) -> i32 { self.screenp } - pub fn setup(&self) -> *const xcb_setup_t { self.setup } + pub fn raw(&self) -> *mut xcb_connection_t { + self.raw + } + pub fn screenp(&self) -> i32 { + self.screenp + } + pub fn setup(&self) -> *const xcb_setup_t { + self.setup + } } impl Drop for Server { @@ -57,7 +66,7 @@ pub enum Error { InsufficientMemory, RequestTooLong, ParseError, - InvalidScreen + InvalidScreen, } impl From for Error { @@ -69,7 +78,7 @@ impl From for Error { 4 => RequestTooLong, 5 => ParseError, 6 => InvalidScreen, - _ => Generic + _ => Generic, } } }