diff --git a/cocoa-foundation/src/foundation.rs b/cocoa-foundation/src/foundation.rs index b9ca8b02e..be934ae2f 100644 --- a/cocoa-foundation/src/foundation.rs +++ b/cocoa-foundation/src/foundation.rs @@ -9,12 +9,11 @@ #![allow(non_upper_case_globals)] -use std::ptr; -use std::os::raw::c_void; -use base::{id, BOOL, NO, SEL, nil}; +use base::{id, nil, BOOL, NO, SEL}; use block::Block; use libc; - +use std::os::raw::c_void; +use std::ptr; #[cfg(target_pointer_width = "32")] pub type NSInteger = libc::c_int; @@ -33,11 +32,11 @@ const UTF8_ENCODING: usize = 4; #[cfg(target_os = "macos")] mod macos { - use std::mem; use base::id; use core_graphics_types::base::CGFloat; use core_graphics_types::geometry::CGRect; use objc; + use std::mem; #[repr(C)] #[derive(Copy, Clone)] @@ -49,18 +48,17 @@ mod macos { impl NSPoint { #[inline] pub fn new(x: CGFloat, y: CGFloat) -> NSPoint { - NSPoint { - x: x, - y: y, - } + NSPoint { x: x, y: y } } } unsafe impl objc::Encode for NSPoint { fn encode() -> objc::Encoding { - let encoding = format!("{{CGPoint={}{}}}", - CGFloat::encode().as_str(), - CGFloat::encode().as_str()); + let encoding = format!( + "{{CGPoint={}{}}}", + CGFloat::encode().as_str(), + CGFloat::encode().as_str() + ); unsafe { objc::Encoding::from_str(&encoding) } } } @@ -84,9 +82,11 @@ mod macos { unsafe impl objc::Encode for NSSize { fn encode() -> objc::Encoding { - let encoding = format!("{{CGSize={}{}}}", - CGFloat::encode().as_str(), - CGFloat::encode().as_str()); + let encoding = format!( + "{{CGSize={}{}}}", + CGFloat::encode().as_str(), + CGFloat::encode().as_str() + ); unsafe { objc::Encoding::from_str(&encoding) } } } @@ -103,30 +103,28 @@ mod macos { pub fn new(origin: NSPoint, size: NSSize) -> NSRect { NSRect { origin: origin, - size: size + size: size, } } #[inline] pub fn as_CGRect(&self) -> &CGRect { - unsafe { - mem::transmute::<&NSRect, &CGRect>(self) - } + unsafe { mem::transmute::<&NSRect, &CGRect>(self) } } #[inline] pub fn inset(&self, x: CGFloat, y: CGFloat) -> NSRect { - unsafe { - NSInsetRect(*self, x, y) - } + unsafe { NSInsetRect(*self, x, y) } } } unsafe impl objc::Encode for NSRect { fn encode() -> objc::Encoding { - let encoding = format!("{{CGRect={}{}}}", - NSPoint::encode().as_str(), - NSSize::encode().as_str()); + let encoding = format!( + "{{CGRect={}{}}}", + NSPoint::encode().as_str(), + NSSize::encode().as_str() + ); unsafe { objc::Encoding::from_str(&encoding) } } } @@ -141,22 +139,21 @@ mod macos { } #[link(name = "Foundation", kind = "framework")] - extern { + extern "C" { fn NSInsetRect(rect: NSRect, x: CGFloat, y: CGFloat) -> NSRect; } pub trait NSValue: Sized { unsafe fn valueWithPoint(_: Self, point: NSPoint) -> id { - msg_send![class!(NSValue), valueWithPoint:point] + msg_send![class!(NSValue), valueWithPoint: point] } unsafe fn valueWithSize(_: Self, size: NSSize) -> id { - msg_send![class!(NSValue), valueWithSize:size] + msg_send![class!(NSValue), valueWithSize: size] } } - impl NSValue for id { - } + impl NSValue for id {} } #[cfg(target_os = "macos")] @@ -174,13 +171,13 @@ impl NSRange { pub fn new(location: NSUInteger, length: NSUInteger) -> NSRange { NSRange { location: location, - length: length + length: length, } } } #[link(name = "Foundation", kind = "framework")] -extern { +extern "C" { pub static NSDefaultRunLoopMode: id; } @@ -203,7 +200,6 @@ impl NSAutoreleasePool for id { } } - #[repr(C)] #[derive(Copy, Clone)] pub struct NSOperatingSystemVersion { @@ -214,16 +210,19 @@ pub struct NSOperatingSystemVersion { impl NSOperatingSystemVersion { #[inline] - pub fn new(majorVersion: NSUInteger, minorVersion: NSUInteger, patchVersion: NSUInteger) -> NSOperatingSystemVersion { + pub fn new( + majorVersion: NSUInteger, + minorVersion: NSUInteger, + patchVersion: NSUInteger, + ) -> NSOperatingSystemVersion { NSOperatingSystemVersion { majorVersion: majorVersion, minorVersion: minorVersion, - patchVersion: patchVersion + patchVersion: patchVersion, } } } - pub trait NSProcessInfo: Sized { unsafe fn processInfo(_: Self) -> id { msg_send![class!(NSProcessInfo), processInfo] @@ -266,7 +265,7 @@ pub trait NSArray: Sized { } unsafe fn arrayWithObject(_: Self, object: id) -> id { - msg_send![class!(NSArray), arrayWithObject:object] + msg_send![class!(NSArray), arrayWithObject: object] } unsafe fn init(self) -> id; @@ -288,15 +287,15 @@ impl NSArray for id { } unsafe fn arrayByAddingObjectFromArray(self, object: id) -> id { - msg_send![self, arrayByAddingObjectFromArray:object] + msg_send![self, arrayByAddingObjectFromArray: object] } unsafe fn arrayByAddingObjectsFromArray(self, objects: id) -> id { - msg_send![self, arrayByAddingObjectsFromArray:objects] + msg_send![self, arrayByAddingObjectsFromArray: objects] } unsafe fn objectAtIndex(self, index: NSUInteger) -> id { - msg_send![self, objectAtIndex:index] + msg_send![self, objectAtIndex: index] } } @@ -306,15 +305,18 @@ pub trait NSDictionary: Sized { } unsafe fn dictionaryWithContentsOfFile_(_: Self, path: id) -> id { - msg_send![class!(NSDictionary), dictionaryWithContentsOfFile:path] + msg_send![class!(NSDictionary), dictionaryWithContentsOfFile: path] } unsafe fn dictionaryWithContentsOfURL_(_: Self, aURL: id) -> id { - msg_send![class!(NSDictionary), dictionaryWithContentsOfURL:aURL] + msg_send![class!(NSDictionary), dictionaryWithContentsOfURL: aURL] } unsafe fn dictionaryWithDictionary_(_: Self, otherDictionary: id) -> id { - msg_send![class!(NSDictionary), dictionaryWithDictionary:otherDictionary] + msg_send![ + class!(NSDictionary), + dictionaryWithDictionary: otherDictionary + ] } unsafe fn dictionaryWithObject_forKey_(_: Self, anObject: id, aKey: id) -> id { @@ -325,12 +327,20 @@ pub trait NSDictionary: Sized { msg_send![class!(NSDictionary), dictionaryWithObjects:objects forKeys:keys] } - unsafe fn dictionaryWithObjects_forKeys_count_(_: Self, objects: *const id, keys: *const id, count: NSUInteger) -> id { + unsafe fn dictionaryWithObjects_forKeys_count_( + _: Self, + objects: *const id, + keys: *const id, + count: NSUInteger, + ) -> id { msg_send![class!(NSDictionary), dictionaryWithObjects:objects forKeys:keys count:count] } unsafe fn dictionaryWithObjectsAndKeys_(_: Self, firstObject: id) -> id { - msg_send![class!(NSDictionary), dictionaryWithObjectsAndKeys:firstObject] + msg_send![ + class!(NSDictionary), + dictionaryWithObjectsAndKeys: firstObject + ] } unsafe fn init(self) -> id; @@ -343,7 +353,7 @@ pub trait NSDictionary: Sized { unsafe fn initWithObjectsAndKeys_(self, firstObject: id) -> id; unsafe fn sharedKeySetForKeys_(_: Self, keys: id) -> id { - msg_send![class!(NSDictionary), sharedKeySetForKeys:keys] + msg_send![class!(NSDictionary), sharedKeySetForKeys: keys] } unsafe fn count(self) -> NSUInteger; @@ -361,16 +371,29 @@ pub trait NSDictionary: Sized { unsafe fn keyEnumerator(self) -> id; unsafe fn objectEnumerator(self) -> id; unsafe fn enumerateKeysAndObjectsUsingBlock_(self, block: *mut Block<(id, id, *mut BOOL), ()>); - unsafe fn enumerateKeysAndObjectsWithOptions_usingBlock_(self, opts: NSEnumerationOptions, - block: *mut Block<(id, id, *mut BOOL), ()>); + unsafe fn enumerateKeysAndObjectsWithOptions_usingBlock_( + self, + opts: NSEnumerationOptions, + block: *mut Block<(id, id, *mut BOOL), ()>, + ); unsafe fn keysSortedByValueUsingSelector_(self, comparator: SEL) -> id; unsafe fn keysSortedByValueUsingComparator_(self, cmptr: NSComparator) -> id; - unsafe fn keysSortedByValueWithOptions_usingComparator_(self, opts: NSEnumerationOptions, cmptr: NSComparator) -> id; - - unsafe fn keysOfEntriesPassingTest_(self, predicate: *mut Block<(id, id, *mut BOOL), BOOL>) -> id; - unsafe fn keysOfEntriesWithOptions_PassingTest_(self, opts: NSEnumerationOptions, - predicate: *mut Block<(id, id, *mut BOOL), BOOL>) -> id; + unsafe fn keysSortedByValueWithOptions_usingComparator_( + self, + opts: NSEnumerationOptions, + cmptr: NSComparator, + ) -> id; + + unsafe fn keysOfEntriesPassingTest_( + self, + predicate: *mut Block<(id, id, *mut BOOL), BOOL>, + ) -> id; + unsafe fn keysOfEntriesWithOptions_PassingTest_( + self, + opts: NSEnumerationOptions, + predicate: *mut Block<(id, id, *mut BOOL), BOOL>, + ) -> id; unsafe fn writeToFile_atomically_(self, path: id, flag: BOOL) -> BOOL; unsafe fn writeToURL_atomically_(self, aURL: id, flag: BOOL) -> BOOL; @@ -402,15 +425,15 @@ impl NSDictionary for id { } unsafe fn initWithContentsOfFile_(self, path: id) -> id { - msg_send![self, initWithContentsOfFile:path] + msg_send![self, initWithContentsOfFile: path] } unsafe fn initWithContentsOfURL_(self, aURL: id) -> id { - msg_send![self, initWithContentsOfURL:aURL] + msg_send![self, initWithContentsOfURL: aURL] } unsafe fn initWithDictionary_(self, otherDictionary: id) -> id { - msg_send![self, initWithDictionary:otherDictionary] + msg_send![self, initWithDictionary: otherDictionary] } unsafe fn initWithDictionary_copyItems_(self, otherDictionary: id, flag: BOOL) -> id { @@ -426,7 +449,7 @@ impl NSDictionary for id { } unsafe fn initWithObjectsAndKeys_(self, firstObject: id) -> id { - msg_send![self, initWithObjectsAndKeys:firstObject] + msg_send![self, initWithObjectsAndKeys: firstObject] } unsafe fn count(self) -> NSUInteger { @@ -434,7 +457,7 @@ impl NSDictionary for id { } unsafe fn isEqualToDictionary_(self, otherDictionary: id) -> BOOL { - msg_send![self, isEqualToDictionary:otherDictionary] + msg_send![self, isEqualToDictionary: otherDictionary] } unsafe fn allKeys(self) -> id { @@ -442,7 +465,7 @@ impl NSDictionary for id { } unsafe fn allKeysForObject_(self, anObject: id) -> id { - msg_send![self, allKeysForObject:anObject] + msg_send![self, allKeysForObject: anObject] } unsafe fn allValues(self) -> id { @@ -450,11 +473,11 @@ impl NSDictionary for id { } unsafe fn objectForKey_(self, aKey: id) -> id { - msg_send![self, objectForKey:aKey] + msg_send![self, objectForKey: aKey] } unsafe fn objectForKeyedSubscript_(self, key: id) -> id { - msg_send![self, objectForKeyedSubscript:key] + msg_send![self, objectForKeyedSubscript: key] } unsafe fn objectsForKeys_notFoundMarker_(self, keys: id, anObject: id) -> id { @@ -462,7 +485,7 @@ impl NSDictionary for id { } unsafe fn valueForKey_(self, key: id) -> id { - msg_send![self, valueForKey:key] + msg_send![self, valueForKey: key] } unsafe fn keyEnumerator(self) -> id { @@ -474,33 +497,46 @@ impl NSDictionary for id { } unsafe fn enumerateKeysAndObjectsUsingBlock_(self, block: *mut Block<(id, id, *mut BOOL), ()>) { - msg_send![self, enumerateKeysAndObjectsUsingBlock:block] + msg_send![self, enumerateKeysAndObjectsUsingBlock: block] } - unsafe fn enumerateKeysAndObjectsWithOptions_usingBlock_(self, opts: NSEnumerationOptions, - block: *mut Block<(id, id, *mut BOOL), ()>) { + unsafe fn enumerateKeysAndObjectsWithOptions_usingBlock_( + self, + opts: NSEnumerationOptions, + block: *mut Block<(id, id, *mut BOOL), ()>, + ) { msg_send![self, enumerateKeysAndObjectsWithOptions:opts usingBlock:block] } unsafe fn keysSortedByValueUsingSelector_(self, comparator: SEL) -> id { - msg_send![self, keysSortedByValueUsingSelector:comparator] + msg_send![self, keysSortedByValueUsingSelector: comparator] } unsafe fn keysSortedByValueUsingComparator_(self, cmptr: NSComparator) -> id { - msg_send![self, keysSortedByValueUsingComparator:cmptr] + msg_send![self, keysSortedByValueUsingComparator: cmptr] } - unsafe fn keysSortedByValueWithOptions_usingComparator_(self, opts: NSEnumerationOptions, cmptr: NSComparator) -> id { + unsafe fn keysSortedByValueWithOptions_usingComparator_( + self, + opts: NSEnumerationOptions, + cmptr: NSComparator, + ) -> id { let rv: id = msg_send![self, keysSortedByValueWithOptions:opts usingComparator:cmptr]; rv } - unsafe fn keysOfEntriesPassingTest_(self, predicate: *mut Block<(id, id, *mut BOOL), BOOL>) -> id { - msg_send![self, keysOfEntriesPassingTest:predicate] + unsafe fn keysOfEntriesPassingTest_( + self, + predicate: *mut Block<(id, id, *mut BOOL), BOOL>, + ) -> id { + msg_send![self, keysOfEntriesPassingTest: predicate] } - unsafe fn keysOfEntriesWithOptions_PassingTest_(self, opts: NSEnumerationOptions, - predicate: *mut Block<(id, id, *mut BOOL), BOOL>) -> id { + unsafe fn keysOfEntriesWithOptions_PassingTest_( + self, + opts: NSEnumerationOptions, + predicate: *mut Block<(id, id, *mut BOOL), BOOL>, + ) -> id { msg_send![self, keysOfEntriesWithOptions:opts PassingTest:predicate] } @@ -577,7 +613,7 @@ impl NSDictionary for id { } unsafe fn descriptionWithLocale_(self, locale: id) -> id { - msg_send![self, descriptionWithLocale:locale] + msg_send![self, descriptionWithLocale: locale] } unsafe fn descriptionWithLocale_indent_(self, locale: id, indent: NSUInteger) -> id { @@ -599,7 +635,7 @@ pub type NSComparator = *mut Block<(id, id), NSComparisonResult>; pub enum NSComparisonResult { NSOrderedAscending = -1, NSOrderedSame = 0, - NSOrderedDescending = 1 + NSOrderedDescending = 1, } pub trait NSString: Sized { @@ -618,12 +654,12 @@ pub trait NSString: Sized { impl NSString for id { unsafe fn isEqualToString(self, other: &str) -> bool { let other = NSString::alloc(nil).init_str(other); - let rv: BOOL = msg_send![self, isEqualToString:other]; + let rv: BOOL = msg_send![self, isEqualToString: other]; rv != NO } unsafe fn stringByAppendingString_(self, other: id) -> id { - msg_send![self, stringByAppendingString:other] + msg_send![self, stringByAppendingString: other] } unsafe fn init_str(self, string: &str) -> id { @@ -634,7 +670,7 @@ impl NSString for id { } unsafe fn len(self) -> usize { - msg_send![self, lengthOfBytesUsingEncoding:UTF8_ENCODING] + msg_send![self, lengthOfBytesUsingEncoding: UTF8_ENCODING] } unsafe fn UTF8String(self) -> *const libc::c_char { @@ -642,7 +678,7 @@ impl NSString for id { } unsafe fn substringWithRange(self, range: NSRange) -> id { - msg_send![self, substringWithRange:range] + msg_send![self, substringWithRange: range] } } @@ -656,16 +692,14 @@ pub trait NSDate: Sized { } } -impl NSDate for id { - -} +impl NSDate for id {} #[repr(C)] struct NSFastEnumerationState { pub state: libc::c_ulong, pub items_ptr: *mut id, pub mutations_ptr: *mut libc::c_ulong, - pub extra: [libc::c_ulong; 5] + pub extra: [libc::c_ulong; 5], } const NS_FAST_ENUM_BUF_SIZE: usize = 16; @@ -676,7 +710,7 @@ pub struct NSFastIterator { mut_val: Option, len: usize, idx: usize, - object: id + object: id, } impl Iterator for NSFastIterator { @@ -690,18 +724,17 @@ impl Iterator for NSFastIterator { self.idx = 0; } - let new_mut = unsafe { - *self.state.mutations_ptr - }; + let new_mut = unsafe { *self.state.mutations_ptr }; if let Some(old_mut) = self.mut_val { - assert!(old_mut == new_mut, "The collection was mutated while being enumerated"); + assert!( + old_mut == new_mut, + "The collection was mutated while being enumerated" + ); } if self.idx < self.len { - let object = unsafe { - *self.state.items_ptr.offset(self.idx as isize) - }; + let object = unsafe { *self.state.items_ptr.offset(self.idx as isize) }; self.mut_val = Some(new_mut); self.idx += 1; Some(object) @@ -722,13 +755,13 @@ impl NSFastEnumeration for id { state: 0, items_ptr: ptr::null_mut(), mutations_ptr: ptr::null_mut(), - extra: [0; 5] + extra: [0; 5], }, buffer: [nil; NS_FAST_ENUM_BUF_SIZE], mut_val: None, len: 0, idx: 0, - object: self + object: self, } } } @@ -736,12 +769,14 @@ impl NSFastEnumeration for id { pub trait NSRunLoop: Sized { unsafe fn currentRunLoop() -> Self; - unsafe fn performSelector_target_argument_order_modes_(self, - aSelector: SEL, - target: id, - anArgument: id, - order: NSUInteger, - modes: id); + unsafe fn performSelector_target_argument_order_modes_( + self, + aSelector: SEL, + target: id, + anArgument: id, + order: NSUInteger, + modes: id, + ); } impl NSRunLoop for id { @@ -749,12 +784,14 @@ impl NSRunLoop for id { msg_send![class!(NSRunLoop), currentRunLoop] } - unsafe fn performSelector_target_argument_order_modes_(self, - aSelector: SEL, - target: id, - anArgument: id, - order: NSUInteger, - modes: id) { + unsafe fn performSelector_target_argument_order_modes_( + self, + aSelector: SEL, + target: id, + anArgument: id, + order: NSUInteger, + modes: id, + ) { msg_send![self, performSelector:aSelector target:target argument:anArgument @@ -783,38 +820,88 @@ bitflags! { } } - pub trait NSURL: Sized { unsafe fn alloc(_: Self) -> id; - unsafe fn URLWithString_(_:Self, string: id) -> id; + unsafe fn URLWithString_(_: Self, string: id) -> id; unsafe fn initWithString_(self, string: id) -> id; - unsafe fn URLWithString_relativeToURL_(_:Self, string: id, url: id) -> id; + unsafe fn URLWithString_relativeToURL_(_: Self, string: id, url: id) -> id; unsafe fn initWithString_relativeToURL_(self, string: id, url: id) -> id; - unsafe fn fileURLWithPath_isDirectory_(_:Self, path: id, is_dir: BOOL) -> id; + unsafe fn fileURLWithPath_isDirectory_(_: Self, path: id, is_dir: BOOL) -> id; unsafe fn initFileURLWithPath_isDirectory_(self, path: id, is_dir: BOOL) -> id; - unsafe fn fileURLWithPath_relativeToURL_(_:Self, path: id, url: id) -> id; + unsafe fn fileURLWithPath_relativeToURL_(_: Self, path: id, url: id) -> id; unsafe fn initFileURLWithPath_relativeToURL_(self, path: id, url: id) -> id; - unsafe fn fileURLWithPath_isDirectory_relativeToURL_(_:Self, path: id, is_dir: BOOL, url: id) -> id; - unsafe fn initFileURLWithPath_isDirectory_relativeToURL_(self, path: id, is_dir: BOOL, url: id) -> id; - unsafe fn fileURLWithPath_(_:Self, path: id) -> id; + unsafe fn fileURLWithPath_isDirectory_relativeToURL_( + _: Self, + path: id, + is_dir: BOOL, + url: id, + ) -> id; + unsafe fn initFileURLWithPath_isDirectory_relativeToURL_( + self, + path: id, + is_dir: BOOL, + url: id, + ) -> id; + unsafe fn fileURLWithPath_(_: Self, path: id) -> id; unsafe fn initFileURLWithPath_(self, path: id) -> id; - unsafe fn fileURLWithPathComponents_(_:Self, path_components: id /* (NSArray*) */) -> id; - unsafe fn URLByResolvingAliasFileAtURL_options_error_(_:Self, url: id, options: NSURLBookmarkResolutionOptions, error: *mut id /* (NSError _Nullable) */) -> id; - unsafe fn URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(_:Self, data: id /* (NSData) */, options: NSURLBookmarkResolutionOptions, relative_to_url: id, is_stale: *mut BOOL, error: *mut id /* (NSError _Nullable) */) -> id; - unsafe fn initByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(self, data: id /* (NSData) */, options: NSURLBookmarkResolutionOptions, relative_to_url: id, is_stale: *mut BOOL, error: *mut id /* (NSError _Nullable) */) -> id; + unsafe fn fileURLWithPathComponents_( + _: Self, + path_components: id, /* (NSArray*) */ + ) -> id; + unsafe fn URLByResolvingAliasFileAtURL_options_error_( + _: Self, + url: id, + options: NSURLBookmarkResolutionOptions, + error: *mut id, /* (NSError _Nullable) */ + ) -> id; + unsafe fn URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_( + _: Self, + data: id, /* (NSData) */ + options: NSURLBookmarkResolutionOptions, + relative_to_url: id, + is_stale: *mut BOOL, + error: *mut id, /* (NSError _Nullable) */ + ) -> id; + unsafe fn initByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_( + self, + data: id, /* (NSData) */ + options: NSURLBookmarkResolutionOptions, + relative_to_url: id, + is_stale: *mut BOOL, + error: *mut id, /* (NSError _Nullable) */ + ) -> id; // unsafe fn fileURLWithFileSystemRepresentation_isDirectory_relativeToURL_ // unsafe fn getFileSystemRepresentation_maxLength_ // unsafe fn initFileURLWithFileSystemRepresentation_isDirectory_relativeToURL_ - unsafe fn absoluteURLWithDataRepresentation_relativeToURL_(_:Self, data: id /* (NSData) */, url: id) -> id; - unsafe fn initAbsoluteURLWithDataRepresentation_relativeToURL_(self, data: id /* (NSData) */, url: id) -> id; - unsafe fn URLWithDataRepresentation_relativeToURL_(_:Self, data: id /* (NSData) */, url: id) -> id; - unsafe fn initWithDataRepresentation_relativeToURL_(self, data: id /* (NSData) */, url: id) -> id; + unsafe fn absoluteURLWithDataRepresentation_relativeToURL_( + _: Self, + data: id, /* (NSData) */ + url: id, + ) -> id; + unsafe fn initAbsoluteURLWithDataRepresentation_relativeToURL_( + self, + data: id, /* (NSData) */ + url: id, + ) -> id; + unsafe fn URLWithDataRepresentation_relativeToURL_( + _: Self, + data: id, /* (NSData) */ + url: id, + ) -> id; + unsafe fn initWithDataRepresentation_relativeToURL_( + self, + data: id, /* (NSData) */ + url: id, + ) -> id; unsafe fn dataRepresentation(self) -> id /* (NSData) */; unsafe fn isEqual_(self, id: id) -> BOOL; - unsafe fn checkResourceIsReachableAndReturnError_(self, error: id /* (NSError _Nullable) */) -> BOOL; + unsafe fn checkResourceIsReachableAndReturnError_( + self, + error: id, /* (NSError _Nullable) */ + ) -> BOOL; unsafe fn isFileReferenceURL(self) -> BOOL; unsafe fn isFileURL(self) -> BOOL; @@ -851,7 +938,11 @@ pub trait NSURL: Sized { unsafe fn filePathURL(self) -> id; unsafe fn fileReferenceURL(self) -> id; unsafe fn URLByAppendingPathComponent_(self, path_component: id /* (NSString) */) -> id; - unsafe fn URLByAppendingPathComponent_isDirectory_(self, path_component: id /* (NSString) */, is_dir: BOOL) -> id; + unsafe fn URLByAppendingPathComponent_isDirectory_( + self, + path_component: id, /* (NSString) */ + is_dir: BOOL, + ) -> id; unsafe fn URLByAppendingPathExtension_(self, extension: id /* (NSString) */) -> id; unsafe fn URLByDeletingLastPathComponent(self) -> id; unsafe fn URLByDeletingPathExtension(self) -> id; @@ -859,10 +950,26 @@ pub trait NSURL: Sized { unsafe fn URLByStandardizingPath(self) -> id; unsafe fn hasDirectoryPath(self) -> BOOL; - unsafe fn bookmarkDataWithContentsOfURL_error_(_:Self, url: id, error: id /* (NSError _Nullable) */) -> id /* (NSData) */; - unsafe fn bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error_(self, options: NSURLBookmarkCreationOptions, resource_value_for_keys: id /* (NSArray) */, relative_to_url: id, error: id /* (NSError _Nullable) */) -> id /* (NSData) */; + unsafe fn bookmarkDataWithContentsOfURL_error_( + _: Self, + url: id, + error: id, /* (NSError _Nullable) */ + ) -> id /* (NSData) */; + unsafe fn bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error_( + self, + options: NSURLBookmarkCreationOptions, + resource_value_for_keys: id, /* (NSArray) */ + relative_to_url: id, + error: id, /* (NSError _Nullable) */ + ) -> id /* (NSData) */; // unsafe fn resourceValuesForKeys_fromBookmarkData_ - unsafe fn writeBookmarkData_toURL_options_error_(_:Self, data: id /* (NSData) */, to_url: id, options: NSURLBookmarkFileCreationOptions, error: id /* (NSError _Nullable) */) -> id; + unsafe fn writeBookmarkData_toURL_options_error_( + _: Self, + data: id, /* (NSData) */ + to_url: id, + options: NSURLBookmarkFileCreationOptions, + error: id, /* (NSError _Nullable) */ + ) -> id; unsafe fn startAccessingSecurityScopedResource(self) -> BOOL; unsafe fn stopAccessingSecurityScopedResource(self); unsafe fn NSURLBookmarkFileCreationOptions(self) -> NSURLBookmarkFileCreationOptions; @@ -882,67 +989,115 @@ impl NSURL for id { msg_send![class!(NSURL), alloc] } - unsafe fn URLWithString_(_:Self, string: id) -> id { - msg_send![class!(NSURL), URLWithString:string] + unsafe fn URLWithString_(_: Self, string: id) -> id { + msg_send![class!(NSURL), URLWithString: string] } unsafe fn initWithString_(self, string: id) -> id { - msg_send![self, initWithString:string] + msg_send![self, initWithString: string] } - unsafe fn URLWithString_relativeToURL_(_:Self, string: id, url: id) -> id { + unsafe fn URLWithString_relativeToURL_(_: Self, string: id, url: id) -> id { msg_send![class!(NSURL), URLWithString: string relativeToURL:url] } unsafe fn initWithString_relativeToURL_(self, string: id, url: id) -> id { msg_send![self, initWithString:string relativeToURL:url] } - unsafe fn fileURLWithPath_isDirectory_(_:Self, path: id, is_dir: BOOL) -> id { + unsafe fn fileURLWithPath_isDirectory_(_: Self, path: id, is_dir: BOOL) -> id { msg_send![class!(NSURL), fileURLWithPath:path isDirectory:is_dir] } unsafe fn initFileURLWithPath_isDirectory_(self, path: id, is_dir: BOOL) -> id { msg_send![self, initFileURLWithPath:path isDirectory:is_dir] } - unsafe fn fileURLWithPath_relativeToURL_(_:Self, path: id, url: id) -> id { + unsafe fn fileURLWithPath_relativeToURL_(_: Self, path: id, url: id) -> id { msg_send![class!(NSURL), fileURLWithPath:path relativeToURL:url] } unsafe fn initFileURLWithPath_relativeToURL_(self, path: id, url: id) -> id { msg_send![self, initFileURLWithPath:path relativeToURL:url] } - unsafe fn fileURLWithPath_isDirectory_relativeToURL_(_:Self, path: id, is_dir: BOOL, url: id) -> id { + unsafe fn fileURLWithPath_isDirectory_relativeToURL_( + _: Self, + path: id, + is_dir: BOOL, + url: id, + ) -> id { msg_send![class!(NSURL), fileURLWithPath:path isDirectory:is_dir relativeToURL:url] } - unsafe fn initFileURLWithPath_isDirectory_relativeToURL_(self, path: id, is_dir: BOOL, url: id) -> id { + unsafe fn initFileURLWithPath_isDirectory_relativeToURL_( + self, + path: id, + is_dir: BOOL, + url: id, + ) -> id { msg_send![self, initFileURLWithPath:path isDirectory:is_dir relativeToURL:url] } - unsafe fn fileURLWithPath_(_:Self, path: id) -> id { - msg_send![class!(NSURL), fileURLWithPath:path] + unsafe fn fileURLWithPath_(_: Self, path: id) -> id { + msg_send![class!(NSURL), fileURLWithPath: path] } unsafe fn initFileURLWithPath_(self, path: id) -> id { - msg_send![self, initFileURLWithPath:path] - } - unsafe fn fileURLWithPathComponents_(_:Self, path_components: id /* (NSArray*) */) -> id { - msg_send![class!(NSURL), fileURLWithPathComponents:path_components] - } - unsafe fn URLByResolvingAliasFileAtURL_options_error_(_:Self, url: id, options: NSURLBookmarkResolutionOptions, error: *mut id /* (NSError _Nullable) */) -> id { + msg_send![self, initFileURLWithPath: path] + } + unsafe fn fileURLWithPathComponents_( + _: Self, + path_components: id, /* (NSArray*) */ + ) -> id { + msg_send![class!(NSURL), fileURLWithPathComponents: path_components] + } + unsafe fn URLByResolvingAliasFileAtURL_options_error_( + _: Self, + url: id, + options: NSURLBookmarkResolutionOptions, + error: *mut id, /* (NSError _Nullable) */ + ) -> id { msg_send![class!(NSURL), URLByResolvingAliasFileAtURL:url options:options error:error] } - unsafe fn URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(_:Self, data: id /* (NSData) */, options: NSURLBookmarkResolutionOptions, relative_to_url: id, is_stale: *mut BOOL, error: *mut id /* (NSError _Nullable) */) -> id { + unsafe fn URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_( + _: Self, + data: id, /* (NSData) */ + options: NSURLBookmarkResolutionOptions, + relative_to_url: id, + is_stale: *mut BOOL, + error: *mut id, /* (NSError _Nullable) */ + ) -> id { msg_send![class!(NSURL), URLByResolvingBookmarkData:data options:options relativeToURL:relative_to_url bookmarkDataIsStale:is_stale error:error] } - unsafe fn initByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(self, data: id /* (NSData) */, options: NSURLBookmarkResolutionOptions, relative_to_url: id, is_stale: *mut BOOL, error: *mut id /* (NSError _Nullable) */) -> id { + unsafe fn initByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_( + self, + data: id, /* (NSData) */ + options: NSURLBookmarkResolutionOptions, + relative_to_url: id, + is_stale: *mut BOOL, + error: *mut id, /* (NSError _Nullable) */ + ) -> id { msg_send![self, initByResolvingBookmarkData:data options:options relativeToURL:relative_to_url bookmarkDataIsStale:is_stale error:error] } // unsafe fn fileURLWithFileSystemRepresentation_isDirectory_relativeToURL_ // unsafe fn getFileSystemRepresentation_maxLength_ // unsafe fn initFileURLWithFileSystemRepresentation_isDirectory_relativeToURL_ - unsafe fn absoluteURLWithDataRepresentation_relativeToURL_(_:Self, data: id /* (NSData) */, url: id) -> id { + unsafe fn absoluteURLWithDataRepresentation_relativeToURL_( + _: Self, + data: id, /* (NSData) */ + url: id, + ) -> id { msg_send![class!(NSURL), absoluteURLWithDataRepresentation:data relativeToURL:url] } - unsafe fn initAbsoluteURLWithDataRepresentation_relativeToURL_(self, data: id /* (NSData) */, url: id) -> id { + unsafe fn initAbsoluteURLWithDataRepresentation_relativeToURL_( + self, + data: id, /* (NSData) */ + url: id, + ) -> id { msg_send![self, initAbsoluteURLWithDataRepresentation:data relativeToURL:url] } - unsafe fn URLWithDataRepresentation_relativeToURL_(_:Self, data: id /* (NSData) */, url: id) -> id { + unsafe fn URLWithDataRepresentation_relativeToURL_( + _: Self, + data: id, /* (NSData) */ + url: id, + ) -> id { msg_send![class!(NSURL), URLWithDataRepresentation:data relativeToURL:url] } - unsafe fn initWithDataRepresentation_relativeToURL_(self, data: id /* (NSData) */, url: id) -> id { + unsafe fn initWithDataRepresentation_relativeToURL_( + self, + data: id, /* (NSData) */ + url: id, + ) -> id { msg_send![self, initWithDataRepresentation:data relativeToURL:url] } unsafe fn dataRepresentation(self) -> id /* (NSData) */ { @@ -950,11 +1105,14 @@ impl NSURL for id { } unsafe fn isEqual_(self, id: id) -> BOOL { - msg_send![self, isEqual:id] + msg_send![self, isEqual: id] } - unsafe fn checkResourceIsReachableAndReturnError_(self, error: id /* (NSError _Nullable) */) -> BOOL { - msg_send![self, checkResourceIsReachableAndReturnError:error] + unsafe fn checkResourceIsReachableAndReturnError_( + self, + error: id, /* (NSError _Nullable) */ + ) -> BOOL { + msg_send![self, checkResourceIsReachableAndReturnError: error] } unsafe fn isFileReferenceURL(self) -> BOOL { msg_send![self, isFileReferenceURL] @@ -1040,13 +1198,17 @@ impl NSURL for id { msg_send![self, fileReferenceURL] } unsafe fn URLByAppendingPathComponent_(self, path_component: id /* (NSString) */) -> id { - msg_send![self, URLByAppendingPathComponent:path_component] + msg_send![self, URLByAppendingPathComponent: path_component] } - unsafe fn URLByAppendingPathComponent_isDirectory_(self, path_component: id /* (NSString) */, is_dir: BOOL) -> id { + unsafe fn URLByAppendingPathComponent_isDirectory_( + self, + path_component: id, /* (NSString) */ + is_dir: BOOL, + ) -> id { msg_send![self, URLByAppendingPathComponent:path_component isDirectory:is_dir] } unsafe fn URLByAppendingPathExtension_(self, extension: id /* (NSString) */) -> id { - msg_send![self, URLByAppendingPathExtension:extension] + msg_send![self, URLByAppendingPathExtension: extension] } unsafe fn URLByDeletingLastPathComponent(self) -> id { msg_send![self, URLByDeletingLastPathComponent] @@ -1064,14 +1226,30 @@ impl NSURL for id { msg_send![self, hasDirectoryPath] } - unsafe fn bookmarkDataWithContentsOfURL_error_(_:Self, url: id, error: id /* (NSError _Nullable) */) -> id /* (NSData) */ { + unsafe fn bookmarkDataWithContentsOfURL_error_( + _: Self, + url: id, + error: id, /* (NSError _Nullable) */ + ) -> id /* (NSData) */ { msg_send![class!(NSURL), bookmarkDataWithContentsOfURL:url error:error] } - unsafe fn bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error_(self, options: NSURLBookmarkCreationOptions, resource_value_for_keys: id /* (NSArray) */, relative_to_url: id, error: id /* (NSError _Nullable) */) -> id /* (NSData) */ { + unsafe fn bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error_( + self, + options: NSURLBookmarkCreationOptions, + resource_value_for_keys: id, /* (NSArray) */ + relative_to_url: id, + error: id, /* (NSError _Nullable) */ + ) -> id /* (NSData) */ { msg_send![self, bookmarkDataWithOptions:options includingResourceValuesForKeys:resource_value_for_keys relativeToURL:relative_to_url error:error] } // unsafe fn resourceValuesForKeys_fromBookmarkData_ - unsafe fn writeBookmarkData_toURL_options_error_(_:Self, data: id /* (NSData) */, to_url: id, options: NSURLBookmarkFileCreationOptions, error: id /* (NSError _Nullable) */) -> id { + unsafe fn writeBookmarkData_toURL_options_error_( + _: Self, + data: id, /* (NSData) */ + to_url: id, + options: NSURLBookmarkFileCreationOptions, + error: id, /* (NSError _Nullable) */ + ) -> id { msg_send![class!(NSURL), writeBookmarkData:data toURL:to_url options:options error:error] } unsafe fn startAccessingSecurityScopedResource(self) -> BOOL { @@ -1101,10 +1279,12 @@ impl NSURL for id { pub trait NSBundle: Sized { unsafe fn mainBundle() -> Self; - unsafe fn loadNibNamed_owner_topLevelObjects_(self, - name: id /* NSString */, - owner: id, - topLevelObjects: *mut id /* NSArray */) -> BOOL; + unsafe fn loadNibNamed_owner_topLevelObjects_( + self, + name: id, /* NSString */ + owner: id, + topLevelObjects: *mut id, /* NSArray */ + ) -> BOOL; unsafe fn bundleIdentifier(self) -> id /* NSString */; @@ -1116,10 +1296,12 @@ impl NSBundle for id { msg_send![class!(NSBundle), mainBundle] } - unsafe fn loadNibNamed_owner_topLevelObjects_(self, - name: id /* NSString */, - owner: id, - topLevelObjects: *mut id /* NSArray* */) -> BOOL { + unsafe fn loadNibNamed_owner_topLevelObjects_( + self, + name: id, /* NSString */ + owner: id, + topLevelObjects: *mut id, /* NSArray* */ + ) -> BOOL { msg_send![self, loadNibNamed:name owner:owner topLevelObjects:topLevelObjects] @@ -1147,60 +1329,100 @@ pub trait NSData: Sized { msg_send![class!(NSData), dataWithBytesNoCopy:bytes length:length] } - unsafe fn dataWithBytesNoCopy_length_freeWhenDone_(_: Self, bytes: *const c_void, - length: NSUInteger, freeWhenDone: BOOL) -> id { + unsafe fn dataWithBytesNoCopy_length_freeWhenDone_( + _: Self, + bytes: *const c_void, + length: NSUInteger, + freeWhenDone: BOOL, + ) -> id { msg_send![class!(NSData), dataWithBytesNoCopy:bytes length:length freeWhenDone:freeWhenDone] } unsafe fn dataWithContentsOfFile_(_: Self, path: id) -> id { - msg_send![class!(NSData), dataWithContentsOfFile:path] + msg_send![class!(NSData), dataWithContentsOfFile: path] } - unsafe fn dataWithContentsOfFile_options_error_(_: Self, path: id, mask: NSDataReadingOptions, - errorPtr: *mut id) -> id { + unsafe fn dataWithContentsOfFile_options_error_( + _: Self, + path: id, + mask: NSDataReadingOptions, + errorPtr: *mut id, + ) -> id { msg_send![class!(NSData), dataWithContentsOfFile:path options:mask error:errorPtr] } unsafe fn dataWithContentsOfURL_(_: Self, aURL: id) -> id { - msg_send![class!(NSData), dataWithContentsOfURL:aURL] + msg_send![class!(NSData), dataWithContentsOfURL: aURL] } - unsafe fn dataWithContentsOfURL_options_error_(_: Self, aURL: id, mask: NSDataReadingOptions, - errorPtr: *mut id) -> id { + unsafe fn dataWithContentsOfURL_options_error_( + _: Self, + aURL: id, + mask: NSDataReadingOptions, + errorPtr: *mut id, + ) -> id { msg_send![class!(NSData), dataWithContentsOfURL:aURL options:mask error:errorPtr] } unsafe fn dataWithData_(_: Self, aData: id) -> id { - msg_send![class!(NSData), dataWithData:aData] - } - - unsafe fn initWithBase64EncodedData_options_(self, base64Data: id, options: NSDataBase64DecodingOptions) - -> id; - unsafe fn initWithBase64EncodedString_options_(self, base64String: id, options: NSDataBase64DecodingOptions) - -> id; + msg_send![class!(NSData), dataWithData: aData] + } + + unsafe fn initWithBase64EncodedData_options_( + self, + base64Data: id, + options: NSDataBase64DecodingOptions, + ) -> id; + unsafe fn initWithBase64EncodedString_options_( + self, + base64String: id, + options: NSDataBase64DecodingOptions, + ) -> id; unsafe fn initWithBytes_length_(self, bytes: *const c_void, length: NSUInteger) -> id; unsafe fn initWithBytesNoCopy_length_(self, bytes: *const c_void, length: NSUInteger) -> id; - unsafe fn initWithBytesNoCopy_length_deallocator_(self, bytes: *const c_void, length: NSUInteger, - deallocator: *mut Block<(*const c_void, NSUInteger), ()>) - -> id; - unsafe fn initWithBytesNoCopy_length_freeWhenDone_(self, bytes: *const c_void, - length: NSUInteger, freeWhenDone: BOOL) -> id; + unsafe fn initWithBytesNoCopy_length_deallocator_( + self, + bytes: *const c_void, + length: NSUInteger, + deallocator: *mut Block<(*const c_void, NSUInteger), ()>, + ) -> id; + unsafe fn initWithBytesNoCopy_length_freeWhenDone_( + self, + bytes: *const c_void, + length: NSUInteger, + freeWhenDone: BOOL, + ) -> id; unsafe fn initWithContentsOfFile_(self, path: id) -> id; - unsafe fn initWithContentsOfFile_options_error(self, path: id, mask: NSDataReadingOptions, errorPtr: *mut id) - -> id; + unsafe fn initWithContentsOfFile_options_error( + self, + path: id, + mask: NSDataReadingOptions, + errorPtr: *mut id, + ) -> id; unsafe fn initWithContentsOfURL_(self, aURL: id) -> id; - unsafe fn initWithContentsOfURL_options_error_(self, aURL: id, mask: NSDataReadingOptions, errorPtr: *mut id) - -> id; + unsafe fn initWithContentsOfURL_options_error_( + self, + aURL: id, + mask: NSDataReadingOptions, + errorPtr: *mut id, + ) -> id; unsafe fn initWithData_(self, data: id) -> id; unsafe fn bytes(self) -> *const c_void; unsafe fn description(self) -> id; - unsafe fn enumerateByteRangesUsingBlock_(self, block: *mut Block<(*const c_void, NSRange, *mut BOOL), ()>); + unsafe fn enumerateByteRangesUsingBlock_( + self, + block: *mut Block<(*const c_void, NSRange, *mut BOOL), ()>, + ); unsafe fn getBytes_length_(self, buffer: *mut c_void, length: NSUInteger); unsafe fn getBytes_range_(self, buffer: *mut c_void, range: NSRange); unsafe fn subdataWithRange_(self, range: NSRange) -> id; - unsafe fn rangeOfData_options_range_(self, dataToFind: id, options: NSDataSearchOptions, searchRange: NSRange) - -> NSRange; + unsafe fn rangeOfData_options_range_( + self, + dataToFind: id, + options: NSDataSearchOptions, + searchRange: NSRange, + ) -> NSRange; unsafe fn base64EncodedDataWithOptions_(self, options: NSDataBase64EncodingOptions) -> id; unsafe fn base64EncodedStringWithOptions_(self, options: NSDataBase64EncodingOptions) -> id; @@ -1209,19 +1431,35 @@ pub trait NSData: Sized { unsafe fn length(self) -> NSUInteger; unsafe fn writeToFile_atomically_(self, path: id, atomically: BOOL) -> BOOL; - unsafe fn writeToFile_options_error_(self, path: id, mask: NSDataWritingOptions, errorPtr: *mut id) -> BOOL; + unsafe fn writeToFile_options_error_( + self, + path: id, + mask: NSDataWritingOptions, + errorPtr: *mut id, + ) -> BOOL; unsafe fn writeToURL_atomically_(self, aURL: id, atomically: BOOL) -> BOOL; - unsafe fn writeToURL_options_error_(self, aURL: id, mask: NSDataWritingOptions, errorPtr: *mut id) -> BOOL; + unsafe fn writeToURL_options_error_( + self, + aURL: id, + mask: NSDataWritingOptions, + errorPtr: *mut id, + ) -> BOOL; } impl NSData for id { - unsafe fn initWithBase64EncodedData_options_(self, base64Data: id, options: NSDataBase64DecodingOptions) - -> id { + unsafe fn initWithBase64EncodedData_options_( + self, + base64Data: id, + options: NSDataBase64DecodingOptions, + ) -> id { msg_send![self, initWithBase64EncodedData:base64Data options:options] } - unsafe fn initWithBase64EncodedString_options_(self, base64String: id, options: NSDataBase64DecodingOptions) - -> id { + unsafe fn initWithBase64EncodedString_options_( + self, + base64String: id, + options: NSDataBase64DecodingOptions, + ) -> id { msg_send![self, initWithBase64EncodedString:base64String options:options] } @@ -1233,37 +1471,52 @@ impl NSData for id { msg_send![self, initWithBytesNoCopy:bytes length:length] } - unsafe fn initWithBytesNoCopy_length_deallocator_(self, bytes: *const c_void, length: NSUInteger, - deallocator: *mut Block<(*const c_void, NSUInteger), ()>) - -> id { + unsafe fn initWithBytesNoCopy_length_deallocator_( + self, + bytes: *const c_void, + length: NSUInteger, + deallocator: *mut Block<(*const c_void, NSUInteger), ()>, + ) -> id { msg_send![self, initWithBytesNoCopy:bytes length:length deallocator:deallocator] } - unsafe fn initWithBytesNoCopy_length_freeWhenDone_(self, bytes: *const c_void, - length: NSUInteger, freeWhenDone: BOOL) -> id { + unsafe fn initWithBytesNoCopy_length_freeWhenDone_( + self, + bytes: *const c_void, + length: NSUInteger, + freeWhenDone: BOOL, + ) -> id { msg_send![self, initWithBytesNoCopy:bytes length:length freeWhenDone:freeWhenDone] } unsafe fn initWithContentsOfFile_(self, path: id) -> id { - msg_send![self, initWithContentsOfFile:path] + msg_send![self, initWithContentsOfFile: path] } - unsafe fn initWithContentsOfFile_options_error(self, path: id, mask: NSDataReadingOptions, errorPtr: *mut id) - -> id { + unsafe fn initWithContentsOfFile_options_error( + self, + path: id, + mask: NSDataReadingOptions, + errorPtr: *mut id, + ) -> id { msg_send![self, initWithContentsOfFile:path options:mask error:errorPtr] } unsafe fn initWithContentsOfURL_(self, aURL: id) -> id { - msg_send![self, initWithContentsOfURL:aURL] + msg_send![self, initWithContentsOfURL: aURL] } - unsafe fn initWithContentsOfURL_options_error_(self, aURL: id, mask: NSDataReadingOptions, errorPtr: *mut id) - -> id { + unsafe fn initWithContentsOfURL_options_error_( + self, + aURL: id, + mask: NSDataReadingOptions, + errorPtr: *mut id, + ) -> id { msg_send![self, initWithContentsOfURL:aURL options:mask error:errorPtr] } unsafe fn initWithData_(self, data: id) -> id { - msg_send![self, initWithData:data] + msg_send![self, initWithData: data] } unsafe fn bytes(self) -> *const c_void { @@ -1274,8 +1527,11 @@ impl NSData for id { msg_send![self, description] } - unsafe fn enumerateByteRangesUsingBlock_(self, block: *mut Block<(*const c_void, NSRange, *mut BOOL), ()>) { - msg_send![self, enumerateByteRangesUsingBlock:block] + unsafe fn enumerateByteRangesUsingBlock_( + self, + block: *mut Block<(*const c_void, NSRange, *mut BOOL), ()>, + ) { + msg_send![self, enumerateByteRangesUsingBlock: block] } unsafe fn getBytes_length_(self, buffer: *mut c_void, length: NSUInteger) { @@ -1287,24 +1543,28 @@ impl NSData for id { } unsafe fn subdataWithRange_(self, range: NSRange) -> id { - msg_send![self, subdataWithRange:range] + msg_send![self, subdataWithRange: range] } - unsafe fn rangeOfData_options_range_(self, dataToFind: id, options: NSDataSearchOptions, searchRange: NSRange) - -> NSRange { + unsafe fn rangeOfData_options_range_( + self, + dataToFind: id, + options: NSDataSearchOptions, + searchRange: NSRange, + ) -> NSRange { msg_send![self, rangeOfData:dataToFind options:options range:searchRange] } unsafe fn base64EncodedDataWithOptions_(self, options: NSDataBase64EncodingOptions) -> id { - msg_send![self, base64EncodedDataWithOptions:options] + msg_send![self, base64EncodedDataWithOptions: options] } unsafe fn base64EncodedStringWithOptions_(self, options: NSDataBase64EncodingOptions) -> id { - msg_send![self, base64EncodedStringWithOptions:options] + msg_send![self, base64EncodedStringWithOptions: options] } unsafe fn isEqualToData_(self, otherData: id) -> id { - msg_send![self, isEqualToData:otherData] + msg_send![self, isEqualToData: otherData] } unsafe fn length(self) -> NSUInteger { @@ -1315,7 +1575,12 @@ impl NSData for id { msg_send![self, writeToFile:path atomically:atomically] } - unsafe fn writeToFile_options_error_(self, path: id, mask: NSDataWritingOptions, errorPtr: *mut id) -> BOOL { + unsafe fn writeToFile_options_error_( + self, + path: id, + mask: NSDataWritingOptions, + errorPtr: *mut id, + ) -> BOOL { msg_send![self, writeToFile:path options:mask error:errorPtr] } @@ -1323,7 +1588,12 @@ impl NSData for id { msg_send![self, writeToURL:aURL atomically:atomically] } - unsafe fn writeToURL_options_error_(self, aURL: id, mask: NSDataWritingOptions, errorPtr: *mut id) -> BOOL { + unsafe fn writeToURL_options_error_( + self, + aURL: id, + mask: NSDataWritingOptions, + errorPtr: *mut id, + ) -> BOOL { msg_send![self, writeToURL:aURL options:mask error:errorPtr] } } @@ -1388,6 +1658,6 @@ impl NSUserDefaults for id { } unsafe fn removeObject_forKey_(self, key: id) { - msg_send![self, removeObjectForKey:key] + msg_send![self, removeObjectForKey: key] } } diff --git a/cocoa-foundation/tests/foundation.rs b/cocoa-foundation/tests/foundation.rs index ab6401bbb..19d7b15c4 100644 --- a/cocoa-foundation/tests/foundation.rs +++ b/cocoa-foundation/tests/foundation.rs @@ -6,8 +6,8 @@ extern crate cocoa_foundation; #[cfg(test)] mod foundation { mod nsstring { - use cocoa_foundation::foundation::NSString; use cocoa_foundation::base::nil; + use cocoa_foundation::foundation::NSString; use std::slice; use std::str; @@ -17,8 +17,8 @@ mod foundation { unsafe { let built = NSString::alloc(nil).init_str(expected); let bytes = built.UTF8String() as *const u8; - let objc_string = str::from_utf8(slice::from_raw_parts(bytes, built.len())) - .unwrap(); + let objc_string = + str::from_utf8(slice::from_raw_parts(bytes, built.len())).unwrap(); assert_eq!(objc_string.len(), expected.len()); assert_eq!(objc_string, expected); } @@ -30,8 +30,8 @@ mod foundation { unsafe { let built = NSString::alloc(nil).init_str(expected); let bytes = built.UTF8String() as *const u8; - let objc_string = str::from_utf8(slice::from_raw_parts(bytes, built.len())) - .unwrap(); + let objc_string = + str::from_utf8(slice::from_raw_parts(bytes, built.len())).unwrap(); assert_eq!(objc_string.len(), expected.len()); assert_eq!(objc_string, expected); } @@ -56,18 +56,18 @@ mod foundation { let built_to_append = NSString::alloc(nil).init_str(to_append); let append_string = built.stringByAppendingString_(built_to_append); let bytes = append_string.UTF8String() as *const u8; - let objc_string = str::from_utf8(slice::from_raw_parts(bytes, append_string.len())) - .unwrap(); + let objc_string = + str::from_utf8(slice::from_raw_parts(bytes, append_string.len())).unwrap(); assert_eq!(objc_string, expected); } } } mod nsfastenumeration { - use std::str; - use std::slice; - use cocoa_foundation::foundation::{NSString, NSFastEnumeration}; use cocoa_foundation::base::{id, nil}; + use cocoa_foundation::foundation::{NSFastEnumeration, NSString}; + use std::slice; + use std::str; #[test] fn test_iter() { @@ -76,7 +76,8 @@ mod foundation { let separator = NSString::alloc(nil).init_str(" "); let components: id = msg_send![string, componentsSeparatedByString: separator]; - let combined = components.iter() + let combined = components + .iter() .map(|s| { let bytes = s.UTF8String() as *const u8; str::from_utf8(slice::from_raw_parts(bytes, s.len())).unwrap() @@ -108,9 +109,10 @@ mod foundation { mod nsdictionary { use block::ConcreteBlock; - use cocoa_foundation::foundation::{NSArray, NSComparisonResult, NSDictionary, NSFastEnumeration, - NSString}; use cocoa_foundation::base::{id, nil}; + use cocoa_foundation::foundation::{ + NSArray, NSComparisonResult, NSDictionary, NSFastEnumeration, NSString, + }; #[test] fn test_get() { @@ -132,8 +134,8 @@ mod foundation { let keys = vec!["a", "b", "c", "d", "e", "f"]; let objects = vec!["1", "2", "3", "4", "5", "6"]; unsafe { - use std::{slice, str}; use std::cmp::{Ord, Ordering}; + use std::{slice, str}; let keys_raw_vec = keys.clone().into_iter().map(&mkstr).collect::>(); let objs_raw_vec = objects.clone().into_iter().map(&mkstr).collect::>(); @@ -152,26 +154,29 @@ mod foundation { unsafe { let (bytes0, len0) = (s0.UTF8String() as *const u8, s0.len()); let (bytes1, len1) = (s1.UTF8String() as *const u8, s1.len()); - let (s0, s1) = (str::from_utf8(slice::from_raw_parts(bytes0, len0)).unwrap(), - str::from_utf8(slice::from_raw_parts(bytes1, len1)).unwrap()); + let (s0, s1) = ( + str::from_utf8(slice::from_raw_parts(bytes0, len0)).unwrap(), + str::from_utf8(slice::from_raw_parts(bytes1, len1)).unwrap(), + ); let (c0, c1) = (s0.chars().next().unwrap(), s1.chars().next().unwrap()); c0.cmp(&c1) } } // First test cocoa sorting... - let mut comparator = ConcreteBlock::new(|s0: id, s1: id| { - match compare_function(&s0, &s1) { + let mut comparator = + ConcreteBlock::new(|s0: id, s1: id| match compare_function(&s0, &s1) { Ordering::Less => NSComparisonResult::NSOrderedAscending, Ordering::Equal => NSComparisonResult::NSOrderedSame, Ordering::Greater => NSComparisonResult::NSOrderedDescending, - } - }); + }); let associated_iter = keys.iter().zip(objects.iter()); - for (k_id, (k, v)) in dict.keysSortedByValueUsingComparator_(&mut *comparator) + for (k_id, (k, v)) in dict + .keysSortedByValueUsingComparator_(&mut *comparator) .iter() - .zip(associated_iter) { + .zip(associated_iter) + { assert!(k_id.isEqualToString(k)); let v_id = dict.objectForKey_(k_id); assert!(v_id.isEqualToString(v)); diff --git a/cocoa/examples/color.rs b/cocoa/examples/color.rs index af31514dd..dbafd1e6e 100644 --- a/cocoa/examples/color.rs +++ b/cocoa/examples/color.rs @@ -1,34 +1,43 @@ extern crate cocoa; -use cocoa::base::{selector, id, nil, NO}; - -use cocoa::foundation::{NSRect, NSPoint, NSSize, NSAutoreleasePool, NSProcessInfo, - NSString}; -use cocoa::appkit::{NSApp, NSColor, NSColorSpace, NSApplication, NSApplicationActivationPolicyRegular, - NSMenu, NSMenuItem, NSWindowStyleMask, NSBackingStoreType, NSWindow, - NSRunningApplication, NSApplicationActivateIgnoringOtherApps}; +use cocoa::base::{id, nil, selector, NO}; +use cocoa::appkit::{ + NSApp, NSApplication, NSApplicationActivateIgnoringOtherApps, + NSApplicationActivationPolicyRegular, NSBackingStoreType, NSColor, NSColorSpace, NSMenu, + NSMenuItem, NSRunningApplication, NSWindow, NSWindowStyleMask, +}; +use cocoa::foundation::{NSAutoreleasePool, NSPoint, NSProcessInfo, NSRect, NSSize, NSString}; fn main() { unsafe { // Create the app. let app = create_app(); - + // Create some colors let clear = NSColor::clearColor(nil); let black = NSColor::colorWithRed_green_blue_alpha_(nil, 0.0, 0.0, 0.0, 1.0); let srgb_red = NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 1.0, 0.0, 0.0, 1.0); let device_green = NSColor::colorWithDeviceRed_green_blue_alpha_(nil, 0.0, 1.0, 0.0, 1.0); - let display_p3_blue = NSColor::colorWithDisplayP3Red_green_blue_alpha_(nil, 0.0, 0.0, 1.0, 1.0); - let calibrated_cyan = NSColor::colorWithCalibratedRed_green_blue_alpha_(nil, 0.0, 1.0, 1.0, 1.0); + let display_p3_blue = + NSColor::colorWithDisplayP3Red_green_blue_alpha_(nil, 0.0, 0.0, 1.0, 1.0); + let calibrated_cyan = + NSColor::colorWithCalibratedRed_green_blue_alpha_(nil, 0.0, 1.0, 1.0, 1.0); // Create windows with different color types. let _win_clear = create_window(NSString::alloc(nil).init_str("clear"), clear); let _win_black = create_window(NSString::alloc(nil).init_str("black"), black); let _win_srgb_red = create_window(NSString::alloc(nil).init_str("srgb_red"), srgb_red); - let _win_device_green = create_window(NSString::alloc(nil).init_str("device_green"), device_green); - let _win_display_p3_blue = create_window(NSString::alloc(nil).init_str("display_p3_blue"), display_p3_blue); - let _win_calibrated_cyan = create_window(NSString::alloc(nil).init_str("calibrated_cyan"), calibrated_cyan); + let _win_device_green = + create_window(NSString::alloc(nil).init_str("device_green"), device_green); + let _win_display_p3_blue = create_window( + NSString::alloc(nil).init_str("display_p3_blue"), + display_p3_blue, + ); + let _win_calibrated_cyan = create_window( + NSString::alloc(nil).init_str("calibrated_cyan"), + calibrated_cyan, + ); // Extract component values from a color. // NOTE: some components will raise an exception if the color is not @@ -42,19 +51,24 @@ fn main() { println!("hueComponent: {:?}", my_color.hueComponent()); println!("saturationComponent: {:?}", my_color.saturationComponent()); println!("brightnessComponent: {:?}", my_color.brightnessComponent()); - + // Changing color spaces. - let my_color_cmyk_cs = my_color.colorUsingColorSpace_(NSColorSpace::deviceCMYKColorSpace(nil)); + let my_color_cmyk_cs = + my_color.colorUsingColorSpace_(NSColorSpace::deviceCMYKColorSpace(nil)); println!("blackComponent: {:?}", my_color_cmyk_cs.blackComponent()); println!("cyanComponent: {:?}", my_color_cmyk_cs.cyanComponent()); - println!("magentaComponent: {:?}", my_color_cmyk_cs.magentaComponent()); + println!( + "magentaComponent: {:?}", + my_color_cmyk_cs.magentaComponent() + ); println!("yellowComponent: {:?}", my_color_cmyk_cs.yellowComponent()); // Getting NSColorSpace name. let cs = NSColorSpace::genericGamma22GrayColorSpace(nil); let cs_name = cs.localizedName(); let cs_name_bytes = cs_name.UTF8String() as *const u8; - let cs_name_string = std::str::from_utf8(std::slice::from_raw_parts(cs_name_bytes, cs_name.len())).unwrap(); + let cs_name_string = + std::str::from_utf8(std::slice::from_raw_parts(cs_name_bytes, cs_name.len())).unwrap(); println!("NSColorSpace: {:?}", cs_name_string); // Creating an NSColorSpace from CGColorSpaceRef. @@ -62,7 +76,8 @@ fn main() { let cs = NSColorSpace::alloc(nil).initWithCGColorSpace_(cg_cs); let cs_name = cs.localizedName(); let cs_name_bytes = cs_name.UTF8String() as *const u8; - let cs_name_string = std::str::from_utf8(std::slice::from_raw_parts(cs_name_bytes, cs_name.len())).unwrap(); + let cs_name_string = + std::str::from_utf8(std::slice::from_raw_parts(cs_name_bytes, cs_name.len())).unwrap(); println!("initWithCGColorSpace_: {:?}", cs_name_string); app.run(); @@ -70,16 +85,18 @@ fn main() { } unsafe fn create_window(title: id, color: id) -> id { - let window = NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_( - NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), - NSWindowStyleMask::NSTitledWindowMask | - NSWindowStyleMask::NSClosableWindowMask | - NSWindowStyleMask::NSResizableWindowMask | - NSWindowStyleMask::NSMiniaturizableWindowMask | - NSWindowStyleMask::NSUnifiedTitleAndToolbarWindowMask, - NSBackingStoreType::NSBackingStoreBuffered, - NO - ).autorelease(); + let window = NSWindow::alloc(nil) + .initWithContentRect_styleMask_backing_defer_( + NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), + NSWindowStyleMask::NSTitledWindowMask + | NSWindowStyleMask::NSClosableWindowMask + | NSWindowStyleMask::NSResizableWindowMask + | NSWindowStyleMask::NSMiniaturizableWindowMask + | NSWindowStyleMask::NSUnifiedTitleAndToolbarWindowMask, + NSBackingStoreType::NSBackingStoreBuffered, + NO, + ) + .autorelease(); window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); window.setTitle_(title); diff --git a/cocoa/examples/fullscreen.rs b/cocoa/examples/fullscreen.rs index c826a29ae..e3772e47b 100644 --- a/cocoa/examples/fullscreen.rs +++ b/cocoa/examples/fullscreen.rs @@ -4,18 +4,21 @@ extern crate core_graphics; #[macro_use] extern crate objc; -use cocoa::base::{selector, nil, NO, id}; -use cocoa::foundation::{NSRect, NSPoint, NSSize, NSAutoreleasePool, NSProcessInfo, - NSString, NSUInteger}; -use cocoa::appkit::{NSApp, NSApplication, NSApplicationActivationPolicyRegular, NSWindow, - NSBackingStoreBuffered, NSMenu, NSMenuItem, NSWindowStyleMask, - NSRunningApplication, NSApplicationActivateIgnoringOtherApps, - NSWindowCollectionBehavior, NSApplicationPresentationOptions}; +use cocoa::appkit::{ + NSApp, NSApplication, NSApplicationActivateIgnoringOtherApps, + NSApplicationActivationPolicyRegular, NSApplicationPresentationOptions, NSBackingStoreBuffered, + NSMenu, NSMenuItem, NSRunningApplication, NSWindow, NSWindowCollectionBehavior, + NSWindowStyleMask, +}; +use cocoa::base::{id, nil, selector, NO}; +use cocoa::foundation::{ + NSAutoreleasePool, NSPoint, NSProcessInfo, NSRect, NSSize, NSString, NSUInteger, +}; use core_graphics::display::CGDisplay; -use objc::runtime::{Object, Sel}; use objc::declare::ClassDecl; +use objc::runtime::{Object, Sel}; fn main() { unsafe { @@ -47,7 +50,12 @@ fn main() { let superclass = class!(NSObject); let mut decl = ClassDecl::new("MyWindowDelegate", superclass).unwrap(); - extern fn will_use_fillscreen_presentation_options(_: &Object, _: Sel, _: id, _: NSUInteger) -> NSUInteger { + extern "C" fn will_use_fillscreen_presentation_options( + _: &Object, + _: Sel, + _: id, + _: NSUInteger, + ) -> NSUInteger { // Set initial presentation options for fullscreen let options = NSApplicationPresentationOptions::NSApplicationPresentationFullScreen | NSApplicationPresentationOptions::NSApplicationPresentationHideDock @@ -56,20 +64,28 @@ fn main() { options.bits() } - extern fn window_entering_fullscreen(_: &Object, _: Sel, _: id) { + extern "C" fn window_entering_fullscreen(_: &Object, _: Sel, _: id) { // Reset HideDock and HideMenuBar settings during/after we entered fullscreen. - let options = NSApplicationPresentationOptions::NSApplicationPresentationHideDock | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar; + let options = NSApplicationPresentationOptions::NSApplicationPresentationHideDock + | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar; unsafe { NSApp().setPresentationOptions_(options); } } - decl.add_method(sel!(window:willUseFullScreenPresentationOptions:), - will_use_fillscreen_presentation_options as extern fn(&Object, Sel, id, NSUInteger) -> NSUInteger); - decl.add_method(sel!(windowWillEnterFullScreen:), - window_entering_fullscreen as extern fn(&Object, Sel, id)); - decl.add_method(sel!(windowDidEnterFullScreen:), - window_entering_fullscreen as extern fn(&Object, Sel, id)); + decl.add_method( + sel!(window:willUseFullScreenPresentationOptions:), + will_use_fillscreen_presentation_options + as extern "C" fn(&Object, Sel, id, NSUInteger) -> NSUInteger, + ); + decl.add_method( + sel!(windowWillEnterFullScreen:), + window_entering_fullscreen as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(windowDidEnterFullScreen:), + window_entering_fullscreen as extern "C" fn(&Object, Sel, id), + ); let delegate_class = decl.register(); let delegate_object = msg_send![delegate_class, new]; @@ -78,10 +94,12 @@ fn main() { let display = CGDisplay::main(); let size = NSSize::new(display.pixels_wide() as _, display.pixels_high() as _); let window = NSWindow::alloc(nil) - .initWithContentRect_styleMask_backing_defer_(NSRect::new(NSPoint::new(0., 0.), size), - NSWindowStyleMask::NSTitledWindowMask, - NSBackingStoreBuffered, - NO) + .initWithContentRect_styleMask_backing_defer_( + NSRect::new(NSPoint::new(0., 0.), size), + NSWindowStyleMask::NSTitledWindowMask, + NSBackingStoreBuffered, + NO, + ) .autorelease(); window.setDelegate_(delegate_object); let title = NSString::alloc(nil).init_str("Fullscreen!"); @@ -90,7 +108,9 @@ fn main() { let current_app = NSRunningApplication::currentApplication(nil); current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps); - window.setCollectionBehavior_(NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenPrimary); + window.setCollectionBehavior_( + NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenPrimary, + ); window.toggleFullScreen_(nil); app.run(); } diff --git a/cocoa/examples/hello_world.rs b/cocoa/examples/hello_world.rs index 4d5c1b08c..2f1f0273b 100644 --- a/cocoa/examples/hello_world.rs +++ b/cocoa/examples/hello_world.rs @@ -1,11 +1,12 @@ extern crate cocoa; -use cocoa::base::{selector, nil, NO}; -use cocoa::foundation::{NSRect, NSPoint, NSSize, NSAutoreleasePool, NSProcessInfo, - NSString}; -use cocoa::appkit::{NSApp, NSApplication, NSApplicationActivationPolicyRegular, NSWindow, - NSBackingStoreBuffered, NSMenu, NSMenuItem, NSWindowStyleMask, - NSRunningApplication, NSApplicationActivateIgnoringOtherApps}; +use cocoa::appkit::{ + NSApp, NSApplication, NSApplicationActivateIgnoringOtherApps, + NSApplicationActivationPolicyRegular, NSBackingStoreBuffered, NSMenu, NSMenuItem, + NSRunningApplication, NSWindow, NSWindowStyleMask, +}; +use cocoa::base::{nil, selector, NO}; +use cocoa::foundation::{NSAutoreleasePool, NSPoint, NSProcessInfo, NSRect, NSSize, NSString}; fn main() { unsafe { @@ -35,11 +36,12 @@ fn main() { // create Window let window = NSWindow::alloc(nil) - .initWithContentRect_styleMask_backing_defer_(NSRect::new(NSPoint::new(0., 0.), - NSSize::new(200., 200.)), - NSWindowStyleMask::NSTitledWindowMask, - NSBackingStoreBuffered, - NO) + .initWithContentRect_styleMask_backing_defer_( + NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), + NSWindowStyleMask::NSTitledWindowMask, + NSBackingStoreBuffered, + NO, + ) .autorelease(); window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); window.center(); diff --git a/cocoa/examples/tab_view.rs b/cocoa/examples/tab_view.rs index 985487f75..73519b39e 100644 --- a/cocoa/examples/tab_view.rs +++ b/cocoa/examples/tab_view.rs @@ -1,32 +1,30 @@ extern crate cocoa; -use cocoa::base::{selector, id, nil, NO}; - - -use cocoa::foundation::{NSRect, NSPoint, NSSize, NSAutoreleasePool, NSProcessInfo, - NSString}; -use cocoa::appkit::{NSApp, NSApplication, NSApplicationActivationPolicyRegular, NSWindow, - NSMenu, NSMenuItem, NSTabView, NSWindowStyleMask, NSBackingStoreType, - NSTabViewItem, NSRunningApplication, NSApplicationActivateIgnoringOtherApps}; +use cocoa::base::{id, nil, selector, NO}; +use cocoa::appkit::{ + NSApp, NSApplication, NSApplicationActivateIgnoringOtherApps, + NSApplicationActivationPolicyRegular, NSBackingStoreType, NSMenu, NSMenuItem, + NSRunningApplication, NSTabView, NSTabViewItem, NSWindow, NSWindowStyleMask, +}; +use cocoa::foundation::{NSAutoreleasePool, NSPoint, NSProcessInfo, NSRect, NSSize, NSString}; fn main() { unsafe { - // create a tab View let tab_view = NSTabView::new(nil) .initWithFrame_(NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.))); // create a tab view item - let tab_view_item = NSTabViewItem::new(nil) - .initWithIdentifier_(NSString::alloc(nil).init_str("TabView1")); + let tab_view_item = + NSTabViewItem::new(nil).initWithIdentifier_(NSString::alloc(nil).init_str("TabView1")); tab_view_item.setLabel_(NSString::alloc(nil).init_str("Tab view item 1")); tab_view.addTabViewItem_(tab_view_item); // create a second tab view item - let tab_view_item2 = NSTabViewItem::new(nil) - .initWithIdentifier_(NSString::alloc(nil).init_str("TabView2")); + let tab_view_item2 = + NSTabViewItem::new(nil).initWithIdentifier_(NSString::alloc(nil).init_str("TabView2")); tab_view_item2.setLabel_(NSString::alloc(nil).init_str("Tab view item 2")); tab_view.addTabViewItem_(tab_view_item2); @@ -63,16 +61,18 @@ unsafe fn create_app(title: id, content: id) -> id { app_menu_item.setSubmenu_(app_menu); // create Window - let window = NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_( - NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), - NSWindowStyleMask::NSTitledWindowMask | - NSWindowStyleMask::NSClosableWindowMask | - NSWindowStyleMask::NSResizableWindowMask | - NSWindowStyleMask::NSMiniaturizableWindowMask | - NSWindowStyleMask::NSUnifiedTitleAndToolbarWindowMask, - NSBackingStoreType::NSBackingStoreBuffered, - NO - ).autorelease(); + let window = NSWindow::alloc(nil) + .initWithContentRect_styleMask_backing_defer_( + NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), + NSWindowStyleMask::NSTitledWindowMask + | NSWindowStyleMask::NSClosableWindowMask + | NSWindowStyleMask::NSResizableWindowMask + | NSWindowStyleMask::NSMiniaturizableWindowMask + | NSWindowStyleMask::NSUnifiedTitleAndToolbarWindowMask, + NSBackingStoreType::NSBackingStoreBuffered, + NO, + ) + .autorelease(); window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); window.center(); diff --git a/cocoa/src/appkit.rs b/cocoa/src/appkit.rs index d282fd1c1..cad852e52 100644 --- a/cocoa/src/appkit.rs +++ b/cocoa/src/appkit.rs @@ -11,19 +11,20 @@ use base::{id, BOOL, SEL}; use block::Block; -use foundation::{NSInteger, NSUInteger, NSTimeInterval, - NSPoint, NSSize, NSRect, NSRange, NSRectEdge}; +use foundation::{ + NSInteger, NSPoint, NSRange, NSRect, NSRectEdge, NSSize, NSTimeInterval, NSUInteger, +}; use libc; pub use core_graphics::base::CGFloat; pub use core_graphics::geometry::CGPoint; -pub use self::NSApplicationActivationPolicy::*; pub use self::NSApplicationActivationOptions::*; +pub use self::NSApplicationActivationPolicy::*; pub use self::NSBackingStoreType::*; -pub use self::NSOpenGLPixelFormatAttribute::*; -pub use self::NSOpenGLPFAOpenGLProfiles::*; pub use self::NSEventType::*; +pub use self::NSOpenGLPFAOpenGLProfiles::*; +pub use self::NSOpenGLPixelFormatAttribute::*; use std::os::raw::c_void; pub type CGLContextObj = *mut c_void; @@ -31,7 +32,7 @@ pub type CGLContextObj = *mut c_void; pub type GLint = i32; #[link(name = "AppKit", kind = "framework")] -extern { +extern "C" { pub static NSAppKitVersionNumber: f64; // Types for Standard Data - OS X v10.6 and later. (NSString *const) @@ -164,14 +165,14 @@ pub enum NSApplicationActivationPolicy { NSApplicationActivationPolicyRegular = 0, NSApplicationActivationPolicyAccessory = 1, NSApplicationActivationPolicyProhibited = 2, - NSApplicationActivationPolicyERROR = -1 + NSApplicationActivationPolicyERROR = -1, } #[repr(u64)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSApplicationActivationOptions { NSApplicationActivateAllWindows = 1 << 0, - NSApplicationActivateIgnoringOtherApps = 1 << 1 + NSApplicationActivateIgnoringOtherApps = 1 << 1, } #[repr(u64)] @@ -222,7 +223,7 @@ bitflags! { #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSWindowTitleVisibility { NSWindowTitleVisible = 0, - NSWindowTitleHidden = 1 + NSWindowTitleHidden = 1, } #[repr(i64)] @@ -230,15 +231,15 @@ pub enum NSWindowTitleVisibility { pub enum NSWindowTabbingMode { NSWindowTabbingModeAutomatic = 0, NSWindowTabbingModeDisallowed = 1, - NSWindowTabbingModePreferred = 2 + NSWindowTabbingModePreferred = 2, } #[repr(u64)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSBackingStoreType { - NSBackingStoreRetained = 0, - NSBackingStoreNonretained = 1, - NSBackingStoreBuffered = 2 + NSBackingStoreRetained = 0, + NSBackingStoreNonretained = 1, + NSBackingStoreBuffered = 2, } bitflags! { @@ -288,45 +289,45 @@ bitflags! { #[repr(u64)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSOpenGLPixelFormatAttribute { - NSOpenGLPFAAllRenderers = 1, - NSOpenGLPFATripleBuffer = 3, - NSOpenGLPFADoubleBuffer = 5, - NSOpenGLPFAStereo = 6, - NSOpenGLPFAAuxBuffers = 7, - NSOpenGLPFAColorSize = 8, - NSOpenGLPFAAlphaSize = 11, - NSOpenGLPFADepthSize = 12, - NSOpenGLPFAStencilSize = 13, - NSOpenGLPFAAccumSize = 14, - NSOpenGLPFAMinimumPolicy = 51, - NSOpenGLPFAMaximumPolicy = 52, - NSOpenGLPFAOffScreen = 53, - NSOpenGLPFAFullScreen = 54, - NSOpenGLPFASampleBuffers = 55, - NSOpenGLPFASamples = 56, - NSOpenGLPFAAuxDepthStencil = 57, - NSOpenGLPFAColorFloat = 58, - NSOpenGLPFAMultisample = 59, - NSOpenGLPFASupersample = 60, - NSOpenGLPFASampleAlpha = 61, - NSOpenGLPFARendererID = 70, - NSOpenGLPFASingleRenderer = 71, - NSOpenGLPFANoRecovery = 72, - NSOpenGLPFAAccelerated = 73, - NSOpenGLPFAClosestPolicy = 74, - NSOpenGLPFARobust = 75, - NSOpenGLPFABackingStore = 76, - NSOpenGLPFAMPSafe = 78, - NSOpenGLPFAWindow = 80, - NSOpenGLPFAMultiScreen = 81, - NSOpenGLPFACompliant = 83, - NSOpenGLPFAScreenMask = 84, - NSOpenGLPFAPixelBuffer = 90, - NSOpenGLPFARemotePixelBuffer = 91, - NSOpenGLPFAAllowOfflineRenderers = 96, - NSOpenGLPFAAcceleratedCompute = 97, - NSOpenGLPFAOpenGLProfile = 99, - NSOpenGLPFAVirtualScreenCount = 128, + NSOpenGLPFAAllRenderers = 1, + NSOpenGLPFATripleBuffer = 3, + NSOpenGLPFADoubleBuffer = 5, + NSOpenGLPFAStereo = 6, + NSOpenGLPFAAuxBuffers = 7, + NSOpenGLPFAColorSize = 8, + NSOpenGLPFAAlphaSize = 11, + NSOpenGLPFADepthSize = 12, + NSOpenGLPFAStencilSize = 13, + NSOpenGLPFAAccumSize = 14, + NSOpenGLPFAMinimumPolicy = 51, + NSOpenGLPFAMaximumPolicy = 52, + NSOpenGLPFAOffScreen = 53, + NSOpenGLPFAFullScreen = 54, + NSOpenGLPFASampleBuffers = 55, + NSOpenGLPFASamples = 56, + NSOpenGLPFAAuxDepthStencil = 57, + NSOpenGLPFAColorFloat = 58, + NSOpenGLPFAMultisample = 59, + NSOpenGLPFASupersample = 60, + NSOpenGLPFASampleAlpha = 61, + NSOpenGLPFARendererID = 70, + NSOpenGLPFASingleRenderer = 71, + NSOpenGLPFANoRecovery = 72, + NSOpenGLPFAAccelerated = 73, + NSOpenGLPFAClosestPolicy = 74, + NSOpenGLPFARobust = 75, + NSOpenGLPFABackingStore = 76, + NSOpenGLPFAMPSafe = 78, + NSOpenGLPFAWindow = 80, + NSOpenGLPFAMultiScreen = 81, + NSOpenGLPFACompliant = 83, + NSOpenGLPFAScreenMask = 84, + NSOpenGLPFAPixelBuffer = 90, + NSOpenGLPFARemotePixelBuffer = 91, + NSOpenGLPFAAllowOfflineRenderers = 96, + NSOpenGLPFAAcceleratedCompute = 97, + NSOpenGLPFAOpenGLProfile = 99, + NSOpenGLPFAVirtualScreenCount = 128, } #[repr(u64)] @@ -341,51 +342,51 @@ pub enum NSOpenGLPFAOpenGLProfiles { #[repr(u64)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSOpenGLContextParameter { - NSOpenGLCPSwapInterval = 222, - NSOpenGLCPSurfaceOrder = 235, - NSOpenGLCPSurfaceOpacity = 236, - NSOpenGLCPSurfaceBackingSize = 304, - NSOpenGLCPReclaimResources = 308, - NSOpenGLCPCurrentRendererID = 309, - NSOpenGLCPGPUVertexProcessing = 310, + NSOpenGLCPSwapInterval = 222, + NSOpenGLCPSurfaceOrder = 235, + NSOpenGLCPSurfaceOpacity = 236, + NSOpenGLCPSurfaceBackingSize = 304, + NSOpenGLCPReclaimResources = 308, + NSOpenGLCPCurrentRendererID = 309, + NSOpenGLCPGPUVertexProcessing = 310, NSOpenGLCPGPUFragmentProcessing = 311, - NSOpenGLCPHasDrawable = 314, - NSOpenGLCPMPSwapsInFlight = 315, + NSOpenGLCPHasDrawable = 314, + NSOpenGLCPMPSwapsInFlight = 315, } #[repr(u64)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSWindowButton { - NSWindowCloseButton = 0, - NSWindowMiniaturizeButton = 1, - NSWindowZoomButton = 2, - NSWindowToolbarButton = 3, - NSWindowDocumentIconButton = 4, + NSWindowCloseButton = 0, + NSWindowMiniaturizeButton = 1, + NSWindowZoomButton = 2, + NSWindowToolbarButton = 3, + NSWindowDocumentIconButton = 4, NSWindowDocumentVersionsButton = 6, - NSWindowFullScreenButton = 7, + NSWindowFullScreenButton = 7, } #[repr(u64)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSBezelStyle { - NSRoundedBezelStyle = 1, - NSRegularSquareBezelStyle = 2, - NSDisclosureBezelStyle = 5, - NSShadowlessSquareBezelStyle = 6, - NSCircularBezelStyle = 7, - NSTexturedSquareBezelStyle = 8, - NSHelpButtonBezelStyle = 9, - NSSmallSquareBezelStyle = 10, - NSTexturedRoundedBezelStyle = 11, - NSRoundRectBezelStyle = 12, - NSRecessedBezelStyle = 13, - NSRoundedDisclosureBezelStyle = 14, + NSRoundedBezelStyle = 1, + NSRegularSquareBezelStyle = 2, + NSDisclosureBezelStyle = 5, + NSShadowlessSquareBezelStyle = 6, + NSCircularBezelStyle = 7, + NSTexturedSquareBezelStyle = 8, + NSHelpButtonBezelStyle = 9, + NSSmallSquareBezelStyle = 10, + NSTexturedRoundedBezelStyle = 11, + NSRoundRectBezelStyle = 12, + NSRecessedBezelStyle = 13, + NSRoundedDisclosureBezelStyle = 14, } #[repr(u64)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSRequestUserAttentionType { - NSCriticalRequest = 0, + NSCriticalRequest = 0, NSInformationalRequest = 10, } @@ -406,11 +407,13 @@ pub trait NSApplication: Sized { unsafe fn activateIgnoringOtherApps_(self, ignore: BOOL); unsafe fn run(self); unsafe fn finishLaunching(self); - unsafe fn nextEventMatchingMask_untilDate_inMode_dequeue_(self, - mask: NSUInteger, - expiration: id, - in_mode: id, - dequeue: BOOL) -> id; + unsafe fn nextEventMatchingMask_untilDate_inMode_dequeue_( + self, + mask: NSUInteger, + expiration: id, + in_mode: id, + dequeue: BOOL, + ) -> id; unsafe fn sendEvent_(self, an_event: id); unsafe fn postEvent_atStart_(self, anEvent: id, flag: BOOL); unsafe fn stop_(self, sender: id); @@ -424,7 +427,7 @@ impl NSApplication for id { } unsafe fn setActivationPolicy_(self, policy: NSApplicationActivationPolicy) -> BOOL { - msg_send![self, setActivationPolicy:policy as NSInteger] + msg_send![self, setActivationPolicy: policy as NSInteger] } unsafe fn setPresentationOptions_(self, options: NSApplicationPresentationOptions) -> BOOL { @@ -437,19 +440,19 @@ impl NSApplication for id { } unsafe fn setMainMenu_(self, menu: id) { - msg_send![self, setMainMenu:menu] + msg_send![self, setMainMenu: menu] } unsafe fn setServicesMenu_(self, menu: id) { - msg_send![self, setServicesMenu:menu] + msg_send![self, setServicesMenu: menu] } unsafe fn setWindowsMenu_(self, menu: id) { - msg_send![self, setWindowsMenu:menu] + msg_send![self, setWindowsMenu: menu] } unsafe fn activateIgnoringOtherApps_(self, ignore: BOOL) { - msg_send![self, activateIgnoringOtherApps:ignore] + msg_send![self, activateIgnoringOtherApps: ignore] } unsafe fn run(self) { @@ -460,11 +463,13 @@ impl NSApplication for id { msg_send![self, finishLaunching] } - unsafe fn nextEventMatchingMask_untilDate_inMode_dequeue_(self, - mask: NSUInteger, - expiration: id, - in_mode: id, - dequeue: BOOL) -> id { + unsafe fn nextEventMatchingMask_untilDate_inMode_dequeue_( + self, + mask: NSUInteger, + expiration: id, + in_mode: id, + dequeue: BOOL, + ) -> id { msg_send![self, nextEventMatchingMask:mask untilDate:expiration inMode:in_mode @@ -472,7 +477,7 @@ impl NSApplication for id { } unsafe fn sendEvent_(self, an_event: id) { - msg_send![self, sendEvent:an_event] + msg_send![self, sendEvent: an_event] } unsafe fn postEvent_atStart_(self, anEvent: id, flag: BOOL) { @@ -480,15 +485,15 @@ impl NSApplication for id { } unsafe fn stop_(self, sender: id) { - msg_send![self, stop:sender] + msg_send![self, stop: sender] } unsafe fn setApplicationIconImage_(self, icon: id) { - msg_send![self, setApplicationIconImage:icon] + msg_send![self, setApplicationIconImage: icon] } unsafe fn requestUserAttention_(self, requestType: NSRequestUserAttentionType) { - msg_send![self, requestUserAttention:requestType] + msg_send![self, requestUserAttention: requestType] } } @@ -500,13 +505,16 @@ pub trait NSRunningApplication: Sized { unsafe fn activateWithOptions_(self, options: NSApplicationActivationOptions) -> BOOL; unsafe fn runningApplicationWithProcessIdentifier(_: Self, pid: libc::pid_t) -> id { - msg_send![class!(NSRunningApplication), runningApplicationWithProcessIdentifier:pid] + msg_send![ + class!(NSRunningApplication), + runningApplicationWithProcessIdentifier: pid + ] } } impl NSRunningApplication for id { unsafe fn activateWithOptions_(self, options: NSApplicationActivationOptions) -> BOOL { - msg_send![self, activateWithOptions:options as NSUInteger] + msg_send![self, activateWithOptions: options as NSUInteger] } } @@ -520,15 +528,18 @@ pub trait NSPasteboard: Sized { } unsafe fn pasteboardByFilteringFile(_: Self, file: id) -> id { - msg_send![class!(NSPasteboard), pasteboardByFilteringFile:file] + msg_send![class!(NSPasteboard), pasteboardByFilteringFile: file] } unsafe fn pasteboardByFilteringTypesInPasteboard(_: Self, pboard: id) -> id { - msg_send![class!(NSPasteboard), pasteboardByFilteringTypesInPasteboard:pboard] + msg_send![ + class!(NSPasteboard), + pasteboardByFilteringTypesInPasteboard: pboard + ] } unsafe fn pasteboardWithName(_: Self, name: id) -> id { - msg_send![class!(NSPasteboard), pasteboardWithName:name] + msg_send![class!(NSPasteboard), pasteboardWithName: name] } unsafe fn pasteboardWithUniqueName(_: Self) -> id { @@ -555,7 +566,7 @@ pub trait NSPasteboard: Sized { unsafe fn canReadObjectForClasses_options(self, classArray: id, options: id) -> BOOL; unsafe fn types(self) -> id; unsafe fn typesFilterableTo(_: Self, _type: id) -> id { - msg_send![class!(NSPasteboard), typesFilterableTo:_type] + msg_send![class!(NSPasteboard), typesFilterableTo: _type] } unsafe fn name(self) -> id; @@ -580,7 +591,7 @@ impl NSPasteboard for id { } unsafe fn writeObjects(self, objects: id) -> BOOL { - msg_send![self, writeObjects:objects] + msg_send![self, writeObjects: objects] } unsafe fn setData_forType(self, data: id, dataType: id) -> BOOL { @@ -604,27 +615,27 @@ impl NSPasteboard for id { } unsafe fn indexOfPasteboardItem(self, pasteboardItem: id) -> NSInteger { - msg_send![self, indexOfPasteboardItem:pasteboardItem] + msg_send![self, indexOfPasteboardItem: pasteboardItem] } unsafe fn dataForType(self, dataType: id) -> id { - msg_send![self, dataForType:dataType] + msg_send![self, dataForType: dataType] } unsafe fn propertyListForType(self, dataType: id) -> id { - msg_send![self, propertyListForType:dataType] + msg_send![self, propertyListForType: dataType] } unsafe fn stringForType(self, dataType: id) -> id { - msg_send![self, stringForType:dataType] + msg_send![self, stringForType: dataType] } unsafe fn availableTypeFromArray(self, types: id) -> id { - msg_send![self, availableTypeFromArray:types] + msg_send![self, availableTypeFromArray: types] } unsafe fn canReadItemWithDataConformingToTypes(self, types: id) -> BOOL { - msg_send![self, canReadItemWithDataConformingToTypes:types] + msg_send![self, canReadItemWithDataConformingToTypes: types] } unsafe fn canReadObjectForClasses_options(self, classArray: id, options: id) -> BOOL { @@ -652,11 +663,11 @@ impl NSPasteboard for id { } unsafe fn writeFileContents(self, filename: id) -> BOOL { - msg_send![self, writeFileContents:filename] + msg_send![self, writeFileContents: filename] } unsafe fn writeFileWrapper(self, wrapper: id) -> BOOL { - msg_send![self, writeFileWrapper:wrapper] + msg_send![self, writeFileWrapper: wrapper] } unsafe fn readFileContentsType_toFile(self, _type: id, filename: id) -> id { @@ -666,7 +677,6 @@ impl NSPasteboard for id { unsafe fn readFileWrapper(self) -> id { msg_send![self, readFileWrapper] } - } pub trait NSPasteboardItem: Sized { @@ -704,15 +714,15 @@ impl NSPasteboardItem for id { } unsafe fn dataForType(self, _type: id) -> id { - msg_send![self, dataForType:_type] + msg_send![self, dataForType: _type] } unsafe fn stringForType(self, _type: id) -> id { - msg_send![self, stringForType:_type] + msg_send![self, stringForType: _type] } unsafe fn propertyListForType(self, _type: id) -> id { - msg_send![self, propertyListForType:_type] + msg_send![self, propertyListForType: _type] } } @@ -727,28 +737,36 @@ impl NSPasteboardItemDataProvider for id { } unsafe fn pasteboardFinishedWithDataProvider(self, pasteboard: id) { - msg_send![self, pasteboardFinishedWithDataProvider:pasteboard] + msg_send![self, pasteboardFinishedWithDataProvider: pasteboard] } } pub trait NSPasteboardWriting: Sized { unsafe fn writableTypesForPasteboard(self, pasteboard: id) -> id; - unsafe fn writingOptionsForType_pasteboard(self, _type: id, pasteboard: id) -> NSPasteboardWritingOptions; + unsafe fn writingOptionsForType_pasteboard( + self, + _type: id, + pasteboard: id, + ) -> NSPasteboardWritingOptions; unsafe fn pasteboardPropertyListForType(self, _type: id) -> id; } impl NSPasteboardWriting for id { unsafe fn writableTypesForPasteboard(self, pasteboard: id) -> id { - msg_send![self, writableTypesForPasteboard:pasteboard] + msg_send![self, writableTypesForPasteboard: pasteboard] } - unsafe fn writingOptionsForType_pasteboard(self, _type: id, pasteboard: id) -> NSPasteboardWritingOptions { + unsafe fn writingOptionsForType_pasteboard( + self, + _type: id, + pasteboard: id, + ) -> NSPasteboardWritingOptions { msg_send![self, writingOptionsForType:_type pasteboard:pasteboard] } unsafe fn pasteboardPropertyListForType(self, _type: id) -> id { - msg_send![self, pasteboardPropertyListForType:_type] + msg_send![self, pasteboardPropertyListForType: _type] } } @@ -756,7 +774,11 @@ pub trait NSPasteboardReading: Sized { unsafe fn initWithPasteboardPropertyList_ofType(self, propertyList: id, _type: id) -> id; unsafe fn readableTypesForPasteboard(self, pasteboard: id) -> id; - unsafe fn readingOptionsForType_pasteboard(self, _type: id, pasteboard: id) -> NSPasteboardReadingOptions; + unsafe fn readingOptionsForType_pasteboard( + self, + _type: id, + pasteboard: id, + ) -> NSPasteboardReadingOptions; } impl NSPasteboardReading for id { @@ -766,9 +788,13 @@ impl NSPasteboardReading for id { unsafe fn readableTypesForPasteboard(self, pasteboard: id) -> id { let class: id = msg_send![self, class]; - msg_send![class, readableTypesForPasteboard:pasteboard] + msg_send![class, readableTypesForPasteboard: pasteboard] } - unsafe fn readingOptionsForType_pasteboard(self, _type: id, pasteboard: id) -> NSPasteboardReadingOptions { + unsafe fn readingOptionsForType_pasteboard( + self, + _type: id, + pasteboard: id, + ) -> NSPasteboardReadingOptions { let class: id = msg_send![self, class]; msg_send![class, readingOptionsForType:_type pasteboard:pasteboard] } @@ -780,7 +806,7 @@ pub enum NSPasteboardReadingOptions { NSPasteboardReadingAsData = 0, NSPasteboardReadingAsString = 1 << 0, NSPasteboardReadingAsPropertyList = 1 << 1, - NSPasteboardReadingAsKeyedArchive = 1 << 2 + NSPasteboardReadingAsKeyedArchive = 1 << 2, } #[repr(u64)] @@ -808,7 +834,7 @@ pub trait NSMenu: Sized { impl NSMenu for id { unsafe fn initWithTitle_(self, title: id /* NSString */) -> id { - msg_send![self, initWithTitle:title] + msg_send![self, initWithTitle: title] } unsafe fn setAutoenablesItems(self, state: BOOL) { @@ -816,7 +842,7 @@ impl NSMenu for id { } unsafe fn addItem_(self, menu_item: id) { - msg_send![self, addItem:menu_item] + msg_send![self, addItem: menu_item] } unsafe fn addItemWithTitle_action_keyEquivalent(self, title: id, action: SEL, key: id) -> id { @@ -824,7 +850,7 @@ impl NSMenu for id { } unsafe fn itemAtIndex_(self, index: NSInteger) -> id { - msg_send![self, itemAtIndex:index] + msg_send![self, itemAtIndex: index] } } @@ -853,15 +879,15 @@ impl NSMenuItem for id { } unsafe fn setKeyEquivalentModifierMask_(self, mask: NSEventModifierFlags) { - msg_send![self, setKeyEquivalentModifierMask:mask] + msg_send![self, setKeyEquivalentModifierMask: mask] } unsafe fn setSubmenu_(self, submenu: id) { - msg_send![self, setSubmenu:submenu] + msg_send![self, setSubmenu: submenu] } unsafe fn setTarget_(self, target: id) { - msg_send![self, setTarget:target] + msg_send![self, setTarget: target] } } @@ -897,17 +923,21 @@ pub trait NSWindow: Sized { } // Creating Windows - unsafe fn initWithContentRect_styleMask_backing_defer_(self, - rect: NSRect, - style: NSWindowStyleMask, - backing: NSBackingStoreType, - defer: BOOL) -> id; - unsafe fn initWithContentRect_styleMask_backing_defer_screen_(self, - rect: NSRect, - style: NSWindowStyleMask, - backing: NSBackingStoreType, - defer: BOOL, - screen: id) -> id; + unsafe fn initWithContentRect_styleMask_backing_defer_( + self, + rect: NSRect, + style: NSWindowStyleMask, + backing: NSBackingStoreType, + defer: BOOL, + ) -> id; + unsafe fn initWithContentRect_styleMask_backing_defer_screen_( + self, + rect: NSRect, + style: NSWindowStyleMask, + backing: NSBackingStoreType, + defer: BOOL, + screen: id, + ) -> id; // Configuring Windows unsafe fn styleMask(self) -> NSWindowStyleMask; @@ -933,9 +963,11 @@ pub trait NSWindow: Sized { unsafe fn setHasShadow_(self, hasShadow: BOOL); unsafe fn invalidateShadow(self); unsafe fn autorecalculatesContentBorderThicknessForEdge_(self, edge: NSRectEdge) -> BOOL; - unsafe fn setAutorecalculatesContentBorderThickness_forEdge_(self, - autorecalculateContentBorderThickness: BOOL, - edge: NSRectEdge) -> BOOL; + unsafe fn setAutorecalculatesContentBorderThickness_forEdge_( + self, + autorecalculateContentBorderThickness: BOOL, + edge: NSRectEdge, + ) -> BOOL; unsafe fn contentBorderThicknessForEdge_(self, edge: NSRectEdge) -> CGFloat; unsafe fn setContentBorderThickness_forEdge_(self, borderThickness: CGFloat, edge: NSRectEdge); unsafe fn delegate(self) -> id; @@ -946,9 +978,21 @@ pub trait NSWindow: Sized { // TODO: Accessing Window Information // Getting Layout Information - unsafe fn contentRectForFrameRect_styleMask_(self, windowFrame: NSRect, windowStyle: NSWindowStyleMask) -> NSRect; - unsafe fn frameRectForContentRect_styleMask_(self, windowContentRect: NSRect, windowStyle: NSWindowStyleMask) -> NSRect; - unsafe fn minFrameWidthWithTitle_styleMask_(self, windowTitle: id, windowStyle: NSWindowStyleMask) -> CGFloat; + unsafe fn contentRectForFrameRect_styleMask_( + self, + windowFrame: NSRect, + windowStyle: NSWindowStyleMask, + ) -> NSRect; + unsafe fn frameRectForContentRect_styleMask_( + self, + windowContentRect: NSRect, + windowStyle: NSWindowStyleMask, + ) -> NSRect; + unsafe fn minFrameWidthWithTitle_styleMask_( + self, + windowTitle: id, + windowStyle: NSWindowStyleMask, + ) -> CGFloat; unsafe fn contentRectForFrameRect_(self, windowFrame: NSRect) -> NSRect; unsafe fn frameRectForContentRect_(self, windowContent: NSRect) -> NSRect; @@ -1005,7 +1049,11 @@ pub trait NSWindow: Sized { unsafe fn orderBack_(self, sender: id); unsafe fn orderFront_(self, sender: id); unsafe fn orderFrontRegardless(self); - unsafe fn orderFrontWindow_relativeTo_(self, orderingMode: NSWindowOrderingMode, otherWindowNumber: NSInteger); + unsafe fn orderFrontWindow_relativeTo_( + self, + orderingMode: NSWindowOrderingMode, + otherWindowNumber: NSInteger, + ); unsafe fn level(self) -> NSInteger; unsafe fn setLevel_(self, level: NSInteger); @@ -1067,9 +1115,11 @@ pub trait NSWindow: Sized { unsafe fn setIgnoresMouseEvents_(self, ignoreMouseEvents: BOOL); unsafe fn mouseLocationOutsideOfEventStream(self) -> NSPoint; unsafe fn setAcceptsMouseMovedEvents_(self, acceptMouseMovedEvents: BOOL); - unsafe fn windowNumberAtPoint_belowWindowWithWindowNumber_(_: Self, - point: NSPoint, - windowNumber: NSInteger) -> NSInteger; + unsafe fn windowNumberAtPoint_belowWindowWithWindowNumber_( + _: Self, + point: NSPoint, + windowNumber: NSInteger, + ) -> NSInteger; // TODO: Handling Window Restoration // TODO: Bracketing Drawing Operations @@ -1080,7 +1130,11 @@ pub trait NSWindow: Sized { // Converting Coordinates unsafe fn backingScaleFactor(self) -> CGFloat; - unsafe fn backingAlignedRect_options_(self, rect: NSRect, options: NSAlignmentOptions) -> NSRect; + unsafe fn backingAlignedRect_options_( + self, + rect: NSRect, + options: NSAlignmentOptions, + ) -> NSRect; unsafe fn convertRectFromBacking_(self, rect: NSRect) -> NSRect; unsafe fn convertRectToBacking_(self, rect: NSRect) -> NSRect; unsafe fn convertRectToScreen_(self, rect: NSRect) -> NSRect; @@ -1138,23 +1192,27 @@ pub trait NSWindow: Sized { impl NSWindow for id { // Creating Windows - unsafe fn initWithContentRect_styleMask_backing_defer_(self, - rect: NSRect, - style: NSWindowStyleMask, - backing: NSBackingStoreType, - defer: BOOL) -> id { + unsafe fn initWithContentRect_styleMask_backing_defer_( + self, + rect: NSRect, + style: NSWindowStyleMask, + backing: NSBackingStoreType, + defer: BOOL, + ) -> id { msg_send![self, initWithContentRect:rect styleMask:style.bits backing:backing as NSUInteger defer:defer] } - unsafe fn initWithContentRect_styleMask_backing_defer_screen_(self, - rect: NSRect, - style: NSWindowStyleMask, - backing: NSBackingStoreType, - defer: BOOL, - screen: id) -> id { + unsafe fn initWithContentRect_styleMask_backing_defer_screen_( + self, + rect: NSRect, + style: NSWindowStyleMask, + backing: NSBackingStoreType, + defer: BOOL, + screen: id, + ) -> id { msg_send![self, initWithContentRect:rect styleMask:style.bits backing:backing as NSUInteger @@ -1173,7 +1231,7 @@ impl NSWindow for id { } unsafe fn toggleFullScreen_(self, sender: id) { - msg_send![self, toggleFullScreen:sender] + msg_send![self, toggleFullScreen: sender] } unsafe fn worksWhenModal(self) -> BOOL { @@ -1185,7 +1243,7 @@ impl NSWindow for id { } unsafe fn setAlphaValue_(self, windowAlpha: CGFloat) { - msg_send![self, setAlphaValue:windowAlpha] + msg_send![self, setAlphaValue: windowAlpha] } unsafe fn backgroundColor(self) -> id { @@ -1193,7 +1251,7 @@ impl NSWindow for id { } unsafe fn setBackgroundColor_(self, color: id) { - msg_send![self, setBackgroundColor:color] + msg_send![self, setBackgroundColor: color] } unsafe fn colorSpace(self) -> id { @@ -1201,7 +1259,7 @@ impl NSWindow for id { } unsafe fn setColorSpace_(self, colorSpace: id) { - msg_send![self, setColorSpace:colorSpace] + msg_send![self, setColorSpace: colorSpace] } unsafe fn contentView(self) -> id { @@ -1209,7 +1267,7 @@ impl NSWindow for id { } unsafe fn setContentView_(self, view: id) { - msg_send![self, setContentView:view] + msg_send![self, setContentView: view] } unsafe fn canHide(self) -> BOOL { @@ -1217,7 +1275,7 @@ impl NSWindow for id { } unsafe fn setCanHide_(self, canHide: BOOL) { - msg_send![self, setCanHide:canHide] + msg_send![self, setCanHide: canHide] } unsafe fn hidesOnDeactivate(self) -> BOOL { @@ -1225,7 +1283,7 @@ impl NSWindow for id { } unsafe fn setHidesOnDeactivate_(self, hideOnDeactivate: BOOL) { - msg_send![self, setHidesOnDeactivate:hideOnDeactivate] + msg_send![self, setHidesOnDeactivate: hideOnDeactivate] } unsafe fn collectionBehavior(self) -> NSWindowCollectionBehavior { @@ -1233,11 +1291,11 @@ impl NSWindow for id { } unsafe fn setCollectionBehavior_(self, collectionBehavior: NSWindowCollectionBehavior) { - msg_send![self, setCollectionBehavior:collectionBehavior] + msg_send![self, setCollectionBehavior: collectionBehavior] } unsafe fn setOpaque_(self, opaque: BOOL) { - msg_send![self, setOpaque:opaque] + msg_send![self, setOpaque: opaque] } unsafe fn hasShadow(self) -> BOOL { @@ -1245,7 +1303,7 @@ impl NSWindow for id { } unsafe fn setHasShadow_(self, hasShadow: BOOL) { - msg_send![self, setHasShadow:hasShadow] + msg_send![self, setHasShadow: hasShadow] } unsafe fn invalidateShadow(self) { @@ -1253,18 +1311,20 @@ impl NSWindow for id { } unsafe fn autorecalculatesContentBorderThicknessForEdge_(self, edge: NSRectEdge) -> BOOL { - msg_send![self, autorecalculatesContentBorderThicknessForEdge:edge] + msg_send![self, autorecalculatesContentBorderThicknessForEdge: edge] } - unsafe fn setAutorecalculatesContentBorderThickness_forEdge_(self, - autorecalculateContentBorderThickness: BOOL, - edge: NSRectEdge) -> BOOL { + unsafe fn setAutorecalculatesContentBorderThickness_forEdge_( + self, + autorecalculateContentBorderThickness: BOOL, + edge: NSRectEdge, + ) -> BOOL { msg_send![self, setAutorecalculatesContentBorderThickness: autorecalculateContentBorderThickness forEdge:edge] } unsafe fn contentBorderThicknessForEdge_(self, edge: NSRectEdge) -> CGFloat { - msg_send![self, contentBorderThicknessForEdge:edge] + msg_send![self, contentBorderThicknessForEdge: edge] } unsafe fn setContentBorderThickness_forEdge_(self, borderThickness: CGFloat, edge: NSRectEdge) { @@ -1276,7 +1336,7 @@ impl NSWindow for id { } unsafe fn setDelegate_(self, delegate: id) { - msg_send![self, setDelegate:delegate] + msg_send![self, setDelegate: delegate] } unsafe fn preventsApplicationTerminationWhenModal(self) -> BOOL { @@ -1284,31 +1344,43 @@ impl NSWindow for id { } unsafe fn setPreventsApplicationTerminationWhenModal_(self, flag: BOOL) { - msg_send![self, setPreventsApplicationTerminationWhenModal:flag] + msg_send![self, setPreventsApplicationTerminationWhenModal: flag] } // TODO: Accessing Window Information // Getting Layout Information - unsafe fn contentRectForFrameRect_styleMask_(self, windowFrame: NSRect, windowStyle: NSWindowStyleMask) -> NSRect { + unsafe fn contentRectForFrameRect_styleMask_( + self, + windowFrame: NSRect, + windowStyle: NSWindowStyleMask, + ) -> NSRect { msg_send![self, contentRectForFrameRect:windowFrame styleMask:windowStyle.bits] } - unsafe fn frameRectForContentRect_styleMask_(self, windowContentRect: NSRect, windowStyle: NSWindowStyleMask) -> NSRect { + unsafe fn frameRectForContentRect_styleMask_( + self, + windowContentRect: NSRect, + windowStyle: NSWindowStyleMask, + ) -> NSRect { msg_send![self, frameRectForContentRect:windowContentRect styleMask:windowStyle.bits] } - unsafe fn minFrameWidthWithTitle_styleMask_(self, windowTitle: id, windowStyle: NSWindowStyleMask) -> CGFloat { + unsafe fn minFrameWidthWithTitle_styleMask_( + self, + windowTitle: id, + windowStyle: NSWindowStyleMask, + ) -> CGFloat { msg_send![self, minFrameWidthWithTitle:windowTitle styleMask:windowStyle.bits] } unsafe fn contentRectForFrameRect_(self, windowFrame: NSRect) -> NSRect { - msg_send![self, contentRectForFrameRect:windowFrame] + msg_send![self, contentRectForFrameRect: windowFrame] } unsafe fn frameRectForContentRect_(self, windowContent: NSRect) -> NSRect { - msg_send![self, frameRectForContentRect:windowContent] + msg_send![self, frameRectForContentRect: windowContent] } // Managing Windows @@ -1322,7 +1394,7 @@ impl NSWindow for id { } unsafe fn setWindowController_(self, windowController: id) { - msg_send![self, setWindowController:windowController] + msg_send![self, setWindowController: windowController] } // TODO: Managing Sheets @@ -1334,11 +1406,11 @@ impl NSWindow for id { } unsafe fn setFrameOrigin_(self, point: NSPoint) { - msg_send![self, setFrameOrigin:point] + msg_send![self, setFrameOrigin: point] } unsafe fn setFrameTopLeftPoint_(self, point: NSPoint) { - msg_send![self, setFrameTopLeftPoint:point] + msg_send![self, setFrameTopLeftPoint: point] } unsafe fn constrainFrameRect_toScreen_(self, frameRect: NSRect, screen: id) { @@ -1346,7 +1418,7 @@ impl NSWindow for id { } unsafe fn cascadeTopLeftFromPoint_(self, topLeft: NSPoint) -> NSPoint { - msg_send![self, cascadeTopLeftFromPoint:topLeft] + msg_send![self, cascadeTopLeftFromPoint: topLeft] } unsafe fn setFrame_display_(self, windowFrame: NSRect, display: BOOL) { @@ -1362,7 +1434,7 @@ impl NSWindow for id { } unsafe fn setAspectRatio_(self, aspectRatio: NSSize) { - msg_send![self, setAspectRatio:aspectRatio] + msg_send![self, setAspectRatio: aspectRatio] } unsafe fn minSize(self) -> NSSize { @@ -1370,7 +1442,7 @@ impl NSWindow for id { } unsafe fn setMinSize_(self, minSize: NSSize) { - msg_send![self, setMinSize:minSize] + msg_send![self, setMinSize: minSize] } unsafe fn maxSize(self) -> NSSize { @@ -1378,15 +1450,15 @@ impl NSWindow for id { } unsafe fn setMaxSize_(self, maxSize: NSSize) { - msg_send![self, setMaxSize:maxSize] + msg_send![self, setMaxSize: maxSize] } unsafe fn performZoom_(self, sender: id) { - msg_send![self, performZoom:sender] + msg_send![self, performZoom: sender] } unsafe fn zoom_(self, sender: id) { - msg_send![self, zoom:sender] + msg_send![self, zoom: sender] } unsafe fn resizeFlags(self) -> NSInteger { @@ -1398,7 +1470,7 @@ impl NSWindow for id { } unsafe fn setShowsResizeIndicator_(self, showsResizeIndicator: BOOL) { - msg_send![self, setShowsResizeIndicator:showsResizeIndicator] + msg_send![self, setShowsResizeIndicator: showsResizeIndicator] } unsafe fn resizeIncrements(self) -> NSSize { @@ -1406,7 +1478,7 @@ impl NSWindow for id { } unsafe fn setResizeIncrements_(self, resizeIncrements: NSSize) { - msg_send![self, setResizeIncrements:resizeIncrements] + msg_send![self, setResizeIncrements: resizeIncrements] } unsafe fn preservesContentDuringLiveResize(self) -> BOOL { @@ -1414,7 +1486,10 @@ impl NSWindow for id { } unsafe fn setPreservesContentDuringLiveResize_(self, preservesContentDuringLiveResize: BOOL) { - msg_send![self, setPreservesContentDuringLiveResize:preservesContentDuringLiveResize] + msg_send![ + self, + setPreservesContentDuringLiveResize: preservesContentDuringLiveResize + ] } unsafe fn inLiveResize(self) -> BOOL { @@ -1428,7 +1503,7 @@ impl NSWindow for id { } unsafe fn setContentAspectRatio_(self, contentAspectRatio: NSSize) { - msg_send![self, setContentAspectRatio:contentAspectRatio] + msg_send![self, setContentAspectRatio: contentAspectRatio] } unsafe fn contentMinSize(self) -> NSSize { @@ -1436,7 +1511,7 @@ impl NSWindow for id { } unsafe fn setContentMinSize_(self, contentMinSize: NSSize) { - msg_send![self, setContentMinSize:contentMinSize] + msg_send![self, setContentMinSize: contentMinSize] } unsafe fn contentSize(self) -> NSSize { @@ -1444,7 +1519,7 @@ impl NSWindow for id { } unsafe fn setContentSize_(self, contentSize: NSSize) { - msg_send![self, setContentSize:contentSize] + msg_send![self, setContentSize: contentSize] } unsafe fn contentMaxSize(self) -> NSSize { @@ -1452,7 +1527,7 @@ impl NSWindow for id { } unsafe fn setContentMaxSize_(self, contentMaxSize: NSSize) { - msg_send![self, setContentMaxSize:contentMaxSize] + msg_send![self, setContentMaxSize: contentMaxSize] } unsafe fn contentResizeIncrements(self) -> NSSize { @@ -1460,7 +1535,7 @@ impl NSWindow for id { } unsafe fn setContentResizeIncrements_(self, contentResizeIncrements: NSSize) { - msg_send![self, setContentResizeIncrements:contentResizeIncrements] + msg_send![self, setContentResizeIncrements: contentResizeIncrements] } // Managing Window Visibility and Occlusion State @@ -1476,22 +1551,26 @@ impl NSWindow for id { // Managing Window Layers unsafe fn orderOut_(self, sender: id) { - msg_send![self, orderOut:sender] + msg_send![self, orderOut: sender] } unsafe fn orderBack_(self, sender: id) { - msg_send![self, orderBack:sender] + msg_send![self, orderBack: sender] } unsafe fn orderFront_(self, sender: id) { - msg_send![self, orderFront:sender] + msg_send![self, orderFront: sender] } unsafe fn orderFrontRegardless(self) { msg_send![self, orderFrontRegardless] } - unsafe fn orderFrontWindow_relativeTo_(self, ordering_mode: NSWindowOrderingMode, other_window_number: NSInteger) { + unsafe fn orderFrontWindow_relativeTo_( + self, + ordering_mode: NSWindowOrderingMode, + other_window_number: NSInteger, + ) { msg_send![self, orderWindow:ordering_mode relativeTo:other_window_number] } @@ -1500,7 +1579,7 @@ impl NSWindow for id { } unsafe fn setLevel_(self, level: NSInteger) { - msg_send![self, setLevel:level] + msg_send![self, setLevel: level] } // Managing Key Status @@ -1518,7 +1597,7 @@ impl NSWindow for id { } unsafe fn makeKeyAndOrderFront_(self, sender: id) { - msg_send![self, makeKeyAndOrderFront:sender] + msg_send![self, makeKeyAndOrderFront: sender] } // Managing Main Status @@ -1538,11 +1617,11 @@ impl NSWindow for id { } unsafe fn setToolbar_(self, toolbar: id /* NSToolbar */) { - msg_send![self, setToolbar:toolbar] + msg_send![self, setToolbar: toolbar] } unsafe fn runToolbarCustomizationPalette(self, sender: id) { - msg_send![self, runToolbarCustomizationPalette:sender] + msg_send![self, runToolbarCustomizationPalette: sender] } // TODO: Managing Attached Windows @@ -1555,7 +1634,7 @@ impl NSWindow for id { // Managing Title Bars unsafe fn standardWindowButton_(self, windowButtonKind: NSWindowButton) -> id { - msg_send![self, standardWindowButton:windowButtonKind] + msg_send![self, standardWindowButton: windowButtonKind] } // Managing Window Tabs @@ -1564,7 +1643,10 @@ impl NSWindow for id { } unsafe fn setAllowsAutomaticWindowTabbing_(_: Self, allowsAutomaticWindowTabbing: BOOL) { - msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing:allowsAutomaticWindowTabbing] + msg_send![ + class!(NSWindow), + setAllowsAutomaticWindowTabbing: allowsAutomaticWindowTabbing + ] } unsafe fn tabbingIdentifier(self) -> id { @@ -1584,7 +1666,7 @@ impl NSWindow for id { } unsafe fn toggleTabBar_(self, sender: id) { - msg_send![self, toggleTabBar:sender] + msg_send![self, toggleTabBar: sender] } // TODO: Managing Tooltips // TODO: Handling Events @@ -1600,11 +1682,11 @@ impl NSWindow for id { } unsafe fn setInitialFirstResponder_(self, responder: id) { - msg_send![self, setInitialFirstResponder:responder] + msg_send![self, setInitialFirstResponder: responder] } unsafe fn makeFirstResponder_(self, responder: id) -> BOOL { - msg_send![self, makeFirstResponder:responder] + msg_send![self, makeFirstResponder: responder] } // TODO: Managing the Key View Loop @@ -1612,7 +1694,7 @@ impl NSWindow for id { // Handling Keyboard Events unsafe fn keyDown_(self, event: id) { - msg_send![self, keyDown:event] + msg_send![self, keyDown: event] } // Handling Mouse Events @@ -1626,7 +1708,7 @@ impl NSWindow for id { } unsafe fn setIgnoresMouseEvents_(self, ignoreMouseEvents: BOOL) { - msg_send![self, setIgnoresMouseEvents:ignoreMouseEvents] + msg_send![self, setIgnoresMouseEvents: ignoreMouseEvents] } unsafe fn mouseLocationOutsideOfEventStream(self) -> NSPoint { @@ -1634,12 +1716,14 @@ impl NSWindow for id { } unsafe fn setAcceptsMouseMovedEvents_(self, acceptMouseMovedEvents: BOOL) { - msg_send![self, setAcceptsMouseMovedEvents:acceptMouseMovedEvents] + msg_send![self, setAcceptsMouseMovedEvents: acceptMouseMovedEvents] } - unsafe fn windowNumberAtPoint_belowWindowWithWindowNumber_(_: Self, - point: NSPoint, - windowNumber: NSInteger) -> NSInteger { + unsafe fn windowNumberAtPoint_belowWindowWithWindowNumber_( + _: Self, + point: NSPoint, + windowNumber: NSInteger, + ) -> NSInteger { msg_send![class!(NSWindow), windowNumberAtPoint:point belowWindowWithWindowNumber:windowNumber] } @@ -1649,24 +1733,28 @@ impl NSWindow for id { msg_send![self, backingScaleFactor] } - unsafe fn backingAlignedRect_options_(self, rect: NSRect, options: NSAlignmentOptions) -> NSRect { + unsafe fn backingAlignedRect_options_( + self, + rect: NSRect, + options: NSAlignmentOptions, + ) -> NSRect { msg_send![self, backingAlignedRect:rect options:options] } unsafe fn convertRectFromBacking_(self, rect: NSRect) -> NSRect { - msg_send![self, convertRectFromBacking:rect] + msg_send![self, convertRectFromBacking: rect] } unsafe fn convertRectToBacking_(self, rect: NSRect) -> NSRect { - msg_send![self, convertRectToBacking:rect] + msg_send![self, convertRectToBacking: rect] } unsafe fn convertRectToScreen_(self, rect: NSRect) -> NSRect { - msg_send![self, convertRectToScreen:rect] + msg_send![self, convertRectToScreen: rect] } unsafe fn convertRectFromScreen_(self, rect: NSRect) -> NSRect { - msg_send![self, convertRectFromScreen:rect] + msg_send![self, convertRectFromScreen: rect] } // Accessing Edited Status @@ -1676,7 +1764,7 @@ impl NSWindow for id { } unsafe fn setDocumentEdited_(self, documentEdited: BOOL) { - msg_send![self, setDocumentEdited:documentEdited] + msg_send![self, setDocumentEdited: documentEdited] } // Managing Titles @@ -1686,19 +1774,19 @@ impl NSWindow for id { } unsafe fn setTitle_(self, title: id) { - msg_send![self, setTitle:title] + msg_send![self, setTitle: title] } unsafe fn setTitleWithRepresentedFilename_(self, filePath: id) { - msg_send![self, setTitleWithRepresentedFilename:filePath] + msg_send![self, setTitleWithRepresentedFilename: filePath] } unsafe fn setTitleVisibility_(self, visibility: NSWindowTitleVisibility) { - msg_send![self, setTitleVisibility:visibility] + msg_send![self, setTitleVisibility: visibility] } unsafe fn setTitlebarAppearsTransparent_(self, transparent: BOOL) { - msg_send![self, setTitlebarAppearsTransparent:transparent] + msg_send![self, setTitlebarAppearsTransparent: transparent] } unsafe fn representedFilename(self) -> id { @@ -1706,7 +1794,7 @@ impl NSWindow for id { } unsafe fn setRepresentedFilename_(self, filePath: id) { - msg_send![self, setRepresentedFilename:filePath] + msg_send![self, setRepresentedFilename: filePath] } unsafe fn representedURL(self) -> id { @@ -1714,7 +1802,7 @@ impl NSWindow for id { } unsafe fn setRepresentedURL_(self, representedURL: id) { - msg_send![self, setRepresentedURL:representedURL] + msg_send![self, setRepresentedURL: representedURL] } // Accessing Screen Information @@ -1732,17 +1820,23 @@ impl NSWindow for id { } unsafe fn setDisplaysWhenScreenProfileChanges_(self, displaysWhenScreenProfileChanges: BOOL) { - msg_send![self, setDisplaysWhenScreenProfileChanges:displaysWhenScreenProfileChanges] + msg_send![ + self, + setDisplaysWhenScreenProfileChanges: displaysWhenScreenProfileChanges + ] } // Moving Windows unsafe fn setMovableByWindowBackground_(self, movableByWindowBackground: BOOL) { - msg_send![self, setMovableByWindowBackground:movableByWindowBackground] + msg_send![ + self, + setMovableByWindowBackground: movableByWindowBackground + ] } unsafe fn setMovable_(self, movable: BOOL) { - msg_send![self, setMovable:movable] + msg_send![self, setMovable: movable] } unsafe fn center(self) { @@ -1752,7 +1846,7 @@ impl NSWindow for id { // Closing Windows unsafe fn performClose_(self, sender: id) { - msg_send![self, performClose:sender] + msg_send![self, performClose: sender] } unsafe fn close(self) { @@ -1760,21 +1854,21 @@ impl NSWindow for id { } unsafe fn setReleasedWhenClosed_(self, releasedWhenClosed: BOOL) { - msg_send![self, setReleasedWhenClosed:releasedWhenClosed] + msg_send![self, setReleasedWhenClosed: releasedWhenClosed] } // Minimizing Windows unsafe fn performMiniaturize_(self, sender: id) { - msg_send![self, performMiniaturize:sender] + msg_send![self, performMiniaturize: sender] } unsafe fn miniaturize_(self, sender: id) { - msg_send![self, miniaturize:sender] + msg_send![self, miniaturize: sender] } unsafe fn deminiaturize_(self, sender: id) { - msg_send![self, deminiaturize:sender] + msg_send![self, deminiaturize: sender] } unsafe fn miniwindowImage(self) -> id { @@ -1782,7 +1876,7 @@ impl NSWindow for id { } unsafe fn setMiniwindowImage_(self, miniwindowImage: id) { - msg_send![self, setMiniwindowImage:miniwindowImage] + msg_send![self, setMiniwindowImage: miniwindowImage] } unsafe fn miniwindowTitle(self) -> id { @@ -1790,7 +1884,7 @@ impl NSWindow for id { } unsafe fn setMiniwindowTitle_(self, miniwindowTitle: id) { - msg_send![self, setMiniwindowTitle:miniwindowTitle] + msg_send![self, setMiniwindowTitle: miniwindowTitle] } // TODO: Getting the Dock Tile @@ -1927,7 +2021,7 @@ impl NSView for id { } unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { - msg_send![self, initWithFrame:frameRect] + msg_send![self, initWithFrame: frameRect] } unsafe fn bounds(self) -> NSRect { @@ -1939,11 +2033,11 @@ impl NSView for id { } unsafe fn setFrameSize(self, frameSize: NSSize) { - msg_send![self, setFrameSize:frameSize] + msg_send![self, setFrameSize: frameSize] } unsafe fn setFrameOrigin(self, frameOrigin: NSPoint) { - msg_send![self, setFrameOrigin:frameOrigin] + msg_send![self, setFrameOrigin: frameOrigin] } unsafe fn display_(self) { @@ -1951,7 +2045,7 @@ impl NSView for id { } unsafe fn setWantsBestResolutionOpenGLSurface_(self, flag: BOOL) { - msg_send![self, setWantsBestResolutionOpenGLSurface:flag] + msg_send![self, setWantsBestResolutionOpenGLSurface: flag] } unsafe fn convertPoint_fromView_(self, point: NSPoint, view: id) -> NSPoint { @@ -1959,7 +2053,7 @@ impl NSView for id { } unsafe fn addSubview_(self, view: id) { - msg_send![self, addSubview:view] + msg_send![self, addSubview: view] } unsafe fn superview(self) -> id { @@ -1971,7 +2065,7 @@ impl NSView for id { } unsafe fn setAutoresizingMask_(self, autoresizingMask: NSAutoresizingMaskOptions) { - msg_send![self, setAutoresizingMask:autoresizingMask] + msg_send![self, setAutoresizingMask: autoresizingMask] } unsafe fn wantsLayer(self) -> BOOL { @@ -1979,7 +2073,7 @@ impl NSView for id { } unsafe fn setWantsLayer(self, wantsLayer: BOOL) { - msg_send![self, setWantsLayer:wantsLayer] + msg_send![self, setWantsLayer: wantsLayer] } unsafe fn layer(self) -> id { @@ -1987,7 +2081,7 @@ impl NSView for id { } unsafe fn setLayer(self, layer: id) { - msg_send![self, setLayer:layer] + msg_send![self, setLayer: layer] } unsafe fn widthAnchor(self) -> id { @@ -1999,7 +2093,7 @@ impl NSView for id { } unsafe fn convertRectToBacking(self, rect: NSRect) -> NSRect { - msg_send![self, convertRectToBacking:rect] + msg_send![self, convertRectToBacking: rect] } unsafe fn layerContentsPlacement(self) -> NSViewLayerContentsPlacement { @@ -2033,7 +2127,7 @@ pub trait NSOpenGLView: Sized { } impl NSOpenGLView for id { - unsafe fn initWithFrame_pixelFormat_(self, frameRect: NSRect, format: id) -> id { + unsafe fn initWithFrame_pixelFormat_(self, frameRect: NSRect, format: id) -> id { msg_send![self, initWithFrame:frameRect pixelFormat:format] } @@ -2042,11 +2136,11 @@ impl NSOpenGLView for id { } unsafe fn setOpenGLContext_(self, context: id) { - msg_send![self, setOpenGLContext:context] + msg_send![self, setOpenGLContext: context] } unsafe fn setPixelFormat_(self, pixelformat: id) { - msg_send![self, setPixelFormat:pixelformat] + msg_send![self, setPixelFormat: pixelformat] } } @@ -2061,21 +2155,30 @@ pub trait NSOpenGLPixelFormat: Sized { // Managing the Pixel Format - unsafe fn getValues_forAttribute_forVirtualScreen_(self, val: *mut GLint, attrib: NSOpenGLPixelFormatAttribute, screen: GLint); + unsafe fn getValues_forAttribute_forVirtualScreen_( + self, + val: *mut GLint, + attrib: NSOpenGLPixelFormatAttribute, + screen: GLint, + ); unsafe fn numberOfVirtualScreens(self) -> GLint; - } impl NSOpenGLPixelFormat for id { // Creating an NSOpenGLPixelFormat Object unsafe fn initWithAttributes_(self, attributes: &[u32]) -> id { - msg_send![self, initWithAttributes:attributes] + msg_send![self, initWithAttributes: attributes] } // Managing the Pixel Format - unsafe fn getValues_forAttribute_forVirtualScreen_(self, val: *mut GLint, attrib: NSOpenGLPixelFormatAttribute, screen: GLint) { + unsafe fn getValues_forAttribute_forVirtualScreen_( + self, + val: *mut GLint, + attrib: NSOpenGLPixelFormatAttribute, + screen: GLint, + ) { msg_send![self, getValues:val forAttribute:attrib forVirtualScreen:screen] } @@ -2090,7 +2193,11 @@ pub trait NSOpenGLContext: Sized { } // Context Creation - unsafe fn initWithFormat_shareContext_(self, format: id /* (NSOpenGLPixelFormat *) */, shareContext: id /* (NSOpenGLContext *) */) -> id /* (instancetype) */; + unsafe fn initWithFormat_shareContext_( + self, + format: id, /* (NSOpenGLPixelFormat *) */ + shareContext: id, /* (NSOpenGLContext *) */ + ) -> id /* (instancetype) */; unsafe fn initWithCGLContextObj_(self, context: CGLContextObj) -> id /* (instancetype) */; // Managing the Current Context @@ -2122,12 +2229,16 @@ pub trait NSOpenGLContext: Sized { impl NSOpenGLContext for id { // Context Creation - unsafe fn initWithFormat_shareContext_(self, format: id /* (NSOpenGLPixelFormat *) */, shareContext: id /* (NSOpenGLContext *) */) -> id /* (instancetype) */ { + unsafe fn initWithFormat_shareContext_( + self, + format: id, /* (NSOpenGLPixelFormat *) */ + shareContext: id, /* (NSOpenGLContext *) */ + ) -> id /* (instancetype) */ { msg_send![self, initWithFormat:format shareContext:shareContext] } unsafe fn initWithCGLContextObj_(self, context: CGLContextObj) -> id /* (instancetype) */ { - msg_send![self, initWithCGLContextObj:context] + msg_send![self, initWithCGLContextObj: context] } // Managing the Current Context @@ -2147,7 +2258,7 @@ impl NSOpenGLContext for id { // Drawable Object Management unsafe fn setView_(self, view: id /* (NSView *) */) { - msg_send![self, setView:view] + msg_send![self, setView: view] } unsafe fn view(self) -> id /* (NSView *) */ { @@ -2181,7 +2292,7 @@ impl NSOpenGLContext for id { // Working with Virtual Screens unsafe fn setCurrentVirtualScreen_(self, screen: GLint) { - msg_send![self, setCurrentVirtualScreen:screen] + msg_send![self, setCurrentVirtualScreen: screen] } unsafe fn currentVirtualScreen(self) -> GLint { @@ -2238,36 +2349,36 @@ bitflags! { #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u64)] // NSUInteger pub enum NSEventType { - NSLeftMouseDown = 1, - NSLeftMouseUp = 2, - NSRightMouseDown = 3, - NSRightMouseUp = 4, - NSMouseMoved = 5, - NSLeftMouseDragged = 6, - NSRightMouseDragged = 7, - NSMouseEntered = 8, - NSMouseExited = 9, - NSKeyDown = 10, - NSKeyUp = 11, - NSFlagsChanged = 12, - NSAppKitDefined = 13, - NSSystemDefined = 14, - NSApplicationDefined = 15, - NSPeriodic = 16, - NSCursorUpdate = 17, - NSScrollWheel = 22, - NSTabletPoint = 23, - NSTabletProximity = 24, - NSOtherMouseDown = 25, - NSOtherMouseUp = 26, - NSOtherMouseDragged = 27, - NSEventTypeGesture = 29, - NSEventTypeMagnify = 30, - NSEventTypeSwipe = 31, - NSEventTypeRotate = 18, + NSLeftMouseDown = 1, + NSLeftMouseUp = 2, + NSRightMouseDown = 3, + NSRightMouseUp = 4, + NSMouseMoved = 5, + NSLeftMouseDragged = 6, + NSRightMouseDragged = 7, + NSMouseEntered = 8, + NSMouseExited = 9, + NSKeyDown = 10, + NSKeyUp = 11, + NSFlagsChanged = 12, + NSAppKitDefined = 13, + NSSystemDefined = 14, + NSApplicationDefined = 15, + NSPeriodic = 16, + NSCursorUpdate = 17, + NSScrollWheel = 22, + NSTabletPoint = 23, + NSTabletProximity = 24, + NSOtherMouseDown = 25, + NSOtherMouseUp = 26, + NSOtherMouseDragged = 27, + NSEventTypeGesture = 29, + NSEventTypeMagnify = 30, + NSEventTypeSwipe = 31, + NSEventTypeRotate = 18, NSEventTypeBeginGesture = 19, - NSEventTypeEndGesture = 20, - NSEventTypePressure = 34, + NSEventTypeEndGesture = 20, + NSEventTypePressure = 34, } bitflags! { @@ -2307,7 +2418,9 @@ bitflags! { impl NSEventMask { pub fn from_type(ty: NSEventType) -> NSEventMask { - NSEventMask { bits: 1 << ty as libc::c_ulonglong } + NSEventMask { + bits: 1 << ty as libc::c_ulonglong, + } } } @@ -2328,18 +2441,18 @@ bitflags! { // Not sure of the type here pub enum NSPointingDeviceType { // TODO: Not sure what these values are - // NSUnknownPointingDevice = NX_TABLET_POINTER_UNKNOWN, - // NSPenPointingDevice = NX_TABLET_POINTER_PEN, - // NSCursorPointingDevice = NX_TABLET_POINTER_CURSOR, - // NSEraserPointingDevice = NX_TABLET_POINTER_ERASER, +// NSUnknownPointingDevice = NX_TABLET_POINTER_UNKNOWN, +// NSPenPointingDevice = NX_TABLET_POINTER_PEN, +// NSCursorPointingDevice = NX_TABLET_POINTER_CURSOR, +// NSEraserPointingDevice = NX_TABLET_POINTER_ERASER, } // Not sure of the type here pub enum NSEventButtonMask { // TODO: Not sure what these values are - // NSPenTipMask = NX_TABLET_BUTTON_PENTIPMASK, - // NSPenLowerSideMask = NX_TABLET_BUTTON_PENLOWERSIDEMASK, - // NSPenUpperSideMask = NX_TABLET_BUTTON_PENUPPERSIDEMASK, +// NSPenTipMask = NX_TABLET_BUTTON_PENTIPMASK, +// NSPenLowerSideMask = NX_TABLET_BUTTON_PENLOWERSIDEMASK, +// NSPenUpperSideMask = NX_TABLET_BUTTON_PENUPPERSIDEMASK, } #[repr(i16)] @@ -2439,11 +2552,12 @@ pub trait NSEvent: Sized { modifierFlags: NSEventModifierFlags, timestamp: NSTimeInterval, windowNumber: NSInteger, - context: id /* (NSGraphicsContext *) */, - characters: id /* (NSString *) */, - unmodCharacters: id /* (NSString *) */, + context: id, /* (NSGraphicsContext *) */ + characters: id, /* (NSString *) */ + unmodCharacters: id, /* (NSString *) */ repeatKey: BOOL, - code: libc::c_ushort) -> id /* (NSEvent *) */; + code: libc::c_ushort, + ) -> id /* (NSEvent *) */; unsafe fn mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_( _: Self, eventType: NSEventType, @@ -2451,10 +2565,11 @@ pub trait NSEvent: Sized { modifierFlags: NSEventModifierFlags, timestamp: NSTimeInterval, windowNumber: NSInteger, - context: id /* (NSGraphicsContext *) */, + context: id, /* (NSGraphicsContext *) */ eventNumber: NSInteger, clickCount: NSInteger, - pressure: libc::c_float) -> id /* (NSEvent *) */; + pressure: libc::c_float, + ) -> id /* (NSEvent *) */; unsafe fn enterExitEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_trackingNumber_userData_( _: Self, eventType: NSEventType, @@ -2462,10 +2577,11 @@ pub trait NSEvent: Sized { modifierFlags: NSEventModifierFlags, timestamp: NSTimeInterval, windowNumber: NSInteger, - context: id /* (NSGraphicsContext *) */, + context: id, /* (NSGraphicsContext *) */ eventNumber: NSInteger, trackingNumber: NSInteger, - userData: *mut c_void) -> id /* (NSEvent *) */; + userData: *mut c_void, + ) -> id /* (NSEvent *) */; unsafe fn otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( _: Self, eventType: NSEventType, @@ -2473,10 +2589,11 @@ pub trait NSEvent: Sized { modifierFlags: NSEventModifierFlags, timestamp: NSTimeInterval, windowNumber: NSInteger, - context: id /* (NSGraphicsContext *) */, + context: id, /* (NSGraphicsContext *) */ subtype: NSEventSubtype, data1: NSInteger, - data2: NSInteger) -> id /* (NSEvent *) */; + data2: NSInteger, + ) -> id /* (NSEvent *) */; unsafe fn eventWithEventRef_(_: Self, eventRef: *const c_void) -> id; unsafe fn eventWithCGEvent_(_: Self, cgEvent: *mut c_void /* CGEventRef */) -> id; @@ -2552,12 +2669,20 @@ pub trait NSEvent: Sized { unsafe fn vendorDefined(self) -> id; // Requesting and Stopping Periodic Events - unsafe fn startPeriodicEventsAfterDelay_withPeriod_(_: Self, delaySeconds: NSTimeInterval, periodSeconds: NSTimeInterval); + unsafe fn startPeriodicEventsAfterDelay_withPeriod_( + _: Self, + delaySeconds: NSTimeInterval, + periodSeconds: NSTimeInterval, + ); unsafe fn stopPeriodicEvents(_: Self); // Getting Touch and Gesture Information unsafe fn magnification(self) -> CGFloat; - unsafe fn touchesMatchingPhase_inView_(self, phase: NSTouchPhase, view: id /* (NSView *) */) -> id /* (NSSet *) */; + unsafe fn touchesMatchingPhase_inView_( + self, + phase: NSTouchPhase, + view: id, /* (NSView *) */ + ) -> id /* (NSSet *) */; unsafe fn isSwipeTrackingFromScrollEventsEnabled(_: Self) -> BOOL; // Monitoring Application Events @@ -2587,12 +2712,12 @@ impl NSEvent for id { modifierFlags: NSEventModifierFlags, timestamp: NSTimeInterval, windowNumber: NSInteger, - context: id /* (NSGraphicsContext *) */, - characters: id /* (NSString *) */, - unmodCharacters: id /* (NSString *) */, + context: id, /* (NSGraphicsContext *) */ + characters: id, /* (NSString *) */ + unmodCharacters: id, /* (NSString *) */ repeatKey: BOOL, - code: libc::c_ushort) -> id /* (NSEvent *) */ - { + code: libc::c_ushort, + ) -> id /* (NSEvent *) */ { msg_send![class!(NSEvent), keyEventWithType:eventType location:location modifierFlags:modifierFlags @@ -2612,11 +2737,11 @@ impl NSEvent for id { modifierFlags: NSEventModifierFlags, timestamp: NSTimeInterval, windowNumber: NSInteger, - context: id /* (NSGraphicsContext *) */, + context: id, /* (NSGraphicsContext *) */ eventNumber: NSInteger, clickCount: NSInteger, - pressure: libc::c_float) -> id /* (NSEvent *) */ - { + pressure: libc::c_float, + ) -> id /* (NSEvent *) */ { msg_send![class!(NSEvent), mouseEventWithType:eventType location:location modifierFlags:modifierFlags @@ -2635,11 +2760,11 @@ impl NSEvent for id { modifierFlags: NSEventModifierFlags, timestamp: NSTimeInterval, windowNumber: NSInteger, - context: id /* (NSGraphicsContext *) */, + context: id, /* (NSGraphicsContext *) */ eventNumber: NSInteger, trackingNumber: NSInteger, - userData: *mut c_void) -> id /* (NSEvent *) */ - { + userData: *mut c_void, + ) -> id /* (NSEvent *) */ { msg_send![class!(NSEvent), enterExitEventWithType:eventType location:location modifierFlags:modifierFlags @@ -2658,11 +2783,11 @@ impl NSEvent for id { modifierFlags: NSEventModifierFlags, timestamp: NSTimeInterval, windowNumber: NSInteger, - context: id /* (NSGraphicsContext *) */, + context: id, /* (NSGraphicsContext *) */ subtype: NSEventSubtype, data1: NSInteger, - data2: NSInteger) -> id /* (NSEvent *) */ - { + data2: NSInteger, + ) -> id /* (NSEvent *) */ { msg_send![class!(NSEvent), otherEventWithType:eventType location:location modifierFlags:modifierFlags @@ -2675,11 +2800,11 @@ impl NSEvent for id { } unsafe fn eventWithEventRef_(_: Self, eventRef: *const c_void) -> id { - msg_send![class!(NSEvent), eventWithEventRef:eventRef] + msg_send![class!(NSEvent), eventWithEventRef: eventRef] } unsafe fn eventWithCGEvent_(_: Self, cgEvent: *mut c_void /* CGEventRef */) -> id { - msg_send![class!(NSEvent), eventWithCGEvent:cgEvent] + msg_send![class!(NSEvent), eventWithCGEvent: cgEvent] } // Getting General Event Information @@ -2779,12 +2904,12 @@ impl NSEvent for id { msg_send![self, pressure] } - unsafe fn stage(self) -> NSInteger{ + unsafe fn stage(self) -> NSInteger { msg_send![self, stage] } unsafe fn setMouseCoalescingEnabled_(_: Self, flag: BOOL) { - msg_send![class!(NSEvent), setMouseCoalescingEnabled:flag] + msg_send![class!(NSEvent), setMouseCoalescingEnabled: flag] } unsafe fn isMouseCoalescingEnabled(_: Self) -> BOOL { @@ -2915,7 +3040,11 @@ impl NSEvent for id { // Requesting and Stopping Periodic Events - unsafe fn startPeriodicEventsAfterDelay_withPeriod_(_: Self, delaySeconds: NSTimeInterval, periodSeconds: NSTimeInterval) { + unsafe fn startPeriodicEventsAfterDelay_withPeriod_( + _: Self, + delaySeconds: NSTimeInterval, + periodSeconds: NSTimeInterval, + ) { msg_send![class!(NSEvent), startPeriodicEventsAfterDelay:delaySeconds withPeriod:periodSeconds] } @@ -2929,7 +3058,11 @@ impl NSEvent for id { msg_send![self, magnification] } - unsafe fn touchesMatchingPhase_inView_(self, phase: NSTouchPhase, view: id /* (NSView *) */) -> id /* (NSSet *) */ { + unsafe fn touchesMatchingPhase_inView_( + self, + phase: NSTouchPhase, + view: id, /* (NSView *) */ + ) -> id /* (NSSet *) */ { msg_send![self, touchesMatchingPhase:phase inView:view] } @@ -2943,7 +3076,7 @@ impl NSEvent for id { // TODO: addLocalMonitorForEventsMatchingMask_handler_ (unsure how to bind to blocks) unsafe fn removeMonitor_(_: Self, eventMonitor: id) { - msg_send![class!(NSEvent), removeMonitor:eventMonitor] + msg_send![class!(NSEvent), removeMonitor: eventMonitor] } // Scroll Wheel and Flick Events @@ -2972,7 +3105,7 @@ impl NSEvent for id { // Converting a Mouse Event’s Position into a Sprite Kit Node’s Coordinate Space unsafe fn locationInNode_(self, node: id /* (SKNode *) */) -> CGPoint { - msg_send![self, locationInNode:node] + msg_send![self, locationInNode: node] } } @@ -2992,7 +3125,11 @@ pub trait NSScreen: Sized { unsafe fn screensHaveSeparateSpaces(_: Self) -> BOOL; // Screen Backing Coordinate Conversion - unsafe fn backingAlignedRect_options_(self, aRect: NSRect, options: NSAlignmentOptions) -> NSRect; + unsafe fn backingAlignedRect_options_( + self, + aRect: NSRect, + options: NSAlignmentOptions, + ) -> NSRect; unsafe fn backingScaleFactor(self) -> CGFloat; unsafe fn convertRectFromBacking_(self, aRect: NSRect) -> NSRect; unsafe fn convertRectToBacking_(self, aRect: NSRect) -> NSRect; @@ -3045,7 +3182,11 @@ impl NSScreen for id { // Screen Backing Coordinate Conversion - unsafe fn backingAlignedRect_options_(self, aRect: NSRect, options: NSAlignmentOptions) -> NSRect { + unsafe fn backingAlignedRect_options_( + self, + aRect: NSRect, + options: NSAlignmentOptions, + ) -> NSRect { msg_send![self, backingAlignedRect:aRect options:options] } @@ -3054,11 +3195,11 @@ impl NSScreen for id { } unsafe fn convertRectFromBacking_(self, aRect: NSRect) -> NSRect { - msg_send![self, convertRectFromBacking:aRect] + msg_send![self, convertRectFromBacking: aRect] } unsafe fn convertRectToBacking_(self, aRect: NSRect) -> NSRect { - msg_send![self, convertRectToBacking:aRect] + msg_send![self, convertRectToBacking: aRect] } } @@ -3074,64 +3215,64 @@ pub trait NSControl: Sized { impl NSControl for id { unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { - msg_send![self, initWithFrame:frameRect] + msg_send![self, initWithFrame: frameRect] } unsafe fn isEnabled_(self) -> BOOL { msg_send![self, isEnabled] } unsafe fn setEnabled_(self, enabled: BOOL) -> BOOL { - msg_send![self, setEnabled:enabled] + msg_send![self, setEnabled: enabled] } } pub trait NSImageView: Sized { - unsafe fn alloc(_: Self) -> id { - msg_send![class!(NSImageView), alloc] - } - unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; - unsafe fn setImage_(self, img: id /* (NSImage *) */); + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSImageView), alloc] + } + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; + unsafe fn setImage_(self, img: id /* (NSImage *) */); } impl NSImageView for id { unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { - msg_send![self, initWithFrame:frameRect] + msg_send![self, initWithFrame: frameRect] } unsafe fn setImage_(self, img: id /* (NSImage *) */) { - msg_send![self, setImage:img] + msg_send![self, setImage: img] } } pub trait NSButton: Sized { - unsafe fn setImage_(self, img: id /* (NSImage *) */); - unsafe fn setBezelStyle_(self, style: NSBezelStyle); - unsafe fn setTitle_(self, title: id /* (NSString*) */); - unsafe fn alloc(_: Self) -> id { - msg_send![class!(NSButton), alloc] - } - unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; - unsafe fn setTarget_(self, target: id /* Instance */); - unsafe fn setAction_(self, selector: objc::runtime::Sel /* (Instance *) */); + unsafe fn setImage_(self, img: id /* (NSImage *) */); + unsafe fn setBezelStyle_(self, style: NSBezelStyle); + unsafe fn setTitle_(self, title: id /* (NSString*) */); + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSButton), alloc] + } + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; + unsafe fn setTarget_(self, target: id /* Instance */); + unsafe fn setAction_(self, selector: objc::runtime::Sel /* (Instance *) */); } impl NSButton for id { unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { - msg_send![self, initWithFrame:frameRect] + msg_send![self, initWithFrame: frameRect] } unsafe fn setBezelStyle_(self, style: NSBezelStyle) { - msg_send![self, setBezelStyle:style] + msg_send![self, setBezelStyle: style] } unsafe fn setTitle_(self, title: id /* (NSString*) */) { - msg_send![self, setTitle:title] + msg_send![self, setTitle: title] } unsafe fn setImage_(self, img: id /* (NSImage *) */) { - msg_send![self, setImage:img] + msg_send![self, setImage: img] } unsafe fn setTarget_(self, target: id /* (Instance *) */) { - msg_send![self, setTarget:target] + msg_send![self, setTarget: target] } unsafe fn setAction_(self, selector: objc::runtime::Sel /* (Instance method *) */) { - msg_send![self, setAction:selector] + msg_send![self, setAction: selector] } } @@ -3145,13 +3286,16 @@ pub trait NSImage: Sized { unsafe fn initWithData_(self, data: id /* (NSData *) */) -> id; unsafe fn initWithDataIgnoringOrientation_(self, data: id /* (NSData *) */) -> id; unsafe fn initWithPasteboard_(self, pasteboard: id /* (NSPasteboard *) */) -> id; - unsafe fn initWithSize_flipped_drawingHandler_(self, size: NSSize, - drawingHandlerShouldBeCalledWithFlippedContext: BOOL, - drawingHandler: *mut Block<(NSRect,), BOOL>); + unsafe fn initWithSize_flipped_drawingHandler_( + self, + size: NSSize, + drawingHandlerShouldBeCalledWithFlippedContext: BOOL, + drawingHandler: *mut Block<(NSRect,), BOOL>, + ); unsafe fn initWithSize_(self, aSize: NSSize) -> id; unsafe fn imageNamed_(_: Self, name: id /* (NSString *) */) -> id { - msg_send![class!(NSImage), imageNamed:name] + msg_send![class!(NSImage), imageNamed: name] } unsafe fn name(self) -> id /* (NSString *) */; @@ -3168,23 +3312,45 @@ pub trait NSImage: Sized { unsafe fn addRepresentations_(self, imageReps: id /* (NSArray *) */); unsafe fn representations(self) -> id /* (NSArray *) */; unsafe fn removeRepresentation_(self, imageRep: id /* (NSImageRep *) */); - unsafe fn bestRepresentationForRect_context_hints_(self, rect: NSRect, - referenceContext: id /* (NSGraphicsContext *) */, - hints: id /* (NSDictionary *) */) - -> id /* (NSImageRep *) */; + unsafe fn bestRepresentationForRect_context_hints_( + self, + rect: NSRect, + referenceContext: id, /* (NSGraphicsContext *) */ + hints: id, /* (NSDictionary *) */ + ) -> id /* (NSImageRep *) */; unsafe fn prefersColorMatch(self) -> BOOL; unsafe fn usesEPSOnResolutionMismatch(self) -> BOOL; unsafe fn matchesOnMultipleResolution(self) -> BOOL; unsafe fn drawInRect_(self, rect: NSRect); - unsafe fn drawAtPoint_fromRect_operation_fraction_(self, point: NSPoint, srcRect: NSRect, - op: NSCompositingOperation, delta: CGFloat); - unsafe fn drawInRect_fromRect_operation_fraction_(self, dstRect: NSRect, srcRect: NSRect, - op: NSCompositingOperation, delta: CGFloat); - unsafe fn drawInRect_fromRect_operation_fraction_respectFlipped_hints_(self, dstSpacePortionRect: NSRect, - srcSpacePortionRect: NSRect, op: NSCompositingOperation, delta: CGFloat, respectContextIsFlipped: BOOL, - hints: id /* (NSDictionary *) */); - unsafe fn drawRepresentation_inRect_(self, imageRep: id /* (NSImageRep *) */, dstRect: NSRect); + unsafe fn drawAtPoint_fromRect_operation_fraction_( + self, + point: NSPoint, + srcRect: NSRect, + op: NSCompositingOperation, + delta: CGFloat, + ); + unsafe fn drawInRect_fromRect_operation_fraction_( + self, + dstRect: NSRect, + srcRect: NSRect, + op: NSCompositingOperation, + delta: CGFloat, + ); + unsafe fn drawInRect_fromRect_operation_fraction_respectFlipped_hints_( + self, + dstSpacePortionRect: NSRect, + srcSpacePortionRect: NSRect, + op: NSCompositingOperation, + delta: CGFloat, + respectContextIsFlipped: BOOL, + hints: id, /* (NSDictionary *) */ + ); + unsafe fn drawRepresentation_inRect_( + self, + imageRep: id, /* (NSImageRep *) */ + dstRect: NSRect, + ); unsafe fn isValid(self) -> BOOL; unsafe fn backgroundColor(self) -> id /* (NSColor *) */; @@ -3201,14 +3367,22 @@ pub trait NSImage: Sized { unsafe fn delegate(self) -> id /* (id *) */; unsafe fn TIFFRepresentation(self) -> id /* (NSData *) */; - unsafe fn TIFFRepresentationUsingCompression_factor_(self, comp: NSTIFFCompression, aFloat: f32) - -> id /* (NSData *) */; + unsafe fn TIFFRepresentationUsingCompression_factor_( + self, + comp: NSTIFFCompression, + aFloat: f32, + ) -> id /* (NSData *) */; unsafe fn cancelIncrementalLoad(self); - unsafe fn hitTestRect_withImageDestinationRect_context_hints_flipped_(self, testRectDestSpace: NSRect, - imageRectDestSpace: NSRect, referenceContext: id /* (NSGraphicsContext *) */, - hints: id /* (NSDictionary *) */, flipped: BOOL) -> BOOL; + unsafe fn hitTestRect_withImageDestinationRect_context_hints_flipped_( + self, + testRectDestSpace: NSRect, + imageRectDestSpace: NSRect, + referenceContext: id, /* (NSGraphicsContext *) */ + hints: id, /* (NSDictionary *) */ + flipped: BOOL, + ) -> BOOL; unsafe fn accessibilityDescription(self) -> id /* (NSString *) */; @@ -3220,35 +3394,38 @@ pub trait NSImage: Sized { impl NSImage for id { unsafe fn initByReferencingFile_(self, file_name: id /* (NSString *) */) -> id { - msg_send![self, initByReferencingFile:file_name] + msg_send![self, initByReferencingFile: file_name] } unsafe fn initWithContentsOfFile_(self, file_name: id /* (NSString *) */) -> id { - msg_send![self, initWithContentsOfFile:file_name] + msg_send![self, initWithContentsOfFile: file_name] } unsafe fn initWithData_(self, data: id /* (NSData *) */) -> id { - msg_send![self, initWithData:data] + msg_send![self, initWithData: data] } unsafe fn initWithDataIgnoringOrientation_(self, data: id /* (NSData *) */) -> id { - msg_send![self, initWithDataIgnoringOrientation:data] + msg_send![self, initWithDataIgnoringOrientation: data] } unsafe fn initWithPasteboard_(self, pasteboard: id /* (NSPasteboard *) */) -> id { - msg_send![self, initWithPasteboard:pasteboard] + msg_send![self, initWithPasteboard: pasteboard] } - unsafe fn initWithSize_flipped_drawingHandler_(self, size: NSSize, - drawingHandlerShouldBeCalledWithFlippedContext: BOOL, - drawingHandler: *mut Block<(NSRect,), BOOL>) { + unsafe fn initWithSize_flipped_drawingHandler_( + self, + size: NSSize, + drawingHandlerShouldBeCalledWithFlippedContext: BOOL, + drawingHandler: *mut Block<(NSRect,), BOOL>, + ) { msg_send![self, initWithSize:size flipped:drawingHandlerShouldBeCalledWithFlippedContext drawingHandler:drawingHandler] } unsafe fn initWithSize_(self, aSize: NSSize) -> id { - msg_send![self, initWithSize:aSize] + msg_send![self, initWithSize: aSize] } unsafe fn name(self) -> id /* (NSString *) */ { @@ -3256,7 +3433,7 @@ impl NSImage for id { } unsafe fn setName_(self, name: id /* (NSString *) */) -> BOOL { - msg_send![self, setName:name] + msg_send![self, setName: name] } unsafe fn size(self) -> NSSize { @@ -3268,7 +3445,7 @@ impl NSImage for id { } unsafe fn canInitWithPasteboard_(self, pasteboard: id /* (NSPasteboard *) */) -> BOOL { - msg_send![self, canInitWithPasteboard:pasteboard] + msg_send![self, canInitWithPasteboard: pasteboard] } unsafe fn imageTypes(self) -> id /* (NSArray ) */ { @@ -3280,11 +3457,11 @@ impl NSImage for id { } unsafe fn addRepresentation_(self, imageRep: id /* (NSImageRep *) */) { - msg_send![self, addRepresentation:imageRep] + msg_send![self, addRepresentation: imageRep] } unsafe fn addRepresentations_(self, imageReps: id /* (NSArray *) */) { - msg_send![self, addRepresentations:imageReps] + msg_send![self, addRepresentations: imageReps] } unsafe fn representations(self) -> id /* (NSArray *) */ { @@ -3292,13 +3469,15 @@ impl NSImage for id { } unsafe fn removeRepresentation_(self, imageRep: id /* (NSImageRep *) */) { - msg_send![self, removeRepresentation:imageRep] + msg_send![self, removeRepresentation: imageRep] } - unsafe fn bestRepresentationForRect_context_hints_(self, rect: NSRect, - referenceContext: id /* (NSGraphicsContext *) */, - hints: id /* (NSDictionary *) */) - -> id /* (NSImageRep *) */ { + unsafe fn bestRepresentationForRect_context_hints_( + self, + rect: NSRect, + referenceContext: id, /* (NSGraphicsContext *) */ + hints: id, /* (NSDictionary *) */ + ) -> id /* (NSImageRep *) */ { msg_send![self, bestRepresentationForRect:rect context:referenceContext hints:hints] } @@ -3315,22 +3494,38 @@ impl NSImage for id { } unsafe fn drawInRect_(self, rect: NSRect) { - msg_send![self, drawInRect:rect] + msg_send![self, drawInRect: rect] } - unsafe fn drawAtPoint_fromRect_operation_fraction_(self, point: NSPoint, srcRect: NSRect, - op: NSCompositingOperation, delta: CGFloat) { + unsafe fn drawAtPoint_fromRect_operation_fraction_( + self, + point: NSPoint, + srcRect: NSRect, + op: NSCompositingOperation, + delta: CGFloat, + ) { msg_send![self, drawAtPoint:point fromRect:srcRect operation:op fraction:delta] } - unsafe fn drawInRect_fromRect_operation_fraction_(self, dstRect: NSRect, srcRect: NSRect, - op: NSCompositingOperation, delta: CGFloat) { + unsafe fn drawInRect_fromRect_operation_fraction_( + self, + dstRect: NSRect, + srcRect: NSRect, + op: NSCompositingOperation, + delta: CGFloat, + ) { msg_send![self, drawInRect:dstRect fromRect:srcRect operation:op fraction:delta] } - unsafe fn drawInRect_fromRect_operation_fraction_respectFlipped_hints_(self, dstSpacePortionRect: NSRect, - srcSpacePortionRect: NSRect, op: NSCompositingOperation, delta: CGFloat, respectContextIsFlipped: BOOL, - hints: id /* (NSDictionary *) */) { + unsafe fn drawInRect_fromRect_operation_fraction_respectFlipped_hints_( + self, + dstSpacePortionRect: NSRect, + srcSpacePortionRect: NSRect, + op: NSCompositingOperation, + delta: CGFloat, + respectContextIsFlipped: BOOL, + hints: id, /* (NSDictionary *) */ + ) { msg_send![self, drawInRect:dstSpacePortionRect fromRect:srcSpacePortionRect operation:op @@ -3339,7 +3534,11 @@ impl NSImage for id { hints:hints] } - unsafe fn drawRepresentation_inRect_(self, imageRep: id /* (NSImageRep *) */, dstRect: NSRect) { + unsafe fn drawRepresentation_inRect_( + self, + imageRep: id, /* (NSImageRep *) */ + dstRect: NSRect, + ) { msg_send![self, drawRepresentation:imageRep inRect:dstRect] } @@ -3356,7 +3555,7 @@ impl NSImage for id { } unsafe fn lockFocusFlipped_(self, flipped: BOOL) { - msg_send![self, lockFocusFlipped:flipped] + msg_send![self, lockFocusFlipped: flipped] } unsafe fn unlockFocus(self) { @@ -3383,8 +3582,11 @@ impl NSImage for id { msg_send![self, TIFFRepresentation] } - unsafe fn TIFFRepresentationUsingCompression_factor_(self, comp: NSTIFFCompression, aFloat: f32) - -> id /* (NSData *) */ { + unsafe fn TIFFRepresentationUsingCompression_factor_( + self, + comp: NSTIFFCompression, + aFloat: f32, + ) -> id /* (NSData *) */ { msg_send![self, TIFFRepresentationUsingCompression:comp factor:aFloat] } @@ -3392,9 +3594,14 @@ impl NSImage for id { msg_send![self, cancelIncrementalLoad] } - unsafe fn hitTestRect_withImageDestinationRect_context_hints_flipped_(self, testRectDestSpace: NSRect, - imageRectDestSpace: NSRect, referenceContext: id /* (NSGraphicsContext *) */, - hints: id /* (NSDictionary *) */, flipped: BOOL) -> BOOL { + unsafe fn hitTestRect_withImageDestinationRect_context_hints_flipped_( + self, + testRectDestSpace: NSRect, + imageRectDestSpace: NSRect, + referenceContext: id, /* (NSGraphicsContext *) */ + hints: id, /* (NSDictionary *) */ + flipped: BOOL, + ) -> BOOL { msg_send![self, hitTestRect:testRectDestSpace withImageDestinationRect:imageRectDestSpace context:referenceContext @@ -3407,11 +3614,11 @@ impl NSImage for id { } unsafe fn layerContentsForContentsScale_(self, layerContentsScale: CGFloat) -> id /* (id) */ { - msg_send![self, layerContentsForContentsScale:layerContentsScale] + msg_send![self, layerContentsForContentsScale: layerContentsScale] } unsafe fn recommendedLayerContentsScale_(self, preferredContentsScale: CGFloat) -> CGFloat { - msg_send![self, recommendedLayerContentsScale:preferredContentsScale] + msg_send![self, recommendedLayerContentsScale: preferredContentsScale] } unsafe fn matchesOnlyOnBestFittingAxis(self) -> BOOL { @@ -3420,7 +3627,7 @@ impl NSImage for id { } #[link(name = "AppKit", kind = "framework")] -extern { +extern "C" { // Image hints (NSString* const) pub static NSImageHintCTM: id; pub static NSImageHintInterpolation: id; @@ -3496,20 +3703,20 @@ extern { #[repr(usize)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum NSCompositingOperation { - NSCompositeClear = 0, - NSCompositeCopy = 1, - NSCompositeSourceOver = 2, - NSCompositeSourceIn = 3, - NSCompositeSourceOut = 4, - NSCompositeSourceAtop = 5, - NSCompositeDestinationOver = 6, - NSCompositeDestinationIn = 7, - NSCompositeDestinationOut = 8, - NSCompositeDestinationAtop = 9, - NSCompositeXOR = 10, - NSCompositePlusDarker = 11, - NSCompositeHighlight = 12, - NSCompositePlusLighter = 13 + NSCompositeClear = 0, + NSCompositeCopy = 1, + NSCompositeSourceOver = 2, + NSCompositeSourceIn = 3, + NSCompositeSourceOut = 4, + NSCompositeSourceAtop = 5, + NSCompositeDestinationOver = 6, + NSCompositeDestinationIn = 7, + NSCompositeDestinationOut = 8, + NSCompositeDestinationAtop = 9, + NSCompositeXOR = 10, + NSCompositePlusDarker = 11, + NSCompositeHighlight = 12, + NSCompositePlusLighter = 13, } #[repr(usize)] @@ -3518,7 +3725,7 @@ pub enum NSImageCacheMode { NSImageCacheDefault, NSImageCacheAlways, NSImageCacheBySize, - NSImageCacheNever + NSImageCacheNever, } #[repr(usize)] @@ -3531,7 +3738,7 @@ pub enum NSTIFFCompression { NSTIFFCompressionJPEG = 6, NSTIFFCompressionNEXT = 32766, NSTIFFCompressionPackBits = 32773, - NSTIFFCompressionOldJPEG = 32865 + NSTIFFCompressionOldJPEG = 32865, } #[repr(usize)] @@ -3541,12 +3748,12 @@ pub enum NSImageLoadStatus { NSImageLoadStatusCancelled, NSImageLoadStatusInvalidData, NSImageLoadStatusUnexpectedEOF, - NSImageLoadStatusReadError + NSImageLoadStatusReadError, } pub trait NSSound: Sized { unsafe fn canInitWithPasteboard_(_: Self, pasteboard: id) -> BOOL { - msg_send![class!(NSSound), canInitWithPasteboard:pasteboard] + msg_send![class!(NSSound), canInitWithPasteboard: pasteboard] } unsafe fn initWithContentsOfFile_withReference_(self, filepath: id, byRef: BOOL) -> id; @@ -3566,7 +3773,7 @@ pub trait NSSound: Sized { } unsafe fn soundNamed_(_: Self, soundName: id) -> id { - msg_send![class!(NSSound), soundNamed:soundName] + msg_send![class!(NSSound), soundNamed: soundName] } unsafe fn duration(self) -> NSTimeInterval; @@ -3590,11 +3797,11 @@ impl NSSound for id { } unsafe fn initWithData_(self, audioData: id) -> id { - msg_send![self, initWithData:audioData] + msg_send![self, initWithData: audioData] } unsafe fn initWithPasteboard_(self, pasteboard: id) -> id { - msg_send![self, initWithPasteboard:pasteboard] + msg_send![self, initWithPasteboard: pasteboard] } unsafe fn name(self) -> id { @@ -3646,7 +3853,7 @@ impl NSSound for id { } unsafe fn writeToPasteboard_(self, pasteboard: id) { - msg_send![self, writeToPasteboard:pasteboard] + msg_send![self, writeToPasteboard: pasteboard] } } @@ -3676,7 +3883,7 @@ impl NSStatusItem for id { } unsafe fn setMenu_(self, menu: id) { - msg_send![self, setMenu:menu] + msg_send![self, setMenu: menu] } unsafe fn length(self) -> CGFloat { @@ -3700,11 +3907,11 @@ pub trait NSStatusBar: Sized { impl NSStatusBar for id { unsafe fn statusItemWithLength_(self, length: CGFloat) -> id /* (NSStatusItem *) */ { - msg_send![self, statusItemWithLength:length] + msg_send![self, statusItemWithLength: length] } unsafe fn removeStatusItem_(self, item: id /* (NSStatusItem *) */) { - msg_send![self, removeStatusItem:item] + msg_send![self, removeStatusItem: item] } unsafe fn isVertical(self) -> BOOL { @@ -3712,7 +3919,7 @@ impl NSStatusBar for id { } } -extern { +extern "C" { pub fn NSRectFill(rect: NSRect); } @@ -3727,192 +3934,195 @@ pub trait NSTextField: Sized { impl NSTextField for id { unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { - msg_send![self, initWithFrame:frameRect] + msg_send![self, initWithFrame: frameRect] } unsafe fn setEditable_(self, editable: BOOL) { - msg_send![self, setEditable:editable] + msg_send![self, setEditable: editable] } unsafe fn setStringValue_(self, label: id) { - msg_send![self, setStringValue:label] + msg_send![self, setStringValue: label] } } #[repr(u64)] pub enum NSTabViewType { - NSTopTabsBezelBorder = 0, - NSLeftTabsBezelBorder = 1, - NSBottomTabsBezelBorder = 2, - NSRightTabsBezelBorder = 3, - NSNoTabsBezelBorder = 4, - NSNoTabsLineBorder = 5, - NSNoTabsNoBorder = 6 + NSTopTabsBezelBorder = 0, + NSLeftTabsBezelBorder = 1, + NSBottomTabsBezelBorder = 2, + NSRightTabsBezelBorder = 3, + NSNoTabsBezelBorder = 4, + NSNoTabsLineBorder = 5, + NSNoTabsNoBorder = 6, } pub trait NSTabView: Sized { - unsafe fn new(_: Self) -> id { + unsafe fn new(_: Self) -> id { msg_send![class!(NSTabView), new] } unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; unsafe fn addTabViewItem_(self, tabViewItem: id); - unsafe fn insertTabViewItem_atIndex_(self,tabViewItem:id, index:NSInteger); - unsafe fn removeTabViewItem_(self,tabViewItem:id); - unsafe fn indexOfTabViewItem_(self, tabViewItem:id) -> id; - unsafe fn indexOfTabViewItemWithIdentifier_(self,identifier:id) -> id; + unsafe fn insertTabViewItem_atIndex_(self, tabViewItem: id, index: NSInteger); + unsafe fn removeTabViewItem_(self, tabViewItem: id); + unsafe fn indexOfTabViewItem_(self, tabViewItem: id) -> id; + unsafe fn indexOfTabViewItemWithIdentifier_(self, identifier: id) -> id; unsafe fn numberOfTabViewItems(self) -> id; - unsafe fn tabViewItemAtIndex_(self,index:id) -> id; + unsafe fn tabViewItemAtIndex_(self, index: id) -> id; unsafe fn tabViewItems(self) -> id; - unsafe fn selectFirstTabViewItem_(self,sender:id); - unsafe fn selectLastTabViewItem_(self,sender:id); - unsafe fn selectNextTabViewItem_(self, sender:id); - unsafe fn selectPreviousTabViewItem_(self,sender:id); - unsafe fn selectTabViewItem_(self,tabViewItem:id); - unsafe fn selectTabViewItemAtIndex_(self,index:id); - unsafe fn selectTabViewItemWithIdentifier_(self,identifier:id); + unsafe fn selectFirstTabViewItem_(self, sender: id); + unsafe fn selectLastTabViewItem_(self, sender: id); + unsafe fn selectNextTabViewItem_(self, sender: id); + unsafe fn selectPreviousTabViewItem_(self, sender: id); + unsafe fn selectTabViewItem_(self, tabViewItem: id); + unsafe fn selectTabViewItemAtIndex_(self, index: id); + unsafe fn selectTabViewItemWithIdentifier_(self, identifier: id); unsafe fn selectedTabViewItem(self) -> id; - unsafe fn takeSelectedTabViewItemFromSender_(self,sender:id); + unsafe fn takeSelectedTabViewItemFromSender_(self, sender: id); unsafe fn font(self) -> id; - unsafe fn setFont_(self, font:id); + unsafe fn setFont_(self, font: id); unsafe fn tabViewType(self) -> NSTabViewType; - unsafe fn setTabViewType_(self,tabViewType: NSTabViewType); + unsafe fn setTabViewType_(self, tabViewType: NSTabViewType); unsafe fn controlTint(self) -> id; - unsafe fn setControlTint_(self,controlTint:id); + unsafe fn setControlTint_(self, controlTint: id); unsafe fn drawsBackground(self) -> BOOL; - unsafe fn setDrawsBackground_(self,drawsBackground:BOOL); + unsafe fn setDrawsBackground_(self, drawsBackground: BOOL); unsafe fn minimumSize(self) -> id; unsafe fn contentRect(self) -> id; unsafe fn controlSize(self) -> id; - unsafe fn setControlSize_(self,controlSize:id); + unsafe fn setControlSize_(self, controlSize: id); unsafe fn allowsTruncatedLabels(self) -> BOOL; - unsafe fn setAllowsTruncatedLabels_(self, allowTruncatedLabels:BOOL); - unsafe fn setDelegate_(self, delegate:id); + unsafe fn setAllowsTruncatedLabels_(self, allowTruncatedLabels: BOOL); + unsafe fn setDelegate_(self, delegate: id); unsafe fn delegate(self) -> id; - unsafe fn tabViewAtPoint_(self, point:id) -> id; + unsafe fn tabViewAtPoint_(self, point: id) -> id; } impl NSTabView for id { unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { - msg_send![self, initWithFrame:frameRect] + msg_send![self, initWithFrame: frameRect] } unsafe fn addTabViewItem_(self, tabViewItem: id) { - msg_send![self, addTabViewItem:tabViewItem] + msg_send![self, addTabViewItem: tabViewItem] } - unsafe fn insertTabViewItem_atIndex_(self, tabViewItem: id,index:NSInteger) { + unsafe fn insertTabViewItem_atIndex_(self, tabViewItem: id, index: NSInteger) { msg_send![self, addTabViewItem:tabViewItem atIndex:index] } - unsafe fn removeTabViewItem_(self,tabViewItem:id){ - msg_send![self, removeTabViewItem:tabViewItem] + unsafe fn removeTabViewItem_(self, tabViewItem: id) { + msg_send![self, removeTabViewItem: tabViewItem] } - unsafe fn indexOfTabViewItem_(self, tabViewItem:id) -> id{ - msg_send![self, indexOfTabViewItem:tabViewItem] + unsafe fn indexOfTabViewItem_(self, tabViewItem: id) -> id { + msg_send![self, indexOfTabViewItem: tabViewItem] } - unsafe fn indexOfTabViewItemWithIdentifier_(self,identifier:id) -> id{ - msg_send![self, indexOfTabViewItemWithIdentifier:identifier] + unsafe fn indexOfTabViewItemWithIdentifier_(self, identifier: id) -> id { + msg_send![self, indexOfTabViewItemWithIdentifier: identifier] } - unsafe fn numberOfTabViewItems(self) -> id{ + unsafe fn numberOfTabViewItems(self) -> id { msg_send![self, numberOfTabViewItems] } - unsafe fn tabViewItemAtIndex_(self,index:id)->id{ - msg_send![self, tabViewItemAtIndex:index] + unsafe fn tabViewItemAtIndex_(self, index: id) -> id { + msg_send![self, tabViewItemAtIndex: index] } - unsafe fn tabViewItems(self)->id{ + unsafe fn tabViewItems(self) -> id { msg_send![self, tabViewItems] } - unsafe fn selectFirstTabViewItem_(self,sender:id){ - msg_send![self, selectFirstTabViewItem:sender] + unsafe fn selectFirstTabViewItem_(self, sender: id) { + msg_send![self, selectFirstTabViewItem: sender] } - unsafe fn selectLastTabViewItem_(self,sender:id){ - msg_send![self, selectLastTabViewItem:sender] + unsafe fn selectLastTabViewItem_(self, sender: id) { + msg_send![self, selectLastTabViewItem: sender] } - unsafe fn selectNextTabViewItem_(self, sender:id){ - msg_send![self, selectNextTabViewItem:sender] + unsafe fn selectNextTabViewItem_(self, sender: id) { + msg_send![self, selectNextTabViewItem: sender] } - unsafe fn selectPreviousTabViewItem_(self,sender:id){ - msg_send![self, selectPreviousTabViewItem:sender] + unsafe fn selectPreviousTabViewItem_(self, sender: id) { + msg_send![self, selectPreviousTabViewItem: sender] } - unsafe fn selectTabViewItem_(self,tabViewItem:id){ - msg_send![self, selectTabViewItem:tabViewItem] + unsafe fn selectTabViewItem_(self, tabViewItem: id) { + msg_send![self, selectTabViewItem: tabViewItem] } - unsafe fn selectTabViewItemAtIndex_(self,index:id){ - msg_send![self, selectTabViewItemAtIndex:index] + unsafe fn selectTabViewItemAtIndex_(self, index: id) { + msg_send![self, selectTabViewItemAtIndex: index] } - unsafe fn selectTabViewItemWithIdentifier_(self,identifier:id){ - msg_send![self, selectTabViewItemWithIdentifier:identifier] + unsafe fn selectTabViewItemWithIdentifier_(self, identifier: id) { + msg_send![self, selectTabViewItemWithIdentifier: identifier] } - unsafe fn selectedTabViewItem(self) -> id{ + unsafe fn selectedTabViewItem(self) -> id { msg_send![self, selectedTabViewItem] } - unsafe fn takeSelectedTabViewItemFromSender_(self,sender:id){ - msg_send![self, takeSelectedTabViewItemFromSender:sender] + unsafe fn takeSelectedTabViewItemFromSender_(self, sender: id) { + msg_send![self, takeSelectedTabViewItemFromSender: sender] } - unsafe fn font(self)->id{ + unsafe fn font(self) -> id { msg_send![self, font] } - unsafe fn setFont_(self, font:id){ - msg_send![self, setFont:font] + unsafe fn setFont_(self, font: id) { + msg_send![self, setFont: font] } - unsafe fn tabViewType(self)->NSTabViewType{ + unsafe fn tabViewType(self) -> NSTabViewType { msg_send![self, tabViewType] } - unsafe fn setTabViewType_(self,tabViewType: NSTabViewType){ - msg_send![self, setTabViewType:tabViewType] + unsafe fn setTabViewType_(self, tabViewType: NSTabViewType) { + msg_send![self, setTabViewType: tabViewType] } - unsafe fn controlTint(self) -> id{ + unsafe fn controlTint(self) -> id { msg_send![self, controlTint] } - unsafe fn setControlTint_(self,controlTint:id){ - msg_send![self, setControlTint:controlTint] + unsafe fn setControlTint_(self, controlTint: id) { + msg_send![self, setControlTint: controlTint] } - unsafe fn drawsBackground(self) -> BOOL{ + unsafe fn drawsBackground(self) -> BOOL { msg_send![self, drawsBackground] } - unsafe fn setDrawsBackground_(self,drawsBackground:BOOL){ - msg_send![self, setDrawsBackground:drawsBackground as libc::c_int] + unsafe fn setDrawsBackground_(self, drawsBackground: BOOL) { + msg_send![self, setDrawsBackground: drawsBackground as libc::c_int] } - unsafe fn minimumSize(self) -> id{ + unsafe fn minimumSize(self) -> id { msg_send![self, minimumSize] } - unsafe fn contentRect(self) -> id{ + unsafe fn contentRect(self) -> id { msg_send![self, contentRect] } - unsafe fn controlSize(self) -> id{ + unsafe fn controlSize(self) -> id { msg_send![self, controlSize] } - unsafe fn setControlSize_(self,controlSize:id){ - msg_send![self, setControlSize:controlSize] + unsafe fn setControlSize_(self, controlSize: id) { + msg_send![self, setControlSize: controlSize] } - unsafe fn allowsTruncatedLabels(self) -> BOOL{ + unsafe fn allowsTruncatedLabels(self) -> BOOL { msg_send![self, allowsTruncatedLabels] } - unsafe fn setAllowsTruncatedLabels_(self, allowTruncatedLabels:BOOL){ - msg_send![self, setAllowsTruncatedLabels:allowTruncatedLabels as libc::c_int] + unsafe fn setAllowsTruncatedLabels_(self, allowTruncatedLabels: BOOL) { + msg_send![ + self, + setAllowsTruncatedLabels: allowTruncatedLabels as libc::c_int + ] } - unsafe fn setDelegate_(self, delegate:id){ - msg_send![self, setDelegate:delegate] + unsafe fn setDelegate_(self, delegate: id) { + msg_send![self, setDelegate: delegate] } unsafe fn delegate(self) -> id { msg_send![self, delegate] } - unsafe fn tabViewAtPoint_(self, point:id) -> id{ - msg_send![self, tabViewAtPoint:point] + unsafe fn tabViewAtPoint_(self, point: id) -> id { + msg_send![self, tabViewAtPoint: point] } } @@ -3920,7 +4130,7 @@ impl NSTabView for id { pub enum NSTabState { NSSelectedTab = 0, NSBackgroundTab = 1, - NSPressedTab = 2 + NSPressedTab = 2, } pub trait NSTabViewItem: Sized { @@ -3931,91 +4141,91 @@ pub trait NSTabViewItem: Sized { msg_send![class!(NSTabViewItem), new] } - unsafe fn initWithIdentifier_(self, identifier:id) -> id; - unsafe fn drawLabel_inRect_(self,shouldTruncateLabel:BOOL,labelRect:NSRect); + unsafe fn initWithIdentifier_(self, identifier: id) -> id; + unsafe fn drawLabel_inRect_(self, shouldTruncateLabel: BOOL, labelRect: NSRect); unsafe fn label(self) -> id; - unsafe fn setLabel_(self,label:id); - unsafe fn sizeOfLabel_(self, computeMin:BOOL); + unsafe fn setLabel_(self, label: id); + unsafe fn sizeOfLabel_(self, computeMin: BOOL); unsafe fn tabState(self) -> NSTabState; - unsafe fn identifier(self)-> id; - unsafe fn setIdentifier_(self,identifier:id); - unsafe fn color(self)-> id; - unsafe fn setColor_(self,color:id); + unsafe fn identifier(self) -> id; + unsafe fn setIdentifier_(self, identifier: id); + unsafe fn color(self) -> id; + unsafe fn setColor_(self, color: id); unsafe fn view(self) -> id; - unsafe fn setView_(self, view:id); - unsafe fn initialFirstResponder(self)->id; - unsafe fn setInitialFirstResponder_(self,initialFirstResponder:id); + unsafe fn setView_(self, view: id); + unsafe fn initialFirstResponder(self) -> id; + unsafe fn setInitialFirstResponder_(self, initialFirstResponder: id); unsafe fn tabView(self) -> id; unsafe fn tooltip(self) -> id; - unsafe fn setTooltip_(self,toolTip:id); + unsafe fn setTooltip_(self, toolTip: id); } impl NSTabViewItem for id { unsafe fn initWithIdentifier_(self, identifier: id) -> id { - msg_send![self, initWithIdentifier:identifier] + msg_send![self, initWithIdentifier: identifier] } - unsafe fn drawLabel_inRect_(self, shouldTruncateLabel:BOOL,labelRect:NSRect){ + unsafe fn drawLabel_inRect_(self, shouldTruncateLabel: BOOL, labelRect: NSRect) { msg_send![self, drawLabel:shouldTruncateLabel as libc::c_int inRect:labelRect] } - unsafe fn label(self)->id{ + unsafe fn label(self) -> id { msg_send![self, label] } - unsafe fn setLabel_(self,label : id){ - msg_send![self, setLabel:label] + unsafe fn setLabel_(self, label: id) { + msg_send![self, setLabel: label] } - unsafe fn sizeOfLabel_(self,computeMin:BOOL){ - msg_send![self, sizeOfLabel:computeMin as libc::c_int] + unsafe fn sizeOfLabel_(self, computeMin: BOOL) { + msg_send![self, sizeOfLabel: computeMin as libc::c_int] } - unsafe fn tabState(self) -> NSTabState{ + unsafe fn tabState(self) -> NSTabState { msg_send![self, tabState] } - unsafe fn identifier(self)-> id { + unsafe fn identifier(self) -> id { msg_send![self, identifier] } - unsafe fn setIdentifier_(self,identifier:id){ - msg_send![self, identifier:identifier] + unsafe fn setIdentifier_(self, identifier: id) { + msg_send![self, identifier: identifier] } - unsafe fn color(self)-> id{ + unsafe fn color(self) -> id { msg_send![self, color] } - unsafe fn setColor_(self,color:id){ - msg_send![self, color:color] + unsafe fn setColor_(self, color: id) { + msg_send![self, color: color] } unsafe fn view(self) -> id { msg_send![self, view] } - unsafe fn setView_(self, view:id){ - msg_send![self, setView:view] + unsafe fn setView_(self, view: id) { + msg_send![self, setView: view] } - unsafe fn initialFirstResponder(self)->id{ + unsafe fn initialFirstResponder(self) -> id { msg_send![self, initialFirstResponder] } - unsafe fn setInitialFirstResponder_(self,initialFirstResponder:id){ - msg_send![self, setInitialFirstResponder:initialFirstResponder] + unsafe fn setInitialFirstResponder_(self, initialFirstResponder: id) { + msg_send![self, setInitialFirstResponder: initialFirstResponder] } - unsafe fn tabView(self) -> id{ + unsafe fn tabView(self) -> id { msg_send![self, tabView] } - unsafe fn tooltip(self) -> id{ + unsafe fn tooltip(self) -> id { msg_send![self, tooltip] } - unsafe fn setTooltip_(self,toolTip:id){ - msg_send![self, setTooltip:toolTip] + unsafe fn setTooltip_(self, toolTip: id) { + msg_send![self, setTooltip: toolTip] } } @@ -4025,7 +4235,7 @@ pub trait NSLayoutConstraint: Sized { impl NSLayoutConstraint for id { unsafe fn activateConstraints(_: Self, constraints: id) -> id { - msg_send![class!(NSLayoutConstraint), activateConstraints:constraints] + msg_send![class!(NSLayoutConstraint), activateConstraints: constraints] } } @@ -4037,74 +4247,77 @@ pub trait NSLayoutDimension: Sized { impl NSLayoutDimension for id { unsafe fn constraintEqualToConstant(self, c: CGFloat) -> id { - msg_send![self, constraintEqualToConstant:c] + msg_send![self, constraintEqualToConstant: c] } unsafe fn constraintLessThanOrEqualToConstant(self, c: CGFloat) -> id { - msg_send![self, constraintLessThanOrEqualToConstant:c] + msg_send![self, constraintLessThanOrEqualToConstant: c] } unsafe fn constraintGreaterThanOrEqualToConstant(self, c: CGFloat) -> id { - msg_send![self, constraintGreaterThanOrEqualToConstant:c] + msg_send![self, constraintGreaterThanOrEqualToConstant: c] } } pub trait NSColorSpace: Sized { - unsafe fn deviceRGBColorSpace(_:Self) -> id; - unsafe fn genericRGBColorSpace(_:Self) -> id; - unsafe fn deviceCMYKColorSpace(_:Self) -> id; - unsafe fn genericCMYKColorSpace(_:Self) -> id; - unsafe fn deviceGrayColorSpace(_:Self) -> id; - unsafe fn genericGrayColorSpace(_:Self) -> id; - unsafe fn sRGBColorSpace(_:Self) -> id; - unsafe fn extendedSRGBColorSpace(_:Self) -> id; - unsafe fn displayP3ColorSpace(_:Self) -> id; - unsafe fn genericGamma22GrayColorSpace(_:Self) -> id; - unsafe fn extendedGenericGamma22GrayColorSpace(_:Self) -> id; - unsafe fn adobeRGB1998ColorSpace(_:Self) -> id; + unsafe fn deviceRGBColorSpace(_: Self) -> id; + unsafe fn genericRGBColorSpace(_: Self) -> id; + unsafe fn deviceCMYKColorSpace(_: Self) -> id; + unsafe fn genericCMYKColorSpace(_: Self) -> id; + unsafe fn deviceGrayColorSpace(_: Self) -> id; + unsafe fn genericGrayColorSpace(_: Self) -> id; + unsafe fn sRGBColorSpace(_: Self) -> id; + unsafe fn extendedSRGBColorSpace(_: Self) -> id; + unsafe fn displayP3ColorSpace(_: Self) -> id; + unsafe fn genericGamma22GrayColorSpace(_: Self) -> id; + unsafe fn extendedGenericGamma22GrayColorSpace(_: Self) -> id; + unsafe fn adobeRGB1998ColorSpace(_: Self) -> id; unsafe fn alloc(_: Self) -> id; - unsafe fn initWithCGColorSpace_(self, cg_color_space: *const c_void /* (CGColorSpaceRef) */) -> id; + unsafe fn initWithCGColorSpace_( + self, + cg_color_space: *const c_void, /* (CGColorSpaceRef) */ + ) -> id; unsafe fn CGColorSpace(self) -> *const c_void /* (CGColorSpaceRef) */; unsafe fn localizedName(self) -> id; } impl NSColorSpace for id { - unsafe fn deviceRGBColorSpace(_:Self) -> id { + unsafe fn deviceRGBColorSpace(_: Self) -> id { msg_send![class!(NSColorSpace), deviceRGBColorSpace] } - unsafe fn genericRGBColorSpace(_:Self) -> id { + unsafe fn genericRGBColorSpace(_: Self) -> id { msg_send![class!(NSColorSpace), genericRGBColorSpace] } - unsafe fn deviceCMYKColorSpace(_:Self) -> id { + unsafe fn deviceCMYKColorSpace(_: Self) -> id { msg_send![class!(NSColorSpace), deviceCMYKColorSpace] } - unsafe fn genericCMYKColorSpace(_:Self) -> id { + unsafe fn genericCMYKColorSpace(_: Self) -> id { msg_send![class!(NSColorSpace), genericCMYKColorSpace] } - unsafe fn deviceGrayColorSpace(_:Self) -> id { + unsafe fn deviceGrayColorSpace(_: Self) -> id { msg_send![class!(NSColorSpace), deviceGrayColorSpace] } - unsafe fn genericGrayColorSpace(_:Self) -> id { + unsafe fn genericGrayColorSpace(_: Self) -> id { msg_send![class!(NSColorSpace), genericGrayColorSpace] } - unsafe fn sRGBColorSpace(_:Self) -> id { + unsafe fn sRGBColorSpace(_: Self) -> id { msg_send![class!(NSColorSpace), sRGBColorSpace] } - unsafe fn extendedSRGBColorSpace(_:Self) -> id { + unsafe fn extendedSRGBColorSpace(_: Self) -> id { msg_send![class!(NSColorSpace), extendedSRGBColorSpace] } - unsafe fn displayP3ColorSpace(_:Self) -> id { + unsafe fn displayP3ColorSpace(_: Self) -> id { msg_send![class!(NSColorSpace), displayP3ColorSpace] } - unsafe fn genericGamma22GrayColorSpace(_:Self) -> id { + unsafe fn genericGamma22GrayColorSpace(_: Self) -> id { msg_send![class!(NSColorSpace), genericGamma22GrayColorSpace] } - unsafe fn extendedGenericGamma22GrayColorSpace(_:Self) -> id { + unsafe fn extendedGenericGamma22GrayColorSpace(_: Self) -> id { msg_send![class!(NSColorSpace), extendedGenericGamma22GrayColorSpace] } - unsafe fn adobeRGB1998ColorSpace(_:Self) -> id { + unsafe fn adobeRGB1998ColorSpace(_: Self) -> id { msg_send![class!(NSColorSpace), adobeRGB1998ColorSpace] } @@ -4112,8 +4325,11 @@ impl NSColorSpace for id { msg_send![class!(NSColorSpace), alloc] } - unsafe fn initWithCGColorSpace_(self, cg_color_space: *const c_void /* (CGColorSpaceRef) */) -> id { - msg_send![self, initWithCGColorSpace:cg_color_space] + unsafe fn initWithCGColorSpace_( + self, + cg_color_space: *const c_void, /* (CGColorSpaceRef) */ + ) -> id { + msg_send![self, initWithCGColorSpace: cg_color_space] } unsafe fn CGColorSpace(self) -> *const c_void /* (CGColorSpaceRef) */ { msg_send![self, CGColorSpace] @@ -4125,11 +4341,41 @@ impl NSColorSpace for id { pub trait NSColor: Sized { unsafe fn clearColor(_: Self) -> id; - unsafe fn colorWithRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; - unsafe fn colorWithSRGBRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; - unsafe fn colorWithDeviceRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; - unsafe fn colorWithDisplayP3Red_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; - unsafe fn colorWithCalibratedRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; + unsafe fn colorWithRed_green_blue_alpha_( + _: Self, + r: CGFloat, + g: CGFloat, + b: CGFloat, + a: CGFloat, + ) -> id; + unsafe fn colorWithSRGBRed_green_blue_alpha_( + _: Self, + r: CGFloat, + g: CGFloat, + b: CGFloat, + a: CGFloat, + ) -> id; + unsafe fn colorWithDeviceRed_green_blue_alpha_( + _: Self, + r: CGFloat, + g: CGFloat, + b: CGFloat, + a: CGFloat, + ) -> id; + unsafe fn colorWithDisplayP3Red_green_blue_alpha_( + _: Self, + r: CGFloat, + g: CGFloat, + b: CGFloat, + a: CGFloat, + ) -> id; + unsafe fn colorWithCalibratedRed_green_blue_alpha_( + _: Self, + r: CGFloat, + g: CGFloat, + b: CGFloat, + a: CGFloat, + ) -> id; unsafe fn colorUsingColorSpace_(self, color_space: id) -> id; @@ -4151,24 +4397,54 @@ impl NSColor for id { unsafe fn clearColor(_: Self) -> id { msg_send![class!(NSColor), clearColor] } - unsafe fn colorWithRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + unsafe fn colorWithRed_green_blue_alpha_( + _: Self, + r: CGFloat, + g: CGFloat, + b: CGFloat, + a: CGFloat, + ) -> id { msg_send![class!(NSColor), colorWithRed:r green:g blue:b alpha:a] } - unsafe fn colorWithSRGBRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + unsafe fn colorWithSRGBRed_green_blue_alpha_( + _: Self, + r: CGFloat, + g: CGFloat, + b: CGFloat, + a: CGFloat, + ) -> id { msg_send![class!(NSColor), colorWithSRGBRed:r green:g blue:b alpha:a] } - unsafe fn colorWithDeviceRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + unsafe fn colorWithDeviceRed_green_blue_alpha_( + _: Self, + r: CGFloat, + g: CGFloat, + b: CGFloat, + a: CGFloat, + ) -> id { msg_send![class!(NSColor), colorWithDeviceRed:r green:g blue:b alpha:a] } - unsafe fn colorWithDisplayP3Red_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + unsafe fn colorWithDisplayP3Red_green_blue_alpha_( + _: Self, + r: CGFloat, + g: CGFloat, + b: CGFloat, + a: CGFloat, + ) -> id { msg_send![class!(NSColor), colorWithDisplayP3Red:r green:g blue:b alpha:a] } - unsafe fn colorWithCalibratedRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + unsafe fn colorWithCalibratedRed_green_blue_alpha_( + _: Self, + r: CGFloat, + g: CGFloat, + b: CGFloat, + a: CGFloat, + ) -> id { msg_send![class!(NSColor), colorWithCalibratedRed:r green:g blue:b alpha:a] } unsafe fn colorUsingColorSpace_(self, color_space: id) -> id { - msg_send![self, colorUsingColorSpace:color_space] + msg_send![self, colorUsingColorSpace: color_space] } unsafe fn alphaComponent(self) -> CGFloat { @@ -4227,7 +4503,7 @@ impl NSToolbar for id { } unsafe fn initWithIdentifier_(self, identifier: id) -> id /* NSToolbar */ { - msg_send![self, initWithIdentifier:identifier] + msg_send![self, initWithIdentifier: identifier] } unsafe fn showsBaselineSeparator(self) -> BOOL { @@ -4235,22 +4511,25 @@ impl NSToolbar for id { } unsafe fn setShowsBaselineSeparator_(self, value: BOOL) { - msg_send![self, setShowsBaselineSeparator:value] + msg_send![self, setShowsBaselineSeparator: value] } } -pub trait NSSpellChecker : Sized { +pub trait NSSpellChecker: Sized { unsafe fn sharedSpellChecker(_: Self) -> id; - unsafe fn checkSpellingOfString_startingAt(self, - stringToCheck: id, - startingOffset: NSInteger) -> NSRange; + unsafe fn checkSpellingOfString_startingAt( + self, + stringToCheck: id, + startingOffset: NSInteger, + ) -> NSRange; unsafe fn checkSpellingOfString_startingAt_language_wrap_inSpellDocumentWithTag_wordCount( self, stringToCheck: id, startingOffset: NSInteger, language: id, wrapFlag: BOOL, - tag: NSInteger) -> (NSRange, NSInteger); + tag: NSInteger, + ) -> (NSRange, NSInteger); unsafe fn uniqueSpellDocumentTag(_: Self) -> NSInteger; unsafe fn closeSpellDocumentWithTag(self, tag: NSInteger); unsafe fn ignoreWord_inSpellDocumentWithTag(self, wordToIgnore: id, tag: NSInteger); @@ -4261,9 +4540,11 @@ impl NSSpellChecker for id { msg_send![class!(NSSpellChecker), sharedSpellChecker] } - unsafe fn checkSpellingOfString_startingAt(self, - stringToCheck: id, - startingOffset: NSInteger) -> NSRange { + unsafe fn checkSpellingOfString_startingAt( + self, + stringToCheck: id, + startingOffset: NSInteger, + ) -> NSRange { msg_send![self, checkSpellingOfString:stringToCheck startingAt:startingOffset] } @@ -4273,7 +4554,8 @@ impl NSSpellChecker for id { startingOffset: NSInteger, language: id, wrapFlag: BOOL, - tag: NSInteger) -> (NSRange, NSInteger) { + tag: NSInteger, + ) -> (NSRange, NSInteger) { let mut wordCount = 0; let range = msg_send![self, checkSpellingOfString:stringToCheck @@ -4291,7 +4573,7 @@ impl NSSpellChecker for id { } unsafe fn closeSpellDocumentWithTag(self, tag: NSInteger) { - msg_send![self, closeSpellDocumentWithTag:tag] + msg_send![self, closeSpellDocumentWithTag: tag] } unsafe fn ignoreWord_inSpellDocumentWithTag(self, wordToIgnore: id, tag: NSInteger) { diff --git a/cocoa/src/base.rs b/cocoa/src/base.rs index 39a0406a8..d1a6f892a 100644 --- a/cocoa/src/base.rs +++ b/cocoa/src/base.rs @@ -7,5 +7,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - pub use cocoa_foundation::base::*; diff --git a/cocoa/src/lib.rs b/cocoa/src/lib.rs index afc053a7d..0d75b7622 100644 --- a/cocoa/src/lib.rs +++ b/cocoa/src/lib.rs @@ -9,15 +9,14 @@ #![crate_name = "cocoa"] #![crate_type = "rlib"] - #![allow(non_snake_case)] extern crate block; #[macro_use] extern crate bitflags; +extern crate cocoa_foundation; extern crate core_foundation; extern crate core_graphics; -extern crate cocoa_foundation; extern crate foreign_types; extern crate libc; #[macro_use] diff --git a/cocoa/src/quartzcore.rs b/cocoa/src/quartzcore.rs index 5a63f4acd..5f4c6da28 100644 --- a/cocoa/src/quartzcore.rs +++ b/cocoa/src/quartzcore.rs @@ -25,15 +25,13 @@ use std::ops::Mul; use std::ptr; use appkit::CGLContextObj; -use base::{BOOL, id, nil, YES}; +use base::{id, nil, BOOL, YES}; use foundation::NSUInteger; // CABase.h pub fn current_media_time() -> CFTimeInterval { - unsafe { - CACurrentMediaTime() - } + unsafe { CACurrentMediaTime() } } // CALayer.h @@ -46,18 +44,14 @@ unsafe impl Sync for CALayer {} impl Clone for CALayer { #[inline] fn clone(&self) -> CALayer { - unsafe { - CALayer(msg_send![self.id(), retain]) - } + unsafe { CALayer(msg_send![self.id(), retain]) } } } impl Drop for CALayer { #[inline] fn drop(&mut self) { - unsafe { - msg_send![self.id(), release] - } + unsafe { msg_send![self.id(), release] } } } @@ -69,9 +63,7 @@ impl CALayer { #[inline] pub fn new() -> CALayer { - unsafe { - CALayer(msg_send![class!(CALayer), layer]) - } + unsafe { CALayer(msg_send![class!(CALayer), layer]) } } #[inline] @@ -84,23 +76,17 @@ impl CALayer { #[inline] pub fn presentation_layer(&self) -> CALayer { - unsafe { - CALayer(msg_send![self.id(), presentationLayer]) - } + unsafe { CALayer(msg_send![self.id(), presentationLayer]) } } #[inline] pub fn model_layer(&self) -> CALayer { - unsafe { - CALayer(msg_send![self.id(), modelLayer]) - } + unsafe { CALayer(msg_send![self.id(), modelLayer]) } } #[inline] pub fn default_value_for_key(key: &CFString) -> id { - unsafe { - msg_send![class!(CALayer), defaultValueForKey:(key.as_CFTypeRef())] - } + unsafe { msg_send![class!(CALayer), defaultValueForKey:(key.as_CFTypeRef())] } } #[inline] @@ -114,121 +100,90 @@ impl CALayer { #[inline] pub fn should_archive_value_for_key(key: &CFString) -> bool { unsafe { - let flag: BOOL = msg_send![class!(CALayer), shouldArchiveValueForKey:(key.as_CFTypeRef())]; + let flag: BOOL = + msg_send![class!(CALayer), shouldArchiveValueForKey:(key.as_CFTypeRef())]; flag == YES } } #[inline] pub fn bounds(&self) -> CGRect { - unsafe { - msg_send![self.id(), bounds] - } + unsafe { msg_send![self.id(), bounds] } } #[inline] pub fn set_bounds(&self, bounds: &CGRect) { - unsafe { - msg_send![self.id(), setBounds:*bounds] - } + unsafe { msg_send![self.id(), setBounds:*bounds] } } #[inline] pub fn position(&self) -> CGPoint { - unsafe { - msg_send![self.id(), position] - } + unsafe { msg_send![self.id(), position] } } #[inline] pub fn set_position(&self, position: &CGPoint) { - unsafe { - msg_send![self.id(), setPosition:*position] - } + unsafe { msg_send![self.id(), setPosition:*position] } } #[inline] pub fn z_position(&self) -> CGFloat { - unsafe { - msg_send![self.id(), zPosition] - } + unsafe { msg_send![self.id(), zPosition] } } #[inline] pub fn set_z_position(&self, z_position: CGFloat) { - unsafe { - msg_send![self.id(), setZPosition:z_position] - } + unsafe { msg_send![self.id(), setZPosition: z_position] } } #[inline] pub fn anchor_point(&self) -> CGPoint { - unsafe { - msg_send![self.id(), anchorPoint] - } + unsafe { msg_send![self.id(), anchorPoint] } } #[inline] pub fn set_anchor_point(&self, anchor_point: &CGPoint) { - unsafe { - msg_send![self.id(), setAnchorPoint:*anchor_point] - } + unsafe { msg_send![self.id(), setAnchorPoint:*anchor_point] } } #[inline] pub fn anchor_point_z(&self) -> CGFloat { - unsafe { - msg_send![self.id(), anchorPointZ] - } + unsafe { msg_send![self.id(), anchorPointZ] } } #[inline] pub fn set_anchor_point_z(&self, anchor_point_z: CGFloat) { - unsafe { - msg_send![self.id(), setAnchorPointZ:anchor_point_z] - } + unsafe { msg_send![self.id(), setAnchorPointZ: anchor_point_z] } } #[inline] pub fn transform(&self) -> CATransform3D { - unsafe { - msg_send![self.id(), transform] - } + unsafe { msg_send![self.id(), transform] } } #[inline] pub fn set_transform(&self, transform: &CATransform3D) { - unsafe { - msg_send![self.id(), setTransform:*transform] - } + unsafe { msg_send![self.id(), setTransform:*transform] } } #[inline] pub fn affine_transform(&self) -> CGAffineTransform { - unsafe { - msg_send![self.id(), affineTransform] - } + unsafe { msg_send![self.id(), affineTransform] } } #[inline] pub fn set_affine_transform(&self, affine_transform: &CGAffineTransform) { - unsafe { - msg_send![self.id(), setAffineTransform:*affine_transform] - } + unsafe { msg_send![self.id(), setAffineTransform:*affine_transform] } } #[inline] pub fn frame(&self) -> CGRect { - unsafe { - msg_send![self.id(), frame] - } + unsafe { msg_send![self.id(), frame] } } #[inline] pub fn set_frame(&self, frame: &CGRect) { - unsafe { - msg_send![self.id(), setFrame:*frame] - } + unsafe { msg_send![self.id(), setFrame:*frame] } } #[inline] @@ -241,9 +196,7 @@ impl CALayer { #[inline] pub fn set_hidden(&self, hidden: bool) { - unsafe { - msg_send![self.id(), setHidden:hidden as BOOL] - } + unsafe { msg_send![self.id(), setHidden: hidden as BOOL] } } #[inline] @@ -256,9 +209,7 @@ impl CALayer { #[inline] pub fn set_double_sided(&self, double_sided: bool) { - unsafe { - msg_send![self.id(), setDoubleSided:double_sided as BOOL] - } + unsafe { msg_send![self.id(), setDoubleSided: double_sided as BOOL] } } #[inline] @@ -271,9 +222,7 @@ impl CALayer { #[inline] pub fn set_geometry_flipped(&self, geometry_flipped: bool) { - unsafe { - msg_send![self.id(), setGeometryFlipped:geometry_flipped as BOOL] - } + unsafe { msg_send![self.id(), setGeometryFlipped: geometry_flipped as BOOL] } } #[inline] @@ -298,9 +247,7 @@ impl CALayer { #[inline] pub fn remove_from_superlayer(&self) { - unsafe { - msg_send![self.id(), removeFromSuperlayer] - } + unsafe { msg_send![self.id(), removeFromSuperlayer] } } #[inline] @@ -313,51 +260,37 @@ impl CALayer { #[inline] pub fn add_sublayer(&self, sublayer: &CALayer) { - unsafe { - msg_send![self.id(), addSublayer:sublayer.id()] - } + unsafe { msg_send![self.id(), addSublayer:sublayer.id()] } } #[inline] pub fn insert_sublayer_at_index(&self, sublayer: &CALayer, index: u32) { - unsafe { - msg_send![self.id(), insertSublayer:sublayer.id() atIndex:index] - } + unsafe { msg_send![self.id(), insertSublayer:sublayer.id() atIndex:index] } } #[inline] pub fn insert_sublayer_below(&self, sublayer: &CALayer, sibling: &CALayer) { - unsafe { - msg_send![self.id(), insertSublayer:sublayer.id() below:sibling.id()] - } + unsafe { msg_send![self.id(), insertSublayer:sublayer.id() below:sibling.id()] } } #[inline] pub fn insert_sublayer_above(&self, sublayer: &CALayer, sibling: &CALayer) { - unsafe { - msg_send![self.id(), insertSublayer:sublayer.id() above:sibling.id()] - } + unsafe { msg_send![self.id(), insertSublayer:sublayer.id() above:sibling.id()] } } #[inline] pub fn replace_sublayer_with(&self, old_layer: &CALayer, new_layer: &CALayer) { - unsafe { - msg_send![self.id(), replaceSublayer:old_layer.id() with:new_layer.id()] - } + unsafe { msg_send![self.id(), replaceSublayer:old_layer.id() with:new_layer.id()] } } #[inline] pub fn sublayer_transform(&self) -> CATransform3D { - unsafe { - msg_send![self.id(), sublayerTransform] - } + unsafe { msg_send![self.id(), sublayerTransform] } } #[inline] pub fn set_sublayer_transform(&self, sublayer_transform: CATransform3D) { - unsafe { - msg_send![self.id(), setSublayerTransform:sublayer_transform] - } + unsafe { msg_send![self.id(), setSublayerTransform: sublayer_transform] } } #[inline] @@ -376,7 +309,7 @@ impl CALayer { pub fn set_mask(&self, mask: Option) { unsafe { match mask { - None => msg_send![self.id(), setMask:nil], + None => msg_send![self.id(), setMask: nil], Some(mask) => msg_send![self.id(), setMask:(mask.id())], } } @@ -392,9 +325,7 @@ impl CALayer { #[inline] pub fn set_masks_to_bounds(&self, flag: bool) { - unsafe { - msg_send![self.id(), setMasksToBounds:flag as BOOL] - } + unsafe { msg_send![self.id(), setMasksToBounds: flag as BOOL] } } #[inline] @@ -442,8 +373,11 @@ impl CALayer { } #[inline] - pub fn convert_time_from_layer(&self, time: CFTimeInterval, layer: Option) - -> CFTimeInterval { + pub fn convert_time_from_layer( + &self, + time: CFTimeInterval, + layer: Option, + ) -> CFTimeInterval { unsafe { let layer = match layer { None => nil, @@ -454,8 +388,11 @@ impl CALayer { } #[inline] - pub fn convert_time_to_layer(&self, time: CFTimeInterval, layer: Option) - -> CFTimeInterval { + pub fn convert_time_to_layer( + &self, + time: CFTimeInterval, + layer: Option, + ) -> CFTimeInterval { unsafe { let layer = match layer { None => nil, @@ -487,28 +424,22 @@ impl CALayer { #[inline] pub fn contents(&self) -> id { - unsafe { - msg_send![self.id(), contents] - } + unsafe { msg_send![self.id(), contents] } } #[inline] pub unsafe fn set_contents(&self, contents: id) { - msg_send![self.id(), setContents:contents] + msg_send![self.id(), setContents: contents] } #[inline] pub fn contents_rect(&self) -> CGRect { - unsafe { - msg_send![self.id(), contentsRect] - } + unsafe { msg_send![self.id(), contentsRect] } } #[inline] pub fn set_contents_rect(&self, contents_rect: &CGRect) { - unsafe { - msg_send![self.id(), setContentsRect:*contents_rect] - } + unsafe { msg_send![self.id(), setContentsRect:*contents_rect] } } #[inline] @@ -529,30 +460,22 @@ impl CALayer { #[inline] pub fn contents_scale(&self) -> CGFloat { - unsafe { - msg_send![self.id(), contentsScale] - } + unsafe { msg_send![self.id(), contentsScale] } } #[inline] pub fn set_contents_scale(&self, new_contents_scale: CGFloat) { - unsafe { - msg_send![self.id(), setContentsScale:new_contents_scale] - } + unsafe { msg_send![self.id(), setContentsScale: new_contents_scale] } } #[inline] pub fn contents_center(&self) -> CGRect { - unsafe { - msg_send![self.id(), contentsCenter] - } + unsafe { msg_send![self.id(), contentsCenter] } } #[inline] pub fn set_contents_center(&self, new_rect: &CGRect) { - unsafe { - msg_send![self.id(), setContentsCenter:*new_rect] - } + unsafe { msg_send![self.id(), setContentsCenter:*new_rect] } } #[inline] @@ -605,16 +528,12 @@ impl CALayer { #[inline] pub fn minification_filter_bias(&self) -> f32 { - unsafe { - msg_send![self.id(), minificationFilterBias] - } + unsafe { msg_send![self.id(), minificationFilterBias] } } #[inline] pub fn set_minification_filter_bias(&self, new_filter_bias: f32) { - unsafe { - msg_send![self.id(), setMinificationFilterBias:new_filter_bias] - } + unsafe { msg_send![self.id(), setMinificationFilterBias: new_filter_bias] } } #[inline] @@ -627,30 +546,22 @@ impl CALayer { #[inline] pub fn set_opaque(&self, opaque: bool) { - unsafe { - msg_send![self.id(), setOpaque:opaque as BOOL] - } + unsafe { msg_send![self.id(), setOpaque: opaque as BOOL] } } #[inline] pub fn display(&self) { - unsafe { - msg_send![self.id(), display] - } + unsafe { msg_send![self.id(), display] } } #[inline] pub fn set_needs_display(&self) { - unsafe { - msg_send![self.id(), setNeedsDisplay] - } + unsafe { msg_send![self.id(), setNeedsDisplay] } } #[inline] pub fn set_needs_display_in_rect(&self, rect: &CGRect) { - unsafe { - msg_send![self.id(), setNeedsDisplayInRect:*rect] - } + unsafe { msg_send![self.id(), setNeedsDisplayInRect:*rect] } } #[inline] @@ -663,9 +574,7 @@ impl CALayer { #[inline] pub fn display_if_needed(&self) { - unsafe { - msg_send![self.id(), displayIfNeeded] - } + unsafe { msg_send![self.id(), displayIfNeeded] } } #[inline] @@ -678,9 +587,7 @@ impl CALayer { #[inline] pub fn set_needs_display_on_bounds_change(&self, flag: bool) { - unsafe { - msg_send![self.id(), setNeedsDisplayOnBoundsChange:flag as BOOL] - } + unsafe { msg_send![self.id(), setNeedsDisplayOnBoundsChange: flag as BOOL] } } #[inline] @@ -693,23 +600,17 @@ impl CALayer { #[inline] pub fn set_draws_asynchronously(&self, flag: bool) { - unsafe { - msg_send![self.id(), setDrawsAsynchronously:flag as BOOL] - } + unsafe { msg_send![self.id(), setDrawsAsynchronously: flag as BOOL] } } #[inline] pub fn draw_in_context(&self, context: &CGContext) { - unsafe { - msg_send![self.id(), drawInContext:(*context).as_ptr()] - } + unsafe { msg_send![self.id(), drawInContext:(*context).as_ptr()] } } #[inline] pub fn render_in_context(&self, context: &CGContext) { - unsafe { - msg_send![self.id(), renderInContext:(*context).as_ptr()] - } + unsafe { msg_send![self.id(), renderInContext:(*context).as_ptr()] } } #[inline] @@ -721,9 +622,7 @@ impl CALayer { #[inline] pub fn set_edge_antialiasing_mask(&self, mask: EdgeAntialiasingMask) { - unsafe { - msg_send![self.id(), setEdgeAntialiasingMask:mask.bits()] - } + unsafe { msg_send![self.id(), setEdgeAntialiasingMask:mask.bits()] } } #[inline] @@ -745,50 +644,38 @@ impl CALayer { None => ptr::null(), Some(color) => color.as_CFTypeRef(), }; - msg_send![self.id(), setBackgroundColor:color] + msg_send![self.id(), setBackgroundColor: color] } } #[inline] pub fn corner_radius(&self) -> CGFloat { - unsafe { - msg_send![self.id(), cornerRadius] - } + unsafe { msg_send![self.id(), cornerRadius] } } #[inline] pub fn set_corner_radius(&self, radius: CGFloat) { - unsafe { - msg_send![self.id(), setCornerRadius:radius] - } + unsafe { msg_send![self.id(), setCornerRadius: radius] } } #[inline] pub fn masked_corners(&self) -> CornerMask { - unsafe { - CornerMask::from_bits_truncate(msg_send![self.id(), maskedCorners]) - } + unsafe { CornerMask::from_bits_truncate(msg_send![self.id(), maskedCorners]) } } #[inline] pub fn set_masked_corners(&self, mask: CornerMask) { - unsafe { - msg_send![self.id(), setCornerMask:mask.bits()] - } + unsafe { msg_send![self.id(), setCornerMask:mask.bits()] } } #[inline] pub fn border_width(&self) -> CGFloat { - unsafe { - msg_send![self.id(), borderWidth] - } + unsafe { msg_send![self.id(), borderWidth] } } #[inline] pub fn set_border_width(&self, border_width: CGFloat) { - unsafe { - msg_send![self.id(), setBorderWidth:border_width] - } + unsafe { msg_send![self.id(), setBorderWidth: border_width] } } #[inline] @@ -810,34 +697,28 @@ impl CALayer { None => ptr::null(), Some(color) => color.as_CFTypeRef(), }; - msg_send![self.id(), setBorderColor:color] + msg_send![self.id(), setBorderColor: color] } } #[inline] pub fn opacity(&self) -> f32 { - unsafe { - msg_send![self.id(), opacity] - } + unsafe { msg_send![self.id(), opacity] } } #[inline] pub fn set_opacity(&self, opacity: f32) { - unsafe { - msg_send![self.id(), setOpacity:opacity] - } + unsafe { msg_send![self.id(), setOpacity: opacity] } } #[inline] pub fn compositing_filter(&self) -> id { - unsafe { - msg_send![self.id(), compositingFilter] - } + unsafe { msg_send![self.id(), compositingFilter] } } #[inline] pub unsafe fn set_compositing_filter(&self, filter: id) { - msg_send![self.id(), setCompositingFilter:filter] + msg_send![self.id(), setCompositingFilter: filter] } #[inline] @@ -856,7 +737,7 @@ impl CALayer { Some(ref filters) => filters.as_CFTypeRef(), None => ptr::null(), }; - msg_send![self.id(), setFilters:filters] + msg_send![self.id(), setFilters: filters] } #[inline] @@ -875,7 +756,7 @@ impl CALayer { Some(ref filters) => filters.as_CFTypeRef(), None => ptr::null(), }; - msg_send![self.id(), setBackgroundFilters:filters] + msg_send![self.id(), setBackgroundFilters: filters] } #[inline] @@ -888,23 +769,17 @@ impl CALayer { #[inline] pub fn set_should_rasterize(&self, flag: bool) { - unsafe { - msg_send![self.id(), setShouldRasterize:(flag as BOOL)] - } + unsafe { msg_send![self.id(), setShouldRasterize:(flag as BOOL)] } } #[inline] pub fn rasterization_scale(&self) -> CGFloat { - unsafe { - msg_send![self.id(), rasterizationScale] - } + unsafe { msg_send![self.id(), rasterizationScale] } } #[inline] pub fn set_rasterization_scale(&self, scale: CGFloat) { - unsafe { - msg_send![self.id(), setRasterizationScale:scale] - } + unsafe { msg_send![self.id(), setRasterizationScale: scale] } } // Shadow properties @@ -928,50 +803,38 @@ impl CALayer { None => ptr::null(), Some(color) => color.as_CFTypeRef(), }; - msg_send![self.id(), setShadowColor:color] + msg_send![self.id(), setShadowColor: color] } } #[inline] pub fn shadow_opacity(&self) -> f32 { - unsafe { - msg_send![self.id(), shadowOpacity] - } + unsafe { msg_send![self.id(), shadowOpacity] } } #[inline] pub fn set_shadow_opacity(&self, opacity: f32) { - unsafe { - msg_send![self.id(), setShadowOpacity:opacity] - } + unsafe { msg_send![self.id(), setShadowOpacity: opacity] } } #[inline] pub fn shadow_offset(&self) -> CGSize { - unsafe { - msg_send![self.id(), shadowOffset] - } + unsafe { msg_send![self.id(), shadowOffset] } } #[inline] pub fn set_shadow_offset(&self, offset: &CGSize) { - unsafe { - msg_send![self.id(), setShadowOffset:*offset] - } + unsafe { msg_send![self.id(), setShadowOffset:*offset] } } #[inline] pub fn shadow_radius(&self) -> CGFloat { - unsafe { - msg_send![self.id(), shadowRadius] - } + unsafe { msg_send![self.id(), shadowRadius] } } #[inline] pub fn set_shadow_radius(&self, radius: CGFloat) { - unsafe { - msg_send![self.id(), setShadowRadius:radius] - } + unsafe { msg_send![self.id(), setShadowRadius: radius] } } #[inline] @@ -993,7 +856,7 @@ impl CALayer { None => ptr::null(), Some(path) => path.as_ptr(), }; - msg_send![self.id(), setShadowPath:sys_path_ref] + msg_send![self.id(), setShadowPath: sys_path_ref] } } @@ -1001,42 +864,32 @@ impl CALayer { #[inline] pub fn autoresizing_mask(&self) -> AutoresizingMask { - unsafe { - AutoresizingMask::from_bits_truncate(msg_send![self.id(), autoresizingMask]) - } + unsafe { AutoresizingMask::from_bits_truncate(msg_send![self.id(), autoresizingMask]) } } #[inline] pub fn set_autoresizing_mask(&self, mask: AutoresizingMask) { - unsafe { - msg_send![self.id(), setAutoresizingMask:mask.bits()] - } + unsafe { msg_send![self.id(), setAutoresizingMask:mask.bits()] } } #[inline] pub fn layout_manager(&self) -> id { - unsafe { - msg_send![self.id(), layoutManager] - } + unsafe { msg_send![self.id(), layoutManager] } } #[inline] pub unsafe fn set_layout_manager(&self, manager: id) { - msg_send![self.id(), setLayoutManager:manager] + msg_send![self.id(), setLayoutManager: manager] } #[inline] pub fn preferred_frame_size(&self) -> CGSize { - unsafe { - msg_send![self.id(), preferredFrameSize] - } + unsafe { msg_send![self.id(), preferredFrameSize] } } #[inline] pub fn set_needs_layout(&self) { - unsafe { - msg_send![self.id(), setNeedsLayout] - } + unsafe { msg_send![self.id(), setNeedsLayout] } } #[inline] @@ -1049,30 +902,22 @@ impl CALayer { #[inline] pub fn layout_if_needed(&self) { - unsafe { - msg_send![self.id(), layoutIfNeeded] - } + unsafe { msg_send![self.id(), layoutIfNeeded] } } #[inline] pub fn layout_sublayers(&self) { - unsafe { - msg_send![self.id(), layoutSublayers] - } + unsafe { msg_send![self.id(), layoutSublayers] } } #[inline] pub fn resize_sublayers_with_old_size(&self, size: &CGSize) { - unsafe { - msg_send![self.id(), resizeSublayersWithOldSize:*size] - } + unsafe { msg_send![self.id(), resizeSublayersWithOldSize:*size] } } #[inline] pub fn resize_with_old_superlayer_size(&self, size: &CGSize) { - unsafe { - msg_send![self.id(), resizeWithOldSuperlayerSize:*size] - } + unsafe { msg_send![self.id(), resizeWithOldSuperlayerSize:*size] } } // Action methods @@ -1095,14 +940,12 @@ impl CALayer { #[inline] pub fn actions(&self) -> CFDictionary { - unsafe { - msg_send![self.id(), actions] - } + unsafe { msg_send![self.id(), actions] } } #[inline] pub unsafe fn set_actions(&self, actions: CFDictionary) { - msg_send![self.id(), setActions:actions] + msg_send![self.id(), setActions: actions] } // TODO(pcwalton): Wrap `CAAnimation`. @@ -1118,9 +961,7 @@ impl CALayer { #[inline] pub fn remove_all_animation(&self) { - unsafe { - msg_send![self.id(), removeAllAnimations] - } + unsafe { msg_send![self.id(), removeAllAnimations] } } #[inline] @@ -1136,9 +977,9 @@ impl CALayer { unsafe { let keys: CFArrayRef = msg_send![self.id(), animationKeys]; let keys: CFArray = TCFType::wrap_under_create_rule(keys); - keys.into_iter().map(|string| { - CFString::wrap_under_get_rule(*string as CFStringRef).to_string() - }).collect() + keys.into_iter() + .map(|string| CFString::wrap_under_get_rule(*string as CFStringRef).to_string()) + .collect() } } @@ -1170,14 +1011,12 @@ impl CALayer { #[inline] pub fn delegate(&self) -> id { - unsafe { - msg_send![self.id(), delegate] - } + unsafe { msg_send![self.id(), delegate] } } #[inline] pub unsafe fn set_delegate(&self, delegate: id) { - msg_send![self.id(), setDelegate:delegate] + msg_send![self.id(), setDelegate: delegate] } #[inline] @@ -1199,7 +1038,7 @@ impl CALayer { None => ptr::null(), Some(ref dictionary) => dictionary.as_CFTypeRef(), }; - msg_send![self.id(), setStyle:dictionary] + msg_send![self.id(), setStyle: dictionary] } } @@ -1215,9 +1054,7 @@ impl CALayer { #[inline] pub fn set_contents_opaque(&self, opaque: bool) { - unsafe { - msg_send![self.id(), setContentsOpaque:opaque as BOOL] - } + unsafe { msg_send![self.id(), setContentsOpaque: opaque as BOOL] } } } @@ -1241,19 +1078,19 @@ pub enum ContentsGravity { impl ContentsGravity { fn into_CFString(self) -> CFString { let string = match self { - ContentsGravity::Center => "center", - ContentsGravity::Top => "top", - ContentsGravity::Bottom => "bottom", - ContentsGravity::Left => "left", - ContentsGravity::Right => "right", - ContentsGravity::TopLeft => "topLeft", - ContentsGravity::TopRight => "topRight", - ContentsGravity::BottomLeft => "bottomLeft", - ContentsGravity::BottomRight => "bottomRight", - ContentsGravity::Resize => "resize", - ContentsGravity::ResizeAspect => "resizeAspect", - ContentsGravity::ResizeAspectFill => "resizeAspectFill", - ContentsGravity::Other(other) => return other, + ContentsGravity::Center => "center", + ContentsGravity::Top => "top", + ContentsGravity::Bottom => "bottom", + ContentsGravity::Left => "left", + ContentsGravity::Right => "right", + ContentsGravity::TopLeft => "topLeft", + ContentsGravity::TopRight => "topRight", + ContentsGravity::BottomLeft => "bottomLeft", + ContentsGravity::BottomRight => "bottomRight", + ContentsGravity::Resize => "resize", + ContentsGravity::ResizeAspect => "resizeAspect", + ContentsGravity::ResizeAspectFill => "resizeAspectFill", + ContentsGravity::Other(other) => return other, }; CFString::from(string) } @@ -1261,38 +1098,38 @@ impl ContentsGravity { // FIXME(pcwalton): Inefficient. fn from_CFString(string: CFString) -> ContentsGravity { match string.to_string() { - ref s if s == "center" => ContentsGravity::Center, - ref s if s == "top" => ContentsGravity::Top, - ref s if s == "bottom" => ContentsGravity::Bottom, - ref s if s == "left" => ContentsGravity::Left, - ref s if s == "right" => ContentsGravity::Right, - ref s if s == "topLeft" => ContentsGravity::TopLeft, - ref s if s == "topRight" => ContentsGravity::TopRight, - ref s if s == "bottomLeft" => ContentsGravity::BottomLeft, - ref s if s == "bottomRight" => ContentsGravity::BottomRight, - ref s if s == "resize" => ContentsGravity::Resize, - ref s if s == "resizeAspect" => ContentsGravity::ResizeAspect, - ref s if s == "resizeAspectFill" => ContentsGravity::ResizeAspectFill, - _ => ContentsGravity::Other(string), + ref s if s == "center" => ContentsGravity::Center, + ref s if s == "top" => ContentsGravity::Top, + ref s if s == "bottom" => ContentsGravity::Bottom, + ref s if s == "left" => ContentsGravity::Left, + ref s if s == "right" => ContentsGravity::Right, + ref s if s == "topLeft" => ContentsGravity::TopLeft, + ref s if s == "topRight" => ContentsGravity::TopRight, + ref s if s == "bottomLeft" => ContentsGravity::BottomLeft, + ref s if s == "bottomRight" => ContentsGravity::BottomRight, + ref s if s == "resize" => ContentsGravity::Resize, + ref s if s == "resizeAspect" => ContentsGravity::ResizeAspect, + ref s if s == "resizeAspectFill" => ContentsGravity::ResizeAspectFill, + _ => ContentsGravity::Other(string), } } } #[derive(Clone, Debug, PartialEq)] pub enum ContentsFormat { - RGBA8Uint, // kCAContentsFormatRGBA8Uint, "RGBA" - RGBA16Float, // kCAContentsFormatRGBA16Float, "RGBAh" - Gray8Uint, // kCAContentsFormatGray8Uint, "Gray8" + RGBA8Uint, // kCAContentsFormatRGBA8Uint, "RGBA" + RGBA16Float, // kCAContentsFormatRGBA16Float, "RGBAh" + Gray8Uint, // kCAContentsFormatGray8Uint, "Gray8" Other(CFString), } impl ContentsFormat { fn into_CFString(self) -> CFString { let string = match self { - ContentsFormat::RGBA8Uint => "RGBA8", - ContentsFormat::RGBA16Float => "RGBAh", - ContentsFormat::Gray8Uint => "Gray8", - ContentsFormat::Other(other) => return other, + ContentsFormat::RGBA8Uint => "RGBA8", + ContentsFormat::RGBA16Float => "RGBAh", + ContentsFormat::Gray8Uint => "Gray8", + ContentsFormat::Other(other) => return other, }; CFString::from(string) } @@ -1300,10 +1137,10 @@ impl ContentsFormat { // FIXME(pcwalton): Inefficient. fn from_CFString(string: CFString) -> ContentsFormat { match string.to_string() { - ref s if s == "RGBA8" => ContentsFormat::RGBA8Uint, - ref s if s == "RGBAh" => ContentsFormat::RGBA16Float, - ref s if s == "Gray8" => ContentsFormat::Gray8Uint, - _ => ContentsFormat::Other(string), + ref s if s == "RGBA8" => ContentsFormat::RGBA8Uint, + ref s if s == "RGBAh" => ContentsFormat::RGBA16Float, + ref s if s == "Gray8" => ContentsFormat::Gray8Uint, + _ => ContentsFormat::Other(string), } } } @@ -1319,10 +1156,10 @@ pub enum Filter { impl Filter { fn into_CFString(self) -> CFString { let string = match self { - Filter::Nearest => "nearest", - Filter::Linear => "linear", - Filter::Trilinear => "trilinear", - Filter::Other(other) => return other, + Filter::Nearest => "nearest", + Filter::Linear => "linear", + Filter::Trilinear => "trilinear", + Filter::Other(other) => return other, }; CFString::from(string) } @@ -1330,10 +1167,10 @@ impl Filter { // FIXME(pcwalton): Inefficient. fn from_CFString(string: CFString) -> Filter { match string.to_string() { - ref s if s == "nearest" => Filter::Nearest, - ref s if s == "linear" => Filter::Linear, - ref s if s == "trilinear" => Filter::Trilinear, - _ => Filter::Other(string), + ref s if s == "nearest" => Filter::Nearest, + ref s if s == "linear" => Filter::Linear, + ref s if s == "trilinear" => Filter::Trilinear, + _ => Filter::Other(string), } } } @@ -1378,18 +1215,14 @@ unsafe impl Sync for CARenderer {} impl Clone for CARenderer { #[inline] fn clone(&self) -> CARenderer { - unsafe { - CARenderer(msg_send![self.id(), retain]) - } + unsafe { CARenderer(msg_send![self.id(), retain]) } } } impl Drop for CARenderer { #[inline] fn drop(&mut self) { - unsafe { - msg_send![self.id(), release] - } + unsafe { msg_send![self.id(), release] } } } @@ -1400,41 +1233,46 @@ impl CARenderer { } #[inline] - pub unsafe fn from_cgl_context(context: CGLContextObj, color_space: Option) - -> CARenderer { + pub unsafe fn from_cgl_context( + context: CGLContextObj, + color_space: Option, + ) -> CARenderer { let mut pairs: Vec<(CFString, CFType)> = vec![]; if let Some(color_space) = color_space { - pairs.push((CFString::wrap_under_get_rule(kCARendererColorSpace), - CFType::wrap_under_get_rule(color_space.as_ptr() as *const _ as *const _))) + pairs.push(( + CFString::wrap_under_get_rule(kCARendererColorSpace), + CFType::wrap_under_get_rule(color_space.as_ptr() as *const _ as *const _), + )) } let options: CFDictionary = CFDictionary::from_CFType_pairs(&pairs); - let renderer: id = - msg_send![class!(CARenderer), rendererWithCGLContext:context + let renderer: id = msg_send![class!(CARenderer), rendererWithCGLContext:context options:options.as_CFTypeRef()]; debug_assert!(renderer != nil); CARenderer(renderer) } #[inline] - pub unsafe fn from_metal_texture(metal_texture: id, - metal_command_queue: id, - color_space: Option) - -> CARenderer { - let mut pairs: Vec<(CFString, CFType)> = vec![ - (CFString::wrap_under_get_rule(kCARendererMetalCommandQueue), - CFType::wrap_under_get_rule(metal_command_queue as *const _ as *const _)), - ]; + pub unsafe fn from_metal_texture( + metal_texture: id, + metal_command_queue: id, + color_space: Option, + ) -> CARenderer { + let mut pairs: Vec<(CFString, CFType)> = vec![( + CFString::wrap_under_get_rule(kCARendererMetalCommandQueue), + CFType::wrap_under_get_rule(metal_command_queue as *const _ as *const _), + )]; if let Some(color_space) = color_space { - pairs.push((CFString::wrap_under_get_rule(kCARendererColorSpace), - CFType::wrap_under_get_rule(color_space.as_ptr() as *const _ as *const _))) + pairs.push(( + CFString::wrap_under_get_rule(kCARendererColorSpace), + CFType::wrap_under_get_rule(color_space.as_ptr() as *const _ as *const _), + )) } let options: CFDictionary = CFDictionary::from_CFType_pairs(&pairs); - let renderer: id = - msg_send![class!(CARenderer), rendererWithMTLTexture:metal_texture + let renderer: id = msg_send![class!(CARenderer), rendererWithMTLTexture:metal_texture options:options.as_CFTypeRef()]; debug_assert!(renderer != nil); CARenderer(renderer) @@ -1459,69 +1297,53 @@ impl CARenderer { Some(ref layer) => layer.id(), None => nil, }; - msg_send![self.id(), setLayer:layer] + msg_send![self.id(), setLayer: layer] } } #[inline] pub fn bounds(&self) -> CGRect { - unsafe { - msg_send![self.id(), bounds] - } + unsafe { msg_send![self.id(), bounds] } } #[inline] pub fn set_bounds(&self, bounds: CGRect) { - unsafe { - msg_send![self.id(), setBounds:bounds] - } + unsafe { msg_send![self.id(), setBounds: bounds] } } #[inline] pub fn begin_frame_at(&self, time: CFTimeInterval, timestamp: Option<&CVTimeStamp>) { - unsafe { - msg_send![self.id(), beginFrameAtTime:time timeStamp:timestamp] - } + unsafe { msg_send![self.id(), beginFrameAtTime:time timeStamp:timestamp] } } #[inline] pub fn update_bounds(&self) -> CGRect { - unsafe { - msg_send![self.id(), updateBounds] - } + unsafe { msg_send![self.id(), updateBounds] } } #[inline] pub fn add_update_rect(&self, rect: CGRect) { - unsafe { - msg_send![self.id(), addUpdateRect:rect] - } + unsafe { msg_send![self.id(), addUpdateRect: rect] } } #[inline] pub fn render(&self) { - unsafe { - msg_send![self.id(), render] - } + unsafe { msg_send![self.id(), render] } } #[inline] pub fn next_frame_time(&self) -> CFTimeInterval { - unsafe { - msg_send![self.id(), nextFrameTime] - } + unsafe { msg_send![self.id(), nextFrameTime] } } #[inline] pub fn end_frame(&self) { - unsafe { - msg_send![self.id(), endFrame] - } + unsafe { msg_send![self.id(), endFrame] } } #[inline] pub unsafe fn set_destination(&self, metal_texture: id) { - msg_send![self.id(), setDestination:metal_texture] + msg_send![self.id(), setDestination: metal_texture] } } @@ -1534,67 +1356,51 @@ pub mod transaction { use core_foundation::date::CFTimeInterval; use core_foundation::string::CFString; - use base::{BOOL, YES, id}; + use base::{id, BOOL, YES}; #[inline] pub fn begin() { - unsafe { - msg_send![class!(CATransaction), begin] - } + unsafe { msg_send![class!(CATransaction), begin] } } #[inline] pub fn commit() { - unsafe { - msg_send![class!(CATransaction), commit] - } + unsafe { msg_send![class!(CATransaction), commit] } } #[inline] pub fn flush() { - unsafe { - msg_send![class!(CATransaction), flush] - } + unsafe { msg_send![class!(CATransaction), flush] } } #[inline] pub fn lock() { - unsafe { - msg_send![class!(CATransaction), lock] - } + unsafe { msg_send![class!(CATransaction), lock] } } #[inline] pub fn unlock() { - unsafe { - msg_send![class!(CATransaction), unlock] - } + unsafe { msg_send![class!(CATransaction), unlock] } } #[inline] pub fn animation_duration() -> CFTimeInterval { - unsafe { - msg_send![class!(CATransaction), animationDuration] - } + unsafe { msg_send![class!(CATransaction), animationDuration] } } #[inline] pub fn set_animation_duration(duration: CFTimeInterval) { - unsafe { - msg_send![class!(CATransaction), setAnimationDuration:duration] - } + unsafe { msg_send![class!(CATransaction), setAnimationDuration: duration] } } #[inline] pub fn animation_timing_function() -> id { - unsafe { - msg_send![class!(CATransaction), animationTimingFunction] - } + unsafe { msg_send![class!(CATransaction), animationTimingFunction] } } #[inline] pub unsafe fn set_animation_timing_function(function: id) { - msg_send![class!(CATransaction), setAnimationTimingFunction:function] + msg_send![class!(CATransaction), setAnimationTimingFunction: function] } #[inline] @@ -1607,9 +1413,7 @@ pub mod transaction { #[inline] pub fn set_disable_actions(flag: bool) { - unsafe { - msg_send![class!(CATransaction), setDisableActions:flag as BOOL] - } + unsafe { msg_send![class!(CATransaction), setDisableActions: flag as BOOL] } } #[inline] @@ -1627,7 +1431,9 @@ pub mod transaction { #[inline] pub fn set_completion_block(block: ConcreteBlock<(), (), F>) - where F: 'static + IntoConcreteBlock<(), Ret = ()> { + where + F: 'static + IntoConcreteBlock<(), Ret = ()>, + { unsafe { let block = block.copy(); msg_send![class!(CATransaction), setCompletionBlock:&*block] @@ -1638,7 +1444,7 @@ pub mod transaction { pub fn value_for_key(key: &str) -> id { unsafe { let key: CFString = CFString::from(key); - msg_send![class!(CATransaction), valueForKey:key] + msg_send![class!(CATransaction), valueForKey: key] } } @@ -1656,18 +1462,28 @@ pub mod transaction { #[repr(C)] #[derive(Clone, Copy)] pub struct CATransform3D { - pub m11: CGFloat, pub m12: CGFloat, pub m13: CGFloat, pub m14: CGFloat, - pub m21: CGFloat, pub m22: CGFloat, pub m23: CGFloat, pub m24: CGFloat, - pub m31: CGFloat, pub m32: CGFloat, pub m33: CGFloat, pub m34: CGFloat, - pub m41: CGFloat, pub m42: CGFloat, pub m43: CGFloat, pub m44: CGFloat, + pub m11: CGFloat, + pub m12: CGFloat, + pub m13: CGFloat, + pub m14: CGFloat, + pub m21: CGFloat, + pub m22: CGFloat, + pub m23: CGFloat, + pub m24: CGFloat, + pub m31: CGFloat, + pub m32: CGFloat, + pub m33: CGFloat, + pub m34: CGFloat, + pub m41: CGFloat, + pub m42: CGFloat, + pub m43: CGFloat, + pub m44: CGFloat, } impl PartialEq for CATransform3D { #[inline] fn eq(&self, other: &CATransform3D) -> bool { - unsafe { - CATransform3DEqualToTransform(*self, *other) - } + unsafe { CATransform3DEqualToTransform(*self, *other) } } } @@ -1676,100 +1492,88 @@ impl Mul for CATransform3D { #[inline] fn mul(self, other: CATransform3D) -> CATransform3D { - unsafe { - CATransform3DConcat(self, other) - } + unsafe { CATransform3DConcat(self, other) } } } impl CATransform3D { pub const IDENTITY: CATransform3D = CATransform3D { - m11: 1.0, m12: 0.0, m13: 0.0, m14: 0.0, - m21: 0.0, m22: 1.0, m23: 0.0, m24: 0.0, - m31: 0.0, m32: 0.0, m33: 1.0, m34: 0.0, - m41: 0.0, m42: 0.0, m43: 0.0, m44: 1.0, + m11: 1.0, + m12: 0.0, + m13: 0.0, + m14: 0.0, + m21: 0.0, + m22: 1.0, + m23: 0.0, + m24: 0.0, + m31: 0.0, + m32: 0.0, + m33: 1.0, + m34: 0.0, + m41: 0.0, + m42: 0.0, + m43: 0.0, + m44: 1.0, }; #[inline] pub fn from_translation(tx: CGFloat, ty: CGFloat, tz: CGFloat) -> CATransform3D { - unsafe { - CATransform3DMakeTranslation(tx, ty, tz) - } + unsafe { CATransform3DMakeTranslation(tx, ty, tz) } } #[inline] pub fn from_scale(sx: CGFloat, sy: CGFloat, sz: CGFloat) -> CATransform3D { - unsafe { - CATransform3DMakeScale(sx, sy, sz) - } + unsafe { CATransform3DMakeScale(sx, sy, sz) } } #[inline] pub fn from_rotation(angle: CGFloat, x: CGFloat, y: CGFloat, z: CGFloat) -> CATransform3D { - unsafe { - CATransform3DMakeRotation(angle, x, y, z) - } + unsafe { CATransform3DMakeRotation(angle, x, y, z) } } #[inline] pub fn affine(affine_transform: CGAffineTransform) -> CATransform3D { - unsafe { - CATransform3DMakeAffineTransform(affine_transform) - } + unsafe { CATransform3DMakeAffineTransform(affine_transform) } } #[inline] pub fn is_identity(&self) -> bool { - unsafe { - CATransform3DIsIdentity(*self) - } + unsafe { CATransform3DIsIdentity(*self) } } #[inline] pub fn translate(&self, tx: CGFloat, ty: CGFloat, tz: CGFloat) -> CATransform3D { - unsafe { - CATransform3DTranslate(*self, tx, ty, tz) - } + unsafe { CATransform3DTranslate(*self, tx, ty, tz) } } #[inline] pub fn scale(&self, sx: CGFloat, sy: CGFloat, sz: CGFloat) -> CATransform3D { - unsafe { - CATransform3DScale(*self, sx, sy, sz) - } + unsafe { CATransform3DScale(*self, sx, sy, sz) } } #[inline] pub fn rotate(&self, angle: CGFloat, x: CGFloat, y: CGFloat, z: CGFloat) -> CATransform3D { - unsafe { - CATransform3DRotate(*self, angle, x, y, z) - } + unsafe { CATransform3DRotate(*self, angle, x, y, z) } } #[inline] pub fn invert(&self) -> CATransform3D { - unsafe { - CATransform3DInvert(*self) - } + unsafe { CATransform3DInvert(*self) } } #[inline] pub fn is_affine(&self) -> bool { - unsafe { - CATransform3DIsAffine(*self) - } + unsafe { CATransform3DIsAffine(*self) } } #[inline] pub fn to_affine(&self) -> CGAffineTransform { - unsafe { - CATransform3DGetAffineTransform(*self) - } + unsafe { CATransform3DGetAffineTransform(*self) } } } #[link(name = "QuartzCore", kind = "framework")] -extern { +extern "C" { static kCARendererColorSpace: CFStringRef; static kCARendererMetalCommandQueue: CFStringRef; @@ -1779,14 +1583,27 @@ extern { fn CATransform3DEqualToTransform(a: CATransform3D, b: CATransform3D) -> bool; fn CATransform3DMakeTranslation(tx: CGFloat, ty: CGFloat, tz: CGFloat) -> CATransform3D; fn CATransform3DMakeScale(sx: CGFloat, sy: CGFloat, sz: CGFloat) -> CATransform3D; - fn CATransform3DMakeRotation(angle: CGFloat, x: CGFloat, y: CGFloat, z: CGFloat) - -> CATransform3D; - fn CATransform3DTranslate(t: CATransform3D, tx: CGFloat, ty: CGFloat, tz: CGFloat) - -> CATransform3D; + fn CATransform3DMakeRotation( + angle: CGFloat, + x: CGFloat, + y: CGFloat, + z: CGFloat, + ) -> CATransform3D; + fn CATransform3DTranslate( + t: CATransform3D, + tx: CGFloat, + ty: CGFloat, + tz: CGFloat, + ) -> CATransform3D; fn CATransform3DScale(t: CATransform3D, sx: CGFloat, sy: CGFloat, sz: CGFloat) - -> CATransform3D; - fn CATransform3DRotate(t: CATransform3D, angle: CGFloat, x: CGFloat, y: CGFloat, z: CGFloat) - -> CATransform3D; + -> CATransform3D; + fn CATransform3DRotate( + t: CATransform3D, + angle: CGFloat, + x: CGFloat, + y: CGFloat, + z: CGFloat, + ) -> CATransform3D; fn CATransform3DConcat(a: CATransform3D, b: CATransform3D) -> CATransform3D; fn CATransform3DInvert(t: CATransform3D) -> CATransform3D; fn CATransform3DMakeAffineTransform(m: CGAffineTransform) -> CATransform3D; @@ -1844,16 +1661,16 @@ pub struct CVSMPTETime { pub type CVSMPTETimeType = u32; -pub const kCVSMPTETimeType24: CVSMPTETimeType = 0; -pub const kCVSMPTETimeType25: CVSMPTETimeType = 1; -pub const kCVSMPTETimeType30Drop: CVSMPTETimeType = 2; -pub const kCVSMPTETimeType30: CVSMPTETimeType = 3; -pub const kCVSMPTETimeType2997: CVSMPTETimeType = 4; +pub const kCVSMPTETimeType24: CVSMPTETimeType = 0; +pub const kCVSMPTETimeType25: CVSMPTETimeType = 1; +pub const kCVSMPTETimeType30Drop: CVSMPTETimeType = 2; +pub const kCVSMPTETimeType30: CVSMPTETimeType = 3; +pub const kCVSMPTETimeType2997: CVSMPTETimeType = 4; pub const kCVSMPTETimeType2997Drop: CVSMPTETimeType = 5; -pub const kCVSMPTETimeType60: CVSMPTETimeType = 6; -pub const kCVSMPTETimeType5994: CVSMPTETimeType = 7; +pub const kCVSMPTETimeType60: CVSMPTETimeType = 6; +pub const kCVSMPTETimeType5994: CVSMPTETimeType = 7; pub type CVSMPTETimeFlags = u32; -pub const kCVSMPTETimeValid: CVSMPTETimeFlags = 1 << 0; -pub const kCVSMPTETimeRunning: CVSMPTETimeFlags = 1 << 1; +pub const kCVSMPTETimeValid: CVSMPTETimeFlags = 1 << 0; +pub const kCVSMPTETimeRunning: CVSMPTETimeFlags = 1 << 1; diff --git a/core-foundation-sys/src/array.rs b/core-foundation-sys/src/array.rs index c73896125..6119d2b0b 100644 --- a/core-foundation-sys/src/array.rs +++ b/core-foundation-sys/src/array.rs @@ -9,15 +9,18 @@ use std::os::raw::c_void; -use base::{CFRange, CFIndex, CFAllocatorRef, CFTypeID, Boolean, CFComparisonResult}; +use base::{Boolean, CFAllocatorRef, CFComparisonResult, CFIndex, CFRange, CFTypeID}; use string::CFStringRef; -pub type CFArrayRetainCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; +pub type CFArrayRetainCallBack = + extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; pub type CFArrayReleaseCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void); pub type CFArrayCopyDescriptionCallBack = extern "C" fn(value: *const c_void) -> CFStringRef; -pub type CFArrayEqualCallBack = extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; +pub type CFArrayEqualCallBack = + extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; pub type CFArrayApplierFunction = extern "C" fn(value: *const c_void, context: *mut c_void); -pub type CFComparatorFunction = extern "C" fn(val1: *const c_void, val2: *const c_void) -> CFComparisonResult; +pub type CFComparatorFunction = + extern "C" fn(val1: *const c_void, val2: *const c_void) -> CFComparisonResult; #[repr(C)] #[derive(Clone, Copy)] @@ -35,33 +38,95 @@ pub struct __CFArray(c_void); pub type CFArrayRef = *const __CFArray; pub type CFMutableArrayRef = *mut __CFArray; -extern { +extern "C" { /* * CFArray.h */ pub static kCFTypeArrayCallBacks: CFArrayCallBacks; pub fn CFArrayGetTypeID() -> CFTypeID; - pub fn CFArrayCreate(allocator: CFAllocatorRef, values: *const *const c_void, numValues: CFIndex, callBacks: *const CFArrayCallBacks) -> CFArrayRef; - pub fn CFArrayCreateCopy(allocator: CFAllocatorRef , theArray: CFArrayRef) -> CFArrayRef; - pub fn CFArrayCreateMutable(allocator: CFAllocatorRef, capacity: CFIndex, callBacks: *const CFArrayCallBacks) -> CFMutableArrayRef; - pub fn CFArrayCreateMutableCopy(allocator: CFAllocatorRef, capacity: CFIndex, theArray: CFArrayRef)-> CFMutableArrayRef; + pub fn CFArrayCreate( + allocator: CFAllocatorRef, + values: *const *const c_void, + numValues: CFIndex, + callBacks: *const CFArrayCallBacks, + ) -> CFArrayRef; + pub fn CFArrayCreateCopy(allocator: CFAllocatorRef, theArray: CFArrayRef) -> CFArrayRef; + pub fn CFArrayCreateMutable( + allocator: CFAllocatorRef, + capacity: CFIndex, + callBacks: *const CFArrayCallBacks, + ) -> CFMutableArrayRef; + pub fn CFArrayCreateMutableCopy( + allocator: CFAllocatorRef, + capacity: CFIndex, + theArray: CFArrayRef, + ) -> CFMutableArrayRef; pub fn CFArrayGetCount(theArray: CFArrayRef) -> CFIndex; - pub fn CFArrayGetCountOfValue(theArray: CFArrayRef, range: CFRange, value: *const c_void) -> CFIndex; - pub fn CFArrayContainsValue(theArray: CFArrayRef, range: CFRange, value: *const c_void) -> Boolean; + pub fn CFArrayGetCountOfValue( + theArray: CFArrayRef, + range: CFRange, + value: *const c_void, + ) -> CFIndex; + pub fn CFArrayContainsValue( + theArray: CFArrayRef, + range: CFRange, + value: *const c_void, + ) -> Boolean; pub fn CFArrayGetValueAtIndex(theArray: CFArrayRef, idx: CFIndex) -> *const c_void; pub fn CFArrayGetValues(theArray: CFArrayRef, range: CFRange, values: *mut *const c_void); - pub fn CFArrayApplyFunction(theArray: CFArrayRef, range: CFRange, applier: CFArrayApplierFunction, context: *mut c_void); - pub fn CFArrayGetFirstIndexOfValue(theArray: CFArrayRef, range: CFRange, value: *const c_void) -> CFIndex; - pub fn CFArrayGetLastIndexOfValue(theArray: CFArrayRef, range: CFRange, value: *const c_void) -> CFIndex; - pub fn CFArrayBSearchValues(theArray: CFArrayRef, range: CFRange, value: *const c_void, comparator: CFComparatorFunction, context: *mut c_void) -> CFIndex; + pub fn CFArrayApplyFunction( + theArray: CFArrayRef, + range: CFRange, + applier: CFArrayApplierFunction, + context: *mut c_void, + ); + pub fn CFArrayGetFirstIndexOfValue( + theArray: CFArrayRef, + range: CFRange, + value: *const c_void, + ) -> CFIndex; + pub fn CFArrayGetLastIndexOfValue( + theArray: CFArrayRef, + range: CFRange, + value: *const c_void, + ) -> CFIndex; + pub fn CFArrayBSearchValues( + theArray: CFArrayRef, + range: CFRange, + value: *const c_void, + comparator: CFComparatorFunction, + context: *mut c_void, + ) -> CFIndex; pub fn CFArrayAppendValue(theArray: CFMutableArrayRef, value: *const c_void); - pub fn CFArrayInsertValueAtIndex(theArray: CFMutableArrayRef, idx: CFIndex, value: *const c_void); + pub fn CFArrayInsertValueAtIndex( + theArray: CFMutableArrayRef, + idx: CFIndex, + value: *const c_void, + ); pub fn CFArraySetValueAtIndex(theArray: CFMutableArrayRef, idx: CFIndex, value: *const c_void); pub fn CFArrayRemoveValueAtIndex(theArray: CFMutableArrayRef, idx: CFIndex); pub fn CFArrayRemoveAllValues(theArray: CFMutableArrayRef); - pub fn CFArrayReplaceValues(theArray: CFMutableArrayRef, range: CFRange, newValues: *mut *const c_void, newCount: CFIndex); - pub fn CFArrayExchangeValuesAtIndices(theArray: CFMutableArrayRef, idx1: CFIndex, idx2: CFIndex); - pub fn CFArraySortValues(theArray: CFMutableArrayRef, range: CFRange, comparator: CFComparatorFunction, context: *mut c_void); - pub fn CFArrayAppendArray(theArray: CFMutableArrayRef, otherArray: CFArrayRef, otherRange: CFRange ); + pub fn CFArrayReplaceValues( + theArray: CFMutableArrayRef, + range: CFRange, + newValues: *mut *const c_void, + newCount: CFIndex, + ); + pub fn CFArrayExchangeValuesAtIndices( + theArray: CFMutableArrayRef, + idx1: CFIndex, + idx2: CFIndex, + ); + pub fn CFArraySortValues( + theArray: CFMutableArrayRef, + range: CFRange, + comparator: CFComparatorFunction, + context: *mut c_void, + ); + pub fn CFArrayAppendArray( + theArray: CFMutableArrayRef, + otherArray: CFArrayRef, + otherRange: CFRange, + ); } diff --git a/core-foundation-sys/src/attributed_string.rs b/core-foundation-sys/src/attributed_string.rs index c91bf5be3..811fb2878 100644 --- a/core-foundation-sys/src/attributed_string.rs +++ b/core-foundation-sys/src/attributed_string.rs @@ -7,10 +7,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use base::{CFAllocatorRef, CFIndex, CFRange, CFTypeID, CFTypeRef}; +use dictionary::CFDictionaryRef; use std::os::raw::c_void; -use base::{CFAllocatorRef, CFTypeRef, CFIndex, CFRange, CFTypeID}; use string::CFStringRef; -use dictionary::CFDictionaryRef; #[repr(C)] pub struct __CFAttributedString(c_void); @@ -18,7 +18,7 @@ pub struct __CFAttributedString(c_void); pub type CFAttributedStringRef = *const __CFAttributedString; pub type CFMutableAttributedStringRef = *const __CFAttributedString; -extern { +extern "C" { /* CFAttributedString */ pub fn CFAttributedStringCreate( @@ -34,7 +34,9 @@ extern { /* CFMutableAttributedString */ pub fn CFAttributedStringCreateMutableCopy( - allocator: CFAllocatorRef, max_length: CFIndex, astr: CFAttributedStringRef + allocator: CFAllocatorRef, + max_length: CFIndex, + astr: CFAttributedStringRef, ) -> CFMutableAttributedStringRef; pub fn CFAttributedStringCreateMutable( @@ -43,7 +45,10 @@ extern { ) -> CFMutableAttributedStringRef; pub fn CFAttributedStringReplaceString( - astr: CFMutableAttributedStringRef, range: CFRange, replacement: CFStringRef); + astr: CFMutableAttributedStringRef, + range: CFRange, + replacement: CFStringRef, + ); pub fn CFAttributedStringSetAttribute( astr: CFMutableAttributedStringRef, diff --git a/core-foundation-sys/src/base.rs b/core-foundation-sys/src/base.rs index 52a166fdf..5c1744f8c 100644 --- a/core-foundation-sys/src/base.rs +++ b/core-foundation-sys/src/base.rs @@ -8,7 +8,7 @@ // except according to those terms. use std::cmp::Ordering; -use std::os::raw::{c_uint, c_void, c_int}; +use std::os::raw::{c_int, c_uint, c_void}; use string::CFStringRef; pub type Boolean = u8; @@ -36,7 +36,7 @@ impl Into for CFComparisonResult { match self { CFComparisonResult::LessThan => Ordering::Less, CFComparisonResult::EqualTo => Ordering::Equal, - CFComparisonResult::GreaterThan => Ordering::Greater + CFComparisonResult::GreaterThan => Ordering::Greater, } } } @@ -45,7 +45,7 @@ impl Into for CFComparisonResult { #[derive(Clone, Copy)] pub struct CFRange { pub location: CFIndex, - pub length: CFIndex + pub length: CFIndex, } // for back-compat @@ -61,10 +61,17 @@ impl CFRange { pub type CFAllocatorRetainCallBack = extern "C" fn(info: *mut c_void) -> *mut c_void; pub type CFAllocatorReleaseCallBack = extern "C" fn(info: *mut c_void); pub type CFAllocatorCopyDescriptionCallBack = extern "C" fn(info: *mut c_void) -> CFStringRef; -pub type CFAllocatorAllocateCallBack = extern "C" fn(allocSize: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> *mut c_void; -pub type CFAllocatorReallocateCallBack = extern "C" fn(ptr: *mut c_void, newsize: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> *mut c_void; +pub type CFAllocatorAllocateCallBack = + extern "C" fn(allocSize: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> *mut c_void; +pub type CFAllocatorReallocateCallBack = extern "C" fn( + ptr: *mut c_void, + newsize: CFIndex, + hint: CFOptionFlags, + info: *mut c_void, +) -> *mut c_void; pub type CFAllocatorDeallocateCallBack = extern "C" fn(ptr: *mut c_void, info: *mut c_void); -pub type CFAllocatorPreferredSizeCallBack = extern "C" fn(size: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> CFIndex; +pub type CFAllocatorPreferredSizeCallBack = + extern "C" fn(size: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> CFIndex; #[repr(C)] #[derive(Clone, Copy)] @@ -77,7 +84,7 @@ pub struct CFAllocatorContext { pub allocate: Option, pub reallocate: Option, pub deallocate: Option, - pub preferredSize: Option + pub preferredSize: Option, } /// Trait for all types which are Core Foundation reference types. @@ -110,7 +117,7 @@ impl TCFTypeRef for *mut T { /// Constant used by some functions to indicate failed searches. pub static kCFNotFound: CFIndex = -1; -extern { +extern "C" { /* * CFBase.h */ @@ -124,11 +131,27 @@ extern { pub static kCFAllocatorNull: CFAllocatorRef; pub static kCFAllocatorUseContext: CFAllocatorRef; - pub fn CFAllocatorCreate(allocator: CFAllocatorRef, context: *mut CFAllocatorContext) -> CFAllocatorRef; - pub fn CFAllocatorAllocate(allocator: CFAllocatorRef, size: CFIndex, hint: CFOptionFlags) -> *mut c_void; + pub fn CFAllocatorCreate( + allocator: CFAllocatorRef, + context: *mut CFAllocatorContext, + ) -> CFAllocatorRef; + pub fn CFAllocatorAllocate( + allocator: CFAllocatorRef, + size: CFIndex, + hint: CFOptionFlags, + ) -> *mut c_void; pub fn CFAllocatorDeallocate(allocator: CFAllocatorRef, ptr: *mut c_void); - pub fn CFAllocatorGetPreferredSizeForSize(allocator: CFAllocatorRef, size: CFIndex, hint: CFOptionFlags) -> CFIndex; - pub fn CFAllocatorReallocate(allocator: CFAllocatorRef, ptr: *mut c_void, newsize: CFIndex, hint: CFOptionFlags) -> *mut c_void; + pub fn CFAllocatorGetPreferredSizeForSize( + allocator: CFAllocatorRef, + size: CFIndex, + hint: CFOptionFlags, + ) -> CFIndex; + pub fn CFAllocatorReallocate( + allocator: CFAllocatorRef, + ptr: *mut c_void, + newsize: CFIndex, + hint: CFOptionFlags, + ) -> *mut c_void; pub fn CFAllocatorGetDefault() -> CFAllocatorRef; pub fn CFAllocatorSetDefault(allocator: CFAllocatorRef); pub fn CFAllocatorGetContext(allocator: CFAllocatorRef, context: *mut CFAllocatorContext); diff --git a/core-foundation-sys/src/bundle.rs b/core-foundation-sys/src/bundle.rs index 29f8e1261..70211554f 100644 --- a/core-foundation-sys/src/bundle.rs +++ b/core-foundation-sys/src/bundle.rs @@ -9,24 +9,27 @@ use std::os::raw::c_void; -use base::{CFTypeID, CFAllocatorRef}; -use url::CFURLRef; +use base::{CFAllocatorRef, CFTypeID}; use dictionary::CFDictionaryRef; use string::CFStringRef; +use url::CFURLRef; #[repr(C)] pub struct __CFBundle(c_void); pub type CFBundleRef = *mut __CFBundle; -extern { +extern "C" { /* * CFBundle.h */ pub fn CFBundleCreate(allocator: CFAllocatorRef, bundleURL: CFURLRef) -> CFBundleRef; pub fn CFBundleGetBundleWithIdentifier(bundleID: CFStringRef) -> CFBundleRef; - pub fn CFBundleGetFunctionPointerForName(bundle: CFBundleRef, function_name: CFStringRef) -> *const c_void; + pub fn CFBundleGetFunctionPointerForName( + bundle: CFBundleRef, + function_name: CFStringRef, + ) -> *const c_void; pub fn CFBundleGetMainBundle() -> CFBundleRef; pub fn CFBundleGetInfoDictionary(bundle: CFBundleRef) -> CFDictionaryRef; diff --git a/core-foundation-sys/src/characterset.rs b/core-foundation-sys/src/characterset.rs index 6b347a5cd..197b9f8bb 100644 --- a/core-foundation-sys/src/characterset.rs +++ b/core-foundation-sys/src/characterset.rs @@ -7,9 +7,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::os::raw::c_void; use base::{Boolean, CFAllocatorRef, CFIndex, CFRange, CFTypeID}; use data::CFDataRef; +use std::os::raw::c_void; use string::{CFStringRef, UniChar}; pub type CFCharacterSetPredefinedSet = CFIndex; @@ -37,22 +37,54 @@ pub struct __CFCharacterSet(c_void); pub type CFCharacterSetRef = *const __CFCharacterSet; pub type CFMutableCharacterSetRef = *const __CFCharacterSet; -extern { +extern "C" { pub fn CFCharacterSetGetTypeID() -> CFTypeID; - pub fn CFCharacterSetGetPredefined(theSetIdentifier: CFCharacterSetPredefinedSet) -> CFCharacterSetRef; - pub fn CFCharacterSetCreateWithCharactersInRange(alloc: CFAllocatorRef, theRange: CFRange) -> CFCharacterSetRef; - pub fn CFCharacterSetCreateWithCharactersInString(alloc: CFAllocatorRef, theString: CFStringRef) -> CFCharacterSetRef; - pub fn CFCharacterSetCreateWithBitmapRepresentation(alloc: CFAllocatorRef, theData: CFDataRef) -> CFCharacterSetRef; + pub fn CFCharacterSetGetPredefined( + theSetIdentifier: CFCharacterSetPredefinedSet, + ) -> CFCharacterSetRef; + pub fn CFCharacterSetCreateWithCharactersInRange( + alloc: CFAllocatorRef, + theRange: CFRange, + ) -> CFCharacterSetRef; + pub fn CFCharacterSetCreateWithCharactersInString( + alloc: CFAllocatorRef, + theString: CFStringRef, + ) -> CFCharacterSetRef; + pub fn CFCharacterSetCreateWithBitmapRepresentation( + alloc: CFAllocatorRef, + theData: CFDataRef, + ) -> CFCharacterSetRef; pub fn CFCharacterSetCreateMutable(alloc: CFAllocatorRef) -> CFMutableCharacterSetRef; - pub fn CFCharacterSetCreateCopy(alloc: CFAllocatorRef, theSet: CFCharacterSetRef) -> CFCharacterSetRef; - pub fn CFCharacterSetCreateMutableCopy(alloc: CFAllocatorRef, theSet: CFCharacterSetRef) -> CFMutableCharacterSetRef; + pub fn CFCharacterSetCreateCopy( + alloc: CFAllocatorRef, + theSet: CFCharacterSetRef, + ) -> CFCharacterSetRef; + pub fn CFCharacterSetCreateMutableCopy( + alloc: CFAllocatorRef, + theSet: CFCharacterSetRef, + ) -> CFMutableCharacterSetRef; pub fn CFCharacterSetIsCharacterMember(theSet: CFCharacterSetRef, theChar: UniChar) -> Boolean; - pub fn CFCharacterSetCreateBitmapRepresentation(alloc: CFAllocatorRef, theSet: CFCharacterSetRef) -> CFDataRef; + pub fn CFCharacterSetCreateBitmapRepresentation( + alloc: CFAllocatorRef, + theSet: CFCharacterSetRef, + ) -> CFDataRef; pub fn CFCharacterSetAddCharactersInRange(theSet: CFMutableCharacterSetRef, theRange: CFRange); - pub fn CFCharacterSetRemoveCharactersInRange(theSet: CFMutableCharacterSetRef, theRange: CFRange); - pub fn CFCharacterSetAddCharactersInString(theSet: CFMutableCharacterSetRef, theString: CFStringRef); - pub fn CFCharacterSetRemoveCharactersInString(theSet: CFMutableCharacterSetRef, theString: CFStringRef); + pub fn CFCharacterSetRemoveCharactersInRange( + theSet: CFMutableCharacterSetRef, + theRange: CFRange, + ); + pub fn CFCharacterSetAddCharactersInString( + theSet: CFMutableCharacterSetRef, + theString: CFStringRef, + ); + pub fn CFCharacterSetRemoveCharactersInString( + theSet: CFMutableCharacterSetRef, + theString: CFStringRef, + ); pub fn CFCharacterSetUnion(theSet: CFMutableCharacterSetRef, theOtherSet: CFCharacterSetRef); - pub fn CFCharacterSetIntersect(theSet: CFMutableCharacterSetRef, theOtherSet: CFCharacterSetRef); + pub fn CFCharacterSetIntersect( + theSet: CFMutableCharacterSetRef, + theOtherSet: CFCharacterSetRef, + ); pub fn CFCharacterSetInvert(theSet: CFMutableCharacterSetRef); } diff --git a/core-foundation-sys/src/data.rs b/core-foundation-sys/src/data.rs index e5ed0dc9f..761c2714d 100644 --- a/core-foundation-sys/src/data.rs +++ b/core-foundation-sys/src/data.rs @@ -9,20 +9,19 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, CFTypeID, CFIndex, CFRange}; +use base::{CFAllocatorRef, CFIndex, CFRange, CFTypeID}; #[repr(C)] pub struct __CFData(c_void); pub type CFDataRef = *const __CFData; -extern { +extern "C" { /* * CFData.h */ - pub fn CFDataCreate(allocator: CFAllocatorRef, - bytes: *const u8, length: CFIndex) -> CFDataRef; + pub fn CFDataCreate(allocator: CFAllocatorRef, bytes: *const u8, length: CFIndex) -> CFDataRef; //fn CFDataFind pub fn CFDataGetBytePtr(theData: CFDataRef) -> *const u8; pub fn CFDataGetBytes(theData: CFDataRef, range: CFRange, buffer: *mut u8); diff --git a/core-foundation-sys/src/date.rs b/core-foundation-sys/src/date.rs index f83ce1dd1..c822eea8d 100644 --- a/core-foundation-sys/src/date.rs +++ b/core-foundation-sys/src/date.rs @@ -19,7 +19,7 @@ pub type CFDateRef = *const __CFDate; pub type CFTimeInterval = f64; pub type CFAbsoluteTime = CFTimeInterval; -extern { +extern "C" { pub static kCFAbsoluteTimeIntervalSince1904: CFTimeInterval; pub static kCFAbsoluteTimeIntervalSince1970: CFTimeInterval; @@ -28,7 +28,11 @@ extern { pub fn CFDateCreate(allocator: CFAllocatorRef, at: CFAbsoluteTime) -> CFDateRef; pub fn CFDateGetAbsoluteTime(date: CFDateRef) -> CFAbsoluteTime; pub fn CFDateGetTimeIntervalSinceDate(date: CFDateRef, other: CFDateRef) -> CFTimeInterval; - pub fn CFDateCompare(date: CFDateRef, other: CFDateRef, context: *mut c_void) -> CFComparisonResult; + pub fn CFDateCompare( + date: CFDateRef, + other: CFDateRef, + context: *mut c_void, + ) -> CFComparisonResult; pub fn CFDateGetTypeID() -> CFTypeID; } diff --git a/core-foundation-sys/src/dictionary.rs b/core-foundation-sys/src/dictionary.rs index d10e9c120..bebeb2631 100644 --- a/core-foundation-sys/src/dictionary.rs +++ b/core-foundation-sys/src/dictionary.rs @@ -9,15 +9,19 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, CFHashCode, CFIndex, CFTypeID, Boolean}; +use base::{Boolean, CFAllocatorRef, CFHashCode, CFIndex, CFTypeID}; use string::CFStringRef; -pub type CFDictionaryApplierFunction = extern "C" fn(key: *const c_void, value: *const c_void, context: *mut c_void); +pub type CFDictionaryApplierFunction = + extern "C" fn(key: *const c_void, value: *const c_void, context: *mut c_void); -pub type CFDictionaryRetainCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; -pub type CFDictionaryReleaseCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void); +pub type CFDictionaryRetainCallBack = + extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; +pub type CFDictionaryReleaseCallBack = + extern "C" fn(allocator: CFAllocatorRef, value: *const c_void); pub type CFDictionaryCopyDescriptionCallBack = extern "C" fn(value: *const c_void) -> CFStringRef; -pub type CFDictionaryEqualCallBack = extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; +pub type CFDictionaryEqualCallBack = + extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; pub type CFDictionaryHashCallBack = extern "C" fn(value: *const c_void) -> CFHashCode; #[repr(C)] @@ -28,7 +32,7 @@ pub struct CFDictionaryKeyCallBacks { pub release: CFDictionaryReleaseCallBack, pub copyDescription: CFDictionaryCopyDescriptionCallBack, pub equal: CFDictionaryEqualCallBack, - pub hash: CFDictionaryHashCallBack + pub hash: CFDictionaryHashCallBack, } #[repr(C)] @@ -38,7 +42,7 @@ pub struct CFDictionaryValueCallBacks { pub retain: CFDictionaryRetainCallBack, pub release: CFDictionaryReleaseCallBack, pub copyDescription: CFDictionaryCopyDescriptionCallBack, - pub equal: CFDictionaryEqualCallBack + pub equal: CFDictionaryEqualCallBack, } #[repr(C)] @@ -47,7 +51,7 @@ pub struct __CFDictionary(c_void); pub type CFDictionaryRef = *const __CFDictionary; pub type CFMutableDictionaryRef = *mut __CFDictionary; -extern { +extern "C" { /* * CFDictionary.h */ @@ -56,36 +60,58 @@ extern { pub static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks; pub fn CFDictionaryContainsKey(theDict: CFDictionaryRef, key: *const c_void) -> Boolean; - pub fn CFDictionaryCreate(allocator: CFAllocatorRef, keys: *const *const c_void, values: *const *const c_void, - numValues: CFIndex, keyCallBacks: *const CFDictionaryKeyCallBacks, - valueCallBacks: *const CFDictionaryValueCallBacks) - -> CFDictionaryRef; + pub fn CFDictionaryCreate( + allocator: CFAllocatorRef, + keys: *const *const c_void, + values: *const *const c_void, + numValues: CFIndex, + keyCallBacks: *const CFDictionaryKeyCallBacks, + valueCallBacks: *const CFDictionaryValueCallBacks, + ) -> CFDictionaryRef; pub fn CFDictionaryGetCount(theDict: CFDictionaryRef) -> CFIndex; pub fn CFDictionaryGetTypeID() -> CFTypeID; - pub fn CFDictionaryGetValueIfPresent(theDict: CFDictionaryRef, key: *const c_void, value: *mut *const c_void) - -> Boolean; - pub fn CFDictionaryApplyFunction(theDict: CFDictionaryRef, - applier: CFDictionaryApplierFunction, - context: *mut c_void); - pub fn CFDictionaryGetKeysAndValues(theDict: CFDictionaryRef, - keys: *mut *const c_void, - values: *mut *const c_void); + pub fn CFDictionaryGetValueIfPresent( + theDict: CFDictionaryRef, + key: *const c_void, + value: *mut *const c_void, + ) -> Boolean; + pub fn CFDictionaryApplyFunction( + theDict: CFDictionaryRef, + applier: CFDictionaryApplierFunction, + context: *mut c_void, + ); + pub fn CFDictionaryGetKeysAndValues( + theDict: CFDictionaryRef, + keys: *mut *const c_void, + values: *mut *const c_void, + ); - pub fn CFDictionaryCreateMutable(allocator: CFAllocatorRef, capacity: CFIndex, - keyCallbacks: *const CFDictionaryKeyCallBacks, - valueCallbacks: *const CFDictionaryValueCallBacks) -> CFMutableDictionaryRef; - pub fn CFDictionaryCreateMutableCopy(allocator: CFAllocatorRef, capacity: CFIndex, - theDict: CFDictionaryRef) -> CFMutableDictionaryRef; - pub fn CFDictionaryAddValue(theDict: CFMutableDictionaryRef, - key: *const c_void, - value: *const c_void); - pub fn CFDictionarySetValue(theDict: CFMutableDictionaryRef, - key: *const c_void, - value: *const c_void); - pub fn CFDictionaryReplaceValue(theDict: CFMutableDictionaryRef, - key: *const c_void, - value: *const c_void); - pub fn CFDictionaryRemoveValue(theDict: CFMutableDictionaryRef, - key: *const c_void); + pub fn CFDictionaryCreateMutable( + allocator: CFAllocatorRef, + capacity: CFIndex, + keyCallbacks: *const CFDictionaryKeyCallBacks, + valueCallbacks: *const CFDictionaryValueCallBacks, + ) -> CFMutableDictionaryRef; + pub fn CFDictionaryCreateMutableCopy( + allocator: CFAllocatorRef, + capacity: CFIndex, + theDict: CFDictionaryRef, + ) -> CFMutableDictionaryRef; + pub fn CFDictionaryAddValue( + theDict: CFMutableDictionaryRef, + key: *const c_void, + value: *const c_void, + ); + pub fn CFDictionarySetValue( + theDict: CFMutableDictionaryRef, + key: *const c_void, + value: *const c_void, + ); + pub fn CFDictionaryReplaceValue( + theDict: CFMutableDictionaryRef, + key: *const c_void, + value: *const c_void, + ); + pub fn CFDictionaryRemoveValue(theDict: CFMutableDictionaryRef, key: *const c_void); pub fn CFDictionaryRemoveAllValues(theDict: CFMutableDictionaryRef); } diff --git a/core-foundation-sys/src/error.rs b/core-foundation-sys/src/error.rs index 8a4c1d494..d5e358cc7 100644 --- a/core-foundation-sys/src/error.rs +++ b/core-foundation-sys/src/error.rs @@ -9,7 +9,7 @@ use std::os::raw::c_void; -use base::{CFTypeID, CFIndex}; +use base::{CFIndex, CFTypeID}; use string::CFStringRef; #[repr(C)] diff --git a/core-foundation-sys/src/filedescriptor.rs b/core-foundation-sys/src/filedescriptor.rs index 3f51d1072..bac6efc74 100644 --- a/core-foundation-sys/src/filedescriptor.rs +++ b/core-foundation-sys/src/filedescriptor.rs @@ -9,9 +9,9 @@ use std::os::raw::{c_int, c_void}; -use base::{Boolean, CFIndex, CFTypeID, CFOptionFlags, CFAllocatorRef}; -use string::CFStringRef; +use base::{Boolean, CFAllocatorRef, CFIndex, CFOptionFlags, CFTypeID}; use runloop::CFRunLoopSourceRef; +use string::CFStringRef; pub type CFFileDescriptorNativeDescriptor = c_int; @@ -21,32 +21,44 @@ pub struct __CFFileDescriptor(c_void); pub type CFFileDescriptorRef = *mut __CFFileDescriptor; /* Callback Reason Types */ -pub const kCFFileDescriptorReadCallBack: CFOptionFlags = 1 << 0; +pub const kCFFileDescriptorReadCallBack: CFOptionFlags = 1 << 0; pub const kCFFileDescriptorWriteCallBack: CFOptionFlags = 1 << 1; -pub type CFFileDescriptorCallBack = extern "C" fn (f: CFFileDescriptorRef, callBackTypes: CFOptionFlags, info: *mut c_void); +pub type CFFileDescriptorCallBack = + extern "C" fn(f: CFFileDescriptorRef, callBackTypes: CFOptionFlags, info: *mut c_void); #[repr(C)] #[derive(Clone, Copy)] pub struct CFFileDescriptorContext { pub version: CFIndex, pub info: *mut c_void, - pub retain: Option *const c_void>, - pub release: Option, - pub copyDescription: Option CFStringRef>, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, } -extern { +extern "C" { /* * CFFileDescriptor.h */ pub fn CFFileDescriptorGetTypeID() -> CFTypeID; - pub fn CFFileDescriptorCreate(allocator: CFAllocatorRef, fd: CFFileDescriptorNativeDescriptor, closeOnInvalidate: Boolean, callout: CFFileDescriptorCallBack, context: *const CFFileDescriptorContext) -> CFFileDescriptorRef; + pub fn CFFileDescriptorCreate( + allocator: CFAllocatorRef, + fd: CFFileDescriptorNativeDescriptor, + closeOnInvalidate: Boolean, + callout: CFFileDescriptorCallBack, + context: *const CFFileDescriptorContext, + ) -> CFFileDescriptorRef; - pub fn CFFileDescriptorGetNativeDescriptor(f: CFFileDescriptorRef) -> CFFileDescriptorNativeDescriptor; + pub fn CFFileDescriptorGetNativeDescriptor( + f: CFFileDescriptorRef, + ) -> CFFileDescriptorNativeDescriptor; - pub fn CFFileDescriptorGetContext(f: CFFileDescriptorRef, context: *mut CFFileDescriptorContext); + pub fn CFFileDescriptorGetContext( + f: CFFileDescriptorRef, + context: *mut CFFileDescriptorContext, + ); pub fn CFFileDescriptorEnableCallBacks(f: CFFileDescriptorRef, callBackTypes: CFOptionFlags); pub fn CFFileDescriptorDisableCallBacks(f: CFFileDescriptorRef, callBackTypes: CFOptionFlags); @@ -54,5 +66,9 @@ extern { pub fn CFFileDescriptorInvalidate(f: CFFileDescriptorRef); pub fn CFFileDescriptorIsValid(f: CFFileDescriptorRef) -> Boolean; - pub fn CFFileDescriptorCreateRunLoopSource(allocator: CFAllocatorRef, f: CFFileDescriptorRef, order: CFIndex) -> CFRunLoopSourceRef; + pub fn CFFileDescriptorCreateRunLoopSource( + allocator: CFAllocatorRef, + f: CFFileDescriptorRef, + order: CFIndex, + ) -> CFRunLoopSourceRef; } diff --git a/core-foundation-sys/src/lib.rs b/core-foundation-sys/src/lib.rs index f9a188416..fc4982c78 100644 --- a/core-foundation-sys/src/lib.rs +++ b/core-foundation-sys/src/lib.rs @@ -6,9 +6,16 @@ // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. -#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, improper_ctypes)] - -#![cfg_attr(all(feature="mac_os_10_7_support", feature="mac_os_10_8_features"), feature(linkage))] // back-compat requires weak linkage +#![allow( + non_snake_case, + non_camel_case_types, + non_upper_case_globals, + improper_ctypes +)] +#![cfg_attr( + all(feature = "mac_os_10_7_support", feature = "mac_os_10_8_features"), + feature(linkage) +)] // back-compat requires weak linkage pub mod array; pub mod attributed_string; @@ -20,6 +27,7 @@ pub mod date; pub mod dictionary; pub mod error; pub mod filedescriptor; +pub mod mach_port; pub mod messageport; pub mod number; pub mod propertylist; @@ -29,4 +37,3 @@ pub mod string; pub mod timezone; pub mod url; pub mod uuid; -pub mod mach_port; diff --git a/core-foundation-sys/src/mach_port.rs b/core-foundation-sys/src/mach_port.rs index 2341fd4e7..8c884b393 100644 --- a/core-foundation-sys/src/mach_port.rs +++ b/core-foundation-sys/src/mach_port.rs @@ -15,6 +15,6 @@ extern "C" { port: CFMachPortRef, order: CFIndex, ) -> CFRunLoopSourceRef; - + pub fn CFMachPortGetTypeID() -> CFTypeID; } diff --git a/core-foundation-sys/src/messageport.rs b/core-foundation-sys/src/messageport.rs index e33d9aa4b..7f62f094a 100644 --- a/core-foundation-sys/src/messageport.rs +++ b/core-foundation-sys/src/messageport.rs @@ -9,71 +9,80 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, CFIndex, CFTypeID, Boolean}; +use base::{Boolean, CFAllocatorRef, CFIndex, CFTypeID}; use data::CFDataRef; use date::CFTimeInterval; use runloop::CFRunLoopSourceRef; use string::CFStringRef; #[repr(C)] -#[derive(Copy, Clone)] -#[derive(Debug)] +#[derive(Copy, Clone, Debug)] pub struct CFMessagePortContext { pub version: CFIndex, pub info: *mut c_void, - pub retain: Option *const c_void>, - pub release: Option, - pub copyDescription: Option CFStringRef>, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, } pub type CFMessagePortCallBack = Option< - unsafe extern fn(local: CFMessagePortRef, - msgid: i32, - data: CFDataRef, - info: *mut c_void) -> CFDataRef>; + unsafe extern "C" fn( + local: CFMessagePortRef, + msgid: i32, + data: CFDataRef, + info: *mut c_void, + ) -> CFDataRef, +>; -pub type CFMessagePortInvalidationCallBack = Option< - unsafe extern "C" fn(ms: CFMessagePortRef, info: *mut c_void)>; +pub type CFMessagePortInvalidationCallBack = + Option; #[repr(C)] pub struct __CFMessagePort(c_void); pub type CFMessagePortRef = *mut __CFMessagePort; -extern { +extern "C" { /* * CFMessagePort.h */ pub fn CFMessagePortGetTypeID() -> CFTypeID; - pub fn CFMessagePortCreateLocal(allocator: CFAllocatorRef, - name: CFStringRef, - callout: CFMessagePortCallBack, - context: *const CFMessagePortContext, - shouldFreeInfo: *mut Boolean) - -> CFMessagePortRef; - pub fn CFMessagePortCreateRemote(allocator: CFAllocatorRef, - name: CFStringRef) -> CFMessagePortRef; + pub fn CFMessagePortCreateLocal( + allocator: CFAllocatorRef, + name: CFStringRef, + callout: CFMessagePortCallBack, + context: *const CFMessagePortContext, + shouldFreeInfo: *mut Boolean, + ) -> CFMessagePortRef; + pub fn CFMessagePortCreateRemote( + allocator: CFAllocatorRef, + name: CFStringRef, + ) -> CFMessagePortRef; pub fn CFMessagePortIsRemote(ms: CFMessagePortRef) -> Boolean; pub fn CFMessagePortGetName(ms: CFMessagePortRef) -> CFStringRef; - pub fn CFMessagePortSetName(ms: CFMessagePortRef, newName: CFStringRef) - -> Boolean; - pub fn CFMessagePortGetContext(ms: CFMessagePortRef, - context: *mut CFMessagePortContext); + pub fn CFMessagePortSetName(ms: CFMessagePortRef, newName: CFStringRef) -> Boolean; + pub fn CFMessagePortGetContext(ms: CFMessagePortRef, context: *mut CFMessagePortContext); pub fn CFMessagePortInvalidate(ms: CFMessagePortRef); pub fn CFMessagePortIsValid(ms: CFMessagePortRef) -> Boolean; - pub fn CFMessagePortGetInvalidationCallBack(ms: CFMessagePortRef) - -> CFMessagePortInvalidationCallBack; - pub fn CFMessagePortSetInvalidationCallBack(ms: CFMessagePortRef, - callout: CFMessagePortInvalidationCallBack); - pub fn CFMessagePortSendRequest(remote: CFMessagePortRef, msgid: i32, - data: CFDataRef, - sendTimeout: CFTimeInterval, - rcvTimeout: CFTimeInterval, - replyMode: CFStringRef, - returnData: *mut CFDataRef) -> i32; - pub fn CFMessagePortCreateRunLoopSource(allocator: CFAllocatorRef, - local: CFMessagePortRef, - order: CFIndex) - -> CFRunLoopSourceRef; + pub fn CFMessagePortGetInvalidationCallBack( + ms: CFMessagePortRef, + ) -> CFMessagePortInvalidationCallBack; + pub fn CFMessagePortSetInvalidationCallBack( + ms: CFMessagePortRef, + callout: CFMessagePortInvalidationCallBack, + ); + pub fn CFMessagePortSendRequest( + remote: CFMessagePortRef, + msgid: i32, + data: CFDataRef, + sendTimeout: CFTimeInterval, + rcvTimeout: CFTimeInterval, + replyMode: CFStringRef, + returnData: *mut CFDataRef, + ) -> i32; + pub fn CFMessagePortCreateRunLoopSource( + allocator: CFAllocatorRef, + local: CFMessagePortRef, + order: CFIndex, + ) -> CFRunLoopSourceRef; // CFMessagePortSetDispatchQueue } diff --git a/core-foundation-sys/src/number.rs b/core-foundation-sys/src/number.rs index c056a245b..d18359657 100644 --- a/core-foundation-sys/src/number.rs +++ b/core-foundation-sys/src/number.rs @@ -9,7 +9,7 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, CFTypeID, CFComparisonResult}; +use base::{CFAllocatorRef, CFComparisonResult, CFTypeID}; #[repr(C)] pub struct __CFBoolean(c_void); @@ -19,23 +19,23 @@ pub type CFBooleanRef = *const __CFBoolean; pub type CFNumberType = u32; // members of enum CFNumberType -pub const kCFNumberSInt8Type: CFNumberType = 1; -pub const kCFNumberSInt16Type: CFNumberType = 2; -pub const kCFNumberSInt32Type: CFNumberType = 3; -pub const kCFNumberSInt64Type: CFNumberType = 4; -pub const kCFNumberFloat32Type: CFNumberType = 5; -pub const kCFNumberFloat64Type: CFNumberType = 6; -pub const kCFNumberCharType: CFNumberType = 7; -pub const kCFNumberShortType: CFNumberType = 8; -pub const kCFNumberIntType: CFNumberType = 9; -pub const kCFNumberLongType: CFNumberType = 10; -pub const kCFNumberLongLongType: CFNumberType = 11; -pub const kCFNumberFloatType: CFNumberType = 12; -pub const kCFNumberDoubleType: CFNumberType = 13; -pub const kCFNumberCFIndexType: CFNumberType = 14; +pub const kCFNumberSInt8Type: CFNumberType = 1; +pub const kCFNumberSInt16Type: CFNumberType = 2; +pub const kCFNumberSInt32Type: CFNumberType = 3; +pub const kCFNumberSInt64Type: CFNumberType = 4; +pub const kCFNumberFloat32Type: CFNumberType = 5; +pub const kCFNumberFloat64Type: CFNumberType = 6; +pub const kCFNumberCharType: CFNumberType = 7; +pub const kCFNumberShortType: CFNumberType = 8; +pub const kCFNumberIntType: CFNumberType = 9; +pub const kCFNumberLongType: CFNumberType = 10; +pub const kCFNumberLongLongType: CFNumberType = 11; +pub const kCFNumberFloatType: CFNumberType = 12; +pub const kCFNumberDoubleType: CFNumberType = 13; +pub const kCFNumberCFIndexType: CFNumberType = 14; pub const kCFNumberNSIntegerType: CFNumberType = 15; -pub const kCFNumberCGFloatType: CFNumberType = 16; -pub const kCFNumberMaxType: CFNumberType = 16; +pub const kCFNumberCGFloatType: CFNumberType = 16; +pub const kCFNumberMaxType: CFNumberType = 16; // This is an enum due to zero-sized types warnings. // For more details see https://github.com/rust-lang/rust/issues/27303 @@ -43,7 +43,7 @@ pub enum __CFNumber {} pub type CFNumberRef = *const __CFNumber; -extern { +extern "C" { /* * CFNumber.h */ @@ -53,11 +53,22 @@ extern { pub fn CFBooleanGetTypeID() -> CFTypeID; pub fn CFBooleanGetValue(boolean: CFBooleanRef) -> bool; - pub fn CFNumberCreate(allocator: CFAllocatorRef, theType: CFNumberType, valuePtr: *const c_void) - -> CFNumberRef; + pub fn CFNumberCreate( + allocator: CFAllocatorRef, + theType: CFNumberType, + valuePtr: *const c_void, + ) -> CFNumberRef; //fn CFNumberGetByteSize - pub fn CFNumberGetValue(number: CFNumberRef, theType: CFNumberType, valuePtr: *mut c_void) -> bool; - pub fn CFNumberCompare(date: CFNumberRef, other: CFNumberRef, context: *mut c_void) -> CFComparisonResult; + pub fn CFNumberGetValue( + number: CFNumberRef, + theType: CFNumberType, + valuePtr: *mut c_void, + ) -> bool; + pub fn CFNumberCompare( + date: CFNumberRef, + other: CFNumberRef, + context: *mut c_void, + ) -> CFComparisonResult; pub fn CFNumberGetTypeID() -> CFTypeID; pub fn CFNumberGetType(number: CFNumberRef) -> CFNumberType; } diff --git a/core-foundation-sys/src/propertylist.rs b/core-foundation-sys/src/propertylist.rs index 574c4d13f..dc260dbdb 100644 --- a/core-foundation-sys/src/propertylist.rs +++ b/core-foundation-sys/src/propertylist.rs @@ -29,18 +29,20 @@ extern "C" { // fn CFPropertyListCreateDeepCopy // fn CFPropertyListIsValid - pub fn CFPropertyListCreateWithData(allocator: CFAllocatorRef, - data: CFDataRef, - options: CFPropertyListMutabilityOptions, - format: *mut CFPropertyListFormat, - error: *mut CFErrorRef) - -> CFPropertyListRef; + pub fn CFPropertyListCreateWithData( + allocator: CFAllocatorRef, + data: CFDataRef, + options: CFPropertyListMutabilityOptions, + format: *mut CFPropertyListFormat, + error: *mut CFErrorRef, + ) -> CFPropertyListRef; // fn CFPropertyListCreateWithStream // fn CFPropertyListWrite - pub fn CFPropertyListCreateData(allocator: CFAllocatorRef, - propertyList: CFPropertyListRef, - format: CFPropertyListFormat, - options: CFOptionFlags, - error: *mut CFErrorRef) - -> CFDataRef; + pub fn CFPropertyListCreateData( + allocator: CFAllocatorRef, + propertyList: CFPropertyListRef, + format: CFPropertyListFormat, + options: CFOptionFlags, + error: *mut CFErrorRef, + ) -> CFDataRef; } diff --git a/core-foundation-sys/src/runloop.rs b/core-foundation-sys/src/runloop.rs index 53035a2e7..0efe4b8b1 100644 --- a/core-foundation-sys/src/runloop.rs +++ b/core-foundation-sys/src/runloop.rs @@ -10,7 +10,7 @@ use std::os::raw::c_void; use array::CFArrayRef; -use base::{Boolean, CFIndex, CFTypeID, CFAllocatorRef, CFOptionFlags, CFHashCode, mach_port_t}; +use base::{mach_port_t, Boolean, CFAllocatorRef, CFHashCode, CFIndex, CFOptionFlags, CFTypeID}; use date::{CFAbsoluteTime, CFTimeInterval}; use string::CFStringRef; @@ -30,78 +30,84 @@ pub struct __CFRunLoopObserver(c_void); pub type CFRunLoopObserverRef = *mut __CFRunLoopObserver; // Reasons for CFRunLoopRunInMode() to Return -pub const kCFRunLoopRunFinished: i32 = 1; -pub const kCFRunLoopRunStopped: i32 = 2; -pub const kCFRunLoopRunTimedOut: i32 = 3; +pub const kCFRunLoopRunFinished: i32 = 1; +pub const kCFRunLoopRunStopped: i32 = 2; +pub const kCFRunLoopRunTimedOut: i32 = 3; pub const kCFRunLoopRunHandledSource: i32 = 4; // Run Loop Observer Activities //typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) { pub type CFRunLoopActivity = CFOptionFlags; -pub const kCFRunLoopEntry: CFOptionFlags = 1 << 0; -pub const kCFRunLoopBeforeTimers: CFOptionFlags = 1 << 1; +pub const kCFRunLoopEntry: CFOptionFlags = 1 << 0; +pub const kCFRunLoopBeforeTimers: CFOptionFlags = 1 << 1; pub const kCFRunLoopBeforeSources: CFOptionFlags = 1 << 2; pub const kCFRunLoopBeforeWaiting: CFOptionFlags = 1 << 5; -pub const kCFRunLoopAfterWaiting: CFOptionFlags = 1 << 6; -pub const kCFRunLoopExit: CFOptionFlags = 1 << 7; +pub const kCFRunLoopAfterWaiting: CFOptionFlags = 1 << 6; +pub const kCFRunLoopExit: CFOptionFlags = 1 << 7; pub const kCFRunLoopAllActivities: CFOptionFlags = 0x0FFFFFFF; #[repr(C)] pub struct CFRunLoopSourceContext { pub version: CFIndex, pub info: *mut c_void, - pub retain: Option *const c_void>, - pub release: Option, - pub copyDescription: Option CFStringRef>, - pub equal: Option Boolean>, - pub hash: Option CFHashCode>, - pub schedule: Option, - pub cancel: Option, - pub perform: extern "C" fn (info: *const c_void), + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, + pub equal: Option Boolean>, + pub hash: Option CFHashCode>, + pub schedule: Option, + pub cancel: Option, + pub perform: extern "C" fn(info: *const c_void), } #[repr(C)] pub struct CFRunLoopSourceContext1 { pub version: CFIndex, pub info: *mut c_void, - pub retain: Option *const c_void>, - pub release: Option, - pub copyDescription: Option CFStringRef>, - pub equal: Option Boolean>, - pub hash: Option CFHashCode>, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, + pub equal: Option Boolean>, + pub hash: Option CFHashCode>, // note that the following two fields are platform dependent in the C header, the ones here are for macOS - pub getPort: extern "C" fn (info: *mut c_void) -> mach_port_t, - pub perform: extern "C" fn (msg: *mut c_void, size: CFIndex, allocator: CFAllocatorRef, info: *mut c_void) -> *mut c_void, + pub getPort: extern "C" fn(info: *mut c_void) -> mach_port_t, + pub perform: extern "C" fn( + msg: *mut c_void, + size: CFIndex, + allocator: CFAllocatorRef, + info: *mut c_void, + ) -> *mut c_void, } #[repr(C)] pub struct CFRunLoopObserverContext { pub version: CFIndex, pub info: *mut c_void, - pub retain: Option *const c_void>, - pub release: Option, - pub copyDescription: Option CFStringRef>, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, } -pub type CFRunLoopObserverCallBack = extern "C" fn (observer: CFRunLoopObserverRef, activity: CFRunLoopActivity, info: *mut c_void); +pub type CFRunLoopObserverCallBack = + extern "C" fn(observer: CFRunLoopObserverRef, activity: CFRunLoopActivity, info: *mut c_void); #[repr(C)] pub struct CFRunLoopTimerContext { pub version: CFIndex, pub info: *mut c_void, - pub retain: Option *const c_void>, - pub release: Option, - pub copyDescription: Option CFStringRef>, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, } -pub type CFRunLoopTimerCallBack = extern "C" fn (timer: CFRunLoopTimerRef, info: *mut c_void); +pub type CFRunLoopTimerCallBack = extern "C" fn(timer: CFRunLoopTimerRef, info: *mut c_void); #[repr(C)] pub struct __CFRunLoopTimer(c_void); pub type CFRunLoopTimerRef = *mut __CFRunLoopTimer; -extern { +extern "C" { /* * CFRunLoop.h */ @@ -115,41 +121,90 @@ extern { pub fn CFRunLoopAddCommonMode(rl: CFRunLoopRef, mode: CFStringRef); pub fn CFRunLoopGetNextTimerFireDate(rl: CFRunLoopRef, mode: CFStringRef) -> CFAbsoluteTime; pub fn CFRunLoopRun(); - pub fn CFRunLoopRunInMode(mode: CFStringRef, seconds: CFTimeInterval, returnAfterSourceHandled: Boolean) -> i32; + pub fn CFRunLoopRunInMode( + mode: CFStringRef, + seconds: CFTimeInterval, + returnAfterSourceHandled: Boolean, + ) -> i32; pub fn CFRunLoopIsWaiting(rl: CFRunLoopRef) -> Boolean; pub fn CFRunLoopWakeUp(rl: CFRunLoopRef); pub fn CFRunLoopStop(rl: CFRunLoopRef); // fn CFRunLoopPerformBlock(rl: CFRunLoopRef, mode: CFTypeRef, block: void (^)(void)); - pub fn CFRunLoopContainsSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef) -> Boolean; + pub fn CFRunLoopContainsSource( + rl: CFRunLoopRef, + source: CFRunLoopSourceRef, + mode: CFStringRef, + ) -> Boolean; pub fn CFRunLoopAddSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef); pub fn CFRunLoopRemoveSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef); - pub fn CFRunLoopContainsObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef) -> Boolean; - pub fn CFRunLoopAddObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef); - pub fn CFRunLoopRemoveObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef); - pub fn CFRunLoopContainsTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef) -> Boolean; + pub fn CFRunLoopContainsObserver( + rl: CFRunLoopRef, + observer: CFRunLoopObserverRef, + mode: CFStringRef, + ) -> Boolean; + pub fn CFRunLoopAddObserver( + rl: CFRunLoopRef, + observer: CFRunLoopObserverRef, + mode: CFStringRef, + ); + pub fn CFRunLoopRemoveObserver( + rl: CFRunLoopRef, + observer: CFRunLoopObserverRef, + mode: CFStringRef, + ); + pub fn CFRunLoopContainsTimer( + rl: CFRunLoopRef, + timer: CFRunLoopTimerRef, + mode: CFStringRef, + ) -> Boolean; pub fn CFRunLoopAddTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef); pub fn CFRunLoopRemoveTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef); pub fn CFRunLoopSourceGetTypeID() -> CFTypeID; - pub fn CFRunLoopSourceCreate(allocator: CFAllocatorRef, order: CFIndex, context: *mut CFRunLoopSourceContext) -> CFRunLoopSourceRef; + pub fn CFRunLoopSourceCreate( + allocator: CFAllocatorRef, + order: CFIndex, + context: *mut CFRunLoopSourceContext, + ) -> CFRunLoopSourceRef; pub fn CFRunLoopSourceGetOrder(source: CFRunLoopSourceRef) -> CFIndex; pub fn CFRunLoopSourceInvalidate(source: CFRunLoopSourceRef); pub fn CFRunLoopSourceIsValid(source: CFRunLoopSourceRef) -> Boolean; - pub fn CFRunLoopSourceGetContext(source: CFRunLoopSourceRef, context: *mut CFRunLoopSourceContext); + pub fn CFRunLoopSourceGetContext( + source: CFRunLoopSourceRef, + context: *mut CFRunLoopSourceContext, + ); pub fn CFRunLoopSourceSignal(source: CFRunLoopSourceRef); pub fn CFRunLoopObserverGetTypeID() -> CFTypeID; - pub fn CFRunLoopObserverCreate(allocator: CFAllocatorRef, activities: CFOptionFlags, repeats: Boolean, order: CFIndex, callout: CFRunLoopObserverCallBack, context: *mut CFRunLoopObserverContext) -> CFRunLoopObserverRef; + pub fn CFRunLoopObserverCreate( + allocator: CFAllocatorRef, + activities: CFOptionFlags, + repeats: Boolean, + order: CFIndex, + callout: CFRunLoopObserverCallBack, + context: *mut CFRunLoopObserverContext, + ) -> CFRunLoopObserverRef; // fn CFRunLoopObserverCreateWithHandler(allocator: CFAllocatorRef, activities: CFOptionFlags, repeats: Boolean, order: CFIndex, block: void (^) (CFRunLoopObserverRef observer, CFRunLoopActivity activity)) -> CFRunLoopObserverRef; pub fn CFRunLoopObserverGetActivities(observer: CFRunLoopObserverRef) -> CFOptionFlags; pub fn CFRunLoopObserverDoesRepeat(observer: CFRunLoopObserverRef) -> Boolean; pub fn CFRunLoopObserverGetOrder(observer: CFRunLoopObserverRef) -> CFIndex; pub fn CFRunLoopObserverInvalidate(observer: CFRunLoopObserverRef); pub fn CFRunLoopObserverIsValid(observer: CFRunLoopObserverRef) -> Boolean; - pub fn CFRunLoopObserverGetContext(observer: CFRunLoopObserverRef, context: *mut CFRunLoopObserverContext); + pub fn CFRunLoopObserverGetContext( + observer: CFRunLoopObserverRef, + context: *mut CFRunLoopObserverContext, + ); pub fn CFRunLoopTimerGetTypeID() -> CFTypeID; - pub fn CFRunLoopTimerCreate(allocator: CFAllocatorRef, fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, callout: CFRunLoopTimerCallBack, context: *mut CFRunLoopTimerContext) -> CFRunLoopTimerRef; + pub fn CFRunLoopTimerCreate( + allocator: CFAllocatorRef, + fireDate: CFAbsoluteTime, + interval: CFTimeInterval, + flags: CFOptionFlags, + order: CFIndex, + callout: CFRunLoopTimerCallBack, + context: *mut CFRunLoopTimerContext, + ) -> CFRunLoopTimerRef; // fn CFRunLoopTimerCreateWithHandler(allocator: CFAllocatorRef, fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, block: void (^) (CFRunLoopTimerRef timer)) -> CFRunLoopTimerRef; pub fn CFRunLoopTimerGetNextFireDate(timer: CFRunLoopTimerRef) -> CFAbsoluteTime; pub fn CFRunLoopTimerSetNextFireDate(timer: CFRunLoopTimerRef, fireDate: CFAbsoluteTime); diff --git a/core-foundation-sys/src/set.rs b/core-foundation-sys/src/set.rs index a5cc1b16f..1b166d963 100644 --- a/core-foundation-sys/src/set.rs +++ b/core-foundation-sys/src/set.rs @@ -9,10 +9,9 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, CFIndex, CFTypeID, Boolean}; +use base::{Boolean, CFAllocatorRef, CFIndex, CFTypeID}; -pub type CFSetApplierFunction = extern "C" fn (value: *const c_void, - context: *const c_void); +pub type CFSetApplierFunction = extern "C" fn(value: *const c_void, context: *const c_void); pub type CFSetRetainCallBack = *const u8; pub type CFSetReleaseCallBack = *const u8; pub type CFSetCopyDescriptionCallBack = *const u8; @@ -35,7 +34,7 @@ pub struct __CFSet(c_void); pub type CFSetRef = *const __CFSet; -extern { +extern "C" { /* * CFSet.h */ @@ -43,8 +42,12 @@ extern { pub static kCFTypeSetCallBacks: CFSetCallBacks; /* Creating Sets */ - pub fn CFSetCreate(allocator: CFAllocatorRef, values: *const *const c_void, numValues: CFIndex, - callBacks: *const CFSetCallBacks) -> CFSetRef; + pub fn CFSetCreate( + allocator: CFAllocatorRef, + values: *const *const c_void, + numValues: CFIndex, + callBacks: *const CFSetCallBacks, + ) -> CFSetRef; pub fn CFSetCreateCopy(allocator: CFAllocatorRef, theSet: CFSetRef) -> CFSetRef; /* Examining a Set */ @@ -52,15 +55,20 @@ extern { pub fn CFSetGetCount(theSet: CFSetRef) -> CFIndex; pub fn CFSetGetCountOfValue(theSet: CFSetRef, value: *const c_void) -> CFIndex; pub fn CFSetGetValue(theSet: CFSetRef, value: *const c_void) -> *const c_void; - pub fn CFSetGetValueIfPresent(theSet: CFSetRef, candidate: *const c_void, value: *mut *const c_void) -> Boolean; + pub fn CFSetGetValueIfPresent( + theSet: CFSetRef, + candidate: *const c_void, + value: *mut *const c_void, + ) -> Boolean; pub fn CFSetGetValues(theSet: CFSetRef, values: *mut *const c_void); /* Applying a Function to Set Members */ - pub fn CFSetApplyFunction(theSet: CFSetRef, - applier: CFSetApplierFunction, - context: *const c_void); + pub fn CFSetApplyFunction( + theSet: CFSetRef, + applier: CFSetApplierFunction, + context: *const c_void, + ); /* Getting the CFSet Type ID */ pub fn CFSetGetTypeID() -> CFTypeID; } - diff --git a/core-foundation-sys/src/string.rs b/core-foundation-sys/src/string.rs index d4f655078..5ce800d3e 100644 --- a/core-foundation-sys/src/string.rs +++ b/core-foundation-sys/src/string.rs @@ -9,7 +9,7 @@ use std::os::raw::{c_char, c_ushort, c_void}; -use base::{Boolean, CFOptionFlags, CFIndex, CFAllocatorRef, CFRange, CFTypeID}; +use base::{Boolean, CFAllocatorRef, CFIndex, CFOptionFlags, CFRange, CFTypeID}; pub type UniChar = c_ushort; @@ -46,7 +46,6 @@ pub static kCFStringEncodingUTF8: CFStringEncoding = 0x08000100; //static kCFStringEncodingUTF32BE: CFStringEncoding = 0x18000100; //static kCFStringEncodingUTF32LE: CFStringEncoding = 0x1c000100; - // CFStringEncodingExt.h pub type CFStringEncodings = CFIndex; @@ -186,13 +185,12 @@ pub type CFStringEncodings = CFIndex; //static kCFStringEncodingUTF7: CFStringEncoding = 0x04000100; //static kCFStringEncodingUTF7_IMAP: CFStringEncoding = 0x0A10; //static kCFStringEncodingShiftJIS_X0213_00: CFStringEncoding = 0x0628; /* Deprecated */ - #[repr(C)] pub struct __CFString(c_void); pub type CFStringRef = *const __CFString; -extern { +extern "C" { /* * CFString.h */ @@ -205,29 +203,33 @@ extern { //fn CFStringCreateByCombiningStrings //fn CFStringCreateCopy //fn CFStringCreateFromExternalRepresentation - pub fn CFStringCreateWithBytes(alloc: CFAllocatorRef, - bytes: *const u8, - numBytes: CFIndex, - encoding: CFStringEncoding, - isExternalRepresentation: Boolean) - -> CFStringRef; - pub fn CFStringCreateWithBytesNoCopy(alloc: CFAllocatorRef, - bytes: *const u8, - numBytes: CFIndex, - encoding: CFStringEncoding, - isExternalRepresentation: Boolean, - contentsDeallocator: CFAllocatorRef) - -> CFStringRef; + pub fn CFStringCreateWithBytes( + alloc: CFAllocatorRef, + bytes: *const u8, + numBytes: CFIndex, + encoding: CFStringEncoding, + isExternalRepresentation: Boolean, + ) -> CFStringRef; + pub fn CFStringCreateWithBytesNoCopy( + alloc: CFAllocatorRef, + bytes: *const u8, + numBytes: CFIndex, + encoding: CFStringEncoding, + isExternalRepresentation: Boolean, + contentsDeallocator: CFAllocatorRef, + ) -> CFStringRef; //fn CFStringCreateWithCharacters - pub fn CFStringCreateWithCharactersNoCopy(alloc: CFAllocatorRef, - chars: *const UniChar, - numChars: CFIndex, - contentsDeallocator: CFAllocatorRef) - -> CFStringRef; - pub fn CFStringCreateWithCString(alloc: CFAllocatorRef, - cStr: *const c_char, - encoding: CFStringEncoding) - -> CFStringRef; + pub fn CFStringCreateWithCharactersNoCopy( + alloc: CFAllocatorRef, + chars: *const UniChar, + numChars: CFIndex, + contentsDeallocator: CFAllocatorRef, + ) -> CFStringRef; + pub fn CFStringCreateWithCString( + alloc: CFAllocatorRef, + cStr: *const c_char, + encoding: CFStringEncoding, + ) -> CFStringRef; //fn CFStringCreateWithCStringNoCopy //fn CFStringCreateWithFormat //fn CFStringCreateWithFormatAndArguments @@ -252,27 +254,30 @@ extern { /* Accessing Characters */ //fn CFStringCreateExternalRepresentation - pub fn CFStringGetBytes(theString: CFStringRef, - range: CFRange, - encoding: CFStringEncoding, - lossByte: u8, - isExternalRepresentation: Boolean, - buffer: *mut u8, - maxBufLen: CFIndex, - usedBufLen: *mut CFIndex) - -> CFIndex; + pub fn CFStringGetBytes( + theString: CFStringRef, + range: CFRange, + encoding: CFStringEncoding, + lossByte: u8, + isExternalRepresentation: Boolean, + buffer: *mut u8, + maxBufLen: CFIndex, + usedBufLen: *mut CFIndex, + ) -> CFIndex; //fn CFStringGetCharacterAtIndex //fn CFStringGetCharacters //fn CFStringGetCharactersPtr //fn CFStringGetCharacterFromInlineBuffer - pub fn CFStringGetCString(theString: CFStringRef, - buffer: *mut c_char, - bufferSize: CFIndex, - encoding: CFStringEncoding) - -> Boolean; - pub fn CFStringGetCStringPtr(theString: CFStringRef, - encoding: CFStringEncoding) - -> *const c_char; + pub fn CFStringGetCString( + theString: CFStringRef, + buffer: *mut c_char, + bufferSize: CFIndex, + encoding: CFStringEncoding, + ) -> Boolean; + pub fn CFStringGetCStringPtr( + theString: CFStringRef, + encoding: CFStringEncoding, + ) -> *const c_char; pub fn CFStringGetLength(theString: CFStringRef) -> CFIndex; //fn CFStringGetPascalString //fn CFStringGetPascalStringPtr diff --git a/core-foundation-sys/src/timezone.rs b/core-foundation-sys/src/timezone.rs index 0b279db18..99fa231f8 100644 --- a/core-foundation-sys/src/timezone.rs +++ b/core-foundation-sys/src/timezone.rs @@ -10,7 +10,7 @@ use std::os::raw::c_void; use base::{CFAllocatorRef, CFTypeID}; -use date::{CFTimeInterval, CFAbsoluteTime}; +use date::{CFAbsoluteTime, CFTimeInterval}; use string::CFStringRef; #[repr(C)] @@ -18,10 +18,13 @@ pub struct __CFTimeZone(c_void); pub type CFTimeZoneRef = *const __CFTimeZone; -extern { +extern "C" { pub fn CFTimeZoneCopySystem() -> CFTimeZoneRef; pub fn CFTimeZoneCopyDefault() -> CFTimeZoneRef; - pub fn CFTimeZoneCreateWithTimeIntervalFromGMT(allocator: CFAllocatorRef, interval: CFTimeInterval) -> CFTimeZoneRef; + pub fn CFTimeZoneCreateWithTimeIntervalFromGMT( + allocator: CFAllocatorRef, + interval: CFTimeInterval, + ) -> CFTimeZoneRef; pub fn CFTimeZoneGetSecondsFromGMT(tz: CFTimeZoneRef, time: CFAbsoluteTime) -> CFTimeInterval; pub fn CFTimeZoneGetTypeID() -> CFTypeID; diff --git a/core-foundation-sys/src/url.rs b/core-foundation-sys/src/url.rs index 08e7bcd9f..e314b3d62 100644 --- a/core-foundation-sys/src/url.rs +++ b/core-foundation-sys/src/url.rs @@ -9,12 +9,12 @@ use std::os::raw::c_void; -use base::{CFOptionFlags, CFIndex, CFAllocatorRef, Boolean, CFTypeID, CFTypeRef, SInt32}; -use data::CFDataRef; use array::CFArrayRef; +use base::{Boolean, CFAllocatorRef, CFIndex, CFOptionFlags, CFTypeID, CFTypeRef, SInt32}; +use data::CFDataRef; use dictionary::CFDictionaryRef; -use string::{CFStringRef, CFStringEncoding}; use error::CFErrorRef; +use string::{CFStringEncoding, CFStringRef}; #[repr(C)] pub struct __CFURL(c_void); @@ -28,8 +28,8 @@ pub type CFURLBookmarkFileCreationOptions = CFOptionFlags; pub type CFURLPathStyle = CFIndex; /* typedef CF_ENUM(CFIndex, CFURLPathStyle) */ -pub const kCFURLPOSIXPathStyle: CFURLPathStyle = 0; -pub const kCFURLHFSPathStyle: CFURLPathStyle = 1; +pub const kCFURLPOSIXPathStyle: CFURLPathStyle = 0; +pub const kCFURLHFSPathStyle: CFURLPathStyle = 1; pub const kCFURLWindowsPathStyle: CFURLPathStyle = 2; pub static kCFURLBookmarkCreationPreferFileIDResolutionMask: CFURLBookmarkCreationOptions = @@ -45,7 +45,7 @@ pub static kCFURLBookmarkCreationSecurityScopeAllowOnlyReadAccess: CFURLBookmark // TODO: there are a lot of missing keys and constants. Add if you are bored or need them. -extern { +extern "C" { /* * CFURL.h */ @@ -81,42 +81,90 @@ extern { pub static kCFURLVolumeIdentifierKey: CFStringRef; pub static kCFURLVolumeURLKey: CFStringRef; - #[cfg(feature="mac_os_10_8_features")] + #[cfg(feature = "mac_os_10_8_features")] #[cfg_attr(feature = "mac_os_10_7_support", linkage = "extern_weak")] pub static kCFURLIsExcludedFromBackupKey: CFStringRef; pub static kCFURLFileResourceTypeKey: CFStringRef; /* Creating a CFURL */ pub fn CFURLCopyAbsoluteURL(anURL: CFURLRef) -> CFURLRef; - pub fn CFURLCreateAbsoluteURLWithBytes(allocator: CFAllocatorRef, relativeURLBytes: *const u8, length: CFIndex, encoding: CFStringEncoding, baseURL: CFURLRef, useCompatibilityMode: Boolean) -> CFURLRef; - pub fn CFURLCreateByResolvingBookmarkData(allocator: CFAllocatorRef, bookmark: CFDataRef, options: CFURLBookmarkResolutionOptions, relativeToURL: CFURLRef, resourcePropertiesToInclude: CFArrayRef, isStale: *mut Boolean, error: *mut CFErrorRef) -> CFURLRef; + pub fn CFURLCreateAbsoluteURLWithBytes( + allocator: CFAllocatorRef, + relativeURLBytes: *const u8, + length: CFIndex, + encoding: CFStringEncoding, + baseURL: CFURLRef, + useCompatibilityMode: Boolean, + ) -> CFURLRef; + pub fn CFURLCreateByResolvingBookmarkData( + allocator: CFAllocatorRef, + bookmark: CFDataRef, + options: CFURLBookmarkResolutionOptions, + relativeToURL: CFURLRef, + resourcePropertiesToInclude: CFArrayRef, + isStale: *mut Boolean, + error: *mut CFErrorRef, + ) -> CFURLRef; //fn CFURLCreateCopyAppendingPathComponent //fn CFURLCreateCopyAppendingPathExtension //fn CFURLCreateCopyDeletingLastPathComponent //fn CFURLCreateCopyDeletingPathExtension - pub fn CFURLCreateFilePathURL(allocator: CFAllocatorRef, url: CFURLRef, error: *mut CFErrorRef) -> CFURLRef; + pub fn CFURLCreateFilePathURL( + allocator: CFAllocatorRef, + url: CFURLRef, + error: *mut CFErrorRef, + ) -> CFURLRef; //fn CFURLCreateFileReferenceURL - pub fn CFURLCreateFromFileSystemRepresentation(allocator: CFAllocatorRef, buffer: *const u8, bufLen: CFIndex, isDirectory: Boolean) -> CFURLRef; + pub fn CFURLCreateFromFileSystemRepresentation( + allocator: CFAllocatorRef, + buffer: *const u8, + bufLen: CFIndex, + isDirectory: Boolean, + ) -> CFURLRef; //fn CFURLCreateFromFileSystemRepresentationRelativeToBase //fn CFURLCreateFromFSRef - pub fn CFURLCreateWithBytes(allocator: CFAllocatorRef, URLBytes: *const u8, length: CFIndex, encoding: CFStringEncoding, baseURL: CFURLRef) -> CFURLRef; - pub fn CFURLCreateWithFileSystemPath(allocator: CFAllocatorRef, filePath: CFStringRef, pathStyle: CFURLPathStyle, isDirectory: Boolean) -> CFURLRef; - pub fn CFURLCreateWithFileSystemPathRelativeToBase(allocator: CFAllocatorRef, filePath: CFStringRef, pathStyle: CFURLPathStyle, isDirectory: Boolean, baseURL: CFURLRef) -> CFURLRef; + pub fn CFURLCreateWithBytes( + allocator: CFAllocatorRef, + URLBytes: *const u8, + length: CFIndex, + encoding: CFStringEncoding, + baseURL: CFURLRef, + ) -> CFURLRef; + pub fn CFURLCreateWithFileSystemPath( + allocator: CFAllocatorRef, + filePath: CFStringRef, + pathStyle: CFURLPathStyle, + isDirectory: Boolean, + ) -> CFURLRef; + pub fn CFURLCreateWithFileSystemPathRelativeToBase( + allocator: CFAllocatorRef, + filePath: CFStringRef, + pathStyle: CFURLPathStyle, + isDirectory: Boolean, + baseURL: CFURLRef, + ) -> CFURLRef; //fn CFURLCreateWithString(allocator: CFAllocatorRef, urlString: CFStringRef, // baseURL: CFURLRef) -> CFURLRef; /* Accessing the Parts of a URL */ pub fn CFURLCanBeDecomposed(anURL: CFURLRef) -> Boolean; pub fn CFURLCopyFileSystemPath(anURL: CFURLRef, pathStyle: CFURLPathStyle) -> CFStringRef; - pub fn CFURLCopyFragment(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; + pub fn CFURLCopyFragment(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) + -> CFStringRef; pub fn CFURLCopyHostName(anURL: CFURLRef) -> CFStringRef; pub fn CFURLCopyLastPathComponent(anURL: CFURLRef) -> CFStringRef; pub fn CFURLCopyNetLocation(anURL: CFURLRef) -> CFStringRef; - pub fn CFURLCopyParameterString(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; + pub fn CFURLCopyParameterString( + anURL: CFURLRef, + charactersToLeaveEscaped: CFStringRef, + ) -> CFStringRef; pub fn CFURLCopyPassword(anURL: CFURLRef) -> CFStringRef; pub fn CFURLCopyPath(anURL: CFURLRef) -> CFStringRef; pub fn CFURLCopyPathExtension(anURL: CFURLRef) -> CFStringRef; - pub fn CFURLCopyQueryString(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; + pub fn CFURLCopyQueryString( + anURL: CFURLRef, + charactersToLeaveEscaped: CFStringRef, + ) -> CFStringRef; pub fn CFURLCopyResourceSpecifier(anURL: CFURLRef) -> CFStringRef; pub fn CFURLCopyScheme(anURL: CFURLRef) -> CFStringRef; pub fn CFURLCopyStrictPath(anURL: CFURLRef, isAbsolute: *mut Boolean) -> CFStringRef; @@ -130,7 +178,12 @@ extern { //fn CFURLCreateStringByAddingPercentEscapes //fn CFURLCreateStringByReplacingPercentEscapes //fn CFURLCreateStringByReplacingPercentEscapesUsingEncoding - pub fn CFURLGetFileSystemRepresentation(anURL: CFURLRef, resolveAgainstBase: Boolean, buffer: *mut u8, maxBufLen: CFIndex) -> Boolean; + pub fn CFURLGetFileSystemRepresentation( + anURL: CFURLRef, + resolveAgainstBase: Boolean, + buffer: *mut u8, + maxBufLen: CFIndex, + ) -> Boolean; //fn CFURLGetFSRef pub fn CFURLGetString(anURL: CFURLRef) -> CFStringRef; @@ -147,23 +200,55 @@ extern { //fn CFURLClearResourcePropertyCacheForKey //fn CFURLCopyResourcePropertiesForKeys //fn CFURLCopyResourcePropertyForKey - pub fn CFURLCreateResourcePropertiesForKeysFromBookmarkData(allocator: CFAllocatorRef, resourcePropertiesToReturn: CFArrayRef, bookmark: CFDataRef) -> CFDictionaryRef; - pub fn CFURLCreateResourcePropertyForKeyFromBookmarkData(allocator: CFAllocatorRef, resourcePropertyKey: CFStringRef, bookmark: CFDataRef) -> CFTypeRef; + pub fn CFURLCreateResourcePropertiesForKeysFromBookmarkData( + allocator: CFAllocatorRef, + resourcePropertiesToReturn: CFArrayRef, + bookmark: CFDataRef, + ) -> CFDictionaryRef; + pub fn CFURLCreateResourcePropertyForKeyFromBookmarkData( + allocator: CFAllocatorRef, + resourcePropertyKey: CFStringRef, + bookmark: CFDataRef, + ) -> CFTypeRef; //fn CFURLSetResourcePropertiesForKeys - pub fn CFURLSetResourcePropertyForKey(url: CFURLRef, key: CFStringRef, value: CFTypeRef, error: *mut CFErrorRef) -> Boolean; + pub fn CFURLSetResourcePropertyForKey( + url: CFURLRef, + key: CFStringRef, + value: CFTypeRef, + error: *mut CFErrorRef, + ) -> Boolean; //fn CFURLSetTemporaryResourcePropertyForKey /* Working with Bookmark Data */ - pub fn CFURLCreateBookmarkData(allocator: CFAllocatorRef, url: CFURLRef, options: CFURLBookmarkCreationOptions, resourcePropertiesToInclude: CFArrayRef, relativeToURL: CFURLRef, error: *mut CFErrorRef) -> CFDataRef; - pub fn CFURLCreateBookmarkDataFromAliasRecord(allocator: CFAllocatorRef, aliasRecordDataRef: CFDataRef) -> CFDataRef; - pub fn CFURLCreateBookmarkDataFromFile(allocator: CFAllocatorRef, fileURL: CFURLRef, errorRef: *mut CFErrorRef) -> CFDataRef; - pub fn CFURLWriteBookmarkDataToFile(bookmarkRef: CFDataRef, fileURL: CFURLRef, options: CFURLBookmarkFileCreationOptions, errorRef: *mut CFErrorRef) -> Boolean; + pub fn CFURLCreateBookmarkData( + allocator: CFAllocatorRef, + url: CFURLRef, + options: CFURLBookmarkCreationOptions, + resourcePropertiesToInclude: CFArrayRef, + relativeToURL: CFURLRef, + error: *mut CFErrorRef, + ) -> CFDataRef; + pub fn CFURLCreateBookmarkDataFromAliasRecord( + allocator: CFAllocatorRef, + aliasRecordDataRef: CFDataRef, + ) -> CFDataRef; + pub fn CFURLCreateBookmarkDataFromFile( + allocator: CFAllocatorRef, + fileURL: CFURLRef, + errorRef: *mut CFErrorRef, + ) -> CFDataRef; + pub fn CFURLWriteBookmarkDataToFile( + bookmarkRef: CFDataRef, + fileURL: CFURLRef, + options: CFURLBookmarkFileCreationOptions, + errorRef: *mut CFErrorRef, + ) -> Boolean; pub fn CFURLStartAccessingSecurityScopedResource(url: CFURLRef) -> Boolean; pub fn CFURLStopAccessingSecurityScopedResource(url: CFURLRef); } #[test] -#[cfg(feature="mac_os_10_8_features")] +#[cfg(feature = "mac_os_10_8_features")] fn can_see_excluded_from_backup_key() { let _ = unsafe { kCFURLIsExcludedFromBackupKey }; } diff --git a/core-foundation-sys/src/uuid.rs b/core-foundation-sys/src/uuid.rs index 425395293..2412f739b 100644 --- a/core-foundation-sys/src/uuid.rs +++ b/core-foundation-sys/src/uuid.rs @@ -19,25 +19,25 @@ pub type CFUUIDRef = *const __CFUUID; #[repr(C)] #[derive(Clone, Copy, Default)] pub struct CFUUIDBytes { - pub byte0: u8, - pub byte1: u8, - pub byte2: u8, - pub byte3: u8, - pub byte4: u8, - pub byte5: u8, - pub byte6: u8, - pub byte7: u8, - pub byte8: u8, - pub byte9: u8, + pub byte0: u8, + pub byte1: u8, + pub byte2: u8, + pub byte3: u8, + pub byte4: u8, + pub byte5: u8, + pub byte6: u8, + pub byte7: u8, + pub byte8: u8, + pub byte9: u8, pub byte10: u8, pub byte11: u8, pub byte12: u8, pub byte13: u8, pub byte14: u8, - pub byte15: u8 + pub byte15: u8, } -extern { +extern "C" { /* * CFUUID.h */ diff --git a/core-foundation/src/array.rs b/core-foundation/src/array.rs index d66ffc5b8..9ddb8c6fa 100644 --- a/core-foundation/src/array.rs +++ b/core-foundation/src/array.rs @@ -11,14 +11,14 @@ pub use core_foundation_sys::array::*; pub use core_foundation_sys::base::CFIndex; -use core_foundation_sys::base::{CFTypeRef, CFRelease, kCFAllocatorDefault}; -use std::mem; +use core_foundation_sys::base::{kCFAllocatorDefault, CFRelease, CFTypeRef}; use std::marker::PhantomData; +use std::mem; use std::os::raw::c_void; use std::ptr; use ConcreteCFType; -use base::{CFIndexConvertible, TCFType, CFRange}; +use base::{CFIndexConvertible, CFRange, TCFType}; use base::{FromVoid, ItemRef}; /// A heterogeneous immutable array. @@ -63,24 +63,34 @@ unsafe impl ConcreteCFType for CFArray<*const c_void> {} impl CFArray { /// Creates a new `CFArray` with the given elements, which must implement `Copy`. - pub fn from_copyable(elems: &[T]) -> CFArray where T: Copy { + pub fn from_copyable(elems: &[T]) -> CFArray + where + T: Copy, + { unsafe { - let array_ref = CFArrayCreate(kCFAllocatorDefault, - elems.as_ptr() as *const *const c_void, - elems.len().to_CFIndex(), - ptr::null()); + let array_ref = CFArrayCreate( + kCFAllocatorDefault, + elems.as_ptr() as *const *const c_void, + elems.len().to_CFIndex(), + ptr::null(), + ); TCFType::wrap_under_create_rule(array_ref) } } /// Creates a new `CFArray` with the given elements, which must be `CFType` objects. - pub fn from_CFTypes(elems: &[T]) -> CFArray where T: TCFType { + pub fn from_CFTypes(elems: &[T]) -> CFArray + where + T: TCFType, + { unsafe { let elems: Vec = elems.iter().map(|elem| elem.as_CFTypeRef()).collect(); - let array_ref = CFArrayCreate(kCFAllocatorDefault, - elems.as_ptr(), - elems.len().to_CFIndex(), - &kCFTypeArrayCallBacks); + let array_ref = CFArrayCreate( + kCFAllocatorDefault, + elems.as_ptr(), + elems.len().to_CFIndex(), + &kCFTypeArrayCallBacks, + ); TCFType::wrap_under_create_rule(array_ref) } } @@ -115,20 +125,24 @@ impl CFArray { #[inline] pub fn len(&self) -> CFIndex { - unsafe { - CFArrayGetCount(self.0) - } + unsafe { CFArrayGetCount(self.0) } } #[inline] - pub unsafe fn get_unchecked<'a>(&'a self, index: CFIndex) -> ItemRef<'a, T> where T: FromVoid { + pub unsafe fn get_unchecked<'a>(&'a self, index: CFIndex) -> ItemRef<'a, T> + where + T: FromVoid, + { T::from_void(CFArrayGetValueAtIndex(self.0, index)) } #[inline] - pub fn get<'a>(&'a self, index: CFIndex) -> Option> where T: FromVoid { + pub fn get<'a>(&'a self, index: CFIndex) -> Option> + where + T: FromVoid, + { if index < self.len() { - Some(unsafe { T::from_void(CFArrayGetValueAtIndex(self.0, index)) } ) + Some(unsafe { T::from_void(CFArrayGetValueAtIndex(self.0, index)) }) } else { None } @@ -146,7 +160,7 @@ impl CFArray { pub fn get_all_values(&self) -> Vec<*const c_void> { self.get_values(CFRange { location: 0, - length: self.len() + length: self.len(), }) } } @@ -163,8 +177,8 @@ impl<'a, T: FromVoid> IntoIterator for &'a CFArray { #[cfg(test)] mod tests { use super::*; - use std::mem; use base::CFType; + use std::mem; #[test] fn to_untyped_correct_retain_count() { @@ -216,15 +230,16 @@ mod tests { #[test] fn iter_untyped_array() { - use string::{CFString, CFStringRef}; use base::TCFTypeRef; + use string::{CFString, CFStringRef}; let cf_string = CFString::from_static_string("bar"); let array: CFArray = CFArray::from_CFTypes(&[cf_string.clone()]).into_untyped(); - let cf_strings = array.iter().map(|ptr| { - unsafe { CFString::wrap_under_get_rule(CFStringRef::from_void_ptr(*ptr)) } - }).collect::>(); + let cf_strings = array + .iter() + .map(|ptr| unsafe { CFString::wrap_under_get_rule(CFStringRef::from_void_ptr(*ptr)) }) + .collect::>(); let strings = cf_strings.iter().map(|s| s.to_string()).collect::>(); assert_eq!(cf_string.retain_count(), 3); assert_eq!(&strings[..], &["bar"]); diff --git a/core-foundation/src/attributed_string.rs b/core-foundation/src/attributed_string.rs index d4a467946..e7794d12b 100644 --- a/core-foundation/src/attributed_string.rs +++ b/core-foundation/src/attributed_string.rs @@ -10,21 +10,25 @@ pub use core_foundation_sys::attributed_string::*; use base::TCFType; -use core_foundation_sys::base::{CFIndex, CFRange, kCFAllocatorDefault}; +use core_foundation_sys::base::{kCFAllocatorDefault, CFIndex, CFRange}; use std::ptr::null; use string::{CFString, CFStringRef}; -declare_TCFType!{ +declare_TCFType! { CFAttributedString, CFAttributedStringRef } -impl_TCFType!(CFAttributedString, CFAttributedStringRef, CFAttributedStringGetTypeID); +impl_TCFType!( + CFAttributedString, + CFAttributedStringRef, + CFAttributedStringGetTypeID +); impl CFAttributedString { #[inline] pub fn new(string: &CFString) -> Self { unsafe { - let astr_ref = CFAttributedStringCreate( - kCFAllocatorDefault, string.as_concrete_TypeRef(), null()); + let astr_ref = + CFAttributedStringCreate(kCFAllocatorDefault, string.as_concrete_TypeRef(), null()); CFAttributedString::wrap_under_create_rule(astr_ref) } @@ -32,23 +36,24 @@ impl CFAttributedString { #[inline] pub fn char_len(&self) -> CFIndex { - unsafe { - CFAttributedStringGetLength(self.0) - } + unsafe { CFAttributedStringGetLength(self.0) } } } -declare_TCFType!{ +declare_TCFType! { CFMutableAttributedString, CFMutableAttributedStringRef } -impl_TCFType!(CFMutableAttributedString, CFMutableAttributedStringRef, CFAttributedStringGetTypeID); +impl_TCFType!( + CFMutableAttributedString, + CFMutableAttributedStringRef, + CFAttributedStringGetTypeID +); impl CFMutableAttributedString { #[inline] pub fn new() -> Self { unsafe { - let astr_ref = CFAttributedStringCreateMutable( - kCFAllocatorDefault, 0); + let astr_ref = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); CFMutableAttributedString::wrap_under_create_rule(astr_ref) } @@ -56,24 +61,20 @@ impl CFMutableAttributedString { #[inline] pub fn char_len(&self) -> CFIndex { - unsafe { - CFAttributedStringGetLength(self.0) - } + unsafe { CFAttributedStringGetLength(self.0) } } #[inline] pub fn replace_str(&mut self, string: &CFString, range: CFRange) { unsafe { - CFAttributedStringReplaceString( - self.0, range, string.as_concrete_TypeRef()); + CFAttributedStringReplaceString(self.0, range, string.as_concrete_TypeRef()); } } #[inline] pub fn set_attribute(&mut self, range: CFRange, name: CFStringRef, value: &T) { unsafe { - CFAttributedStringSetAttribute( - self.0, range, name, value.as_CFTypeRef()); + CFAttributedStringSetAttribute(self.0, range, name, value.as_CFTypeRef()); } } } @@ -84,7 +85,6 @@ impl Default for CFMutableAttributedString { } } - #[cfg(test)] mod tests { use super::*; @@ -93,6 +93,9 @@ mod tests { fn attributed_string_type_id_comparison() { // CFMutableAttributedString TypeID must be equal to CFAttributedString TypeID. // Compilation must not fail. - assert_eq!(::type_id(), ::type_id()); + assert_eq!( + ::type_id(), + ::type_id() + ); } -} \ No newline at end of file +} diff --git a/core-foundation/src/base.rs b/core-foundation/src/base.rs index f08f2b2e8..fa1c5d8bd 100644 --- a/core-foundation/src/base.rs +++ b/core-foundation/src/base.rs @@ -37,7 +37,7 @@ impl CFIndexConvertible for usize { } } -declare_TCFType!{ +declare_TCFType! { /// Superclass of all Core Foundation objects. CFType, CFTypeRef } @@ -111,13 +111,11 @@ impl CFType { } impl fmt::Debug for CFType { - /// Formats the value using [`CFCopyDescription`]. - /// - /// [`CFCopyDescription`]: https://developer.apple.com/documentation/corefoundation/1521252-cfcopydescription?language=objc + /// Formats the value using [`CFCopyDescription`]. + /// + /// [`CFCopyDescription`]: https://developer.apple.com/documentation/corefoundation/1521252-cfcopydescription?language=objc fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let desc = unsafe { - CFString::wrap_under_create_rule(CFCopyDescription(self.0)) - }; + let desc = unsafe { CFString::wrap_under_create_rule(CFCopyDescription(self.0)) }; desc.fmt(f) } } @@ -125,18 +123,14 @@ impl fmt::Debug for CFType { impl Clone for CFType { #[inline] fn clone(&self) -> CFType { - unsafe { - TCFType::wrap_under_get_rule(self.0) - } + unsafe { TCFType::wrap_under_get_rule(self.0) } } } impl PartialEq for CFType { #[inline] fn eq(&self, other: &CFType) -> bool { - unsafe { - CFEqual(self.as_CFTypeRef(), other.as_CFTypeRef()) != 0 - } + unsafe { CFEqual(self.as_CFTypeRef(), other.as_CFTypeRef()) != 0 } } } @@ -153,7 +147,6 @@ impl CFAllocator { } } - /// All Core Foundation types implement this trait. The associated type `Ref` specifies the /// associated Core Foundation type: e.g. for `CFType` this is `CFTypeRef`; for `CFArray` this is /// `CFArrayRef`. @@ -178,9 +171,7 @@ pub trait TCFType { /// Returns the object as a wrapped `CFType`. The reference count is incremented by one. #[inline] fn as_CFType(&self) -> CFType { - unsafe { - TCFType::wrap_under_get_rule(self.as_CFTypeRef()) - } + unsafe { TCFType::wrap_under_get_rule(self.as_CFTypeRef()) } } /// Returns the object as a wrapped `CFType`. Consumes self and avoids changing the reference @@ -206,24 +197,18 @@ pub trait TCFType { /// whether the return value of this method is greater than zero. #[inline] fn retain_count(&self) -> CFIndex { - unsafe { - CFGetRetainCount(self.as_CFTypeRef()) - } + unsafe { CFGetRetainCount(self.as_CFTypeRef()) } } /// Returns the type ID of this object. #[inline] fn type_of(&self) -> CFTypeID { - unsafe { - CFGetTypeID(self.as_CFTypeRef()) - } + unsafe { CFGetTypeID(self.as_CFTypeRef()) } } /// Writes a debugging version of this object on standard error. fn show(&self) { - unsafe { - CFShow(self.as_CFTypeRef()) - } + unsafe { CFShow(self.as_CFTypeRef()) } } /// Returns true if this value is an instance of another type. @@ -320,7 +305,9 @@ impl<'a, T: PartialEq> PartialEq for ItemMutRef<'a, T> { /// A trait describing how to convert from the stored *mut c_void to the desired T pub unsafe trait FromMutVoid { - unsafe fn from_mut_void<'a>(x: *mut c_void) -> ItemMutRef<'a, Self> where Self: std::marker::Sized; + unsafe fn from_mut_void<'a>(x: *mut c_void) -> ItemMutRef<'a, Self> + where + Self: std::marker::Sized; } unsafe impl FromMutVoid for u32 { @@ -337,13 +324,18 @@ unsafe impl FromMutVoid for *const c_void { unsafe impl FromMutVoid for T { unsafe fn from_mut_void<'a>(x: *mut c_void) -> ItemMutRef<'a, Self> { - ItemMutRef(ManuallyDrop::new(TCFType::wrap_under_create_rule(T::Ref::from_void_ptr(x))), PhantomData) + ItemMutRef( + ManuallyDrop::new(TCFType::wrap_under_create_rule(T::Ref::from_void_ptr(x))), + PhantomData, + ) } } /// A trait describing how to convert from the stored *const c_void to the desired T pub unsafe trait FromVoid { - unsafe fn from_void<'a>(x: *const c_void) -> ItemRef<'a, Self> where Self: std::marker::Sized; + unsafe fn from_void<'a>(x: *const c_void) -> ItemRef<'a, Self> + where + Self: std::marker::Sized; } unsafe impl FromVoid for u32 { @@ -362,7 +354,10 @@ unsafe impl FromVoid for *const c_void { unsafe impl FromVoid for T { unsafe fn from_void<'a>(x: *const c_void) -> ItemRef<'a, Self> { - ItemRef(ManuallyDrop::new(TCFType::wrap_under_create_rule(T::Ref::from_void_ptr(x))), PhantomData) + ItemRef( + ManuallyDrop::new(TCFType::wrap_under_create_rule(T::Ref::from_void_ptr(x))), + PhantomData, + ) } } @@ -395,12 +390,11 @@ unsafe impl ToVoid for CFTypeRef { } } - #[cfg(test)] mod tests { use super::*; - use std::mem; use boolean::CFBoolean; + use std::mem; #[test] fn cftype_instance_of() { diff --git a/core-foundation/src/boolean.rs b/core-foundation/src/boolean.rs index 8c13b907d..13606f97c 100644 --- a/core-foundation/src/boolean.rs +++ b/core-foundation/src/boolean.rs @@ -9,12 +9,13 @@ //! A Boolean type. -pub use core_foundation_sys::number::{CFBooleanRef, CFBooleanGetTypeID, kCFBooleanTrue, kCFBooleanFalse}; +pub use core_foundation_sys::number::{ + kCFBooleanFalse, kCFBooleanTrue, CFBooleanGetTypeID, CFBooleanRef, +}; use base::TCFType; - -declare_TCFType!{ +declare_TCFType! { /// A Boolean type. /// /// FIXME(pcwalton): Should be a newtype struct, but that fails due to a Rust compiler bug. @@ -25,15 +26,11 @@ impl_CFTypeDescription!(CFBoolean); impl CFBoolean { pub fn true_value() -> CFBoolean { - unsafe { - TCFType::wrap_under_get_rule(kCFBooleanTrue) - } + unsafe { TCFType::wrap_under_get_rule(kCFBooleanTrue) } } pub fn false_value() -> CFBoolean { - unsafe { - TCFType::wrap_under_get_rule(kCFBooleanFalse) - } + unsafe { TCFType::wrap_under_get_rule(kCFBooleanFalse) } } } diff --git a/core-foundation/src/bundle.rs b/core-foundation/src/bundle.rs index b9ab1f65f..183dc8e8e 100644 --- a/core-foundation/src/bundle.rs +++ b/core-foundation/src/bundle.rs @@ -15,12 +15,12 @@ use core_foundation_sys::url::kCFURLPOSIXPathStyle; use std::path::PathBuf; use base::{CFType, TCFType}; -use url::CFURL; use dictionary::CFDictionary; use std::os::raw::c_void; use string::CFString; +use url::CFURL; -declare_TCFType!{ +declare_TCFType! { /// A Bundle type. CFBundle, CFBundleRef } @@ -51,8 +51,10 @@ impl CFBundle { pub fn function_pointer_for_name(&self, function_name: CFString) -> *const c_void { unsafe { - CFBundleGetFunctionPointerForName(self.as_concrete_TypeRef(), - function_name.as_concrete_TypeRef()) + CFBundleGetFunctionPointerForName( + self.as_concrete_TypeRef(), + function_name.as_concrete_TypeRef(), + ) } } @@ -96,7 +98,9 @@ impl CFBundle { /// Bundle's own location pub fn path(&self) -> Option { let url = self.bundle_url()?; - Some(PathBuf::from(url.get_file_system_path(kCFURLPOSIXPathStyle).to_string())) + Some(PathBuf::from( + url.get_file_system_path(kCFURLPOSIXPathStyle).to_string(), + )) } /// Bundle's resources location @@ -114,7 +118,9 @@ impl CFBundle { /// Bundle's resources location pub fn resources_path(&self) -> Option { let url = self.bundle_resources_url()?; - Some(PathBuf::from(url.get_file_system_path(kCFURLPOSIXPathStyle).to_string())) + Some(PathBuf::from( + url.get_file_system_path(kCFURLPOSIXPathStyle).to_string(), + )) } pub fn private_frameworks_url(&self) -> Option { @@ -140,11 +146,10 @@ impl CFBundle { } } - #[test] fn safari_executable_url() { use string::CFString; - use url::{CFURL, kCFURLPOSIXPathStyle}; + use url::{kCFURLPOSIXPathStyle, CFURL}; let cfstr_path = CFString::from_static_string("/Applications/Safari.app"); let cfurl_path = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); @@ -152,18 +157,20 @@ fn safari_executable_url() { .expect("Safari not present") .executable_url(); assert!(cfurl_executable.is_some()); - assert_eq!(cfurl_executable - .unwrap() - .absolute() - .get_file_system_path(kCFURLPOSIXPathStyle) - .to_string(), - "/Applications/Safari.app/Contents/MacOS/Safari"); + assert_eq!( + cfurl_executable + .unwrap() + .absolute() + .get_file_system_path(kCFURLPOSIXPathStyle) + .to_string(), + "/Applications/Safari.app/Contents/MacOS/Safari" + ); } #[test] fn safari_private_frameworks_url() { use string::CFString; - use url::{CFURL, kCFURLPOSIXPathStyle}; + use url::{kCFURLPOSIXPathStyle, CFURL}; let cfstr_path = CFString::from_static_string("/Applications/Safari.app"); let cfurl_path = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); @@ -171,18 +178,20 @@ fn safari_private_frameworks_url() { .expect("Safari not present") .private_frameworks_url(); assert!(cfurl_executable.is_some()); - assert_eq!(cfurl_executable - .unwrap() - .absolute() - .get_file_system_path(kCFURLPOSIXPathStyle) - .to_string(), - "/Applications/Safari.app/Contents/Frameworks"); + assert_eq!( + cfurl_executable + .unwrap() + .absolute() + .get_file_system_path(kCFURLPOSIXPathStyle) + .to_string(), + "/Applications/Safari.app/Contents/Frameworks" + ); } #[test] fn non_existant_bundle() { use string::CFString; - use url::{CFURL, kCFURLPOSIXPathStyle}; + use url::{kCFURLPOSIXPathStyle, CFURL}; let cfstr_path = CFString::from_static_string("/usr/local/foo"); let cfurl_path = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); diff --git a/core-foundation/src/characterset.rs b/core-foundation/src/characterset.rs index d1b9439d6..28dba0b7f 100644 --- a/core-foundation/src/characterset.rs +++ b/core-foundation/src/characterset.rs @@ -13,7 +13,7 @@ pub use core_foundation_sys::characterset::*; use base::TCFType; -declare_TCFType!{ +declare_TCFType! { /// An immutable set of Unicde characters. CFCharacterSet, CFCharacterSetRef } diff --git a/core-foundation/src/data.rs b/core-foundation/src/data.rs index c510c7434..15cbbe041 100644 --- a/core-foundation/src/data.rs +++ b/core-foundation/src/data.rs @@ -9,18 +9,16 @@ //! Core Foundation byte buffers. -pub use core_foundation_sys::data::*; +use core_foundation_sys::base::kCFAllocatorDefault; use core_foundation_sys::base::CFIndex; -use core_foundation_sys::base::{kCFAllocatorDefault}; +pub use core_foundation_sys::data::*; use std::ops::Deref; use std::slice; use std::sync::Arc; - use base::{CFIndexConvertible, TCFType}; - -declare_TCFType!{ +declare_TCFType! { /// A byte buffer. CFData, CFDataRef } @@ -31,17 +29,19 @@ impl CFData { /// Creates a CFData around a copy `buffer` pub fn from_buffer(buffer: &[u8]) -> CFData { unsafe { - let data_ref = CFDataCreate(kCFAllocatorDefault, - buffer.as_ptr(), - buffer.len().to_CFIndex()); + let data_ref = CFDataCreate( + kCFAllocatorDefault, + buffer.as_ptr(), + buffer.len().to_CFIndex(), + ); TCFType::wrap_under_create_rule(data_ref) } } /// Creates a CFData referencing `buffer` without creating a copy pub fn from_arc + Sync + Send>(buffer: Arc) -> Self { - use std::os::raw::c_void; use crate::base::{CFAllocator, CFAllocatorContext}; + use std::os::raw::c_void; unsafe { let ptr = (*buffer).as_ref().as_ptr() as *const _; @@ -67,8 +67,12 @@ impl CFData { deallocate: Some(deallocate::), preferredSize: None, }); - let data_ref = - CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, ptr, len, allocator.as_CFTypeRef()); + let data_ref = CFDataCreateWithBytesNoCopy( + kCFAllocatorDefault, + ptr, + len, + allocator.as_CFTypeRef(), + ); TCFType::wrap_under_create_rule(data_ref) } } @@ -77,17 +81,13 @@ impl CFData { /// read-only. #[inline] pub fn bytes<'a>(&'a self) -> &'a [u8] { - unsafe { - slice::from_raw_parts(CFDataGetBytePtr(self.0), self.len() as usize) - } + unsafe { slice::from_raw_parts(CFDataGetBytePtr(self.0), self.len() as usize) } } /// Returns the length of this byte buffer. #[inline] pub fn len(&self) -> CFIndex { - unsafe { - CFDataGetLength(self.0) - } + unsafe { CFDataGetLength(self.0) } } } @@ -133,7 +133,10 @@ mod test { } let dropped = Arc::new(AtomicBool::default()); - let l = Arc::new(VecWrapper {inner: vec![5], dropped: dropped.clone() }); + let l = Arc::new(VecWrapper { + inner: vec![5], + dropped: dropped.clone(), + }); let m = l.clone(); let dp = CFData::from_arc(l); drop(m); diff --git a/core-foundation/src/date.rs b/core-foundation/src/date.rs index 57ee7211e..5dc7bdb2f 100644 --- a/core-foundation/src/date.rs +++ b/core-foundation/src/date.rs @@ -9,16 +9,15 @@ //! Core Foundation date objects. -pub use core_foundation_sys::date::*; use core_foundation_sys::base::kCFAllocatorDefault; +pub use core_foundation_sys::date::*; use base::TCFType; #[cfg(feature = "with-chrono")] use chrono::NaiveDateTime; - -declare_TCFType!{ +declare_TCFType! { /// A date. CFDate, CFDateRef } @@ -42,16 +41,12 @@ impl CFDate { #[inline] pub fn abs_time(&self) -> CFAbsoluteTime { - unsafe { - CFDateGetAbsoluteTime(self.0) - } + unsafe { CFDateGetAbsoluteTime(self.0) } } #[cfg(feature = "with-chrono")] pub fn naive_utc(&self) -> NaiveDateTime { - let ts = unsafe { - self.abs_time() + kCFAbsoluteTimeIntervalSince1970 - }; + let ts = unsafe { self.abs_time() + kCFAbsoluteTimeIntervalSince1970 }; let (secs, nanos) = if ts.is_sign_positive() { (ts.trunc() as i64, ts.fract()) } else { @@ -65,9 +60,7 @@ impl CFDate { pub fn from_naive_utc(time: NaiveDateTime) -> CFDate { let secs = time.timestamp(); let nanos = time.timestamp_subsec_nanos(); - let ts = unsafe { - secs as f64 + (nanos as f64 / 1e9) - kCFAbsoluteTimeIntervalSince1970 - }; + let ts = unsafe { secs as f64 + (nanos as f64 / 1e9) - kCFAbsoluteTimeIntervalSince1970 }; CFDate::new(ts) } } @@ -119,9 +112,7 @@ mod test { fn date_chrono_conversion_negative() { use super::kCFAbsoluteTimeIntervalSince1970; - let ts = unsafe { - kCFAbsoluteTimeIntervalSince1970 - 420.0 - }; + let ts = unsafe { kCFAbsoluteTimeIntervalSince1970 - 420.0 }; let date = CFDate::new(ts); let datetime: NaiveDateTime = date.naive_utc(); let converted = CFDate::from_naive_utc(datetime); diff --git a/core-foundation/src/dictionary.rs b/core-foundation/src/dictionary.rs index efcbba117..ac798f32e 100644 --- a/core-foundation/src/dictionary.rs +++ b/core-foundation/src/dictionary.rs @@ -11,18 +11,22 @@ pub use core_foundation_sys::dictionary::*; -use core_foundation_sys::base::{CFTypeRef, CFRelease, kCFAllocatorDefault}; +use core_foundation_sys::base::{kCFAllocatorDefault, CFRelease, CFTypeRef}; +use std::marker::PhantomData; use std::mem; use std::os::raw::c_void; use std::ptr; -use std::marker::PhantomData; -use base::{ItemRef, FromVoid, ToVoid}; use base::{CFIndexConvertible, TCFType}; +use base::{FromVoid, ItemRef, ToVoid}; use ConcreteCFType; // consume the type parameters with PhantomDatas -pub struct CFDictionary(CFDictionaryRef, PhantomData, PhantomData); +pub struct CFDictionary( + CFDictionaryRef, + PhantomData, + PhantomData, +); impl Drop for CFDictionary { fn drop(&mut self) { @@ -36,19 +40,25 @@ impl_CFTypeDescription!(CFDictionary); unsafe impl ConcreteCFType for CFDictionary<*const c_void, *const c_void> {} impl CFDictionary { - pub fn from_CFType_pairs(pairs: &[(K, V)]) -> CFDictionary where K: TCFType, V: TCFType { + pub fn from_CFType_pairs(pairs: &[(K, V)]) -> CFDictionary + where + K: TCFType, + V: TCFType, + { let (keys, values): (Vec, Vec) = pairs .iter() .map(|&(ref key, ref value)| (key.as_CFTypeRef(), value.as_CFTypeRef())) .unzip(); unsafe { - let dictionary_ref = CFDictionaryCreate(kCFAllocatorDefault, - keys.as_ptr(), - values.as_ptr(), - keys.len().to_CFIndex(), - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); + let dictionary_ref = CFDictionaryCreate( + kCFAllocatorDefault, + keys.as_ptr(), + values.as_ptr(), + keys.len().to_CFIndex(), + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks, + ); TCFType::wrap_under_create_rule(dictionary_ref) } } @@ -76,9 +86,7 @@ impl CFDictionary { #[inline] pub fn len(&self) -> usize { - unsafe { - CFDictionaryGetCount(self.0) as usize - } + unsafe { CFDictionaryGetCount(self.0) as usize } } #[inline] @@ -87,12 +95,19 @@ impl CFDictionary { } #[inline] - pub fn contains_key(&self, key: &K) -> bool where K: ToVoid { + pub fn contains_key(&self, key: &K) -> bool + where + K: ToVoid, + { unsafe { CFDictionaryContainsKey(self.0, key.to_void()) != 0 } } #[inline] - pub fn find<'a, T: ToVoid>(&'a self, key: T) -> Option> where V: FromVoid, K: ToVoid { + pub fn find<'a, T: ToVoid>(&'a self, key: T) -> Option> + where + V: FromVoid, + K: ToVoid, + { unsafe { let mut value: *const c_void = ptr::null(); if CFDictionaryGetValueIfPresent(self.0, key.to_void(), &mut value) != 0 { @@ -108,9 +123,14 @@ impl CFDictionary { /// Panics if the key is not present in the dictionary. Use `find` to get an `Option` instead /// of panicking. #[inline] - pub fn get<'a, T: ToVoid>(&'a self, key: T) -> ItemRef<'a, V> where V: FromVoid, K: ToVoid { + pub fn get<'a, T: ToVoid>(&'a self, key: T) -> ItemRef<'a, V> + where + V: FromVoid, + K: ToVoid, + { let ptr = key.to_void(); - self.find(key).unwrap_or_else(|| panic!("No entry found for key {:p}", ptr)) + self.find(key) + .unwrap_or_else(|| panic!("No entry found for key {:p}", ptr)) } pub fn get_keys_and_values(&self) -> (Vec<*const c_void>, Vec<*const c_void>) { @@ -129,7 +149,11 @@ impl CFDictionary { } // consume the type parameters with PhantomDatas -pub struct CFMutableDictionary(CFMutableDictionaryRef, PhantomData, PhantomData); +pub struct CFMutableDictionary( + CFMutableDictionaryRef, + PhantomData, + PhantomData, +); impl Drop for CFMutableDictionary { fn drop(&mut self) { @@ -147,22 +171,29 @@ impl CFMutableDictionary { pub fn with_capacity(capacity: isize) -> Self { unsafe { - let dictionary_ref = CFDictionaryCreateMutable(kCFAllocatorDefault, - capacity as _, - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); + let dictionary_ref = CFDictionaryCreateMutable( + kCFAllocatorDefault, + capacity as _, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks, + ); TCFType::wrap_under_create_rule(dictionary_ref) } } pub fn copy_with_capacity(&self, capacity: isize) -> Self { unsafe { - let dictionary_ref = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, capacity as _, self.0); + let dictionary_ref = + CFDictionaryCreateMutableCopy(kCFAllocatorDefault, capacity as _, self.0); TCFType::wrap_under_get_rule(dictionary_ref) } } - pub fn from_CFType_pairs(pairs: &[(K, V)]) -> CFMutableDictionary where K: ToVoid, V: ToVoid { + pub fn from_CFType_pairs(pairs: &[(K, V)]) -> CFMutableDictionary + where + K: ToVoid, + V: ToVoid, + { let mut result = Self::with_capacity(pairs.len() as _); for &(ref key, ref value) in pairs { result.add(key, value); @@ -194,9 +225,7 @@ impl CFMutableDictionary { #[inline] pub fn len(&self) -> usize { - unsafe { - CFDictionaryGetCount(self.0) as usize - } + unsafe { CFDictionaryGetCount(self.0) as usize } } #[inline] @@ -206,13 +235,15 @@ impl CFMutableDictionary { #[inline] pub fn contains_key(&self, key: *const c_void) -> bool { - unsafe { - CFDictionaryContainsKey(self.0, key) != 0 - } + unsafe { CFDictionaryContainsKey(self.0, key) != 0 } } #[inline] - pub fn find<'a>(&'a self, key: &K) -> Option> where V: FromVoid, K: ToVoid { + pub fn find<'a>(&'a self, key: &K) -> Option> + where + V: FromVoid, + K: ToVoid, + { unsafe { let mut value: *const c_void = ptr::null(); if CFDictionaryGetValueIfPresent(self.0, key.to_void(), &mut value) != 0 { @@ -228,9 +259,14 @@ impl CFMutableDictionary { /// Panics if the key is not present in the dictionary. Use `find` to get an `Option` instead /// of panicking. #[inline] - pub fn get<'a>(&'a self, key: &K) -> ItemRef<'a, V> where V: FromVoid, K: ToVoid { + pub fn get<'a>(&'a self, key: &K) -> ItemRef<'a, V> + where + V: FromVoid, + K: ToVoid, + { let ptr = key.to_void(); - self.find(&key).unwrap_or_else(|| panic!("No entry found for key {:p}", ptr)) + self.find(&key) + .unwrap_or_else(|| panic!("No entry found for key {:p}", ptr)) } pub fn get_keys_and_values(&self) -> (Vec<*const c_void>, Vec<*const c_void>) { @@ -251,25 +287,40 @@ impl CFMutableDictionary { /// Adds the key-value pair to the dictionary if no such key already exist. #[inline] - pub fn add(&mut self, key: &K, value: &V) where K: ToVoid, V: ToVoid { + pub fn add(&mut self, key: &K, value: &V) + where + K: ToVoid, + V: ToVoid, + { unsafe { CFDictionaryAddValue(self.0, key.to_void(), value.to_void()) } } /// Sets the value of the key in the dictionary. #[inline] - pub fn set(&mut self, key: K, value: V) where K: ToVoid, V: ToVoid { + pub fn set(&mut self, key: K, value: V) + where + K: ToVoid, + V: ToVoid, + { unsafe { CFDictionarySetValue(self.0, key.to_void(), value.to_void()) } } /// Replaces the value of the key in the dictionary. #[inline] - pub fn replace(&mut self, key: K, value: V) where K: ToVoid, V: ToVoid { + pub fn replace(&mut self, key: K, value: V) + where + K: ToVoid, + V: ToVoid, + { unsafe { CFDictionaryReplaceValue(self.0, key.to_void(), value.to_void()) } } /// Removes the value of the key from the dictionary. #[inline] - pub fn remove(&mut self, key: K) where K: ToVoid { + pub fn remove(&mut self, key: K) + where + K: ToVoid, + { unsafe { CFDictionaryRemoveValue(self.0, key.to_void()) } } @@ -296,7 +347,6 @@ impl<'a, K, V> From<&'a CFDictionary> for CFMutableDictionary { } } - #[cfg(test)] pub mod test { use super::*; @@ -305,7 +355,6 @@ pub mod test { use number::CFNumber; use string::CFString; - #[test] fn dictionary() { let bar = CFString::from_static_string("Bar"); @@ -322,8 +371,14 @@ pub mod test { ]); let (v1, v2) = d.get_keys_and_values(); - assert_eq!(v1, &[bar.as_CFTypeRef(), baz.as_CFTypeRef(), foo.as_CFTypeRef()]); - assert_eq!(v2, &[boo.as_CFTypeRef(), tru.as_CFTypeRef(), n42.as_CFTypeRef()]); + assert_eq!( + v1, + &[bar.as_CFTypeRef(), baz.as_CFTypeRef(), foo.as_CFTypeRef()] + ); + assert_eq!( + v2, + &[boo.as_CFTypeRef(), tru.as_CFTypeRef(), n42.as_CFTypeRef()] + ); } #[test] @@ -342,8 +397,14 @@ pub mod test { assert_eq!(d.len(), 3); let (v1, v2) = d.get_keys_and_values(); - assert_eq!(v1, &[bar.as_CFTypeRef(), baz.as_CFTypeRef(), foo.as_CFTypeRef()]); - assert_eq!(v2, &[boo.as_CFTypeRef(), tru.as_CFTypeRef(), n42.as_CFTypeRef()]); + assert_eq!( + v1, + &[bar.as_CFTypeRef(), baz.as_CFTypeRef(), foo.as_CFTypeRef()] + ); + assert_eq!( + v2, + &[boo.as_CFTypeRef(), tru.as_CFTypeRef(), n42.as_CFTypeRef()] + ); d.remove(baz); assert_eq!(d.len(), 2); @@ -358,12 +419,10 @@ pub mod test { #[test] fn dict_find_and_contains_key() { - let dict = CFDictionary::from_CFType_pairs(&[ - ( - CFString::from_static_string("hello"), - CFBoolean::true_value(), - ), - ]); + let dict = CFDictionary::from_CFType_pairs(&[( + CFString::from_static_string("hello"), + CFBoolean::true_value(), + )]); let key = CFString::from_static_string("hello"); let invalid_key = CFString::from_static_string("foobar"); @@ -377,17 +436,24 @@ pub mod test { #[test] fn convert_immutable_to_mutable_dict() { - let dict: CFDictionary = CFDictionary::from_CFType_pairs(&[ - (CFString::from_static_string("Foo"), CFBoolean::true_value()), - ]); + let dict: CFDictionary = CFDictionary::from_CFType_pairs(&[( + CFString::from_static_string("Foo"), + CFBoolean::true_value(), + )]); let mut mut_dict = CFMutableDictionary::from(&dict); assert_eq!(dict.retain_count(), 1); assert_eq!(mut_dict.retain_count(), 1); assert_eq!(mut_dict.len(), 1); - assert_eq!(*mut_dict.get(&CFString::from_static_string("Foo")), CFBoolean::true_value()); - - mut_dict.add(&CFString::from_static_string("Bar"), &CFBoolean::false_value()); + assert_eq!( + *mut_dict.get(&CFString::from_static_string("Foo")), + CFBoolean::true_value() + ); + + mut_dict.add( + &CFString::from_static_string("Bar"), + &CFBoolean::false_value(), + ); assert_eq!(dict.len(), 1); assert_eq!(mut_dict.len(), 2); } @@ -395,13 +461,19 @@ pub mod test { #[test] fn mutable_dictionary_as_immutable() { let mut mut_dict: CFMutableDictionary = CFMutableDictionary::new(); - mut_dict.add(&CFString::from_static_string("Bar"), &CFBoolean::false_value()); + mut_dict.add( + &CFString::from_static_string("Bar"), + &CFBoolean::false_value(), + ); assert_eq!(mut_dict.retain_count(), 1); let dict = mut_dict.to_immutable(); assert_eq!(mut_dict.retain_count(), 2); assert_eq!(dict.retain_count(), 2); - assert_eq!(*dict.get(&CFString::from_static_string("Bar")), CFBoolean::false_value()); + assert_eq!( + *dict.get(&CFString::from_static_string("Bar")), + CFBoolean::false_value() + ); mem::drop(dict); assert_eq!(mut_dict.retain_count(), 1); diff --git a/core-foundation/src/error.rs b/core-foundation/src/error.rs index f100171bc..86319b0fe 100644 --- a/core-foundation/src/error.rs +++ b/core-foundation/src/error.rs @@ -17,8 +17,7 @@ use std::fmt; use base::{CFIndex, TCFType}; use string::CFString; - -declare_TCFType!{ +declare_TCFType! { /// An error value. CFError, CFErrorRef } @@ -27,10 +26,10 @@ impl_TCFType!(CFError, CFErrorRef, CFErrorGetTypeID); impl fmt::Debug for CFError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("CFError") - .field("domain", &self.domain()) - .field("code", &self.code()) - .field("description", &self.description()) - .finish() + .field("domain", &self.domain()) + .field("code", &self.code()) + .field("description", &self.description()) + .finish() } } diff --git a/core-foundation/src/filedescriptor.rs b/core-foundation/src/filedescriptor.rs index e153c70b2..6207489fd 100644 --- a/core-foundation/src/filedescriptor.rs +++ b/core-foundation/src/filedescriptor.rs @@ -9,8 +9,8 @@ pub use core_foundation_sys::filedescriptor::*; -use core_foundation_sys::base::{Boolean, CFIndex}; use core_foundation_sys::base::{kCFAllocatorDefault, CFOptionFlags}; +use core_foundation_sys::base::{Boolean, CFIndex}; use base::TCFType; use runloop::CFRunLoopSource; @@ -19,23 +19,31 @@ use std::mem::MaybeUninit; use std::os::unix::io::{AsRawFd, RawFd}; use std::ptr; -declare_TCFType!{ +declare_TCFType! { CFFileDescriptor, CFFileDescriptorRef } -impl_TCFType!(CFFileDescriptor, CFFileDescriptorRef, CFFileDescriptorGetTypeID); +impl_TCFType!( + CFFileDescriptor, + CFFileDescriptorRef, + CFFileDescriptorGetTypeID +); impl CFFileDescriptor { - pub fn new(fd: RawFd, - closeOnInvalidate: bool, - callout: CFFileDescriptorCallBack, - context: Option<&CFFileDescriptorContext>) -> Option { + pub fn new( + fd: RawFd, + closeOnInvalidate: bool, + callout: CFFileDescriptorCallBack, + context: Option<&CFFileDescriptorContext>, + ) -> Option { let context = context.map_or(ptr::null(), |c| c as *const _); unsafe { - let fd_ref = CFFileDescriptorCreate(kCFAllocatorDefault, - fd, - closeOnInvalidate as Boolean, - callout, - context); + let fd_ref = CFFileDescriptorCreate( + kCFAllocatorDefault, + fd, + closeOnInvalidate as Boolean, + callout, + context, + ); if fd_ref.is_null() { None } else { @@ -53,36 +61,25 @@ impl CFFileDescriptor { } pub fn enable_callbacks(&self, callback_types: CFOptionFlags) { - unsafe { - CFFileDescriptorEnableCallBacks(self.0, callback_types) - } + unsafe { CFFileDescriptorEnableCallBacks(self.0, callback_types) } } pub fn disable_callbacks(&self, callback_types: CFOptionFlags) { - unsafe { - CFFileDescriptorDisableCallBacks(self.0, callback_types) - } + unsafe { CFFileDescriptorDisableCallBacks(self.0, callback_types) } } pub fn valid(&self) -> bool { - unsafe { - CFFileDescriptorIsValid(self.0) != 0 - } + unsafe { CFFileDescriptorIsValid(self.0) != 0 } } pub fn invalidate(&self) { - unsafe { - CFFileDescriptorInvalidate(self.0) - } + unsafe { CFFileDescriptorInvalidate(self.0) } } pub fn to_run_loop_source(&self, order: CFIndex) -> Option { unsafe { - let source_ref = CFFileDescriptorCreateRunLoopSource( - kCFAllocatorDefault, - self.0, - order - ); + let source_ref = + CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, self.0, order); if source_ref.is_null() { None } else { @@ -94,24 +91,21 @@ impl CFFileDescriptor { impl AsRawFd for CFFileDescriptor { fn as_raw_fd(&self) -> RawFd { - unsafe { - CFFileDescriptorGetNativeDescriptor(self.0) - } + unsafe { CFFileDescriptorGetNativeDescriptor(self.0) } } } - #[cfg(test)] mod test { extern crate libc; use super::*; + use core_foundation_sys::base::CFOptionFlags; + use core_foundation_sys::runloop::kCFRunLoopDefaultMode; + use libc::O_RDWR; + use runloop::CFRunLoop; use std::ffi::CString; use std::os::raw::c_void; - use core_foundation_sys::base::{CFOptionFlags}; - use core_foundation_sys::runloop::{kCFRunLoopDefaultMode}; - use libc::O_RDWR; - use runloop::{CFRunLoop}; #[test] fn test_unconsumed() { @@ -129,14 +123,16 @@ mod test { assert_eq!(unsafe { libc::close(raw_fd) }, 0); } - extern "C" fn never_callback(_f: CFFileDescriptorRef, - _callback_types: CFOptionFlags, - _info_ptr: *mut c_void) { + extern "C" fn never_callback( + _f: CFFileDescriptorRef, + _callback_types: CFOptionFlags, + _info_ptr: *mut c_void, + ) { unreachable!(); } struct TestInfo { - value: CFOptionFlags + value: CFOptionFlags, } #[test] @@ -147,7 +143,7 @@ mod test { info: &mut info as *mut _ as *mut c_void, retain: None, release: None, - copyDescription: None + copyDescription: None, }; let path = CString::new("/dev/null").unwrap(); @@ -182,7 +178,11 @@ mod test { assert!(!cf_fd.valid()); } - extern "C" fn callback(_f: CFFileDescriptorRef, callback_types: CFOptionFlags, info_ptr: *mut c_void) { + extern "C" fn callback( + _f: CFFileDescriptorRef, + callback_types: CFOptionFlags, + info_ptr: *mut c_void, + ) { assert!(!info_ptr.is_null()); let info: *mut TestInfo = info_ptr as *mut TestInfo; diff --git a/core-foundation/src/lib.rs b/core-foundation/src/lib.rs index b93593899..bdef988d1 100644 --- a/core-foundation/src/lib.rs +++ b/core-foundation/src/lib.rs @@ -165,7 +165,6 @@ macro_rules! impl_TCFType { (@Phantom $x:ident) => { ::std::marker::PhantomData }; } - /// Implement `std::fmt::Debug` for the given type. /// /// This will invoke the implementation of `Debug` for [`CFType`] @@ -200,7 +199,14 @@ macro_rules! impl_CFComparison { #[inline] fn partial_cmp(&self, other: &$ty) -> Option<::std::cmp::Ordering> { unsafe { - Some($compare(self.as_concrete_TypeRef(), other.as_concrete_TypeRef(), ::std::ptr::null_mut()).into()) + Some( + $compare( + self.as_concrete_TypeRef(), + other.as_concrete_TypeRef(), + ::std::ptr::null_mut(), + ) + .into(), + ) } } } @@ -211,26 +217,26 @@ macro_rules! impl_CFComparison { self.partial_cmp(other).unwrap() } } - } + }; } pub mod array; pub mod attributed_string; pub mod base; pub mod boolean; +pub mod bundle; pub mod characterset; pub mod data; pub mod date; pub mod dictionary; pub mod error; pub mod filedescriptor; +pub mod mach_port; pub mod number; -pub mod set; -pub mod string; -pub mod url; -pub mod bundle; pub mod propertylist; pub mod runloop; +pub mod set; +pub mod string; pub mod timezone; +pub mod url; pub mod uuid; -pub mod mach_port; diff --git a/core-foundation/src/mach_port.rs b/core-foundation/src/mach_port.rs index 6112e3aae..776c4708c 100644 --- a/core-foundation/src/mach_port.rs +++ b/core-foundation/src/mach_port.rs @@ -1,8 +1,7 @@ use base::TCFType; use core_foundation_sys::base::kCFAllocatorDefault; -use runloop::CFRunLoopSource; pub use core_foundation_sys::mach_port::*; - +use runloop::CFRunLoopSource; declare_TCFType! { /// An immutable numeric value. @@ -12,12 +11,10 @@ impl_TCFType!(CFMachPort, CFMachPortRef, CFMachPortGetTypeID); impl_CFTypeDescription!(CFMachPort); impl CFMachPort { - pub fn create_runloop_source( - &self, - order: CFIndex, - ) -> Result { + pub fn create_runloop_source(&self, order: CFIndex) -> Result { unsafe { - let runloop_source_ref = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, self.0, order); + let runloop_source_ref = + CFMachPortCreateRunLoopSource(kCFAllocatorDefault, self.0, order); if runloop_source_ref.is_null() { Err(()) } else { diff --git a/core-foundation/src/number.rs b/core-foundation/src/number.rs index a4b2affaa..5d2240973 100644 --- a/core-foundation/src/number.rs +++ b/core-foundation/src/number.rs @@ -15,8 +15,7 @@ use std::os::raw::c_void; use base::TCFType; - -declare_TCFType!{ +declare_TCFType! { /// An immutable numeric value. CFNumber, CFNumberRef } @@ -25,13 +24,20 @@ impl_CFTypeDescription!(CFNumber); impl_CFComparison!(CFNumber, CFNumberCompare); impl CFNumber { - #[inline] pub fn to_i32(&self) -> Option { unsafe { let mut value: i32 = 0; - let ok = CFNumberGetValue(self.0, kCFNumberSInt32Type, &mut value as *mut i32 as *mut c_void); - if ok { Some(value) } else { None } + let ok = CFNumberGetValue( + self.0, + kCFNumberSInt32Type, + &mut value as *mut i32 as *mut c_void, + ); + if ok { + Some(value) + } else { + None + } } } @@ -39,8 +45,16 @@ impl CFNumber { pub fn to_i64(&self) -> Option { unsafe { let mut value: i64 = 0; - let ok = CFNumberGetValue(self.0, kCFNumberSInt64Type, &mut value as *mut i64 as *mut c_void); - if ok { Some(value) } else { None } + let ok = CFNumberGetValue( + self.0, + kCFNumberSInt64Type, + &mut value as *mut i64 as *mut c_void, + ); + if ok { + Some(value) + } else { + None + } } } @@ -48,8 +62,16 @@ impl CFNumber { pub fn to_f32(&self) -> Option { unsafe { let mut value: f32 = 0.0; - let ok = CFNumberGetValue(self.0, kCFNumberFloat32Type, &mut value as *mut f32 as *mut c_void); - if ok { Some(value) } else { None } + let ok = CFNumberGetValue( + self.0, + kCFNumberFloat32Type, + &mut value as *mut f32 as *mut c_void, + ); + if ok { + Some(value) + } else { + None + } } } @@ -57,8 +79,16 @@ impl CFNumber { pub fn to_f64(&self) -> Option { unsafe { let mut value: f64 = 0.0; - let ok = CFNumberGetValue(self.0, kCFNumberFloat64Type, &mut value as *mut f64 as *mut c_void); - if ok { Some(value) } else { None } + let ok = CFNumberGetValue( + self.0, + kCFNumberFloat64Type, + &mut value as *mut f64 as *mut c_void, + ); + if ok { + Some(value) + } else { + None + } } } } diff --git a/core-foundation/src/propertylist.rs b/core-foundation/src/propertylist.rs index e8fceac58..e101d0e13 100644 --- a/core-foundation/src/propertylist.rs +++ b/core-foundation/src/propertylist.rs @@ -9,30 +9,34 @@ //! Core Foundation property lists -use std::ptr; use std::mem; use std::os::raw::c_void; +use std::ptr; -use error::CFError; -use data::CFData; use base::{CFType, TCFType, TCFTypeRef}; +use data::CFData; +use error::CFError; -pub use core_foundation_sys::propertylist::*; +use core_foundation_sys::base::{ + kCFAllocatorDefault, CFGetRetainCount, CFGetTypeID, CFIndex, CFRetain, CFShow, CFTypeID, +}; use core_foundation_sys::error::CFErrorRef; -use core_foundation_sys::base::{CFGetRetainCount, CFGetTypeID, CFIndex, CFRetain, - CFShow, CFTypeID, kCFAllocatorDefault}; +pub use core_foundation_sys::propertylist::*; -pub fn create_with_data(data: CFData, - options: CFPropertyListMutabilityOptions) - -> Result<(*const c_void, CFPropertyListFormat), CFError> { +pub fn create_with_data( + data: CFData, + options: CFPropertyListMutabilityOptions, +) -> Result<(*const c_void, CFPropertyListFormat), CFError> { unsafe { let mut error: CFErrorRef = ptr::null_mut(); let mut format: CFPropertyListFormat = 0; - let property_list = CFPropertyListCreateWithData(kCFAllocatorDefault, - data.as_concrete_TypeRef(), - options, - &mut format, - &mut error); + let property_list = CFPropertyListCreateWithData( + kCFAllocatorDefault, + data.as_concrete_TypeRef(), + options, + &mut format, + &mut error, + ); if property_list.is_null() { Err(TCFType::wrap_under_create_rule(error)) } else { @@ -41,14 +45,14 @@ pub fn create_with_data(data: CFData, } } -pub fn create_data(property_list: *const c_void, format: CFPropertyListFormat) -> Result { +pub fn create_data( + property_list: *const c_void, + format: CFPropertyListFormat, +) -> Result { unsafe { let mut error: CFErrorRef = ptr::null_mut(); - let data_ref = CFPropertyListCreateData(kCFAllocatorDefault, - property_list, - format, - 0, - &mut error); + let data_ref = + CFPropertyListCreateData(kCFAllocatorDefault, property_list, format, 0, &mut error); if data_ref.is_null() { Err(TCFType::wrap_under_create_rule(error)) } else { @@ -57,7 +61,6 @@ pub fn create_data(property_list: *const c_void, format: CFPropertyListFormat) - } } - /// Trait for all subclasses of [`CFPropertyList`]. /// /// [`CFPropertyList`]: struct.CFPropertyList.html @@ -92,8 +95,7 @@ impl CFPropertyListSubClass for ::date::CFDate {} impl CFPropertyListSubClass for ::boolean::CFBoolean {} impl CFPropertyListSubClass for ::number::CFNumber {} - -declare_TCFType!{ +declare_TCFType! { /// A CFPropertyList struct. This is superclass to [`CFData`], [`CFString`], [`CFArray`], /// [`CFDictionary`], [`CFDate`], [`CFBoolean`], and [`CFNumber`]. /// @@ -244,33 +246,33 @@ impl CFPropertyList { } } - - #[cfg(test)] pub mod test { use super::*; - use string::CFString; use boolean::CFBoolean; + use string::CFString; #[test] fn test_property_list_serialization() { - use base::{TCFType, CFEqual}; + use super::*; + use base::{CFEqual, TCFType}; use boolean::CFBoolean; - use number::CFNumber; use dictionary::CFDictionary; + use number::CFNumber; use string::CFString; - use super::*; let bar = CFString::from_static_string("Bar"); let baz = CFString::from_static_string("Baz"); let boo = CFString::from_static_string("Boo"); let foo = CFString::from_static_string("Foo"); let tru = CFBoolean::true_value(); - let n42 = CFNumber::from(1i64<<33); + let n42 = CFNumber::from(1i64 << 33); - let dict1 = CFDictionary::from_CFType_pairs(&[(bar.as_CFType(), boo.as_CFType()), - (baz.as_CFType(), tru.as_CFType()), - (foo.as_CFType(), n42.as_CFType())]); + let dict1 = CFDictionary::from_CFType_pairs(&[ + (bar.as_CFType(), boo.as_CFType()), + (baz.as_CFType(), tru.as_CFType()), + (foo.as_CFType(), n42.as_CFType()), + ]); let data = create_data(dict1.as_CFTypeRef(), kCFPropertyListXMLFormat_v1_0).unwrap(); let (dict2, _) = create_with_data(data, kCFPropertyListImmutable).unwrap(); @@ -295,7 +297,10 @@ pub mod test { #[test] fn downcast_string() { let propertylist = CFString::from_static_string("Bar").to_CFPropertyList(); - assert_eq!(propertylist.downcast::().unwrap().to_string(), "Bar"); + assert_eq!( + propertylist.downcast::().unwrap().to_string(), + "Bar" + ); assert!(propertylist.downcast::().is_none()); } diff --git a/core-foundation/src/runloop.rs b/core-foundation/src/runloop.rs index be06f4ec7..29654450b 100644 --- a/core-foundation/src/runloop.rs +++ b/core-foundation/src/runloop.rs @@ -9,19 +9,18 @@ #![allow(non_upper_case_globals)] -pub use core_foundation_sys::runloop::*; use core_foundation_sys::base::CFIndex; use core_foundation_sys::base::{kCFAllocatorDefault, CFOptionFlags}; +pub use core_foundation_sys::runloop::*; use core_foundation_sys::string::CFStringRef; -use base::{TCFType}; +use base::TCFType; use date::{CFAbsoluteTime, CFTimeInterval}; use filedescriptor::CFFileDescriptor; -use string::{CFString}; +use string::CFString; pub type CFRunLoopMode = CFStringRef; - declare_TCFType!(CFRunLoop, CFRunLoopRef); impl_TCFType!(CFRunLoop, CFRunLoopRef, CFRunLoopGetTypeID); impl_CFTypeDescription!(CFRunLoop); @@ -92,9 +91,7 @@ impl CFRunLoop { } pub fn contains_timer(&self, timer: &CFRunLoopTimer, mode: CFRunLoopMode) -> bool { - unsafe { - CFRunLoopContainsTimer(self.0, timer.0, mode) != 0 - } + unsafe { CFRunLoopContainsTimer(self.0, timer.0, mode) != 0 } } pub fn add_timer(&self, timer: &CFRunLoopTimer, mode: CFRunLoopMode) { @@ -110,9 +107,7 @@ impl CFRunLoop { } pub fn contains_source(&self, source: &CFRunLoopSource, mode: CFRunLoopMode) -> bool { - unsafe { - CFRunLoopContainsSource(self.0, source.0, mode) != 0 - } + unsafe { CFRunLoopContainsSource(self.0, source.0, mode) != 0 } } pub fn add_source(&self, source: &CFRunLoopSource, mode: CFRunLoopMode) { @@ -128,9 +123,7 @@ impl CFRunLoop { } pub fn contains_observer(&self, observer: &CFRunLoopObserver, mode: CFRunLoopMode) -> bool { - unsafe { - CFRunLoopContainsObserver(self.0, observer.0, mode) != 0 - } + unsafe { CFRunLoopContainsObserver(self.0, observer.0, mode) != 0 } } pub fn add_observer(&self, observer: &CFRunLoopObserver, mode: CFRunLoopMode) { @@ -144,25 +137,41 @@ impl CFRunLoop { CFRunLoopRemoveObserver(self.0, observer.0, mode); } } - } - declare_TCFType!(CFRunLoopTimer, CFRunLoopTimerRef); impl_TCFType!(CFRunLoopTimer, CFRunLoopTimerRef, CFRunLoopTimerGetTypeID); impl CFRunLoopTimer { - pub fn new(fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, callout: CFRunLoopTimerCallBack, context: *mut CFRunLoopTimerContext) -> CFRunLoopTimer { - unsafe { - let timer_ref = CFRunLoopTimerCreate(kCFAllocatorDefault, fireDate, interval, flags, order, callout, context); + pub fn new( + fireDate: CFAbsoluteTime, + interval: CFTimeInterval, + flags: CFOptionFlags, + order: CFIndex, + callout: CFRunLoopTimerCallBack, + context: *mut CFRunLoopTimerContext, + ) -> CFRunLoopTimer { + unsafe { + let timer_ref = CFRunLoopTimerCreate( + kCFAllocatorDefault, + fireDate, + interval, + flags, + order, + callout, + context, + ); TCFType::wrap_under_create_rule(timer_ref) } } } - declare_TCFType!(CFRunLoopSource, CFRunLoopSourceRef); -impl_TCFType!(CFRunLoopSource, CFRunLoopSourceRef, CFRunLoopSourceGetTypeID); +impl_TCFType!( + CFRunLoopSource, + CFRunLoopSourceRef, + CFRunLoopSourceGetTypeID +); impl CFRunLoopSource { pub fn from_file_descriptor(fd: &CFFileDescriptor, order: CFIndex) -> Option { @@ -171,12 +180,16 @@ impl CFRunLoopSource { } declare_TCFType!(CFRunLoopObserver, CFRunLoopObserverRef); -impl_TCFType!(CFRunLoopObserver, CFRunLoopObserverRef, CFRunLoopObserverGetTypeID); +impl_TCFType!( + CFRunLoopObserver, + CFRunLoopObserverRef, + CFRunLoopObserverGetTypeID +); #[cfg(test)] mod test { use super::*; - use date::{CFDate, CFAbsoluteTime}; + use date::{CFAbsoluteTime, CFDate}; use std::mem; use std::os::raw::c_void; use std::sync::mpsc; @@ -199,7 +212,8 @@ mod test { copyDescription: None, }; - let run_loop_timer = CFRunLoopTimer::new(now + 0.20f64, 0f64, 0, 0, timer_popped, &mut context); + let run_loop_timer = + CFRunLoopTimer::new(now + 0.20f64, 0f64, 0, 0, timer_popped, &mut context); unsafe { run_loop.add_timer(&run_loop_timer, kCFRunLoopDefaultMode); } diff --git a/core-foundation/src/set.rs b/core-foundation/src/set.rs index eb1d357a0..6896ba10c 100644 --- a/core-foundation/src/set.rs +++ b/core-foundation/src/set.rs @@ -9,13 +9,13 @@ //! An immutable bag of elements. +use core_foundation_sys::base::{kCFAllocatorDefault, CFRelease, CFTypeRef}; pub use core_foundation_sys::set::*; -use core_foundation_sys::base::{CFTypeRef, CFRelease, kCFAllocatorDefault}; use base::{CFIndexConvertible, TCFType}; -use std::os::raw::c_void; use std::marker::PhantomData; +use std::os::raw::c_void; /// An immutable bag of elements. pub struct CFSet(CFSetRef, PhantomData); @@ -31,13 +31,18 @@ impl_CFTypeDescription!(CFSet); impl CFSet { /// Creates a new set from a list of `CFType` instances. - pub fn from_slice(elems: &[T]) -> CFSet where T: TCFType { + pub fn from_slice(elems: &[T]) -> CFSet + where + T: TCFType, + { unsafe { let elems: Vec = elems.iter().map(|elem| elem.as_CFTypeRef()).collect(); - let set_ref = CFSetCreate(kCFAllocatorDefault, - elems.as_ptr(), - elems.len().to_CFIndex(), - &kCFTypeSetCallBacks); + let set_ref = CFSetCreate( + kCFAllocatorDefault, + elems.as_ptr(), + elems.len().to_CFIndex(), + &kCFTypeSetCallBacks, + ); TCFType::wrap_under_create_rule(set_ref) } } @@ -46,8 +51,6 @@ impl CFSet { impl CFSet { /// Get the number of elements in the CFSet pub fn len(&self) -> usize { - unsafe { - CFSetGetCount(self.0) as usize - } + unsafe { CFSetGetCount(self.0) as usize } } } diff --git a/core-foundation/src/string.rs b/core-foundation/src/string.rs index 3f5994bc5..13879e29e 100644 --- a/core-foundation/src/string.rs +++ b/core-foundation/src/string.rs @@ -13,16 +13,15 @@ pub use core_foundation_sys::string::*; use base::{CFIndexConvertible, TCFType}; -use core_foundation_sys::base::{Boolean, CFIndex, CFRange}; use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull}; +use core_foundation_sys::base::{Boolean, CFIndex, CFRange}; use std::borrow::Cow; +use std::ffi::CStr; use std::fmt; -use std::str::{self, FromStr}; use std::ptr; -use std::ffi::CStr; - +use std::str::{self, FromStr}; -declare_TCFType!{ +declare_TCFType! { /// An immutable string in one of a variety of encodings. CFString, CFStringRef } @@ -58,27 +57,37 @@ impl<'a> From<&'a CFString> for Cow<'a, str> { // First, ask how big the buffer ought to be. let mut bytes_required: CFIndex = 0; - CFStringGetBytes(cf_str.0, - CFRange { location: 0, length: char_len }, - kCFStringEncodingUTF8, - 0, - false as Boolean, - ptr::null_mut(), - 0, - &mut bytes_required); + CFStringGetBytes( + cf_str.0, + CFRange { + location: 0, + length: char_len, + }, + kCFStringEncodingUTF8, + 0, + false as Boolean, + ptr::null_mut(), + 0, + &mut bytes_required, + ); // Then, allocate the buffer and actually copy. let mut buffer = vec![b'\x00'; bytes_required as usize]; let mut bytes_used: CFIndex = 0; - let chars_written = CFStringGetBytes(cf_str.0, - CFRange { location: 0, length: char_len }, - kCFStringEncodingUTF8, - 0, - false as Boolean, - buffer.as_mut_ptr(), - buffer.len().to_CFIndex(), - &mut bytes_used); + let chars_written = CFStringGetBytes( + cf_str.0, + CFRange { + location: 0, + length: char_len, + }, + kCFStringEncodingUTF8, + 0, + false as Boolean, + buffer.as_mut_ptr(), + buffer.len().to_CFIndex(), + &mut bytes_used, + ); assert_eq!(chars_written, char_len); // This is dangerous; we over-allocate and null-terminate the string (during @@ -102,17 +111,18 @@ impl fmt::Debug for CFString { } } - impl CFString { /// Creates a new `CFString` instance from a Rust string. #[inline] pub fn new(string: &str) -> CFString { unsafe { - let string_ref = CFStringCreateWithBytes(kCFAllocatorDefault, - string.as_ptr(), - string.len().to_CFIndex(), - kCFStringEncodingUTF8, - false as Boolean); + let string_ref = CFStringCreateWithBytes( + kCFAllocatorDefault, + string.as_ptr(), + string.len().to_CFIndex(), + kCFStringEncodingUTF8, + false as Boolean, + ); CFString::wrap_under_create_rule(string_ref) } } @@ -122,12 +132,14 @@ impl CFString { #[inline] pub fn from_static_string(string: &'static str) -> CFString { unsafe { - let string_ref = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, - string.as_ptr(), - string.len().to_CFIndex(), - kCFStringEncodingUTF8, - false as Boolean, - kCFAllocatorNull); + let string_ref = CFStringCreateWithBytesNoCopy( + kCFAllocatorDefault, + string.as_ptr(), + string.len().to_CFIndex(), + kCFStringEncodingUTF8, + false as Boolean, + kCFAllocatorNull, + ); TCFType::wrap_under_create_rule(string_ref) } } @@ -135,21 +147,21 @@ impl CFString { /// Returns the number of characters in the string. #[inline] pub fn char_len(&self) -> CFIndex { - unsafe { - CFStringGetLength(self.0) - } + unsafe { CFStringGetLength(self.0) } } } impl<'a> PartialEq<&'a str> for CFString { fn eq(&self, other: &&str) -> bool { unsafe { - let temp = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, - other.as_ptr(), - other.len().to_CFIndex(), - kCFStringEncodingUTF8, - false as Boolean, - kCFAllocatorNull); + let temp = CFStringCreateWithBytesNoCopy( + kCFAllocatorDefault, + other.as_ptr(), + other.len().to_CFIndex(), + kCFStringEncodingUTF8, + false as Boolean, + kCFAllocatorNull, + ); self.eq(&CFString::wrap_under_create_rule(temp)) } } diff --git a/core-foundation/src/timezone.rs b/core-foundation/src/timezone.rs index a8bb2ed1d..c7f3b0225 100644 --- a/core-foundation/src/timezone.rs +++ b/core-foundation/src/timezone.rs @@ -9,8 +9,8 @@ //! Core Foundation time zone objects. -pub use core_foundation_sys::timezone::*; use core_foundation_sys::base::kCFAllocatorDefault; +pub use core_foundation_sys::timezone::*; use base::TCFType; use date::{CFDate, CFTimeInterval}; @@ -19,8 +19,7 @@ use string::CFString; #[cfg(feature = "with-chrono")] use chrono::{FixedOffset, NaiveDateTime}; - -declare_TCFType!{ +declare_TCFType! { /// A time zone. CFTimeZone, CFTimeZoneRef } @@ -54,9 +53,7 @@ impl CFTimeZone { } pub fn seconds_from_gmt(&self, date: CFDate) -> CFTimeInterval { - unsafe { - CFTimeZoneGetSecondsFromGMT(self.0, date.abs_time()) - } + unsafe { CFTimeZoneGetSecondsFromGMT(self.0, date.abs_time()) } } #[cfg(feature = "with-chrono")] @@ -73,9 +70,7 @@ impl CFTimeZone { /// The timezone database ID that identifies the time zone. E.g. "America/Los_Angeles" or /// "Europe/Paris". pub fn name(&self) -> CFString { - unsafe { - CFString::wrap_under_get_rule(CFTimeZoneGetName(self.0)) - } + unsafe { CFString::wrap_under_get_rule(CFTimeZoneGetName(self.0)) } } } @@ -84,7 +79,7 @@ mod test { use super::CFTimeZone; #[cfg(feature = "with-chrono")] - use chrono::{NaiveDateTime, FixedOffset}; + use chrono::{FixedOffset, NaiveDateTime}; #[test] fn timezone_comparison() { diff --git a/core-foundation/src/url.rs b/core-foundation/src/url.rs index 064dd7b5e..9077061c2 100644 --- a/core-foundation/src/url.rs +++ b/core-foundation/src/url.rs @@ -11,21 +11,20 @@ pub use core_foundation_sys::url::*; -use base::{TCFType, CFIndex}; -use string::{CFString}; +use base::{CFIndex, TCFType}; +use string::CFString; use core_foundation_sys::base::{kCFAllocatorDefault, Boolean}; use std::fmt; -use std::ptr; use std::path::{Path, PathBuf}; +use std::ptr; use libc::{c_char, strlen, PATH_MAX}; -#[cfg(unix)] -use std::os::unix::ffi::OsStrExt; #[cfg(unix)] use std::ffi::OsStr; - +#[cfg(unix)] +use std::os::unix::ffi::OsStrExt; declare_TCFType!(CFURL, CFURLRef); impl_TCFType!(CFURL, CFURLRef, CFURLGetTypeID); @@ -58,7 +57,12 @@ impl CFURL { } unsafe { - let url_ref = CFURLCreateFromFileSystemRepresentation(ptr::null_mut(), path_bytes.as_ptr(), path_bytes.len() as CFIndex, isDirectory as u8); + let url_ref = CFURLCreateFromFileSystemRepresentation( + ptr::null_mut(), + path_bytes.as_ptr(), + path_bytes.len() as CFIndex, + isDirectory as u8, + ); if url_ref.is_null() { return None; } @@ -66,9 +70,18 @@ impl CFURL { } } - pub fn from_file_system_path(filePath: CFString, pathStyle: CFURLPathStyle, isDirectory: bool) -> CFURL { + pub fn from_file_system_path( + filePath: CFString, + pathStyle: CFURLPathStyle, + isDirectory: bool, + ) -> CFURL { unsafe { - let url_ref = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, filePath.as_concrete_TypeRef(), pathStyle, isDirectory as u8); + let url_ref = CFURLCreateWithFileSystemPath( + kCFAllocatorDefault, + filePath.as_concrete_TypeRef(), + pathStyle, + isDirectory as u8, + ); TCFType::wrap_under_create_rule(url_ref) } } @@ -78,7 +91,12 @@ impl CFURL { // implementing this on Windows is more complicated because of the different OsStr representation unsafe { let mut buf = [0u8; PATH_MAX as usize]; - let result = CFURLGetFileSystemRepresentation(self.0, true as Boolean, buf.as_mut_ptr(), buf.len() as CFIndex); + let result = CFURLGetFileSystemRepresentation( + self.0, + true as Boolean, + buf.as_mut_ptr(), + buf.len() as CFIndex, + ); if result == false as Boolean { return None; } @@ -89,21 +107,20 @@ impl CFURL { } pub fn get_string(&self) -> CFString { - unsafe { - TCFType::wrap_under_get_rule(CFURLGetString(self.0)) - } + unsafe { TCFType::wrap_under_get_rule(CFURLGetString(self.0)) } } pub fn get_file_system_path(&self, pathStyle: CFURLPathStyle) -> CFString { unsafe { - TCFType::wrap_under_create_rule(CFURLCopyFileSystemPath(self.as_concrete_TypeRef(), pathStyle)) + TCFType::wrap_under_create_rule(CFURLCopyFileSystemPath( + self.as_concrete_TypeRef(), + pathStyle, + )) } } pub fn absolute(&self) -> CFURL { - unsafe { - TCFType::wrap_under_create_rule(CFURLCopyAbsoluteURL(self.as_concrete_TypeRef())) - } + unsafe { TCFType::wrap_under_create_rule(CFURLCopyAbsoluteURL(self.as_concrete_TypeRef())) } } } @@ -138,18 +155,30 @@ fn absolute_file_url() { let cfstr_file = CFString::from_static_string(file); let cfurl_base = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); let cfurl_relative: CFURL = unsafe { - let url_ref = CFURLCreateWithFileSystemPathRelativeToBase(kCFAllocatorDefault, + let url_ref = CFURLCreateWithFileSystemPathRelativeToBase( + kCFAllocatorDefault, cfstr_file.as_concrete_TypeRef(), kCFURLPOSIXPathStyle, false as u8, - cfurl_base.as_concrete_TypeRef()); + cfurl_base.as_concrete_TypeRef(), + ); TCFType::wrap_under_create_rule(url_ref) }; let mut absolute_path = PathBuf::from(path); absolute_path.push(file); - assert_eq!(cfurl_relative.get_file_system_path(kCFURLPOSIXPathStyle).to_string(), file); - assert_eq!(cfurl_relative.absolute().get_file_system_path(kCFURLPOSIXPathStyle).to_string(), - absolute_path.to_str().unwrap()); + assert_eq!( + cfurl_relative + .get_file_system_path(kCFURLPOSIXPathStyle) + .to_string(), + file + ); + assert_eq!( + cfurl_relative + .absolute() + .get_file_system_path(kCFURLPOSIXPathStyle) + .to_string(), + absolute_path.to_str().unwrap() + ); } diff --git a/core-foundation/src/uuid.rs b/core-foundation/src/uuid.rs index 6be734dab..5c3aefc6c 100644 --- a/core-foundation/src/uuid.rs +++ b/core-foundation/src/uuid.rs @@ -12,15 +12,14 @@ #[cfg(feature = "with-uuid")] extern crate uuid; -pub use core_foundation_sys::uuid::*; use core_foundation_sys::base::kCFAllocatorDefault; +pub use core_foundation_sys::uuid::*; use base::TCFType; #[cfg(feature = "with-uuid")] use self::uuid::Uuid; - declare_TCFType! { /// A UUID. CFUUID, CFUUIDRef @@ -47,26 +46,10 @@ impl Default for CFUUID { #[cfg(feature = "with-uuid")] impl Into for CFUUID { fn into(self) -> Uuid { - let b = unsafe { - CFUUIDGetUUIDBytes(self.0) - }; + let b = unsafe { CFUUIDGetUUIDBytes(self.0) }; let bytes = [ - b.byte0, - b.byte1, - b.byte2, - b.byte3, - b.byte4, - b.byte5, - b.byte6, - b.byte7, - b.byte8, - b.byte9, - b.byte10, - b.byte11, - b.byte12, - b.byte13, - b.byte14, - b.byte15, + b.byte0, b.byte1, b.byte2, b.byte3, b.byte4, b.byte5, b.byte6, b.byte7, b.byte8, + b.byte9, b.byte10, b.byte11, b.byte12, b.byte13, b.byte14, b.byte15, ]; Uuid::from_bytes(&bytes).unwrap() } @@ -101,7 +84,6 @@ impl From for CFUUID { } } - #[cfg(test)] #[cfg(feature = "with-uuid")] mod test { diff --git a/core-graphics-types/src/base.rs b/core-graphics-types/src/base.rs index d5efc3b62..76cd31fa6 100644 --- a/core-graphics-types/src/base.rs +++ b/core-graphics-types/src/base.rs @@ -14,9 +14,7 @@ use libc; -#[cfg(any(target_arch = "x86", - target_arch = "arm", - target_arch = "aarch64"))] +#[cfg(any(target_arch = "x86", target_arch = "arm", target_arch = "aarch64"))] pub type boolean_t = libc::c_int; #[cfg(target_arch = "x86_64")] pub type boolean_t = libc::c_uint; @@ -29,4 +27,3 @@ pub type CGFloat = libc::c_float; pub type CGError = libc::int32_t; pub type CGGlyph = libc::c_ushort; - diff --git a/core-graphics-types/src/geometry.rs b/core-graphics-types/src/geometry.rs index 906c605ec..27c24b6bc 100644 --- a/core-graphics-types/src/geometry.rs +++ b/core-graphics-types/src/geometry.rs @@ -11,10 +11,7 @@ use base::CGFloat; use core_foundation::base::TCFType; use core_foundation::dictionary::CFDictionary; -pub const CG_ZERO_POINT: CGPoint = CGPoint { - x: 0.0, - y: 0.0, -}; +pub const CG_ZERO_POINT: CGPoint = CGPoint { x: 0.0, y: 0.0 }; pub const CG_ZERO_SIZE: CGSize = CGSize { width: 0.0, @@ -27,9 +24,12 @@ pub const CG_ZERO_RECT: CGRect = CGRect { }; pub const CG_AFFINE_TRANSFORM_IDENTITY: CGAffineTransform = CGAffineTransform { - a: 1.0, b: 0.0, - c: 0.0, d: 1.0, - tx: 0.0, ty: 0.0, + a: 1.0, + b: 0.0, + c: 0.0, + d: 1.0, + tx: 0.0, + ty: 0.0, }; #[repr(C)] @@ -50,9 +50,7 @@ impl CGSize { #[inline] pub fn apply_transform(&self, t: &CGAffineTransform) -> CGSize { - unsafe { - ffi::CGSizeApplyAffineTransform(*self, *t) - } + unsafe { ffi::CGSizeApplyAffineTransform(*self, *t) } } } @@ -66,17 +64,12 @@ pub struct CGPoint { impl CGPoint { #[inline] pub fn new(x: CGFloat, y: CGFloat) -> CGPoint { - CGPoint { - x: x, - y: y, - } + CGPoint { x: x, y: y } } #[inline] pub fn apply_transform(&self, t: &CGAffineTransform) -> CGPoint { - unsafe { - ffi::CGPointApplyAffineTransform(*self, *t) - } + unsafe { ffi::CGPointApplyAffineTransform(*self, *t) } } } @@ -84,7 +77,7 @@ impl CGPoint { #[derive(Clone, Copy, Debug, Default)] pub struct CGRect { pub origin: CGPoint, - pub size: CGSize + pub size: CGSize, } impl CGRect { @@ -98,9 +91,7 @@ impl CGRect { #[inline] pub fn inset(&self, size: &CGSize) -> CGRect { - unsafe { - ffi::CGRectInset(*self, size.width, size.height) - } + unsafe { ffi::CGRectInset(*self, size.width, size.height) } } #[inline] @@ -134,9 +125,7 @@ impl CGRect { #[inline] pub fn apply_transform(&self, t: &CGAffineTransform) -> CGRect { - unsafe { - ffi::CGRectApplyAffineTransform(*self, *t) - } + unsafe { ffi::CGRectApplyAffineTransform(*self, *t) } } } @@ -166,22 +155,22 @@ impl CGAffineTransform { #[inline] pub fn invert(&self) -> CGAffineTransform { - unsafe { - ffi::CGAffineTransformInvert(*self) - } + unsafe { ffi::CGAffineTransformInvert(*self) } } } mod ffi { - use base::{CGFloat, boolean_t}; - use geometry::{CGAffineTransform, CGPoint, CGRect, CGSize}; + use base::{boolean_t, CGFloat}; use core_foundation::dictionary::CFDictionaryRef; + use geometry::{CGAffineTransform, CGPoint, CGRect, CGSize}; #[link(name = "CoreGraphics", kind = "framework")] - extern { + extern "C" { pub fn CGRectInset(rect: CGRect, dx: CGFloat, dy: CGFloat) -> CGRect; - pub fn CGRectMakeWithDictionaryRepresentation(dict: CFDictionaryRef, - rect: *mut CGRect) -> boolean_t; + pub fn CGRectMakeWithDictionaryRepresentation( + dict: CFDictionaryRef, + rect: *mut CGRect, + ) -> boolean_t; pub fn CGRectIsEmpty(rect: CGRect) -> boolean_t; pub fn CGRectIntersectsRect(rect1: CGRect, rect2: CGRect) -> boolean_t; @@ -192,4 +181,3 @@ mod ffi { pub fn CGSizeApplyAffineTransform(size: CGSize, t: CGAffineTransform) -> CGSize; } } - diff --git a/core-graphics-types/src/lib.rs b/core-graphics-types/src/lib.rs index f34bf0120..94a4eb979 100644 --- a/core-graphics-types/src/lib.rs +++ b/core-graphics-types/src/lib.rs @@ -7,8 +7,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern crate libc; extern crate core_foundation; +extern crate libc; pub mod base; pub mod geometry; diff --git a/core-graphics/src/color.rs b/core-graphics/src/color.rs index 79ef9a007..679138268 100644 --- a/core-graphics/src/color.rs +++ b/core-graphics/src/color.rs @@ -7,21 +7,21 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core_foundation::base::{CFTypeID}; +use super::sys::CGColorRef; use base::CGFloat; +use core_foundation::base::CFTypeID; use core_foundation::base::TCFType; -use super::sys::{CGColorRef}; pub use super::sys::CGColorRef as SysCGColorRef; -declare_TCFType!{ +declare_TCFType! { CGColor, CGColorRef } impl_TCFType!(CGColor, CGColorRef, CGColorGetTypeID); impl CGColor { pub fn rgb(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> Self { - unsafe { + unsafe { let ptr = CGColorCreateGenericRGB(red, green, blue, alpha); CGColor::wrap_under_create_rule(ptr) } @@ -29,7 +29,12 @@ impl CGColor { } #[link(name = "CoreGraphics", kind = "framework")] -extern { - fn CGColorCreateGenericRGB(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> ::sys::CGColorRef; +extern "C" { + fn CGColorCreateGenericRGB( + red: CGFloat, + green: CGFloat, + blue: CGFloat, + alpha: CGFloat, + ) -> ::sys::CGColorRef; fn CGColorGetTypeID() -> CFTypeID; } diff --git a/core-graphics/src/color_space.rs b/core-graphics/src/color_space.rs index 9eef09c30..6a9a37d35 100644 --- a/core-graphics/src/color_space.rs +++ b/core-graphics/src/color_space.rs @@ -22,15 +22,17 @@ foreign_type! { impl CGColorSpace { pub fn type_id() -> CFTypeID { - unsafe { - CGColorSpaceGetTypeID() - } + unsafe { CGColorSpaceGetTypeID() } } pub fn create_with_name(name: CFStringRef) -> Option { unsafe { let p = CGColorSpaceCreateWithName(name); - if !p.is_null() {Some(CGColorSpace::from_ptr(p))} else {None} + if !p.is_null() { + Some(CGColorSpace::from_ptr(p)) + } else { + None + } } } @@ -52,7 +54,7 @@ impl CGColorSpace { } #[link(name = "CoreGraphics", kind = "framework")] -extern { +extern "C" { pub static kCGColorSpaceSRGB: CFStringRef; pub static kCGColorSpaceAdobeRGB1998: CFStringRef; pub static kCGColorSpaceGenericGray: CFStringRef; @@ -66,4 +68,3 @@ extern { fn CGColorSpaceCreateWithName(name: CFStringRef) -> ::sys::CGColorSpaceRef; fn CGColorSpaceGetTypeID() -> CFTypeID; } - diff --git a/core-graphics/src/context.rs b/core-graphics/src/context.rs index 4efc0f70a..e723410c2 100644 --- a/core-graphics/src/context.rs +++ b/core-graphics/src/context.rs @@ -8,22 +8,22 @@ // except according to those terms. use base::CGFloat; +use color::CGColor; use color_space::CGColorSpace; use core_foundation::base::{CFTypeID, TCFType}; use font::{CGFont, CGGlyph}; use geometry::{CGPoint, CGSize}; use gradient::{CGGradient, CGGradientDrawingOptions}; -use color::CGColor; -use path::CGPathRef; use libc::{c_int, size_t}; +use path::CGPathRef; use std::os::raw::c_void; +use foreign_types::{ForeignType, ForeignTypeRef}; +use geometry::{CGAffineTransform, CGRect}; +use image::CGImage; use std::cmp; use std::ptr; use std::slice; -use geometry::{CGAffineTransform, CGRect}; -use image::CGImage; -use foreign_types::{ForeignType, ForeignTypeRef}; #[repr(C)] #[derive(Clone, Copy, Debug)] @@ -68,7 +68,7 @@ pub enum CGTextDrawingMode { CGTextFillClip, CGTextStrokeClip, CGTextFillStrokeClip, - CGTextClip + CGTextClip, } #[repr(C)] @@ -118,19 +118,17 @@ foreign_type! { impl CGContext { pub fn type_id() -> CFTypeID { - unsafe { - CGContextGetTypeID() - } + unsafe { CGContextGetTypeID() } } - /// Creates a `CGContext` instance from an existing [`CGContextRef`] pointer. - /// + /// Creates a `CGContext` instance from an existing [`CGContextRef`] pointer. + /// /// This funtion will internally call [`CGRetain`] and hence there is no need to call it explicitly. - /// + /// /// This function is particularly useful for cases when the context is not instantiated/managed /// by the caller, but it's retrieve via other means (e.g., by calling the method [`NSGraphicsContext::CGContext`] /// in a cocoa application). - /// + /// /// [`CGContextRef`]: https://developer.apple.com/documentation/coregraphics/cgcontextref /// [`CGRetain`]: https://developer.apple.com/documentation/coregraphics/1586506-cgcontextretain /// [`NSGraphicsContext::CGContext`]: https://developer.apple.com/documentation/appkit/nsgraphicscontext/1535352-currentcontext @@ -139,22 +137,25 @@ impl CGContext { Self::from_ptr(ctx) } - pub fn create_bitmap_context(data: Option<*mut c_void>, - width: size_t, - height: size_t, - bits_per_component: size_t, - bytes_per_row: size_t, - space: &CGColorSpace, - bitmap_info: u32) - -> CGContext { - unsafe { - let result = CGBitmapContextCreate(data.unwrap_or(ptr::null_mut()), - width, - height, - bits_per_component, - bytes_per_row, - space.as_ptr(), - bitmap_info); + pub fn create_bitmap_context( + data: Option<*mut c_void>, + width: size_t, + height: size_t, + bits_per_component: size_t, + bytes_per_row: size_t, + space: &CGColorSpace, + bitmap_info: u32, + ) -> CGContext { + unsafe { + let result = CGBitmapContextCreate( + data.unwrap_or(ptr::null_mut()), + width, + height, + bits_per_component, + bytes_per_row, + space.as_ptr(), + bitmap_info, + ); assert!(!result.is_null()); Self::from_ptr(result) } @@ -163,41 +164,32 @@ impl CGContext { pub fn data(&mut self) -> &mut [u8] { unsafe { slice::from_raw_parts_mut( - CGBitmapContextGetData(self.as_ptr()) as *mut u8, - (self.height() * self.bytes_per_row()) as usize) + CGBitmapContextGetData(self.as_ptr()) as *mut u8, + (self.height() * self.bytes_per_row()) as usize, + ) } } } impl CGContextRef { pub fn flush(&self) { - unsafe { - CGContextFlush(self.as_ptr()) - } + unsafe { CGContextFlush(self.as_ptr()) } } pub fn width(&self) -> size_t { - unsafe { - CGBitmapContextGetWidth(self.as_ptr()) - } + unsafe { CGBitmapContextGetWidth(self.as_ptr()) } } pub fn height(&self) -> size_t { - unsafe { - CGBitmapContextGetHeight(self.as_ptr()) - } + unsafe { CGBitmapContextGetHeight(self.as_ptr()) } } pub fn bytes_per_row(&self) -> size_t { - unsafe { - CGBitmapContextGetBytesPerRow(self.as_ptr()) - } + unsafe { CGBitmapContextGetBytesPerRow(self.as_ptr()) } } pub fn clip_bounding_box(&self) -> CGRect { - unsafe { - CGContextGetClipBoundingBox(self.as_ptr()) - } + unsafe { CGContextGetClipBoundingBox(self.as_ptr()) } } pub fn set_fill_color(&self, color: &CGColor) { @@ -207,33 +199,29 @@ impl CGContextRef { } pub fn set_rgb_fill_color(&self, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { - unsafe { - CGContextSetRGBFillColor(self.as_ptr(), red, green, blue, alpha) - } + unsafe { CGContextSetRGBFillColor(self.as_ptr(), red, green, blue, alpha) } } - pub fn set_rgb_stroke_color(&self, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { - unsafe { - CGContextSetRGBStrokeColor(self.as_ptr(), red, green, blue, alpha) - } + pub fn set_rgb_stroke_color( + &self, + red: CGFloat, + green: CGFloat, + blue: CGFloat, + alpha: CGFloat, + ) { + unsafe { CGContextSetRGBStrokeColor(self.as_ptr(), red, green, blue, alpha) } } pub fn set_gray_fill_color(&self, gray: CGFloat, alpha: CGFloat) { - unsafe { - CGContextSetGrayFillColor(self.as_ptr(), gray, alpha) - } + unsafe { CGContextSetGrayFillColor(self.as_ptr(), gray, alpha) } } pub fn set_blend_mode(&self, blend_mode: CGBlendMode) { - unsafe { - CGContextSetBlendMode(self.as_ptr(), blend_mode) - } + unsafe { CGContextSetBlendMode(self.as_ptr(), blend_mode) } } pub fn set_allows_font_smoothing(&self, allows_font_smoothing: bool) { - unsafe { - CGContextSetAllowsFontSmoothing(self.as_ptr(), allows_font_smoothing) - } + unsafe { CGContextSetAllowsFontSmoothing(self.as_ptr(), allows_font_smoothing) } } pub fn set_font_smoothing_style(&self, style: i32) { @@ -243,26 +231,23 @@ impl CGContextRef { } pub fn set_should_smooth_fonts(&self, should_smooth_fonts: bool) { - unsafe { - CGContextSetShouldSmoothFonts(self.as_ptr(), should_smooth_fonts) - } + unsafe { CGContextSetShouldSmoothFonts(self.as_ptr(), should_smooth_fonts) } } pub fn set_allows_antialiasing(&self, allows_antialiasing: bool) { - unsafe { - CGContextSetAllowsAntialiasing(self.as_ptr(), allows_antialiasing) - } + unsafe { CGContextSetAllowsAntialiasing(self.as_ptr(), allows_antialiasing) } } pub fn set_should_antialias(&self, should_antialias: bool) { - unsafe { - CGContextSetShouldAntialias(self.as_ptr(), should_antialias) - } + unsafe { CGContextSetShouldAntialias(self.as_ptr(), should_antialias) } } pub fn set_allows_font_subpixel_quantization(&self, allows_font_subpixel_quantization: bool) { unsafe { - CGContextSetAllowsFontSubpixelQuantization(self.as_ptr(), allows_font_subpixel_quantization) + CGContextSetAllowsFontSubpixelQuantization( + self.as_ptr(), + allows_font_subpixel_quantization, + ) } } @@ -274,7 +259,10 @@ impl CGContextRef { pub fn set_allows_font_subpixel_positioning(&self, allows_font_subpixel_positioning: bool) { unsafe { - CGContextSetAllowsFontSubpixelPositioning(self.as_ptr(), allows_font_subpixel_positioning) + CGContextSetAllowsFontSubpixelPositioning( + self.as_ptr(), + allows_font_subpixel_positioning, + ) } } @@ -285,39 +273,27 @@ impl CGContextRef { } pub fn set_text_drawing_mode(&self, mode: CGTextDrawingMode) { - unsafe { - CGContextSetTextDrawingMode(self.as_ptr(), mode) - } + unsafe { CGContextSetTextDrawingMode(self.as_ptr(), mode) } } pub fn set_line_cap(&self, cap: CGLineCap) { - unsafe { - CGContextSetLineCap(self.as_ptr(), cap) - } + unsafe { CGContextSetLineCap(self.as_ptr(), cap) } } pub fn set_line_dash(&self, phase: CGFloat, lengths: &[CGFloat]) { - unsafe { - CGContextSetLineDash(self.as_ptr(), phase, lengths.as_ptr(), lengths.len()) - } + unsafe { CGContextSetLineDash(self.as_ptr(), phase, lengths.as_ptr(), lengths.len()) } } pub fn set_line_join(&self, join: CGLineJoin) { - unsafe { - CGContextSetLineJoin(self.as_ptr(), join) - } + unsafe { CGContextSetLineJoin(self.as_ptr(), join) } } pub fn set_line_width(&self, width: CGFloat) { - unsafe { - CGContextSetLineWidth(self.as_ptr(), width) - } + unsafe { CGContextSetLineWidth(self.as_ptr(), width) } } pub fn set_miter_limit(&self, limit: CGFloat) { - unsafe { - CGContextSetMiterLimit(self.as_ptr(), limit) - } + unsafe { CGContextSetMiterLimit(self.as_ptr(), limit) } } pub fn add_path(&self, path: &CGPathRef) { @@ -326,30 +302,23 @@ impl CGContextRef { } } - pub fn add_curve_to_point(&self, - cp1x: CGFloat, - cp1y: CGFloat, - cp2x: CGFloat, - cp2y: CGFloat, - x: CGFloat, - y: CGFloat) { + pub fn add_curve_to_point( + &self, + cp1x: CGFloat, + cp1y: CGFloat, + cp2x: CGFloat, + cp2y: CGFloat, + x: CGFloat, + y: CGFloat, + ) { unsafe { - CGContextAddCurveToPoint(self.as_ptr(), - cp1x, cp1y, - cp2x, cp2y, - x, y); + CGContextAddCurveToPoint(self.as_ptr(), cp1x, cp1y, cp2x, cp2y, x, y); } } - pub fn add_quad_curve_to_point(&self, - cpx: CGFloat, - cpy: CGFloat, - x: CGFloat, - y: CGFloat) { + pub fn add_quad_curve_to_point(&self, cpx: CGFloat, cpy: CGFloat, x: CGFloat, y: CGFloat) { unsafe { - CGContextAddQuadCurveToPoint(self.as_ptr(), - cpx, cpy, - x, y); + CGContextAddQuadCurveToPoint(self.as_ptr(), cpx, cpy, x, y); } } @@ -360,7 +329,7 @@ impl CGContextRef { } pub fn begin_path(&self) { - unsafe { + unsafe { CGContextBeginPath(self.as_ptr()); } } @@ -414,75 +383,51 @@ impl CGContextRef { } pub fn fill_rect(&self, rect: CGRect) { - unsafe { - CGContextFillRect(self.as_ptr(), rect) - } + unsafe { CGContextFillRect(self.as_ptr(), rect) } } pub fn fill_rects(&self, rects: &[CGRect]) { - unsafe { - CGContextFillRects(self.as_ptr(), rects.as_ptr(), rects.len()) - } + unsafe { CGContextFillRects(self.as_ptr(), rects.as_ptr(), rects.len()) } } pub fn clear_rect(&self, rect: CGRect) { - unsafe { - CGContextClearRect(self.as_ptr(), rect) - } + unsafe { CGContextClearRect(self.as_ptr(), rect) } } pub fn stroke_rect(&self, rect: CGRect) { - unsafe { - CGContextStrokeRect(self.as_ptr(), rect) - } + unsafe { CGContextStrokeRect(self.as_ptr(), rect) } } pub fn stroke_rect_with_width(&self, rect: CGRect, width: CGFloat) { - unsafe { - CGContextStrokeRectWithWidth(self.as_ptr(), rect, width) - } + unsafe { CGContextStrokeRectWithWidth(self.as_ptr(), rect, width) } } pub fn clip_to_rect(&self, rect: CGRect) { - unsafe { - CGContextClipToRect(self.as_ptr(), rect) - } + unsafe { CGContextClipToRect(self.as_ptr(), rect) } } pub fn clip_to_rects(&self, rects: &[CGRect]) { - unsafe { - CGContextClipToRects(self.as_ptr(), rects.as_ptr(), rects.len()) - } + unsafe { CGContextClipToRects(self.as_ptr(), rects.as_ptr(), rects.len()) } } pub fn clip_to_mask(&self, rect: CGRect, image: &CGImage) { - unsafe { - CGContextClipToMask(self.as_ptr(), rect, image.as_ptr()) - } + unsafe { CGContextClipToMask(self.as_ptr(), rect, image.as_ptr()) } } pub fn replace_path_with_stroked_path(&self) { - unsafe { - CGContextReplacePathWithStrokedPath(self.as_ptr()) - } + unsafe { CGContextReplacePathWithStrokedPath(self.as_ptr()) } } pub fn fill_ellipse_in_rect(&self, rect: CGRect) { - unsafe { - CGContextFillEllipseInRect(self.as_ptr(), rect) - } + unsafe { CGContextFillEllipseInRect(self.as_ptr(), rect) } } pub fn stroke_ellipse_in_rect(&self, rect: CGRect) { - unsafe { - CGContextStrokeEllipseInRect(self.as_ptr(), rect) - } + unsafe { CGContextStrokeEllipseInRect(self.as_ptr(), rect) } } pub fn stroke_line_segments(&self, points: &[CGPoint]) { - unsafe { - CGContextStrokeLineSegments(self.as_ptr(), points.as_ptr(), points.len()) - } + unsafe { CGContextStrokeLineSegments(self.as_ptr(), points.as_ptr(), points.len()) } } pub fn set_interpolation_quality(&self, quality: CGInterpolationQuality) { @@ -492,10 +437,7 @@ impl CGContextRef { } pub fn get_interpolation_quality(&self) -> CGInterpolationQuality { - unsafe { - CGContextGetInterpolationQuality(self.as_ptr()) - - } + unsafe { CGContextGetInterpolationQuality(self.as_ptr()) } } pub fn draw_image(&self, rect: CGRect, image: &CGImage) { @@ -514,36 +456,30 @@ impl CGContextRef { } pub fn set_font(&self, font: &CGFont) { - unsafe { - CGContextSetFont(self.as_ptr(), font.as_ptr()) - } + unsafe { CGContextSetFont(self.as_ptr(), font.as_ptr()) } } pub fn set_font_size(&self, size: CGFloat) { - unsafe { - CGContextSetFontSize(self.as_ptr(), size) - } + unsafe { CGContextSetFontSize(self.as_ptr(), size) } } pub fn set_text_matrix(&self, t: &CGAffineTransform) { - unsafe { - CGContextSetTextMatrix(self.as_ptr(), *t) - } + unsafe { CGContextSetTextMatrix(self.as_ptr(), *t) } } pub fn set_text_position(&self, x: CGFloat, y: CGFloat) { - unsafe { - CGContextSetTextPosition(self.as_ptr(), x, y) - } + unsafe { CGContextSetTextPosition(self.as_ptr(), x, y) } } pub fn show_glyphs_at_positions(&self, glyphs: &[CGGlyph], positions: &[CGPoint]) { unsafe { let count = cmp::min(glyphs.len(), positions.len()); - CGContextShowGlyphsAtPositions(self.as_ptr(), - glyphs.as_ptr(), - positions.as_ptr(), - count) + CGContextShowGlyphsAtPositions( + self.as_ptr(), + glyphs.as_ptr(), + positions.as_ptr(), + count, + ) } } @@ -578,26 +514,50 @@ impl CGContextRef { } pub fn get_ctm(&self) -> CGAffineTransform { - unsafe { - CGContextGetCTM(self.as_ptr()) - } + unsafe { CGContextGetCTM(self.as_ptr()) } } pub fn concat_ctm(&self, transform: CGAffineTransform) { - unsafe { - CGContextConcatCTM(self.as_ptr(), transform) - } + unsafe { CGContextConcatCTM(self.as_ptr(), transform) } } - pub fn draw_linear_gradient(&self, gradient: &CGGradient, start_point: CGPoint, end_point: CGPoint, options: CGGradientDrawingOptions) { + pub fn draw_linear_gradient( + &self, + gradient: &CGGradient, + start_point: CGPoint, + end_point: CGPoint, + options: CGGradientDrawingOptions, + ) { unsafe { - CGContextDrawLinearGradient(self.as_ptr(), gradient.as_ptr(), start_point, end_point, options); + CGContextDrawLinearGradient( + self.as_ptr(), + gradient.as_ptr(), + start_point, + end_point, + options, + ); } } - pub fn draw_radial_gradient(&self, gradient: &CGGradient, start_center: CGPoint, start_radius: CGFloat, end_center: CGPoint, end_radius: CGFloat, options: CGGradientDrawingOptions) { + pub fn draw_radial_gradient( + &self, + gradient: &CGGradient, + start_center: CGPoint, + start_radius: CGFloat, + end_center: CGPoint, + end_radius: CGFloat, + options: CGGradientDrawingOptions, + ) { unsafe { - CGContextDrawRadialGradient(self.as_ptr(), gradient.as_ptr(), start_center, start_radius, end_center, end_radius, options); + CGContextDrawRadialGradient( + self.as_ptr(), + gradient.as_ptr(), + start_center, + start_radius, + end_center, + end_radius, + options, + ); } } @@ -619,14 +579,18 @@ fn create_bitmap_context_test() { use geometry::*; let cs = CGColorSpace::create_device_rgb(); - let ctx = CGContext::create_bitmap_context(None, - 16, 8, - 8, 0, - &cs, - ::base::kCGImageAlphaPremultipliedLast); - ctx.set_rgb_fill_color(1.,0.,1.,1.); + let ctx = CGContext::create_bitmap_context( + None, + 16, + 8, + 8, + 0, + &cs, + ::base::kCGImageAlphaPremultipliedLast, + ); + ctx.set_rgb_fill_color(1., 0., 1., 1.); ctx.set_miter_limit(4.); - ctx.fill_rect(CGRect::new(&CGPoint::new(0.,0.), &CGSize::new(8.,8.))); + ctx.fill_rect(CGRect::new(&CGPoint::new(0., 0.), &CGSize::new(8., 8.))); let img = ctx.create_image().unwrap(); assert_eq!(16, img.width()); assert_eq!(8, img.height()); @@ -640,18 +604,19 @@ fn create_bitmap_context_test() { } #[link(name = "CoreGraphics", kind = "framework")] -extern { +extern "C" { fn CGContextRetain(c: ::sys::CGContextRef) -> ::sys::CGContextRef; fn CGContextRelease(c: ::sys::CGContextRef); - fn CGBitmapContextCreate(data: *mut c_void, - width: size_t, - height: size_t, - bitsPerComponent: size_t, - bytesPerRow: size_t, - space: ::sys::CGColorSpaceRef, - bitmapInfo: u32) - -> ::sys::CGContextRef; + fn CGBitmapContextCreate( + data: *mut c_void, + width: size_t, + height: size_t, + bitsPerComponent: size_t, + bytesPerRow: size_t, + space: ::sys::CGColorSpaceRef, + bitmapInfo: u32, + ) -> ::sys::CGContextRef; fn CGBitmapContextGetData(context: ::sys::CGContextRef) -> *mut c_void; fn CGBitmapContextGetWidth(context: ::sys::CGContextRef) -> size_t; fn CGBitmapContextGetHeight(context: ::sys::CGContextRef) -> size_t; @@ -666,86 +631,93 @@ extern { fn CGContextSetFontSmoothingStyle(c: ::sys::CGContextRef, style: c_int); fn CGContextSetAllowsAntialiasing(c: ::sys::CGContextRef, allowsAntialiasing: bool); fn CGContextSetShouldAntialias(c: ::sys::CGContextRef, shouldAntialias: bool); - fn CGContextSetAllowsFontSubpixelQuantization(c: ::sys::CGContextRef, - allowsFontSubpixelQuantization: bool); - fn CGContextSetShouldSubpixelQuantizeFonts(c: ::sys::CGContextRef, - shouldSubpixelQuantizeFonts: bool); - fn CGContextSetAllowsFontSubpixelPositioning(c: ::sys::CGContextRef, - allowsFontSubpixelPositioning: bool); - fn CGContextSetShouldSubpixelPositionFonts(c: ::sys::CGContextRef, - shouldSubpixelPositionFonts: bool); + fn CGContextSetAllowsFontSubpixelQuantization( + c: ::sys::CGContextRef, + allowsFontSubpixelQuantization: bool, + ); + fn CGContextSetShouldSubpixelQuantizeFonts( + c: ::sys::CGContextRef, + shouldSubpixelQuantizeFonts: bool, + ); + fn CGContextSetAllowsFontSubpixelPositioning( + c: ::sys::CGContextRef, + allowsFontSubpixelPositioning: bool, + ); + fn CGContextSetShouldSubpixelPositionFonts( + c: ::sys::CGContextRef, + shouldSubpixelPositionFonts: bool, + ); fn CGContextSetTextDrawingMode(c: ::sys::CGContextRef, mode: CGTextDrawingMode); fn CGContextSetFillColorWithColor(c: ::sys::CGContextRef, color: ::sys::CGColorRef); fn CGContextSetLineCap(c: ::sys::CGContextRef, cap: CGLineCap); - fn CGContextSetLineDash(c: ::sys::CGContextRef, phase: CGFloat, lengths: *const CGFloat, count: size_t); + fn CGContextSetLineDash( + c: ::sys::CGContextRef, + phase: CGFloat, + lengths: *const CGFloat, + count: size_t, + ); fn CGContextSetLineJoin(c: ::sys::CGContextRef, join: CGLineJoin); fn CGContextSetLineWidth(c: ::sys::CGContextRef, width: CGFloat); fn CGContextSetMiterLimit(c: ::sys::CGContextRef, limit: CGFloat); fn CGContextAddPath(c: ::sys::CGContextRef, path: ::sys::CGPathRef); - fn CGContextAddCurveToPoint(c: ::sys::CGContextRef, - cp1x: CGFloat, - cp1y: CGFloat, - cp2x: CGFloat, - cp2y: CGFloat, - x: CGFloat, - y: CGFloat); - fn CGContextAddQuadCurveToPoint(c: ::sys::CGContextRef, - cpx: CGFloat, - cpy: CGFloat, - x: CGFloat, - y: CGFloat); - fn CGContextAddLineToPoint(c: ::sys::CGContextRef, - x: CGFloat, - y: CGFloat); + fn CGContextAddCurveToPoint( + c: ::sys::CGContextRef, + cp1x: CGFloat, + cp1y: CGFloat, + cp2x: CGFloat, + cp2y: CGFloat, + x: CGFloat, + y: CGFloat, + ); + fn CGContextAddQuadCurveToPoint( + c: ::sys::CGContextRef, + cpx: CGFloat, + cpy: CGFloat, + x: CGFloat, + y: CGFloat, + ); + fn CGContextAddLineToPoint(c: ::sys::CGContextRef, x: CGFloat, y: CGFloat); fn CGContextBeginPath(c: ::sys::CGContextRef); fn CGContextClosePath(c: ::sys::CGContextRef); - fn CGContextMoveToPoint(c: ::sys::CGContextRef, - x: CGFloat, - y: CGFloat); + fn CGContextMoveToPoint(c: ::sys::CGContextRef, x: CGFloat, y: CGFloat); fn CGContextDrawPath(c: ::sys::CGContextRef, mode: CGPathDrawingMode); fn CGContextFillPath(c: ::sys::CGContextRef); fn CGContextEOFillPath(c: ::sys::CGContextRef); fn CGContextClip(c: ::sys::CGContextRef); fn CGContextEOClip(c: ::sys::CGContextRef); fn CGContextStrokePath(c: ::sys::CGContextRef); - fn CGContextSetRGBFillColor(context: ::sys::CGContextRef, - red: CGFloat, - green: CGFloat, - blue: CGFloat, - alpha: CGFloat); - fn CGContextSetRGBStrokeColor(context: ::sys::CGContextRef, - red: CGFloat, - green: CGFloat, - blue: CGFloat, - alpha: CGFloat); + fn CGContextSetRGBFillColor( + context: ::sys::CGContextRef, + red: CGFloat, + green: CGFloat, + blue: CGFloat, + alpha: CGFloat, + ); + fn CGContextSetRGBStrokeColor( + context: ::sys::CGContextRef, + red: CGFloat, + green: CGFloat, + blue: CGFloat, + alpha: CGFloat, + ); fn CGContextSetGrayFillColor(context: ::sys::CGContextRef, gray: CGFloat, alpha: CGFloat); - fn CGContextClearRect(context: ::sys::CGContextRef, - rect: CGRect); - fn CGContextFillRect(context: ::sys::CGContextRef, - rect: CGRect); - fn CGContextFillRects(context: ::sys::CGContextRef, - rects: *const CGRect, - count: size_t); - fn CGContextStrokeRect(context: ::sys::CGContextRef, - rect: CGRect); - fn CGContextStrokeRectWithWidth(context: ::sys::CGContextRef, - rect: CGRect, - width: CGFloat); - fn CGContextClipToRect(context: ::sys::CGContextRef, - rect: CGRect); - fn CGContextClipToRects(context: ::sys::CGContextRef, - rects: *const CGRect, - count: size_t); + fn CGContextClearRect(context: ::sys::CGContextRef, rect: CGRect); + fn CGContextFillRect(context: ::sys::CGContextRef, rect: CGRect); + fn CGContextFillRects(context: ::sys::CGContextRef, rects: *const CGRect, count: size_t); + fn CGContextStrokeRect(context: ::sys::CGContextRef, rect: CGRect); + fn CGContextStrokeRectWithWidth(context: ::sys::CGContextRef, rect: CGRect, width: CGFloat); + fn CGContextClipToRect(context: ::sys::CGContextRef, rect: CGRect); + fn CGContextClipToRects(context: ::sys::CGContextRef, rects: *const CGRect, count: size_t); fn CGContextClipToMask(ctx: ::sys::CGContextRef, rect: CGRect, mask: ::sys::CGImageRef); fn CGContextReplacePathWithStrokedPath(context: ::sys::CGContextRef); - fn CGContextFillEllipseInRect(context: ::sys::CGContextRef, - rect: CGRect); - fn CGContextStrokeEllipseInRect(context: ::sys::CGContextRef, - rect: CGRect); - fn CGContextStrokeLineSegments(context: ::sys::CGContextRef, - points: *const CGPoint, - count: size_t); + fn CGContextFillEllipseInRect(context: ::sys::CGContextRef, rect: CGRect); + fn CGContextStrokeEllipseInRect(context: ::sys::CGContextRef, rect: CGRect); + fn CGContextStrokeLineSegments( + context: ::sys::CGContextRef, + points: *const CGPoint, + count: size_t, + ); fn CGContextDrawImage(c: ::sys::CGContextRef, rect: CGRect, image: ::sys::CGImageRef); fn CGContextSetInterpolationQuality(c: ::sys::CGContextRef, quality: CGInterpolationQuality); fn CGContextGetInterpolationQuality(c: ::sys::CGContextRef) -> CGInterpolationQuality; @@ -753,10 +725,12 @@ extern { fn CGContextSetFontSize(c: ::sys::CGContextRef, size: CGFloat); fn CGContextSetTextMatrix(c: ::sys::CGContextRef, t: CGAffineTransform); fn CGContextSetTextPosition(c: ::sys::CGContextRef, x: CGFloat, y: CGFloat); - fn CGContextShowGlyphsAtPositions(c: ::sys::CGContextRef, - glyphs: *const CGGlyph, - positions: *const CGPoint, - count: size_t); + fn CGContextShowGlyphsAtPositions( + c: ::sys::CGContextRef, + glyphs: *const CGGlyph, + positions: *const CGPoint, + count: size_t, + ); fn CGContextSaveGState(c: ::sys::CGContextRef); fn CGContextRestoreGState(c: ::sys::CGContextRef); @@ -766,10 +740,28 @@ extern { fn CGContextGetCTM(c: ::sys::CGContextRef) -> CGAffineTransform; fn CGContextConcatCTM(c: ::sys::CGContextRef, transform: CGAffineTransform); - fn CGContextDrawLinearGradient(c: ::sys::CGContextRef, gradient: ::sys::CGGradientRef, startPoint: CGPoint, endPoint: CGPoint, options: CGGradientDrawingOptions); - fn CGContextDrawRadialGradient(c: ::sys::CGContextRef, gradient: ::sys::CGGradientRef, startCenter: CGPoint, startRadius: CGFloat, endCenter:CGPoint, endRadius:CGFloat, options: CGGradientDrawingOptions); + fn CGContextDrawLinearGradient( + c: ::sys::CGContextRef, + gradient: ::sys::CGGradientRef, + startPoint: CGPoint, + endPoint: CGPoint, + options: CGGradientDrawingOptions, + ); + fn CGContextDrawRadialGradient( + c: ::sys::CGContextRef, + gradient: ::sys::CGGradientRef, + startCenter: CGPoint, + startRadius: CGFloat, + endCenter: CGPoint, + endRadius: CGFloat, + options: CGGradientDrawingOptions, + ); fn CGContextSetShadow(c: ::sys::CGContextRef, offset: CGSize, blur: CGFloat); - fn CGContextSetShadowWithColor(c: ::sys::CGContextRef, offset: CGSize, blur: CGFloat, color: ::sys::CGColorRef); + fn CGContextSetShadowWithColor( + c: ::sys::CGContextRef, + offset: CGSize, + blur: CGFloat, + color: ::sys::CGColorRef, + ); } - diff --git a/core-graphics/src/data_provider.rs b/core-graphics/src/data_provider.rs index e8bb0a024..e55827a06 100644 --- a/core-graphics/src/data_provider.rs +++ b/core-graphics/src/data_provider.rs @@ -10,25 +10,32 @@ use core_foundation::base::{CFRelease, CFRetain, CFTypeID, TCFType}; use core_foundation::data::{CFData, CFDataRef}; -use libc::{size_t, off_t}; +use libc::{off_t, size_t}; use std::mem; +use std::os::raw::c_void; use std::ptr; use std::sync::Arc; -use std::os::raw::c_void; use foreign_types::{ForeignType, ForeignTypeRef}; -pub type CGDataProviderGetBytesCallback = Option size_t>; -pub type CGDataProviderReleaseInfoCallback = Option; -pub type CGDataProviderRewindCallback = Option; -pub type CGDataProviderSkipBytesCallback = Option; -pub type CGDataProviderSkipForwardCallback = Option off_t>; - -pub type CGDataProviderGetBytePointerCallback = Option *mut c_void>; -pub type CGDataProviderGetBytesAtOffsetCallback = Option; -pub type CGDataProviderReleaseBytePointerCallback = Option; -pub type CGDataProviderReleaseDataCallback = Option; -pub type CGDataProviderGetBytesAtPositionCallback = Option; +pub type CGDataProviderGetBytesCallback = + Option size_t>; +pub type CGDataProviderReleaseInfoCallback = Option; +pub type CGDataProviderRewindCallback = Option; +pub type CGDataProviderSkipBytesCallback = Option; +pub type CGDataProviderSkipForwardCallback = + Option off_t>; + +pub type CGDataProviderGetBytePointerCallback = + Option *mut c_void>; +pub type CGDataProviderGetBytesAtOffsetCallback = + Option; +pub type CGDataProviderReleaseBytePointerCallback = + Option; +pub type CGDataProviderReleaseDataCallback = + Option; +pub type CGDataProviderGetBytesAtPositionCallback = + Option; foreign_type! { #[doc(hidden)] @@ -41,9 +48,7 @@ foreign_type! { impl CGDataProvider { pub fn type_id() -> CFTypeID { - unsafe { - CGDataProviderGetTypeID() - } + unsafe { CGDataProviderGetTypeID() } } /// Creates a data provider from the given reference-counted buffer. @@ -84,7 +89,9 @@ impl CGDataProvider { return CGDataProvider::from_ptr(data_provider); unsafe extern "C" fn release(info: *mut c_void, _: *const c_void, _: size_t) { - drop(mem::transmute::<*mut c_void, Box>>(info)) + drop(mem::transmute::<*mut c_void, Box>>( + info, + )) } } } @@ -134,7 +141,10 @@ fn test_data_provider() { } let dropped = Arc::new(AtomicBool::default()); - let l = Arc::new(VecWrapper {inner: vec![5], dropped: dropped.clone() }); + let l = Arc::new(VecWrapper { + inner: vec![5], + dropped: dropped.clone(), + }); let m = l.clone(); let dp = CGDataProvider::from_buffer(l); drop(m); @@ -144,16 +154,17 @@ fn test_data_provider() { } #[link(name = "CoreGraphics", kind = "framework")] -extern { +extern "C" { fn CGDataProviderCopyData(provider: ::sys::CGDataProviderRef) -> CFDataRef; //fn CGDataProviderCreateDirect //fn CGDataProviderCreateSequential //fn CGDataProviderCreateWithCFData - fn CGDataProviderCreateWithData(info: *mut c_void, - data: *const c_void, - size: size_t, - releaseData: CGDataProviderReleaseDataCallback - ) -> ::sys::CGDataProviderRef; + fn CGDataProviderCreateWithData( + info: *mut c_void, + data: *const c_void, + size: size_t, + releaseData: CGDataProviderReleaseDataCallback, + ) -> ::sys::CGDataProviderRef; //fn CGDataProviderCreateWithFilename(filename: *c_char) -> CGDataProviderRef; //fn CGDataProviderCreateWithURL fn CGDataProviderGetTypeID() -> CFTypeID; diff --git a/core-graphics/src/display.rs b/core-graphics/src/display.rs index 394520bae..3ed180727 100644 --- a/core-graphics/src/display.rs +++ b/core-graphics/src/display.rs @@ -10,31 +10,31 @@ #![allow(non_upper_case_globals)] use libc; -use std::ptr; use std::ops::Deref; +use std::ptr; -pub use base::{CGError, boolean_t}; -pub use geometry::{CGRect, CGPoint, CGSize}; +pub use base::{boolean_t, CGError}; +pub use geometry::{CGPoint, CGRect, CGSize}; -use core_foundation::string::{CFString, CFStringRef}; use core_foundation::base::{CFRetain, TCFType}; -use image::CGImage; +use core_foundation::string::{CFString, CFStringRef}; use foreign_types::ForeignType; +use image::CGImage; pub type CGDirectDisplayID = u32; -pub type CGWindowID = u32; +pub type CGWindowID = u32; pub const kCGNullWindowID: CGWindowID = 0 as CGWindowID; pub const kCGNullDirectDisplayID: CGDirectDisplayID = 0 as CGDirectDisplayID; pub type CGWindowListOption = u32; -pub const kCGWindowListOptionAll: CGWindowListOption = 0; -pub const kCGWindowListOptionOnScreenOnly: CGWindowListOption = 1 << 0; +pub const kCGWindowListOptionAll: CGWindowListOption = 0; +pub const kCGWindowListOptionOnScreenOnly: CGWindowListOption = 1 << 0; pub const kCGWindowListOptionOnScreenAboveWindow: CGWindowListOption = 1 << 1; pub const kCGWindowListOptionOnScreenBelowWindow: CGWindowListOption = 1 << 2; -pub const kCGWindowListOptionIncludingWindow: CGWindowListOption = 1 << 3; -pub const kCGWindowListExcludeDesktopElements: CGWindowListOption = 1 << 4; +pub const kCGWindowListOptionIncludingWindow: CGWindowListOption = 1 << 3; +pub const kCGWindowListExcludeDesktopElements: CGWindowListOption = 1 << 4; pub type CGWindowImageOption = u32; @@ -45,47 +45,48 @@ pub const kCGWindowImageOnlyShadows: CGWindowImageOption = 1 << 2; pub const kCGWindowImageBestResolution: CGWindowImageOption = 1 << 3; pub const kCGWindowImageNominalResolution: CGWindowImageOption = 1 << 4; -pub const kDisplayModeValidFlag: u32 = 0x00000001; -pub const kDisplayModeSafeFlag: u32 = 0x00000002; -pub const kDisplayModeDefaultFlag: u32 = 0x00000004; -pub const kDisplayModeAlwaysShowFlag: u32 = 0x00000008; -pub const kDisplayModeNeverShowFlag: u32 = 0x00000080; -pub const kDisplayModeNotResizeFlag: u32 = 0x00000010; -pub const kDisplayModeRequiresPanFlag: u32 = 0x00000020; -pub const kDisplayModeInterlacedFlag: u32 = 0x00000040; -pub const kDisplayModeSimulscanFlag: u32 = 0x00000100; -pub const kDisplayModeBuiltInFlag: u32 = 0x00000400; -pub const kDisplayModeNotPresetFlag: u32 = 0x00000200; -pub const kDisplayModeStretchedFlag: u32 = 0x00000800; -pub const kDisplayModeNotGraphicsQualityFlag: u32 = 0x00001000; -pub const kDisplayModeValidateAgainstDisplay: u32 = 0x00002000; -pub const kDisplayModeTelevisionFlag: u32 = 0x00100000; -pub const kDisplayModeValidForMirroringFlag: u32 = 0x00200000; -pub const kDisplayModeAcceleratorBackedFlag: u32 = 0x00400000; -pub const kDisplayModeValidForHiResFlag: u32 = 0x00800000; -pub const kDisplayModeValidForAirPlayFlag: u32 = 0x01000000; -pub const kDisplayModeNativeFlag: u32 = 0x02000000; - -pub const kDisplayModeSafetyFlags: u32 = 0x00000007; - -pub const IO1BitIndexedPixels: &str = "P"; -pub const IO2BitIndexedPixels: &str = "PP"; -pub const IO4BitIndexedPixels: &str = "PPPP"; -pub const IO8BitIndexedPixels: &str = "PPPPPPPP"; -pub const IO16BitDirectPixels: &str = "-RRRRRGGGGGBBBBB"; -pub const IO32BitDirectPixels: &str = "--------RRRRRRRRGGGGGGGGBBBBBBBB"; -pub const kIO30BitDirectPixels: &str = "--RRRRRRRRRRGGGGGGGGGGBBBBBBBBBB"; -pub const kIO64BitDirectPixels: &str = "-16R16G16B16"; -pub const kIO16BitFloatPixels: &str = "-16FR16FG16FB16"; -pub const kIO32BitFloatPixels: &str = "-32FR32FG32FB32"; -pub const IOYUV422Pixels: &str = "Y4U2V2"; -pub const IO8BitOverlayPixels: &str = "O8"; - - -pub use core_foundation::dictionary::{ CFDictionary, CFDictionaryRef, CFDictionaryGetValueIfPresent }; -pub use core_foundation::array::{ CFArray, CFArrayRef }; -pub use core_foundation::array::{ CFArrayGetCount, CFArrayGetValueAtIndex }; -pub use core_foundation::base::{ CFIndex, CFRelease, CFTypeRef }; +pub const kDisplayModeValidFlag: u32 = 0x00000001; +pub const kDisplayModeSafeFlag: u32 = 0x00000002; +pub const kDisplayModeDefaultFlag: u32 = 0x00000004; +pub const kDisplayModeAlwaysShowFlag: u32 = 0x00000008; +pub const kDisplayModeNeverShowFlag: u32 = 0x00000080; +pub const kDisplayModeNotResizeFlag: u32 = 0x00000010; +pub const kDisplayModeRequiresPanFlag: u32 = 0x00000020; +pub const kDisplayModeInterlacedFlag: u32 = 0x00000040; +pub const kDisplayModeSimulscanFlag: u32 = 0x00000100; +pub const kDisplayModeBuiltInFlag: u32 = 0x00000400; +pub const kDisplayModeNotPresetFlag: u32 = 0x00000200; +pub const kDisplayModeStretchedFlag: u32 = 0x00000800; +pub const kDisplayModeNotGraphicsQualityFlag: u32 = 0x00001000; +pub const kDisplayModeValidateAgainstDisplay: u32 = 0x00002000; +pub const kDisplayModeTelevisionFlag: u32 = 0x00100000; +pub const kDisplayModeValidForMirroringFlag: u32 = 0x00200000; +pub const kDisplayModeAcceleratorBackedFlag: u32 = 0x00400000; +pub const kDisplayModeValidForHiResFlag: u32 = 0x00800000; +pub const kDisplayModeValidForAirPlayFlag: u32 = 0x01000000; +pub const kDisplayModeNativeFlag: u32 = 0x02000000; + +pub const kDisplayModeSafetyFlags: u32 = 0x00000007; + +pub const IO1BitIndexedPixels: &str = "P"; +pub const IO2BitIndexedPixels: &str = "PP"; +pub const IO4BitIndexedPixels: &str = "PPPP"; +pub const IO8BitIndexedPixels: &str = "PPPPPPPP"; +pub const IO16BitDirectPixels: &str = "-RRRRRGGGGGBBBBB"; +pub const IO32BitDirectPixels: &str = "--------RRRRRRRRGGGGGGGGBBBBBBBB"; +pub const kIO30BitDirectPixels: &str = "--RRRRRRRRRRGGGGGGGGGGBBBBBBBBBB"; +pub const kIO64BitDirectPixels: &str = "-16R16G16B16"; +pub const kIO16BitFloatPixels: &str = "-16FR16FG16FB16"; +pub const kIO32BitFloatPixels: &str = "-32FR32FG32FB32"; +pub const IOYUV422Pixels: &str = "Y4U2V2"; +pub const IO8BitOverlayPixels: &str = "O8"; + +pub use core_foundation::array::{CFArray, CFArrayRef}; +pub use core_foundation::array::{CFArrayGetCount, CFArrayGetValueAtIndex}; +pub use core_foundation::base::{CFIndex, CFRelease, CFTypeRef}; +pub use core_foundation::dictionary::{ + CFDictionary, CFDictionaryGetValueIfPresent, CFDictionaryRef, +}; pub type CGDisplayConfigRef = *mut libc::c_void; @@ -537,7 +538,8 @@ impl CGDisplayMode { .map(|value0| { let x = *value0.deref() as *mut ::sys::CGDisplayMode; unsafe { CGDisplayMode::from_ptr(x) } - }).collect(); + }) + .collect(); Some(vec) } None => None, @@ -604,7 +606,7 @@ impl CGDisplayMode { 16 } else if pixel_encoding.eq_ignore_ascii_case(IO8BitIndexedPixels) { 8 - }else{ + } else { 0 } } diff --git a/core-graphics/src/event.rs b/core-graphics/src/event.rs index 8cf9c6262..87c3043c9 100644 --- a/core-graphics/src/event.rs +++ b/core-graphics/src/event.rs @@ -440,7 +440,6 @@ unsafe extern "C" fn cg_event_tap_callback_internal( ManuallyDrop::new(event).as_ptr() } - /// ```no_run ///extern crate core_foundation; ///use core_foundation::runloop::{kCFRunLoopCommonModes, CFRunLoop}; @@ -527,9 +526,7 @@ foreign_type! { impl CGEvent { pub fn type_id() -> CFTypeID { - unsafe { - CGEventGetTypeID() - } + unsafe { CGEventGetTypeID() } } pub fn new(source: CGEventSource) -> Result { @@ -546,7 +543,7 @@ impl CGEvent { pub fn new_keyboard_event( source: CGEventSource, keycode: CGKeyCode, - keydown: bool + keydown: bool, ) -> Result { unsafe { let event_ref = CGEventCreateKeyboardEvent(source.as_ptr(), keycode, keydown); @@ -562,11 +559,15 @@ impl CGEvent { source: CGEventSource, mouse_type: CGEventType, mouse_cursor_position: CGPoint, - mouse_button: CGMouseButton + mouse_button: CGMouseButton, ) -> Result { unsafe { - let event_ref = CGEventCreateMouseEvent(source.as_ptr(), mouse_type, - mouse_cursor_position, mouse_button); + let event_ref = CGEventCreateMouseEvent( + source.as_ptr(), + mouse_type, + mouse_cursor_position, + mouse_button, + ); if !event_ref.is_null() { Ok(Self::from_ptr(event_ref)) } else { @@ -608,9 +609,7 @@ impl CGEvent { } pub fn location(&self) -> CGPoint { - unsafe { - CGEventGetLocation(self.as_ptr()) - } + unsafe { CGEventGetLocation(self.as_ptr()) } } #[cfg(feature = "elcapitan")] @@ -627,9 +626,7 @@ impl CGEvent { } pub fn get_flags(&self) -> CGEventFlags { - unsafe { - CGEventGetFlags(self.as_ptr()) - } + unsafe { CGEventGetFlags(self.as_ptr()) } } pub fn set_type(&self, event_type: CGEventType) { @@ -639,9 +636,7 @@ impl CGEvent { } pub fn get_type(&self) -> CGEventType { - unsafe { - CGEventGetType(self.as_ptr()) - } + unsafe { CGEventGetType(self.as_ptr()) } } pub fn set_string_from_utf16_unchecked(&self, buf: &[u16]) { @@ -674,7 +669,7 @@ impl CGEvent { } #[link(name = "CoreGraphics", kind = "framework")] -extern { +extern "C" { /// Return the type identifier for the opaque type `CGEventRef'. fn CGEventGetTypeID() -> CFTypeID; @@ -692,8 +687,11 @@ extern { /// SHIFT, CONTROL, OPTION, and COMMAND keys. For example, to produce a 'Z', /// the SHIFT key must be down, the 'z' key must go down, and then the SHIFT /// and 'z' key must be released: - fn CGEventCreateKeyboardEvent(source: ::sys::CGEventSourceRef, keycode: CGKeyCode, - keydown: bool) -> ::sys::CGEventRef; + fn CGEventCreateKeyboardEvent( + source: ::sys::CGEventSourceRef, + keycode: CGKeyCode, + keydown: bool, + ) -> ::sys::CGEventRef; /// Return a new mouse event. /// @@ -708,8 +706,12 @@ extern { /// thirty-two buttons. Mouse button 0 is the primary button on the mouse. /// Mouse button 1 is the secondary mouse button (right). Mouse button 2 is /// the center button, and the remaining buttons are in USB device order. - fn CGEventCreateMouseEvent(source: ::sys::CGEventSourceRef, mouseType: CGEventType, - mouseCursorPosition: CGPoint, mouseButton: CGMouseButton) -> ::sys::CGEventRef; + fn CGEventCreateMouseEvent( + source: ::sys::CGEventSourceRef, + mouseType: CGEventType, + mouseCursorPosition: CGPoint, + mouseButton: CGMouseButton, + ) -> ::sys::CGEventRef; /// A non-variadic variant version of CGEventCreateScrollWheelEvent. /// @@ -762,9 +764,11 @@ extern { /// Note that application frameworks may ignore the Unicode string in a /// keyboard event and do their own translation based on the virtual /// keycode and perceived event state. - fn CGEventKeyboardSetUnicodeString(event: ::sys::CGEventRef, - length: libc::c_ulong, - string: *const u16); + fn CGEventKeyboardSetUnicodeString( + event: ::sys::CGEventRef, + length: libc::c_ulong, + string: *const u16, + ); /// Return the integer value of a field in an event. fn CGEventGetIntegerValueField(event: ::sys::CGEventRef, field: CGEventField) -> i64; diff --git a/core-graphics/src/event_source.rs b/core-graphics/src/event_source.rs index ce13f5a91..3044b9fe1 100644 --- a/core-graphics/src/event_source.rs +++ b/core-graphics/src/event_source.rs @@ -21,9 +21,7 @@ foreign_type! { impl CGEventSource { pub fn type_id() -> CFTypeID { - unsafe { - CGEventSourceGetTypeID() - } + unsafe { CGEventSourceGetTypeID() } } pub fn new(state_id: CGEventSourceStateID) -> Result { @@ -39,7 +37,7 @@ impl CGEventSource { } #[link(name = "CoreGraphics", kind = "framework")] -extern { +extern "C" { /// Return the type identifier for the opaque type `CGEventSourceRef'. fn CGEventSourceGetTypeID() -> CFTypeID; diff --git a/core-graphics/src/font.rs b/core-graphics/src/font.rs index adf7a1493..cde80d435 100644 --- a/core-graphics/src/font.rs +++ b/core-graphics/src/font.rs @@ -7,12 +7,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core_foundation::base::{CFRelease, CFRetain, CFType, CFTypeID, TCFType}; use core_foundation::array::{CFArray, CFArrayRef}; +use core_foundation::base::{CFRelease, CFRetain, CFType, CFTypeID, TCFType}; use core_foundation::data::{CFData, CFDataRef}; +use core_foundation::dictionary::{CFDictionary, CFDictionaryRef}; use core_foundation::number::CFNumber; use core_foundation::string::{CFString, CFStringRef}; -use core_foundation::dictionary::{CFDictionary, CFDictionaryRef}; use data_provider::CGDataProvider; use geometry::CGRect; @@ -36,9 +36,7 @@ unsafe impl Sync for CGFont {} impl CGFont { pub fn type_id() -> CFTypeID { - unsafe { - CGFontGetTypeID() - } + unsafe { CGFontGetTypeID() } } pub fn from_data_provider(provider: CGDataProvider) -> Result { @@ -63,10 +61,13 @@ impl CGFont { } } - pub fn create_copy_from_variations(&self, vars: &CFDictionary) -> Result { + pub fn create_copy_from_variations( + &self, + vars: &CFDictionary, + ) -> Result { unsafe { - let font_ref = CGFontCreateCopyWithVariations(self.as_ptr(), - vars.as_concrete_TypeRef()); + let font_ref = + CGFontCreateCopyWithVariations(self.as_ptr(), vars.as_concrete_TypeRef()); if !font_ref.is_null() { Ok(CGFont::from_ptr(font_ref)) } else { @@ -85,33 +86,33 @@ impl CGFont { pub fn get_glyph_b_boxes(&self, glyphs: &[CGGlyph], bboxes: &mut [CGRect]) -> bool { unsafe { assert!(bboxes.len() >= glyphs.len()); - CGFontGetGlyphBBoxes(self.as_ptr(), - glyphs.as_ptr(), - glyphs.len(), - bboxes.as_mut_ptr()) + CGFontGetGlyphBBoxes( + self.as_ptr(), + glyphs.as_ptr(), + glyphs.len(), + bboxes.as_mut_ptr(), + ) } } pub fn get_glyph_advances(&self, glyphs: &[CGGlyph], advances: &mut [c_int]) -> bool { unsafe { assert!(advances.len() >= glyphs.len()); - CGFontGetGlyphAdvances(self.as_ptr(), - glyphs.as_ptr(), - glyphs.len(), - advances.as_mut_ptr()) + CGFontGetGlyphAdvances( + self.as_ptr(), + glyphs.as_ptr(), + glyphs.len(), + advances.as_mut_ptr(), + ) } } pub fn get_units_per_em(&self) -> c_int { - unsafe { - CGFontGetUnitsPerEm(self.as_ptr()) - } + unsafe { CGFontGetUnitsPerEm(self.as_ptr()) } } pub fn copy_table_tags(&self) -> CFArray { - unsafe { - TCFType::wrap_under_create_rule(CGFontCopyTableTags(self.as_ptr())) - } + unsafe { TCFType::wrap_under_create_rule(CGFontCopyTableTags(self.as_ptr())) } } pub fn copy_table_for_tag(&self, tag: u32) -> Option { @@ -143,11 +144,14 @@ impl CGFont { } #[link(name = "CoreGraphics", kind = "framework")] -extern { +extern "C" { // TODO: basically nothing has bindings (even commented-out) besides what we use. fn CGFontCreateWithDataProvider(provider: ::sys::CGDataProviderRef) -> ::sys::CGFontRef; fn CGFontCreateWithFontName(name: CFStringRef) -> ::sys::CGFontRef; - fn CGFontCreateCopyWithVariations(font: ::sys::CGFontRef, vars: CFDictionaryRef) -> ::sys::CGFontRef; + fn CGFontCreateCopyWithVariations( + font: ::sys::CGFontRef, + vars: CFDictionaryRef, + ) -> ::sys::CGFontRef; fn CGFontGetTypeID() -> CFTypeID; fn CGFontCopyPostScriptName(font: ::sys::CGFontRef) -> CFStringRef; @@ -157,16 +161,18 @@ extern { //fn CGFontRetain(font: ::sys::CGFontRef); //fn CGFontRelease(font: ::sys::CGFontRef); - fn CGFontGetGlyphBBoxes(font: ::sys::CGFontRef, - glyphs: *const CGGlyph, - count: size_t, - bboxes: *mut CGRect) - -> bool; - fn CGFontGetGlyphAdvances(font: ::sys::CGFontRef, - glyphs: *const CGGlyph, - count: size_t, - advances: *mut c_int) - -> bool; + fn CGFontGetGlyphBBoxes( + font: ::sys::CGFontRef, + glyphs: *const CGGlyph, + count: size_t, + bboxes: *mut CGRect, + ) -> bool; + fn CGFontGetGlyphAdvances( + font: ::sys::CGFontRef, + glyphs: *const CGGlyph, + count: size_t, + advances: *mut c_int, + ) -> bool; fn CGFontGetUnitsPerEm(font: ::sys::CGFontRef) -> c_int; fn CGFontCopyTableTags(font: ::sys::CGFontRef) -> CFArrayRef; diff --git a/core-graphics/src/geometry.rs b/core-graphics/src/geometry.rs index fd4dc977e..6e6f03634 100644 --- a/core-graphics/src/geometry.rs +++ b/core-graphics/src/geometry.rs @@ -7,4 +7,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub use core_graphics_types::geometry::*; \ No newline at end of file +pub use core_graphics_types::geometry::*; diff --git a/core-graphics/src/gradient.rs b/core-graphics/src/gradient.rs index 5c6cde846..57104f580 100644 --- a/core-graphics/src/gradient.rs +++ b/core-graphics/src/gradient.rs @@ -13,7 +13,7 @@ use base::CGFloat; use color::CGColor; use color_space::CGColorSpace; -use core_foundation::array::{ CFArray, CFArrayRef }; +use core_foundation::array::{CFArray, CFArrayRef}; use core_foundation::base::{CFRelease, CFRetain, TCFType}; use foreign_types::ForeignType; @@ -37,17 +37,35 @@ foreign_type! { } impl CGGradient { - pub fn create_with_color_components(color_space: &CGColorSpace, components: &[CGFloat], locations: &[CGFloat], count: usize) -> CGGradient { + pub fn create_with_color_components( + color_space: &CGColorSpace, + components: &[CGFloat], + locations: &[CGFloat], + count: usize, + ) -> CGGradient { unsafe { - let result = CGGradientCreateWithColorComponents(color_space.as_ptr(), components.as_ptr(), locations.as_ptr(), count); + let result = CGGradientCreateWithColorComponents( + color_space.as_ptr(), + components.as_ptr(), + locations.as_ptr(), + count, + ); assert!(!result.is_null()); Self::from_ptr(result) } } - pub fn create_with_colors(color_space: &CGColorSpace, colors: &CFArray, locations: &[CGFloat]) -> CGGradient { + pub fn create_with_colors( + color_space: &CGColorSpace, + colors: &CFArray, + locations: &[CGFloat], + ) -> CGGradient { unsafe { - let result = CGGradientCreateWithColors(color_space.as_ptr(), colors.as_concrete_TypeRef(), locations.as_ptr()); + let result = CGGradientCreateWithColors( + color_space.as_ptr(), + colors.as_concrete_TypeRef(), + locations.as_ptr(), + ); assert!(!result.is_null()); Self::from_ptr(result) } @@ -55,8 +73,16 @@ impl CGGradient { } #[link(name = "CoreGraphics", kind = "framework")] -extern { - fn CGGradientCreateWithColorComponents(color_space: ::sys::CGColorSpaceRef, components: *const CGFloat, locations: *const CGFloat, count: size_t) -> ::sys::CGGradientRef; - fn CGGradientCreateWithColors(color_space: ::sys::CGColorSpaceRef, colors: CFArrayRef, locations: *const CGFloat) -> ::sys::CGGradientRef; +extern "C" { + fn CGGradientCreateWithColorComponents( + color_space: ::sys::CGColorSpaceRef, + components: *const CGFloat, + locations: *const CGFloat, + count: size_t, + ) -> ::sys::CGGradientRef; + fn CGGradientCreateWithColors( + color_space: ::sys::CGColorSpaceRef, + colors: CFArrayRef, + locations: *const CGFloat, + ) -> ::sys::CGGradientRef; } - diff --git a/core-graphics/src/image.rs b/core-graphics/src/image.rs index f1b95096d..fdf7dd83d 100644 --- a/core-graphics/src/image.rs +++ b/core-graphics/src/image.rs @@ -1,24 +1,24 @@ use std::ptr; use base::CGFloat; +use color_space::CGColorSpace; use core_foundation::base::{CFRetain, CFTypeID}; use core_foundation::data::CFData; -use color_space::CGColorSpace; -use data_provider::{CGDataProviderRef, CGDataProvider}; +use data_provider::{CGDataProvider, CGDataProviderRef}; +use foreign_types::{ForeignType, ForeignTypeRef}; use geometry::CGRect; use libc::size_t; -use foreign_types::{ForeignType, ForeignTypeRef}; #[repr(C)] pub enum CGImageAlphaInfo { - CGImageAlphaNone, /* For example, RGB. */ - CGImageAlphaPremultipliedLast, /* For example, premultiplied RGBA */ + CGImageAlphaNone, /* For example, RGB. */ + CGImageAlphaPremultipliedLast, /* For example, premultiplied RGBA */ CGImageAlphaPremultipliedFirst, /* For example, premultiplied ARGB */ - CGImageAlphaLast, /* For example, non-premultiplied RGBA */ - CGImageAlphaFirst, /* For example, non-premultiplied ARGB */ - CGImageAlphaNoneSkipLast, /* For example, RBGX. */ - CGImageAlphaNoneSkipFirst, /* For example, XRBG. */ - CGImageAlphaOnly /* No color data, alpha data only */ + CGImageAlphaLast, /* For example, non-premultiplied RGBA */ + CGImageAlphaFirst, /* For example, non-premultiplied ARGB */ + CGImageAlphaNoneSkipLast, /* For example, RBGX. */ + CGImageAlphaNoneSkipFirst, /* For example, XRBG. */ + CGImageAlphaOnly, /* No color data, alpha data only */ } #[repr(C)] @@ -27,7 +27,7 @@ pub enum CGImageByteOrderInfo { CGImageByteOrder16Little = 1 << 12, CGImageByteOrder32Little = 2 << 12, CGImageByteOrder16Big = 3 << 12, - CGImageByteOrder32Big = 4 << 12 + CGImageByteOrder32Big = 4 << 12, } foreign_type! { @@ -40,70 +40,61 @@ foreign_type! { } impl CGImage { - pub fn new(width: size_t, - height: size_t, - bits_per_component: size_t, - bits_per_pixel: size_t, - bytes_per_row: size_t, - colorspace: &CGColorSpace, - bitmap_info: u32, - provider: &CGDataProvider, - should_interpolate: bool, - rendering_intent: u32) - -> Self { + pub fn new( + width: size_t, + height: size_t, + bits_per_component: size_t, + bits_per_pixel: size_t, + bytes_per_row: size_t, + colorspace: &CGColorSpace, + bitmap_info: u32, + provider: &CGDataProvider, + should_interpolate: bool, + rendering_intent: u32, + ) -> Self { unsafe { - let result = CGImageCreate(width, - height, - bits_per_component, - bits_per_pixel, - bytes_per_row, - colorspace.as_ptr(), - bitmap_info, - provider.as_ptr(), - ptr::null_mut(), - should_interpolate, - rendering_intent); + let result = CGImageCreate( + width, + height, + bits_per_component, + bits_per_pixel, + bytes_per_row, + colorspace.as_ptr(), + bitmap_info, + provider.as_ptr(), + ptr::null_mut(), + should_interpolate, + rendering_intent, + ); assert!(!result.is_null()); Self::from_ptr(result) } } pub fn type_id() -> CFTypeID { - unsafe { - CGImageGetTypeID() - } + unsafe { CGImageGetTypeID() } } } impl CGImageRef { pub fn width(&self) -> size_t { - unsafe { - CGImageGetWidth(self.as_ptr()) - } + unsafe { CGImageGetWidth(self.as_ptr()) } } pub fn height(&self) -> size_t { - unsafe { - CGImageGetHeight(self.as_ptr()) - } + unsafe { CGImageGetHeight(self.as_ptr()) } } pub fn bits_per_component(&self) -> size_t { - unsafe { - CGImageGetBitsPerComponent(self.as_ptr()) - } + unsafe { CGImageGetBitsPerComponent(self.as_ptr()) } } pub fn bits_per_pixel(&self) -> size_t { - unsafe { - CGImageGetBitsPerPixel(self.as_ptr()) - } + unsafe { CGImageGetBitsPerPixel(self.as_ptr()) } } pub fn bytes_per_row(&self) -> size_t { - unsafe { - CGImageGetBytesPerRow(self.as_ptr()) - } + unsafe { CGImageGetBytesPerRow(self.as_ptr()) } } pub fn color_space(&self) -> CGColorSpace { @@ -117,9 +108,8 @@ impl CGImageRef { /// Returns the raw image bytes wrapped in `CFData`. Note, the returned `CFData` owns the /// underlying buffer. pub fn data(&self) -> CFData { - let data_provider = unsafe { - CGDataProviderRef::from_ptr(CGImageGetDataProvider(self.as_ptr())) - }; + let data_provider = + unsafe { CGDataProviderRef::from_ptr(CGImageGetDataProvider(self.as_ptr())) }; data_provider.copy_data() } @@ -136,7 +126,7 @@ impl CGImageRef { } #[link(name = "CoreGraphics", kind = "framework")] -extern { +extern "C" { fn CGImageGetTypeID() -> CFTypeID; fn CGImageGetWidth(image: ::sys::CGImageRef) -> size_t; fn CGImageGetHeight(image: ::sys::CGImageRef) -> size_t; @@ -146,18 +136,19 @@ extern { fn CGImageGetColorSpace(image: ::sys::CGImageRef) -> ::sys::CGColorSpaceRef; fn CGImageGetDataProvider(image: ::sys::CGImageRef) -> ::sys::CGDataProviderRef; fn CGImageRelease(image: ::sys::CGImageRef); - fn CGImageCreate(width: size_t, - height: size_t, - bitsPerComponent: size_t, - bitsPerPixel: size_t, - bytesPerRow: size_t, - space: ::sys::CGColorSpaceRef, - bitmapInfo: u32, - provider: ::sys::CGDataProviderRef, - decode: *const CGFloat, - shouldInterpolate: bool, - intent: u32) - -> ::sys::CGImageRef; + fn CGImageCreate( + width: size_t, + height: size_t, + bitsPerComponent: size_t, + bitsPerPixel: size_t, + bytesPerRow: size_t, + space: ::sys::CGColorSpaceRef, + bitmapInfo: u32, + provider: ::sys::CGDataProviderRef, + decode: *const CGFloat, + shouldInterpolate: bool, + intent: u32, + ) -> ::sys::CGImageRef; fn CGImageCreateWithImageInRect(image: ::sys::CGImageRef, rect: CGRect) -> ::sys::CGImageRef; //fn CGImageGetAlphaInfo(image: ::sys::CGImageRef) -> CGImageAlphaInfo; diff --git a/core-graphics/src/lib.rs b/core-graphics/src/lib.rs index 5238774e7..4679d9b2f 100644 --- a/core-graphics/src/lib.rs +++ b/core-graphics/src/lib.rs @@ -34,10 +34,10 @@ pub mod event_source; pub mod font; pub mod geometry; pub mod gradient; -#[cfg(target_os = "macos")] -pub mod window; -#[cfg(target_os = "macos")] -pub mod private; pub mod image; pub mod path; +#[cfg(target_os = "macos")] +pub mod private; pub mod sys; +#[cfg(target_os = "macos")] +pub mod window; diff --git a/core-graphics/src/path.rs b/core-graphics/src/path.rs index dc1c80464..bb267123f 100644 --- a/core-graphics/src/path.rs +++ b/core-graphics/src/path.rs @@ -40,18 +40,25 @@ impl CGPath { } pub fn type_id() -> CFTypeID { - unsafe { - CGPathGetTypeID() - } + unsafe { CGPathGetTypeID() } } - pub fn apply<'a, F>(&'a self, mut closure: &'a F) where F: FnMut(CGPathElementRef<'a>) { + pub fn apply<'a, F>(&'a self, mut closure: &'a F) + where + F: FnMut(CGPathElementRef<'a>), + { unsafe { - CGPathApply(self.as_ptr(), &mut closure as *mut _ as *mut c_void, do_apply::); + CGPathApply( + self.as_ptr(), + &mut closure as *mut _ as *mut c_void, + do_apply::, + ); } unsafe extern "C" fn do_apply<'a, F>(info: *mut c_void, element: *const CGPathElement) - where F: FnMut(CGPathElementRef<'a>) { + where + F: FnMut(CGPathElementRef<'a>), + { let closure = info as *mut *mut F; (**closure)(CGPathElementRef::new(element)) } @@ -85,9 +92,7 @@ impl<'a> CGPathElementRef<'a> { impl<'a> Deref for CGPathElementRef<'a> { type Target = CGPathElement; fn deref(&self) -> &CGPathElement { - unsafe { - &*self.element - } + unsafe { &*self.element } } } @@ -118,11 +123,10 @@ impl CGPathElement { } } -type CGPathApplierFunction = unsafe extern "C" fn(info: *mut c_void, - element: *const CGPathElement); +type CGPathApplierFunction = unsafe extern "C" fn(info: *mut c_void, element: *const CGPathElement); #[link(name = "CoreGraphics", kind = "framework")] -extern { +extern "C" { fn CGPathCreateWithRect(rect: CGRect, transform: *const CGAffineTransform) -> ::sys::CGPathRef; fn CGPathApply(path: ::sys::CGPathRef, info: *mut c_void, function: CGPathApplierFunction); fn CGPathGetTypeID() -> CFTypeID; diff --git a/core-graphics/src/private.rs b/core-graphics/src/private.rs index 0bc193b40..d28d45266 100644 --- a/core-graphics/src/private.rs +++ b/core-graphics/src/private.rs @@ -21,9 +21,7 @@ pub struct CGSRegion { impl Drop for CGSRegion { fn drop(&mut self) { - unsafe { - ffi::CGSRegionRelease(self.region) - } + unsafe { ffi::CGSRegionRelease(self.region) } } } @@ -33,9 +31,7 @@ impl CGSRegion { unsafe { let mut region = ptr::null_mut(); assert!(ffi::CGSNewRegionWithRect(rect, &mut region) == 0); - CGSRegion { - region: region, - } + CGSRegion { region: region } } } @@ -43,12 +39,11 @@ impl CGSRegion { pub fn from_rects(rects: &[CGRect]) -> CGSRegion { unsafe { let mut region = ptr::null_mut(); - assert!(ffi::CGSNewRegionWithRectList(rects.as_ptr(), - rects.len() as c_uint, - &mut region) == 0); - CGSRegion { - region: region, - } + assert!( + ffi::CGSNewRegionWithRectList(rects.as_ptr(), rects.len() as c_uint, &mut region) + == 0 + ); + CGSRegion { region: region } } } } @@ -78,10 +73,14 @@ impl CGSSurface { #[inline] pub fn set_shape(&self, region: &CGSRegion) { unsafe { - assert!(ffi::CGSSetSurfaceShape(self.context_id, - self.window_number, - self.surface_id, - region.region) == 0) + assert!( + ffi::CGSSetSurfaceShape( + self.context_id, + self.window_number, + self.surface_id, + region.region + ) == 0 + ) } } } @@ -98,19 +97,20 @@ mod ffi { pub type OSStatus = i32; #[link(name = "CoreGraphics", kind = "framework")] - extern { + extern "C" { pub fn CGSRegionRelease(region: CGSRegionRef); pub fn CGSNewRegionWithRect(rect: *const CGRect, outRegion: *mut CGSRegionRef) -> CGError; - pub fn CGSNewRegionWithRectList(rects: *const CGRect, - rectCount: c_uint, - outRegion: *mut CGSRegionRef) - -> CGError; - - pub fn CGSSetSurfaceShape(contextID: c_uint, - windowNumber: c_int, - surfaceID: c_uint, - region: CGSRegionRef) - -> CGError; + pub fn CGSNewRegionWithRectList( + rects: *const CGRect, + rectCount: c_uint, + outRegion: *mut CGSRegionRef, + ) -> CGError; + + pub fn CGSSetSurfaceShape( + contextID: c_uint, + windowNumber: c_int, + surfaceID: c_uint, + region: CGSRegionRef, + ) -> CGError; } } - diff --git a/core-graphics/src/sys.rs b/core-graphics/src/sys.rs index 85df442d5..9e0e80004 100644 --- a/core-graphics/src/sys.rs +++ b/core-graphics/src/sys.rs @@ -28,16 +28,16 @@ pub type CGGradientRef = *mut CGGradient; #[cfg(target_os = "macos")] mod macos { - pub enum CGEventTap {} - pub type CGEventTapRef = core_foundation::mach_port::CFMachPortRef; - pub enum CGEvent {} - pub type CGEventRef = *mut CGEvent; + pub enum CGEventTap {} + pub type CGEventTapRef = core_foundation::mach_port::CFMachPortRef; + pub enum CGEvent {} + pub type CGEventRef = *mut CGEvent; - pub enum CGEventSource {} - pub type CGEventSourceRef = *mut CGEventSource; + pub enum CGEventSource {} + pub type CGEventSourceRef = *mut CGEventSource; - pub enum CGDisplayMode {} - pub type CGDisplayModeRef = *mut CGDisplayMode; + pub enum CGDisplayMode {} + pub type CGDisplayModeRef = *mut CGDisplayMode; } #[cfg(target_os = "macos")] diff --git a/core-graphics/src/window.rs b/core-graphics/src/window.rs index aa7293ff7..97f08d30b 100644 --- a/core-graphics/src/window.rs +++ b/core-graphics/src/window.rs @@ -49,8 +49,10 @@ pub const kCGWindowImageNominalResolution: CGWindowImageOption = 1 << 4; pub const kCGNullWindowID: CGWindowID = 0; -pub fn copy_window_info(option: CGWindowListOption, relative_to_window: CGWindowID) - -> Option { +pub fn copy_window_info( + option: CGWindowListOption, + relative_to_window: CGWindowID, +) -> Option { unsafe { let array = CGWindowListCopyWindowInfo(option, relative_to_window); if array.is_null() { @@ -61,8 +63,10 @@ pub fn copy_window_info(option: CGWindowListOption, relative_to_window: CGWindow } } -pub fn create_window_list(option: CGWindowListOption, relative_to_window: CGWindowID) - -> Option> { +pub fn create_window_list( + option: CGWindowListOption, + relative_to_window: CGWindowID, +) -> Option> { unsafe { let array = CGWindowListCreate(option, relative_to_window); if array.is_null() { @@ -73,8 +77,9 @@ pub fn create_window_list(option: CGWindowListOption, relative_to_window: CGWind } } -pub fn create_description_from_array(window_array: CFArray) -> - Option>> { +pub fn create_description_from_array( + window_array: CFArray, +) -> Option>> { unsafe { let array = CGWindowListCreateDescriptionFromArray(window_array.as_concrete_TypeRef()); if array.is_null() { @@ -85,11 +90,12 @@ pub fn create_description_from_array(window_array: CFArray) -> } } -pub fn create_image(screen_bounds: CGRect, - list_option: CGWindowListOption, - window_id: CGWindowID, - image_option: CGWindowImageOption) - -> Option { +pub fn create_image( + screen_bounds: CGRect, + list_option: CGWindowListOption, + window_id: CGWindowID, + image_option: CGWindowImageOption, +) -> Option { unsafe { let image = CGWindowListCreateImage(screen_bounds, list_option, window_id, image_option); if image.is_null() { @@ -100,14 +106,17 @@ pub fn create_image(screen_bounds: CGRect, } } -pub fn create_image_from_array(screen_bounds: CGRect, - window_array: CFArray, - image_option: CGWindowImageOption) - -> Option { +pub fn create_image_from_array( + screen_bounds: CGRect, + window_array: CFArray, + image_option: CGWindowImageOption, +) -> Option { unsafe { - let image = CGWindowListCreateImageFromArray(screen_bounds, - window_array.as_concrete_TypeRef(), - image_option); + let image = CGWindowListCreateImageFromArray( + screen_bounds, + window_array.as_concrete_TypeRef(), + image_option, + ); if image.is_null() { None } else { @@ -117,7 +126,7 @@ pub fn create_image_from_array(screen_bounds: CGRect, } #[link(name = "CoreGraphics", kind = "framework")] -extern { +extern "C" { pub static kCGWindowNumber: CFStringRef; pub static kCGWindowStoreType: CFStringRef; pub static kCGWindowLayer: CFStringRef; @@ -132,18 +141,24 @@ extern { pub static kCGWindowIsOnscreen: CFStringRef; pub static kCGWindowBackingLocationVideoMemory: CFStringRef; - pub fn CGWindowListCopyWindowInfo(option: CGWindowListOption, relativeToWindow: CGWindowID) - -> CFArrayRef; - pub fn CGWindowListCreate(option: CGWindowListOption, relativeToWindow: CGWindowID) - -> CFArrayRef; + pub fn CGWindowListCopyWindowInfo( + option: CGWindowListOption, + relativeToWindow: CGWindowID, + ) -> CFArrayRef; + pub fn CGWindowListCreate( + option: CGWindowListOption, + relativeToWindow: CGWindowID, + ) -> CFArrayRef; pub fn CGWindowListCreateDescriptionFromArray(windowArray: CFArrayRef) -> CFArrayRef; - pub fn CGWindowListCreateImage(screenBounds: CGRect, - listOption: CGWindowListOption, - windowID: CGWindowID, - imageOption: CGWindowImageOption) - -> *mut sys::CGImage; - pub fn CGWindowListCreateImageFromArray(screenBounds: CGRect, - windowArray: CFArrayRef, - imageOption: CGWindowImageOption) - -> *mut sys::CGImage; + pub fn CGWindowListCreateImage( + screenBounds: CGRect, + listOption: CGWindowListOption, + windowID: CGWindowID, + imageOption: CGWindowImageOption, + ) -> *mut sys::CGImage; + pub fn CGWindowListCreateImageFromArray( + screenBounds: CGRect, + windowArray: CFArrayRef, + imageOption: CGWindowImageOption, + ) -> *mut sys::CGImage; } diff --git a/core-text/src/font.rs b/core-text/src/font.rs index 5f5df74fe..6d87d5112 100644 --- a/core-text/src/font.rs +++ b/core-text/src/font.rs @@ -20,10 +20,10 @@ use core_foundation::data::{CFData, CFDataRef}; use core_foundation::dictionary::{CFDictionary, CFDictionaryRef}; use core_foundation::number::CFNumber; use core_foundation::string::{CFString, CFStringRef, UniChar}; -use core_foundation::url::{CFURL, CFURLRef}; +use core_foundation::url::{CFURLRef, CFURL}; use core_graphics::base::CGFloat; use core_graphics::context::CGContext; -use core_graphics::font::{CGGlyph, CGFont}; +use core_graphics::font::{CGFont, CGGlyph}; use core_graphics::geometry::{CGAffineTransform, CGPoint, CGRect, CGSize}; use core_graphics::path::CGPath; @@ -94,33 +94,40 @@ unsafe impl Sync for CTFont {} pub fn new_from_CGFont(cgfont: &CGFont, pt_size: f64) -> CTFont { unsafe { - let font_ref = CTFontCreateWithGraphicsFont(cgfont.as_ptr() as *mut _, - pt_size as CGFloat, - ptr::null(), - ptr::null()); + let font_ref = CTFontCreateWithGraphicsFont( + cgfont.as_ptr() as *mut _, + pt_size as CGFloat, + ptr::null(), + ptr::null(), + ); CTFont::wrap_under_create_rule(font_ref) } } -pub fn new_from_CGFont_with_variations(cgfont: &CGFont, - pt_size: f64, - variations: &CFDictionary) - -> CTFont { +pub fn new_from_CGFont_with_variations( + cgfont: &CGFont, + pt_size: f64, + variations: &CFDictionary, +) -> CTFont { unsafe { let font_desc = font_descriptor::new_from_variations(variations); - let font_ref = CTFontCreateWithGraphicsFont(cgfont.as_ptr() as *mut _, - pt_size as CGFloat, - ptr::null(), - font_desc.as_concrete_TypeRef()); + let font_ref = CTFontCreateWithGraphicsFont( + cgfont.as_ptr() as *mut _, + pt_size as CGFloat, + ptr::null(), + font_desc.as_concrete_TypeRef(), + ); CTFont::wrap_under_create_rule(font_ref) } } pub fn new_from_descriptor(desc: &CTFontDescriptor, pt_size: f64) -> CTFont { unsafe { - let font_ref = CTFontCreateWithFontDescriptor(desc.as_concrete_TypeRef(), - pt_size as CGFloat, - ptr::null()); + let font_ref = CTFontCreateWithFontDescriptor( + desc.as_concrete_TypeRef(), + pt_size as CGFloat, + ptr::null(), + ); CTFont::wrap_under_create_rule(font_ref) } } @@ -133,9 +140,8 @@ pub fn new_from_buffer(buffer: &[u8]) -> Result { pub fn new_from_name(name: &str, pt_size: f64) -> Result { unsafe { let name: CFString = name.parse().unwrap(); - let font_ref = CTFontCreateWithName(name.as_concrete_TypeRef(), - pt_size as CGFloat, - ptr::null()); + let font_ref = + CTFontCreateWithName(name.as_concrete_TypeRef(), pt_size as CGFloat, ptr::null()); if font_ref.is_null() { Err(()) } else { @@ -144,15 +150,17 @@ pub fn new_from_name(name: &str, pt_size: f64) -> Result { } } -pub fn new_ui_font_for_language(ui_type: CTFontUIFontType, - size: f64, - language: Option) - -> CTFont { +pub fn new_ui_font_for_language( + ui_type: CTFontUIFontType, + size: f64, + language: Option, +) -> CTFont { unsafe { let font_ref = CTFontCreateUIFontForLanguage( ui_type, size, - language.as_ref() + language + .as_ref() .map(|x| x.as_concrete_TypeRef()) .unwrap_or(std::ptr::null()), ); @@ -170,9 +178,7 @@ pub fn new_ui_font_for_language(ui_type: CTFontUIFontType, impl CTFont { // Properties pub fn symbolic_traits(&self) -> CTFontSymbolicTraits { - unsafe { - CTFontGetSymbolicTraits(self.0) - } + unsafe { CTFontGetSymbolicTraits(self.0) } } } @@ -194,24 +200,25 @@ impl CTFont { pub fn clone_with_font_size(&self, size: f64) -> CTFont { unsafe { - let font_ref = CTFontCreateCopyWithAttributes(self.0, - size as CGFloat, - ptr::null(), - ptr::null()); + let font_ref = + CTFontCreateCopyWithAttributes(self.0, size as CGFloat, ptr::null(), ptr::null()); CTFont::wrap_under_create_rule(font_ref) } } - pub fn clone_with_symbolic_traits(&self, - trait_value: CTFontSymbolicTraits, - trait_mask: CTFontSymbolicTraits) - -> Option { + pub fn clone_with_symbolic_traits( + &self, + trait_value: CTFontSymbolicTraits, + trait_mask: CTFontSymbolicTraits, + ) -> Option { unsafe { - let font_ref = CTFontCreateCopyWithSymbolicTraits(self.0, - 0.0, - ptr::null(), - trait_value, - trait_mask); + let font_ref = CTFontCreateCopyWithSymbolicTraits( + self.0, + 0.0, + ptr::null(), + trait_value, + trait_mask, + ); if font_ref.is_null() { None } else { @@ -264,119 +271,95 @@ impl CTFont { } pub fn all_traits(&self) -> CTFontTraits { - unsafe { - CTFontTraits::wrap_under_create_rule(CTFontCopyTraits(self.0)) - } + unsafe { CTFontTraits::wrap_under_create_rule(CTFontCopyTraits(self.0)) } } // Font metrics pub fn ascent(&self) -> CGFloat { - unsafe { - CTFontGetAscent(self.0) - } + unsafe { CTFontGetAscent(self.0) } } pub fn descent(&self) -> CGFloat { - unsafe { - CTFontGetDescent(self.0) - } + unsafe { CTFontGetDescent(self.0) } } pub fn underline_thickness(&self) -> CGFloat { - unsafe { - CTFontGetUnderlineThickness(self.0) - } + unsafe { CTFontGetUnderlineThickness(self.0) } } pub fn underline_position(&self) -> CGFloat { - unsafe { - CTFontGetUnderlinePosition(self.0) - } + unsafe { CTFontGetUnderlinePosition(self.0) } } pub fn slant_angle(&self) -> CGFloat { - unsafe { - CTFontGetSlantAngle(self.0) - } + unsafe { CTFontGetSlantAngle(self.0) } } pub fn cap_height(&self) -> CGFloat { - unsafe { - CTFontGetCapHeight(self.0) - } + unsafe { CTFontGetCapHeight(self.0) } } pub fn bounding_box(&self) -> CGRect { - unsafe { - CTFontGetBoundingBox(self.0) - } + unsafe { CTFontGetBoundingBox(self.0) } } pub fn leading(&self) -> CGFloat { - unsafe { - CTFontGetLeading(self.0) - } + unsafe { CTFontGetLeading(self.0) } } pub fn units_per_em(&self) -> libc::c_uint { - unsafe { - CTFontGetUnitsPerEm(self.0) - } + unsafe { CTFontGetUnitsPerEm(self.0) } } pub fn x_height(&self) -> CGFloat { - unsafe { - CTFontGetXHeight(self.0) - } + unsafe { CTFontGetXHeight(self.0) } } pub fn pt_size(&self) -> CGFloat { - unsafe { - CTFontGetSize(self.0) - } + unsafe { CTFontGetSize(self.0) } } pub fn get_glyph_with_name(&self, glyph_name: &str) -> CGGlyph { let glyph_name = CFString::new(glyph_name); - unsafe { - CTFontGetGlyphWithName(self.0, glyph_name.as_concrete_TypeRef()) - } + unsafe { CTFontGetGlyphWithName(self.0, glyph_name.as_concrete_TypeRef()) } } - pub unsafe fn get_glyphs_for_characters(&self, - characters: *const UniChar, - glyphs: *mut CGGlyph, - count: CFIndex) - -> bool { + pub unsafe fn get_glyphs_for_characters( + &self, + characters: *const UniChar, + glyphs: *mut CGGlyph, + count: CFIndex, + ) -> bool { CTFontGetGlyphsForCharacters(self.0, characters, glyphs, count) } - pub unsafe fn get_advances_for_glyphs(&self, - orientation: CTFontOrientation, - glyphs: *const CGGlyph, - advances: *mut CGSize, - count: CFIndex) - -> f64 { + pub unsafe fn get_advances_for_glyphs( + &self, + orientation: CTFontOrientation, + glyphs: *const CGGlyph, + advances: *mut CGSize, + count: CFIndex, + ) -> f64 { CTFontGetAdvancesForGlyphs(self.0, orientation, glyphs, advances, count) as f64 } - pub unsafe fn get_vertical_translations_for_glyphs(&self, - orientation: CTFontOrientation, - glyphs: *const CGGlyph, - translations: *mut CGSize, - count: CFIndex) { - CTFontGetVerticalTranslationsForGlyphs(self.0, - orientation, - glyphs, - translations, - count) + pub unsafe fn get_vertical_translations_for_glyphs( + &self, + orientation: CTFontOrientation, + glyphs: *const CGGlyph, + translations: *mut CGSize, + count: CFIndex, + ) { + CTFontGetVerticalTranslationsForGlyphs(self.0, orientation, glyphs, translations, count) } pub fn get_font_table(&self, tag: u32) -> Option { unsafe { - let result = CTFontCopyTable(self.0, - tag as CTFontTableTag, - kCTFontTableOptionsExcludeSynthetic); + let result = CTFontCopyTable( + self.0, + tag as CTFontTableTag, + kCTFontTableOptionsExcludeSynthetic, + ); if result.is_null() { None } else { @@ -396,25 +379,32 @@ impl CTFont { } } - pub fn get_bounding_rects_for_glyphs(&self, orientation: CTFontOrientation, glyphs: &[CGGlyph]) - -> CGRect { + pub fn get_bounding_rects_for_glyphs( + &self, + orientation: CTFontOrientation, + glyphs: &[CGGlyph], + ) -> CGRect { unsafe { - CTFontGetBoundingRectsForGlyphs(self.as_concrete_TypeRef(), - orientation, - glyphs.as_ptr(), - ptr::null_mut(), - glyphs.len() as CFIndex) + CTFontGetBoundingRectsForGlyphs( + self.as_concrete_TypeRef(), + orientation, + glyphs.as_ptr(), + ptr::null_mut(), + glyphs.len() as CFIndex, + ) } } pub fn draw_glyphs(&self, glyphs: &[CGGlyph], positions: &[CGPoint], context: CGContext) { assert_eq!(glyphs.len(), positions.len()); unsafe { - CTFontDrawGlyphs(self.as_concrete_TypeRef(), - glyphs.as_ptr(), - positions.as_ptr(), - glyphs.len() as size_t, - context.as_ptr()) + CTFontDrawGlyphs( + self.as_concrete_TypeRef(), + glyphs.as_ptr(), + positions.as_ptr(), + glyphs.len() as size_t, + context.as_ptr(), + ) } } @@ -439,8 +429,11 @@ impl CTFont { } } - pub fn create_path_for_glyph(&self, glyph: CGGlyph, matrix: &CGAffineTransform) - -> Result { + pub fn create_path_for_glyph( + &self, + glyph: CGGlyph, + matrix: &CGAffineTransform, + ) -> Result { unsafe { let path = CTFontCreatePathForGlyph(self.0, glyph, matrix); if path.is_null() { @@ -453,9 +446,7 @@ impl CTFont { #[inline] pub fn glyph_count(&self) -> CFIndex { - unsafe { - CTFontGetGlyphCount(self.0) - } + unsafe { CTFontGetGlyphCount(self.0) } } } @@ -477,12 +468,27 @@ pub fn debug_font_names(font: &CTFont) { } unsafe { - println!("kCTFontFamilyNameKey: {}", get_key(font, kCTFontFamilyNameKey)); - println!("kCTFontSubFamilyNameKey: {}", get_key(font, kCTFontSubFamilyNameKey)); - println!("kCTFontStyleNameKey: {}", get_key(font, kCTFontStyleNameKey)); - println!("kCTFontUniqueNameKey: {}", get_key(font, kCTFontUniqueNameKey)); + println!( + "kCTFontFamilyNameKey: {}", + get_key(font, kCTFontFamilyNameKey) + ); + println!( + "kCTFontSubFamilyNameKey: {}", + get_key(font, kCTFontSubFamilyNameKey) + ); + println!( + "kCTFontStyleNameKey: {}", + get_key(font, kCTFontStyleNameKey) + ); + println!( + "kCTFontUniqueNameKey: {}", + get_key(font, kCTFontUniqueNameKey) + ); println!("kCTFontFullNameKey: {}", get_key(font, kCTFontFullNameKey)); - println!("kCTFontPostScriptNameKey: {}", get_key(font, kCTFontPostScriptNameKey)); + println!( + "kCTFontPostScriptNameKey: {}", + get_key(font, kCTFontPostScriptNameKey) + ); } } @@ -497,21 +503,25 @@ pub fn debug_font_traits(font: &CTFont) { let traits = font.all_traits(); println!("kCTFontWeightTrait: {}", traits.normalized_weight()); println!("kCTFontWidthTrait: {}", traits.normalized_width()); -// println!("kCTFontSlantTrait: {}", traits.normalized_slant()); + // println!("kCTFontSlantTrait: {}", traits.normalized_slant()); } #[cfg(feature = "mountainlion")] -pub fn cascade_list_for_languages(font: &CTFont, language_pref_list: &CFArray) -> CFArray { +pub fn cascade_list_for_languages( + font: &CTFont, + language_pref_list: &CFArray, +) -> CFArray { unsafe { - let font_collection_ref = - CTFontCopyDefaultCascadeListForLanguages(font.as_concrete_TypeRef(), - language_pref_list.as_concrete_TypeRef()); + let font_collection_ref = CTFontCopyDefaultCascadeListForLanguages( + font.as_concrete_TypeRef(), + language_pref_list.as_concrete_TypeRef(), + ); CFArray::wrap_under_create_rule(font_collection_ref) } } #[link(name = "CoreText", kind = "framework")] -extern { +extern "C" { /* * CTFont.h */ @@ -559,20 +569,36 @@ extern { // to the documentation's Functions By Task listing, because there so many functions. /* Creating Fonts */ - fn CTFontCreateWithName(name: CFStringRef, size: CGFloat, matrix: *const CGAffineTransform) -> CTFontRef; + fn CTFontCreateWithName( + name: CFStringRef, + size: CGFloat, + matrix: *const CGAffineTransform, + ) -> CTFontRef; //fn CTFontCreateWithNameAndOptions - fn CTFontCreateWithFontDescriptor(descriptor: CTFontDescriptorRef, size: CGFloat, - matrix: *const CGAffineTransform) -> CTFontRef; + fn CTFontCreateWithFontDescriptor( + descriptor: CTFontDescriptorRef, + size: CGFloat, + matrix: *const CGAffineTransform, + ) -> CTFontRef; //fn CTFontCreateWithFontDescriptorAndOptions - fn CTFontCreateUIFontForLanguage(uiType: CTFontUIFontType, size: CGFloat, language: CFStringRef) -> CTFontRef; - fn CTFontCreateCopyWithAttributes(font: CTFontRef, size: CGFloat, matrix: *const CGAffineTransform, - attributes: CTFontDescriptorRef) -> CTFontRef; - fn CTFontCreateCopyWithSymbolicTraits(font: CTFontRef, - size: CGFloat, - matrix: *const CGAffineTransform, - symTraitValue: CTFontSymbolicTraits, - symTraitMask: CTFontSymbolicTraits) - -> CTFontRef; + fn CTFontCreateUIFontForLanguage( + uiType: CTFontUIFontType, + size: CGFloat, + language: CFStringRef, + ) -> CTFontRef; + fn CTFontCreateCopyWithAttributes( + font: CTFontRef, + size: CGFloat, + matrix: *const CGAffineTransform, + attributes: CTFontDescriptorRef, + ) -> CTFontRef; + fn CTFontCreateCopyWithSymbolicTraits( + font: CTFontRef, + size: CGFloat, + matrix: *const CGAffineTransform, + symTraitValue: CTFontSymbolicTraits, + symTraitMask: CTFontSymbolicTraits, + ) -> CTFontRef; //fn CTFontCreateCopyWithFamily //fn CTFontCreateForString @@ -593,8 +619,10 @@ extern { //fn CTFontCopyLocalizedName(font: CTFontRef, nameKey: CFStringRef, // language: *CFStringRef) -> CFStringRef; #[cfg(feature = "mountainlion")] - fn CTFontCopyDefaultCascadeListForLanguages(font: CTFontRef, languagePrefList: CFArrayRef) -> CFArrayRef; - + fn CTFontCopyDefaultCascadeListForLanguages( + font: CTFontRef, + languagePrefList: CFArrayRef, + ) -> CFArrayRef; /* Working With Encoding */ //fn CTFontCopyCharacterSet @@ -615,26 +643,33 @@ extern { fn CTFontGetXHeight(font: CTFontRef) -> CGFloat; /* Getting Glyph Data */ - fn CTFontCreatePathForGlyph(font: CTFontRef, glyph: CGGlyph, matrix: *const CGAffineTransform) - -> CGPathRef; + fn CTFontCreatePathForGlyph( + font: CTFontRef, + glyph: CGGlyph, + matrix: *const CGAffineTransform, + ) -> CGPathRef; fn CTFontGetGlyphWithName(font: CTFontRef, glyphName: CFStringRef) -> CGGlyph; - fn CTFontGetBoundingRectsForGlyphs(font: CTFontRef, - orientation: CTFontOrientation, - glyphs: *const CGGlyph, - boundingRects: *mut CGRect, - count: CFIndex) - -> CGRect; - fn CTFontGetAdvancesForGlyphs(font: CTFontRef, - orientation: CTFontOrientation, - glyphs: *const CGGlyph, - advances: *mut CGSize, - count: CFIndex) - -> libc::c_double; - fn CTFontGetVerticalTranslationsForGlyphs(font: CTFontRef, - orientation: CTFontOrientation, - glyphs: *const CGGlyph, - translations: *mut CGSize, - count: CFIndex); + fn CTFontGetBoundingRectsForGlyphs( + font: CTFontRef, + orientation: CTFontOrientation, + glyphs: *const CGGlyph, + boundingRects: *mut CGRect, + count: CFIndex, + ) -> CGRect; + fn CTFontGetAdvancesForGlyphs( + font: CTFontRef, + orientation: CTFontOrientation, + glyphs: *const CGGlyph, + advances: *mut CGSize, + count: CFIndex, + ) -> libc::c_double; + fn CTFontGetVerticalTranslationsForGlyphs( + font: CTFontRef, + orientation: CTFontOrientation, + glyphs: *const CGGlyph, + translations: *mut CGSize, + count: CFIndex, + ); /* Working With Font Variations */ fn CTFontCopyVariationAxes(font: CTFontRef) -> CFArrayRef; @@ -645,27 +680,40 @@ extern { //fn CTFontCopyFeatureSettings /* Working with Glyphs */ - fn CTFontGetGlyphsForCharacters(font: CTFontRef, characters: *const UniChar, glyphs: *mut CGGlyph, count: CFIndex) -> bool; - fn CTFontDrawGlyphs(font: CTFontRef, - glyphs: *const CGGlyph, - positions: *const CGPoint, - count: size_t, - context: CGContextRef); + fn CTFontGetGlyphsForCharacters( + font: CTFontRef, + characters: *const UniChar, + glyphs: *mut CGGlyph, + count: CFIndex, + ) -> bool; + fn CTFontDrawGlyphs( + font: CTFontRef, + glyphs: *const CGGlyph, + positions: *const CGPoint, + count: size_t, + context: CGContextRef, + ); //fn CTFontGetLigatureCaretPositions /* Converting Fonts */ - fn CTFontCopyGraphicsFont(font: CTFontRef, attributes: *mut CTFontDescriptorRef) - -> CGFontRef; - fn CTFontCreateWithGraphicsFont(graphicsFont: CGFontRef, size: CGFloat, - matrix: *const CGAffineTransform, - attributes: CTFontDescriptorRef) -> CTFontRef; + fn CTFontCopyGraphicsFont(font: CTFontRef, attributes: *mut CTFontDescriptorRef) -> CGFontRef; + fn CTFontCreateWithGraphicsFont( + graphicsFont: CGFontRef, + size: CGFloat, + matrix: *const CGAffineTransform, + attributes: CTFontDescriptorRef, + ) -> CTFontRef; //fn CTFontGetPlatformFont //fn CTFontCreateWithPlatformFont //fn CTFontCreateWithQuickdrawInstance /* Getting Font Table Data */ fn CTFontCopyAvailableTables(font: CTFontRef, options: CTFontTableOptions) -> CFArrayRef; - fn CTFontCopyTable(font: CTFontRef, table: CTFontTableTag, options: CTFontTableOptions) -> CFDataRef; + fn CTFontCopyTable( + font: CTFontRef, + table: CTFontTableTag, + options: CTFontTableOptions, + ) -> CFDataRef; fn CTFontGetTypeID() -> CFTypeID; } @@ -696,20 +744,35 @@ fn macos_version() -> (i32, i32, i32) { f.read_to_end(&mut system_version_data).unwrap(); use core_foundation::propertylist; - let (list, _) = propertylist::create_with_data(core_foundation::data::CFData::from_buffer(&system_version_data), propertylist::kCFPropertyListImmutable).unwrap(); + let (list, _) = propertylist::create_with_data( + core_foundation::data::CFData::from_buffer(&system_version_data), + propertylist::kCFPropertyListImmutable, + ) + .unwrap(); let k = unsafe { propertylist::CFPropertyList::wrap_under_create_rule(list) }; - let dict = unsafe { std::mem::transmute::<_, CFDictionary>(k.downcast::().unwrap()) }; + let dict = unsafe { + std::mem::transmute::<_, CFDictionary>( + k.downcast::().unwrap(), + ) + }; - let version = dict.find(&CFString::new("ProductVersion").as_CFType()) - .as_ref().unwrap() - .downcast::().unwrap() + let version = dict + .find(&CFString::new("ProductVersion").as_CFType()) + .as_ref() + .unwrap() + .downcast::() + .unwrap() .to_string(); - match version.split(".").map(|x| x.parse().unwrap()).collect::>()[..] { + match version + .split(".") + .map(|x| x.parse().unwrap()) + .collect::>()[..] + { [a, b, c] => (a, b, c), [a, b] => (a, b, 0), - _ => panic!() + _ => panic!(), } } @@ -757,16 +820,32 @@ fn copy_system_font() { let cgfont = new_from_CGFont(&cgfont, 0.); println!("{:?}", cgfont); let desc = cgfont.copy_descriptor(); - let matching = unsafe { crate::font_descriptor::CTFontDescriptorCreateMatchingFontDescriptor(desc.as_concrete_TypeRef(), std::ptr::null()) }; - let matching = unsafe { CTFontDescriptor::wrap_under_create_rule(matching) }; + let matching = unsafe { + crate::font_descriptor::CTFontDescriptorCreateMatchingFontDescriptor( + desc.as_concrete_TypeRef(), + std::ptr::null(), + ) + }; + let matching = unsafe { CTFontDescriptor::wrap_under_create_rule(matching) }; println!("{:?}", cgfont.copy_descriptor()); - assert!(desc.attributes().find(CFString::from_static_string("NSFontSizeAttribute")).is_some()); + assert!(desc + .attributes() + .find(CFString::from_static_string("NSFontSizeAttribute")) + .is_some()); println!("{:?}", matching); - println!("{:?}", matching.attributes().find(CFString::from_static_string("NSFontSizeAttribute"))); - - assert!(matching.attributes().find(CFString::from_static_string("NSFontSizeAttribute")).is_none()); + println!( + "{:?}", + matching + .attributes() + .find(CFString::from_static_string("NSFontSizeAttribute")) + ); + + assert!(matching + .attributes() + .find(CFString::from_static_string("NSFontSizeAttribute")) + .is_none()); assert_eq!(small.postscript_name(), cgfont.postscript_name()); } @@ -787,17 +866,30 @@ fn out_of_range_variations() { let mut vals = Vec::new(); dbg!(&axes); for axis in axes.iter() { - let tag = axis.find(unsafe { kCTFontVariationAxisIdentifierKey } ) - .unwrap().downcast::().unwrap().to_i64().unwrap(); - let max = axis.find(unsafe { kCTFontVariationAxisMaximumValueKey } ) - .unwrap().downcast::().unwrap().to_f64().unwrap(); + let tag = axis + .find(unsafe { kCTFontVariationAxisIdentifierKey }) + .unwrap() + .downcast::() + .unwrap() + .to_i64() + .unwrap(); + let max = axis + .find(unsafe { kCTFontVariationAxisMaximumValueKey }) + .unwrap() + .downcast::() + .unwrap() + .to_f64() + .unwrap(); vals.push((CFNumber::from(tag), CFNumber::from(max + 1.))); - } let vals_dict = CFDictionary::from_CFType_pairs(&vals); - let variation_attribute = unsafe { CFString::wrap_under_get_rule(font_descriptor::kCTFontVariationAttribute) }; + let variation_attribute = + unsafe { CFString::wrap_under_get_rule(font_descriptor::kCTFontVariationAttribute) }; let attrs_dict = CFDictionary::from_CFType_pairs(&[(variation_attribute.clone(), vals_dict)]); - let ct_var_font_desc = small.copy_descriptor().create_copy_with_attributes(attrs_dict.to_untyped()).unwrap(); + let ct_var_font_desc = small + .copy_descriptor() + .create_copy_with_attributes(attrs_dict.to_untyped()) + .unwrap(); let variation_font = crate::font::new_from_descriptor(&ct_var_font_desc, 19.); let var_desc = variation_font.copy_descriptor(); let var_attrs = var_desc.attributes(); @@ -811,11 +903,23 @@ fn out_of_range_variations() { let var_attrs: CFDictionary = unsafe { std::mem::transmute(var_attrs) }; // attributes greater than max remain for axis in axes.iter() { - let tag = axis.find(unsafe { kCTFontVariationAxisIdentifierKey } ) - .unwrap(); - let max = axis.find(unsafe { kCTFontVariationAxisMaximumValueKey } ) - .unwrap().downcast::().unwrap().to_f64().unwrap(); - let val = var_attrs.find(tag.clone()).unwrap().downcast::().unwrap().to_f64().unwrap(); + let tag = axis + .find(unsafe { kCTFontVariationAxisIdentifierKey }) + .unwrap(); + let max = axis + .find(unsafe { kCTFontVariationAxisMaximumValueKey }) + .unwrap() + .downcast::() + .unwrap() + .to_f64() + .unwrap(); + let val = var_attrs + .find(tag.clone()) + .unwrap() + .downcast::() + .unwrap() + .to_f64() + .unwrap(); assert_eq!(val, max + 1.); } } else if macos_version() >= (10, 15, 0) { @@ -830,51 +934,76 @@ fn out_of_range_variations() { fn equal_descriptor_different_font() { use crate::*; - let variation_attribute = unsafe { CFString::wrap_under_get_rule(font_descriptor::kCTFontVariationAttribute) }; - let size_attribute = unsafe { CFString::wrap_under_get_rule(font_descriptor::kCTFontSizeAttribute) }; + let variation_attribute = + unsafe { CFString::wrap_under_get_rule(font_descriptor::kCTFontVariationAttribute) }; + let size_attribute = + unsafe { CFString::wrap_under_get_rule(font_descriptor::kCTFontSizeAttribute) }; let sys_font = new_ui_font_for_language(kCTFontSystemDetailFontType, 19., None); - // but we can still construct the CGFont by name let create_vars = |desc| { let mut vals: Vec<(CFNumber, CFNumber)> = Vec::new(); vals.push((CFNumber::from(0x6f70737a), CFNumber::from(17.))); let vals_dict = CFDictionary::from_CFType_pairs(&vals); - let attrs_dict = CFDictionary::from_CFType_pairs(&[(variation_attribute.clone(), vals_dict)]); - let size_attrs_dict = CFDictionary::from_CFType_pairs(&[(size_attribute.clone(), CFNumber::from(120.))]); + let attrs_dict = + CFDictionary::from_CFType_pairs(&[(variation_attribute.clone(), vals_dict)]); + let size_attrs_dict = + CFDictionary::from_CFType_pairs(&[(size_attribute.clone(), CFNumber::from(120.))]); dbg!(&desc); let from_font_desc = new_from_descriptor(&desc, 120.).copy_descriptor(); - let resized_font_desc = desc.create_copy_with_attributes(size_attrs_dict.to_untyped()).unwrap(); + let resized_font_desc = desc + .create_copy_with_attributes(size_attrs_dict.to_untyped()) + .unwrap(); if macos_version() >= (11, 0, 0) { assert_eq!(from_font_desc, resized_font_desc); } else { // we won't have a name if we're using system font desc - if from_font_desc.attributes().find(unsafe { font_descriptor::kCTFontNameAttribute }).is_none() { + if from_font_desc + .attributes() + .find(unsafe { font_descriptor::kCTFontNameAttribute }) + .is_none() + { // it's surprising that desc's are the not equal but the attributes are assert_ne!(from_font_desc, resized_font_desc); - assert_eq!(from_font_desc.attributes().to_untyped(), resized_font_desc.attributes().to_untyped()); + assert_eq!( + from_font_desc.attributes().to_untyped(), + resized_font_desc.attributes().to_untyped() + ); } else { if macos_version() >= (10, 13, 0) { // this is unsurprising assert_ne!(from_font_desc, resized_font_desc); - assert_ne!(from_font_desc.attributes().to_untyped(), resized_font_desc.attributes().to_untyped()); + assert_ne!( + from_font_desc.attributes().to_untyped(), + resized_font_desc.attributes().to_untyped() + ); } else { assert_ne!(from_font_desc, resized_font_desc); - assert_eq!(from_font_desc.attributes().to_untyped(), resized_font_desc.attributes().to_untyped()); + assert_eq!( + from_font_desc.attributes().to_untyped(), + resized_font_desc.attributes().to_untyped() + ); } } } - let from_font_desc = from_font_desc.create_copy_with_attributes(attrs_dict.to_untyped()).unwrap(); - let resized_font_desc = resized_font_desc.create_copy_with_attributes(attrs_dict.to_untyped()).unwrap(); + let from_font_desc = from_font_desc + .create_copy_with_attributes(attrs_dict.to_untyped()) + .unwrap(); + let resized_font_desc = resized_font_desc + .create_copy_with_attributes(attrs_dict.to_untyped()) + .unwrap(); (from_font_desc, resized_font_desc) }; // setting the variation works properly if we use system font desc let (from_font_desc, resized_font_desc) = create_vars(sys_font.copy_descriptor()); assert_eq!(from_font_desc, resized_font_desc); - assert!(resized_font_desc.attributes().find(variation_attribute.clone()).is_some()); + assert!(resized_font_desc + .attributes() + .find(variation_attribute.clone()) + .is_some()); // but doesn't if we refer to it by name let ps = sys_font.postscript_name(); @@ -887,11 +1016,20 @@ fn equal_descriptor_different_font() { } if macos_version() >= (10, 13, 0) { - assert!(from_font_desc.attributes().find(variation_attribute.clone()).is_some()); + assert!(from_font_desc + .attributes() + .find(variation_attribute.clone()) + .is_some()); if macos_version() >= (11, 0, 0) { - assert!(resized_font_desc.attributes().find(variation_attribute).is_none()); + assert!(resized_font_desc + .attributes() + .find(variation_attribute) + .is_none()); } else { - assert!(resized_font_desc.attributes().find(variation_attribute).is_some()); + assert!(resized_font_desc + .attributes() + .find(variation_attribute) + .is_some()); }; } } @@ -911,9 +1049,12 @@ fn system_font_variation() { let mut vals: Vec<(CFNumber, CFNumber)> = Vec::new(); vals.push((CFNumber::from(0x6f70737a /* opsz */), CFNumber::from(17.))); let vals_dict = CFDictionary::from_CFType_pairs(&vals); - let variation_attribute = unsafe { CFString::wrap_under_get_rule(font_descriptor::kCTFontVariationAttribute) }; + let variation_attribute = + unsafe { CFString::wrap_under_get_rule(font_descriptor::kCTFontVariationAttribute) }; let attrs_dict = CFDictionary::from_CFType_pairs(&[(variation_attribute, vals_dict)]); - let ct_var_font_desc = desc.create_copy_with_attributes(attrs_dict.to_untyped()).unwrap(); + let ct_var_font_desc = desc + .create_copy_with_attributes(attrs_dict.to_untyped()) + .unwrap(); let attrs = ct_var_font_desc.attributes(); let var_attr = attrs.find(CFString::from_static_string("NSCTFontVariationAttribute")); if macos_version() >= (11, 0, 0) { @@ -929,5 +1070,9 @@ fn system_font_variation() { #[test] fn ui_font() { // pass some garbagey inputs - new_ui_font_for_language(kCTFontSystemDetailFontType, 10000009., Some(CFString::from("Gofld"))); -} \ No newline at end of file + new_ui_font_for_language( + kCTFontSystemDetailFontType, + 10000009., + Some(CFString::from("Gofld")), + ); +} diff --git a/core-text/src/font_collection.rs b/core-text/src/font_collection.rs index 8f3f2c561..bf5822249 100644 --- a/core-text/src/font_collection.rs +++ b/core-text/src/font_collection.rs @@ -9,7 +9,9 @@ use font_descriptor; use font_descriptor::{CTFontDescriptor, CTFontDescriptorCreateMatchingFontDescriptors}; -use font_manager::{CTFontManagerCopyAvailableFontFamilyNames, CTFontManagerCopyAvailablePostScriptNames}; +use font_manager::{ + CTFontManagerCopyAvailableFontFamilyNames, CTFontManagerCopyAvailablePostScriptNames, +}; use core_foundation::array::{CFArray, CFArrayRef}; use core_foundation::base::{CFTypeID, TCFType}; @@ -28,10 +30,13 @@ pub type CTFontCollectionRef = *const __CTFontCollection; declare_TCFType! { CTFontCollection, CTFontCollectionRef } -impl_TCFType!(CTFontCollection, CTFontCollectionRef, CTFontCollectionGetTypeID); +impl_TCFType!( + CTFontCollection, + CTFontCollectionRef, + CTFontCollectionGetTypeID +); impl_CFTypeDescription!(CTFontCollection); - impl CTFontCollection { pub fn get_descriptors(&self) -> Option> { // surprise! this function follows the Get rule, despite being named *Create*. @@ -52,10 +57,11 @@ pub fn new_from_descriptors(descs: &CFArray) -> CTFontCollecti unsafe { let key = CFString::wrap_under_get_rule(kCTFontCollectionRemoveDuplicatesOption); let value = CFNumber::from(1i64); - let options = CFDictionary::from_CFType_pairs(&[ (key.as_CFType(), value.as_CFType()) ]); - let font_collection_ref = - CTFontCollectionCreateWithFontDescriptors(descs.as_concrete_TypeRef(), - options.as_concrete_TypeRef()); + let options = CFDictionary::from_CFType_pairs(&[(key.as_CFType(), value.as_CFType())]); + let font_collection_ref = CTFontCollectionCreateWithFontDescriptors( + descs.as_concrete_TypeRef(), + options.as_concrete_TypeRef(), + ); CTFontCollection::wrap_under_create_rule(font_collection_ref) } } @@ -64,7 +70,7 @@ pub fn create_for_all_families() -> CTFontCollection { unsafe { let key = CFString::wrap_under_get_rule(kCTFontCollectionRemoveDuplicatesOption); let value = CFNumber::from(1i64); - let options = CFDictionary::from_CFType_pairs(&[ (key.as_CFType(), value.as_CFType()) ]); + let options = CFDictionary::from_CFType_pairs(&[(key.as_CFType(), value.as_CFType())]); let font_collection_ref = CTFontCollectionCreateFromAvailableFonts(options.as_concrete_TypeRef()); CTFontCollection::wrap_under_create_rule(font_collection_ref) @@ -77,16 +83,16 @@ pub fn create_for_family(family: &str) -> Option { unsafe { let family_attr = CFString::wrap_under_get_rule(kCTFontFamilyNameAttribute); let family_name: CFString = family.parse().unwrap(); - let specified_attrs = CFDictionary::from_CFType_pairs(&[ - (family_attr.clone(), family_name.as_CFType()) - ]); + let specified_attrs = + CFDictionary::from_CFType_pairs(&[(family_attr.clone(), family_name.as_CFType())]); let wildcard_desc: CTFontDescriptor = font_descriptor::new_from_attributes(&specified_attrs); - let mandatory_attrs = CFSet::from_slice(&[ family_attr.as_CFType() ]); + let mandatory_attrs = CFSet::from_slice(&[family_attr.as_CFType()]); let matched_descs = CTFontDescriptorCreateMatchingFontDescriptors( - wildcard_desc.as_concrete_TypeRef(), - mandatory_attrs.as_concrete_TypeRef()); + wildcard_desc.as_concrete_TypeRef(), + mandatory_attrs.as_concrete_TypeRef(), + ); if matched_descs.is_null() { return None; } @@ -98,18 +104,14 @@ pub fn create_for_family(family: &str) -> Option { } pub fn get_family_names() -> CFArray { - unsafe { - CFArray::wrap_under_create_rule(CTFontManagerCopyAvailableFontFamilyNames()) - } + unsafe { CFArray::wrap_under_create_rule(CTFontManagerCopyAvailableFontFamilyNames()) } } pub fn get_postscript_names() -> CFArray { - unsafe { - CFArray::wrap_under_create_rule(CTFontManagerCopyAvailablePostScriptNames()) - } + unsafe { CFArray::wrap_under_create_rule(CTFontManagerCopyAvailablePostScriptNames()) } } -extern { +extern "C" { /* * CTFontCollection.h */ @@ -123,9 +125,12 @@ extern { // this stupid function doesn't actually do any wildcard expansion; // it just chooses the best match. Use // CTFontDescriptorCreateMatchingDescriptors instead. - fn CTFontCollectionCreateMatchingFontDescriptors(collection: CTFontCollectionRef) -> CFArrayRef; - fn CTFontCollectionCreateWithFontDescriptors(descriptors: CFArrayRef, - options: CFDictionaryRef) -> CTFontCollectionRef; + fn CTFontCollectionCreateMatchingFontDescriptors(collection: CTFontCollectionRef) + -> CFArrayRef; + fn CTFontCollectionCreateWithFontDescriptors( + descriptors: CFArrayRef, + options: CFDictionaryRef, + ) -> CTFontCollectionRef; //fn CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback; fn CTFontCollectionGetTypeID() -> CFTypeID; } diff --git a/core-text/src/font_descriptor.rs b/core-text/src/font_descriptor.rs index c70495c82..0ade74cbd 100644 --- a/core-text/src/font_descriptor.rs +++ b/core-text/src/font_descriptor.rs @@ -15,7 +15,7 @@ use core_foundation::dictionary::{CFDictionary, CFDictionaryRef}; use core_foundation::number::{CFNumber, CFNumberRef}; use core_foundation::set::CFSetRef; use core_foundation::string::{CFString, CFStringRef}; -use core_foundation::url::{CFURL, CFURLRef}; +use core_foundation::url::{CFURLRef, CFURL}; use core_graphics::base::CGFloat; use std::os::raw::c_void; @@ -56,12 +56,24 @@ pub trait SymbolicTraitAccessors { } impl SymbolicTraitAccessors for CTFontSymbolicTraits { - fn is_italic(&self) -> bool { (*self & kCTFontItalicTrait) != 0 } - fn is_bold(&self) -> bool { (*self & kCTFontBoldTrait) != 0 } - fn is_expanded(&self) -> bool { (*self & kCTFontExpandedTrait) != 0 } - fn is_condensed(&self) -> bool { (*self & kCTFontCondensedTrait) != 0 } - fn is_monospace(&self) -> bool { (*self & kCTFontMonoSpaceTrait) != 0 } - fn is_vertical(&self) -> bool { (*self & kCTFontVerticalTrait) != 0 } + fn is_italic(&self) -> bool { + (*self & kCTFontItalicTrait) != 0 + } + fn is_bold(&self) -> bool { + (*self & kCTFontBoldTrait) != 0 + } + fn is_expanded(&self) -> bool { + (*self & kCTFontExpandedTrait) != 0 + } + fn is_condensed(&self) -> bool { + (*self & kCTFontCondensedTrait) != 0 + } + fn is_monospace(&self) -> bool { + (*self & kCTFontMonoSpaceTrait) != 0 + } + fn is_vertical(&self) -> bool { + (*self & kCTFontVerticalTrait) != 0 + } } pub type CTFontStylisticClass = u32; @@ -134,7 +146,6 @@ impl TraitAccessorPrivate for CTFontTraits { let cftype = self.get(key); cftype.downcast::().unwrap() } - } impl TraitAccessors for CTFontTraits { @@ -191,7 +202,11 @@ pub type CTFontDescriptorRef = *const __CTFontDescriptor; declare_TCFType! { CTFontDescriptor, CTFontDescriptorRef } -impl_TCFType!(CTFontDescriptor, CTFontDescriptorRef, CTFontDescriptorGetTypeID); +impl_TCFType!( + CTFontDescriptor, + CTFontDescriptorRef, + CTFontDescriptorGetTypeID +); impl_CFTypeDescription!(CTFontDescriptor); // "Font objects (CTFont, CTFontDescriptor, and associated objects) can be used @@ -204,7 +219,7 @@ impl CTFontDescriptor { unsafe { let value = CTFontDescriptorCopyAttribute(self.0, attribute); if value.is_null() { - return None + return None; } let value = CFType::wrap_under_create_rule(value); @@ -213,7 +228,6 @@ impl CTFontDescriptor { Some(s.to_string()) } } - } impl CTFontDescriptor { @@ -285,8 +299,10 @@ impl CTFontDescriptor { pub fn create_copy_with_attributes(&self, attr: CFDictionary) -> Result { unsafe { - let desc = CTFontDescriptorCreateCopyWithAttributes(self.as_concrete_TypeRef(), - attr.as_concrete_TypeRef()); + let desc = CTFontDescriptorCreateCopyWithAttributes( + self.as_concrete_TypeRef(), + attr.as_concrete_TypeRef(), + ); if desc.is_null() { return Err(()); } @@ -336,7 +352,7 @@ pub fn debug_descriptor(desc: &CTFontDescriptor) { desc.show(); } -extern { +extern "C" { /* * CTFontTraits.h */ @@ -354,51 +370,69 @@ extern { // font attribute constants. Note that the name-related attributes // here are somewhat flaky. Servo creates CTFont instances and // then uses CTFontCopyName to get more fine-grained names. - pub static kCTFontURLAttribute: CFStringRef; // value: CFURLRef - pub static kCTFontNameAttribute: CFStringRef; // value: CFStringRef - pub static kCTFontDisplayNameAttribute: CFStringRef; // value: CFStringRef - pub static kCTFontFamilyNameAttribute: CFStringRef; // value: CFStringRef - pub static kCTFontStyleNameAttribute: CFStringRef; // value: CFStringRef - pub static kCTFontTraitsAttribute: CFStringRef; - pub static kCTFontVariationAttribute: CFStringRef; - pub static kCTFontSizeAttribute: CFStringRef; - pub static kCTFontMatrixAttribute: CFStringRef; - pub static kCTFontCascadeListAttribute: CFStringRef; - pub static kCTFontCharacterSetAttribute: CFStringRef; - pub static kCTFontLanguagesAttribute: CFStringRef; - pub static kCTFontBaselineAdjustAttribute: CFStringRef; - pub static kCTFontMacintoshEncodingsAttribute: CFStringRef; - pub static kCTFontFeaturesAttribute: CFStringRef; - pub static kCTFontFeatureSettingsAttribute: CFStringRef; - pub static kCTFontFixedAdvanceAttribute: CFStringRef; - pub static kCTFontOrientationAttribute: CFStringRef; - pub static kCTFontFormatAttribute: CFStringRef; - pub static kCTFontRegistrationScopeAttribute: CFStringRef; - pub static kCTFontPriorityAttribute: CFStringRef; - pub static kCTFontEnabledAttribute: CFStringRef; - - pub fn CTFontDescriptorCopyAttribute(descriptor: CTFontDescriptorRef, - attribute: CFStringRef) -> CFTypeRef; + pub static kCTFontURLAttribute: CFStringRef; // value: CFURLRef + pub static kCTFontNameAttribute: CFStringRef; // value: CFStringRef + pub static kCTFontDisplayNameAttribute: CFStringRef; // value: CFStringRef + pub static kCTFontFamilyNameAttribute: CFStringRef; // value: CFStringRef + pub static kCTFontStyleNameAttribute: CFStringRef; // value: CFStringRef + pub static kCTFontTraitsAttribute: CFStringRef; + pub static kCTFontVariationAttribute: CFStringRef; + pub static kCTFontSizeAttribute: CFStringRef; + pub static kCTFontMatrixAttribute: CFStringRef; + pub static kCTFontCascadeListAttribute: CFStringRef; + pub static kCTFontCharacterSetAttribute: CFStringRef; + pub static kCTFontLanguagesAttribute: CFStringRef; + pub static kCTFontBaselineAdjustAttribute: CFStringRef; + pub static kCTFontMacintoshEncodingsAttribute: CFStringRef; + pub static kCTFontFeaturesAttribute: CFStringRef; + pub static kCTFontFeatureSettingsAttribute: CFStringRef; + pub static kCTFontFixedAdvanceAttribute: CFStringRef; + pub static kCTFontOrientationAttribute: CFStringRef; + pub static kCTFontFormatAttribute: CFStringRef; + pub static kCTFontRegistrationScopeAttribute: CFStringRef; + pub static kCTFontPriorityAttribute: CFStringRef; + pub static kCTFontEnabledAttribute: CFStringRef; + + pub fn CTFontDescriptorCopyAttribute( + descriptor: CTFontDescriptorRef, + attribute: CFStringRef, + ) -> CFTypeRef; pub fn CTFontDescriptorCopyAttributes(descriptor: CTFontDescriptorRef) -> CFDictionaryRef; - pub fn CTFontDescriptorCopyLocalizedAttribute(descriptor: CTFontDescriptorRef, - attribute: CFStringRef, - language: *mut CFStringRef) -> CFTypeRef; - pub fn CTFontDescriptorCreateCopyWithAttributes(original: CTFontDescriptorRef, - attributes: CFDictionaryRef) -> CTFontDescriptorRef; - pub fn CTFontDescriptorCreateCopyWithFeature(original: CTFontDescriptorRef, - featureTypeIdentifier: CFNumberRef, - featureSelectorIdentifier: CFNumberRef) -> CTFontDescriptorRef; - pub fn CTFontDescriptorCreateCopyWithVariation(original: CTFontDescriptorRef, - variationIdentifier: CFNumberRef, - variationValue: CGFloat) -> CTFontDescriptorRef; - pub fn CTFontDescriptorCreateMatchingFontDescriptor(descriptor: CTFontDescriptorRef, - mandatoryAttributes: CFSetRef) -> CTFontDescriptorRef; - pub fn CTFontDescriptorCreateWithAttributes(attributes: CFDictionaryRef) -> CTFontDescriptorRef; - pub fn CTFontDescriptorCreateWithNameAndSize(name: CFStringRef, size: CGFloat) -> CTFontDescriptorRef; + pub fn CTFontDescriptorCopyLocalizedAttribute( + descriptor: CTFontDescriptorRef, + attribute: CFStringRef, + language: *mut CFStringRef, + ) -> CFTypeRef; + pub fn CTFontDescriptorCreateCopyWithAttributes( + original: CTFontDescriptorRef, + attributes: CFDictionaryRef, + ) -> CTFontDescriptorRef; + pub fn CTFontDescriptorCreateCopyWithFeature( + original: CTFontDescriptorRef, + featureTypeIdentifier: CFNumberRef, + featureSelectorIdentifier: CFNumberRef, + ) -> CTFontDescriptorRef; + pub fn CTFontDescriptorCreateCopyWithVariation( + original: CTFontDescriptorRef, + variationIdentifier: CFNumberRef, + variationValue: CGFloat, + ) -> CTFontDescriptorRef; + pub fn CTFontDescriptorCreateMatchingFontDescriptor( + descriptor: CTFontDescriptorRef, + mandatoryAttributes: CFSetRef, + ) -> CTFontDescriptorRef; + pub fn CTFontDescriptorCreateWithAttributes(attributes: CFDictionaryRef) + -> CTFontDescriptorRef; + pub fn CTFontDescriptorCreateWithNameAndSize( + name: CFStringRef, + size: CGFloat, + ) -> CTFontDescriptorRef; pub fn CTFontDescriptorGetTypeID() -> CFTypeID; } -extern { - pub fn CTFontDescriptorCreateMatchingFontDescriptors(descriptor: CTFontDescriptorRef, - mandatoryAttributes: CFSetRef) -> CFArrayRef; +extern "C" { + pub fn CTFontDescriptorCreateMatchingFontDescriptors( + descriptor: CTFontDescriptorRef, + mandatoryAttributes: CFSetRef, + ) -> CFArrayRef; } diff --git a/core-text/src/font_manager.rs b/core-text/src/font_manager.rs index cdf65ee3b..dff0f8d0f 100644 --- a/core-text/src/font_manager.rs +++ b/core-text/src/font_manager.rs @@ -7,41 +7,45 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use crate::font_descriptor::{CTFontDescriptor, CTFontDescriptorRef}; use core_foundation::array::{CFArray, CFArrayRef}; use core_foundation::base::TCFType; +use core_foundation::data::{CFData, CFDataRef}; use core_foundation::string::CFString; use core_foundation::url::CFURLRef; -use core_foundation::data::{CFDataRef, CFData}; -use crate::font_descriptor::{CTFontDescriptorRef, CTFontDescriptor}; pub fn copy_available_font_family_names() -> CFArray { - unsafe { - TCFType::wrap_under_create_rule(CTFontManagerCopyAvailableFontFamilyNames()) - } + unsafe { TCFType::wrap_under_create_rule(CTFontManagerCopyAvailableFontFamilyNames()) } } pub fn create_font_descriptor(buffer: &[u8]) -> Result { let cf_data = CFData::from_buffer(buffer); unsafe { - let ct_font_descriptor_ref = CTFontManagerCreateFontDescriptorFromData(cf_data.as_concrete_TypeRef()); + let ct_font_descriptor_ref = + CTFontManagerCreateFontDescriptorFromData(cf_data.as_concrete_TypeRef()); if ct_font_descriptor_ref.is_null() { return Err(()); } - Ok(CTFontDescriptor::wrap_under_create_rule(ct_font_descriptor_ref)) + Ok(CTFontDescriptor::wrap_under_create_rule( + ct_font_descriptor_ref, + )) } } pub fn create_font_descriptor_with_data(data: CFData) -> Result { unsafe { - let ct_font_descriptor_ref = CTFontManagerCreateFontDescriptorFromData(data.as_concrete_TypeRef()); + let ct_font_descriptor_ref = + CTFontManagerCreateFontDescriptorFromData(data.as_concrete_TypeRef()); if ct_font_descriptor_ref.is_null() { return Err(()); } - Ok(CTFontDescriptor::wrap_under_create_rule(ct_font_descriptor_ref)) + Ok(CTFontDescriptor::wrap_under_create_rule( + ct_font_descriptor_ref, + )) } } -extern { +extern "C" { /* * CTFontManager.h */ diff --git a/core-text/src/frame.rs b/core-text/src/frame.rs index 95b97c802..03fcee902 100644 --- a/core-text/src/frame.rs +++ b/core-text/src/frame.rs @@ -7,14 +7,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::os::raw::c_void; +use crate::line::CTLine; +use core_foundation::array::{CFArray, CFArrayRef}; use core_foundation::base::{CFRange, CFTypeID, TCFType}; -use core_foundation::array::{CFArrayRef, CFArray}; use core_graphics::context::{CGContext, CGContextRef}; use core_graphics::geometry::CGPoint; use core_graphics::path::{CGPath, SysCGPathRef}; use foreign_types::{ForeignType, ForeignTypeRef}; -use crate::line::CTLine; +use std::os::raw::c_void; #[repr(C)] pub struct __CTFrame(c_void); @@ -30,9 +30,7 @@ impl_CFTypeDescription!(CTFrame); impl CTFrame { /// The `CGPath` used to create this `CTFrame`. pub fn get_path(&self) -> CGPath { - unsafe { - CGPath::from_ptr(CTFrameGetPath(self.as_concrete_TypeRef())).clone() - } + unsafe { CGPath::from_ptr(CTFrameGetPath(self.as_concrete_TypeRef())).clone() } } /// Returns an owned copy of the underlying lines. @@ -42,7 +40,10 @@ impl CTFrame { unsafe { let array_ref = CTFrameGetLines(self.as_concrete_TypeRef()); let array: CFArray = CFArray::wrap_under_get_rule(array_ref); - array.iter().map(|l| CTLine::wrap_under_get_rule(l.as_concrete_TypeRef())).collect() + array + .iter() + .map(|l| CTLine::wrap_under_get_rule(l.as_concrete_TypeRef())) + .collect() } } @@ -65,7 +66,7 @@ impl CTFrame { let array_ref = CTFrameGetLines(self.as_concrete_TypeRef()); let array: CFArray = CFArray::wrap_under_get_rule(array_ref); array.len() - range.location - } + }, n => n, }; let len = len.max(0) as usize; @@ -84,7 +85,7 @@ impl CTFrame { } #[link(name = "CoreText", kind = "framework")] -extern { +extern "C" { fn CTFrameGetTypeID() -> CFTypeID; fn CTFrameGetLines(frame: CTFrameRef) -> CFArrayRef; fn CTFrameDraw(frame: CTFrameRef, context: *mut ::CType); diff --git a/core-text/src/lib.rs b/core-text/src/lib.rs index 1e6288bcd..be394b020 100644 --- a/core-text/src/lib.rs +++ b/core-text/src/lib.rs @@ -9,7 +9,6 @@ #![crate_name = "core_text"] #![crate_type = "rlib"] - #![allow(non_snake_case)] /*! diff --git a/core-text/src/line.rs b/core-text/src/line.rs index 50c1b4785..b2645aaf5 100644 --- a/core-text/src/line.rs +++ b/core-text/src/line.rs @@ -7,15 +7,15 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::os::raw::c_void; -use core_foundation::attributed_string::CFAttributedStringRef; use core_foundation::array::{CFArray, CFArrayRef}; +use core_foundation::attributed_string::CFAttributedStringRef; use core_foundation::base::{CFIndex, CFRange, CFTypeID, TCFType}; -use core_graphics::base::{CGFloat}; -use core_graphics::context::{CGContext}; -use core_graphics::geometry::{CGPoint,CGRect}; -use foreign_types::{ForeignType}; +use core_graphics::base::CGFloat; +use core_graphics::context::CGContext; +use core_graphics::geometry::{CGPoint, CGRect}; +use foreign_types::ForeignType; use run::CTRun; +use std::os::raw::c_void; #[repr(C)] pub struct __CTLine(c_void); @@ -45,27 +45,19 @@ impl CTLine { } pub fn glyph_runs(&self) -> CFArray { - unsafe { - TCFType::wrap_under_get_rule(CTLineGetGlyphRuns(self.0)) - } + unsafe { TCFType::wrap_under_get_rule(CTLineGetGlyphRuns(self.0)) } } pub fn get_string_range(&self) -> CFRange { - unsafe { - CTLineGetStringRange(self.as_concrete_TypeRef()) - } + unsafe { CTLineGetStringRange(self.as_concrete_TypeRef()) } } pub fn draw(&self, context: &CGContext) { - unsafe { - CTLineDraw(self.as_concrete_TypeRef(), context.as_ptr()) - } + unsafe { CTLineDraw(self.as_concrete_TypeRef(), context.as_ptr()) } } pub fn get_image_bounds(&self, context: &CGContext) -> CGRect { - unsafe { - CTLineGetImageBounds(self.as_concrete_TypeRef(), context.as_ptr()) - } + unsafe { CTLineGetImageBounds(self.as_concrete_TypeRef(), context.as_ptr()) } } pub fn get_typographic_bounds(&self) -> TypographicBounds { @@ -73,15 +65,23 @@ impl CTLine { let mut descent = 0.0; let mut leading = 0.0; unsafe { - let width = CTLineGetTypographicBounds(self.as_concrete_TypeRef(), &mut ascent, &mut descent, &mut leading); - TypographicBounds { width, ascent, descent, leading } + let width = CTLineGetTypographicBounds( + self.as_concrete_TypeRef(), + &mut ascent, + &mut descent, + &mut leading, + ); + TypographicBounds { + width, + ascent, + descent, + leading, + } } } pub fn get_string_index_for_position(&self, position: CGPoint) -> CFIndex { - unsafe { - CTLineGetStringIndexForPosition(self.as_concrete_TypeRef(), position) - } + unsafe { CTLineGetStringIndexForPosition(self.as_concrete_TypeRef(), position) } } pub fn get_string_offset_for_string_index(&self, charIndex: CFIndex) -> CGFloat { @@ -92,7 +92,7 @@ impl CTLine { } #[link(name = "CoreText", kind = "framework")] -extern { +extern "C" { fn CTLineGetTypeID() -> CFTypeID; fn CTLineGetGlyphRuns(line: CTLineRef) -> CFArrayRef; fn CTLineGetStringRange(line: CTLineRef) -> CFRange; @@ -101,13 +101,25 @@ extern { fn CTLineCreateWithAttributedString(string: CFAttributedStringRef) -> CTLineRef; // Drawing the Line - fn CTLineDraw(line: CTLineRef, context: * const core_graphics::sys::CGContext); + fn CTLineDraw(line: CTLineRef, context: *const core_graphics::sys::CGContext); // Measuring Lines - fn CTLineGetImageBounds(line: CTLineRef, context: * const core_graphics::sys::CGContext) -> CGRect; - fn CTLineGetTypographicBounds(line: CTLineRef, ascent: *mut CGFloat, descent: *mut CGFloat, leading: *mut CGFloat) -> CGFloat; + fn CTLineGetImageBounds( + line: CTLineRef, + context: *const core_graphics::sys::CGContext, + ) -> CGRect; + fn CTLineGetTypographicBounds( + line: CTLineRef, + ascent: *mut CGFloat, + descent: *mut CGFloat, + leading: *mut CGFloat, + ) -> CGFloat; // Getting Line Positioning fn CTLineGetStringIndexForPosition(line: CTLineRef, position: CGPoint) -> CFIndex; - fn CTLineGetOffsetForStringIndex(line: CTLineRef, charIndex: CFIndex, secondaryOffset: *const CGFloat) -> CGFloat; + fn CTLineGetOffsetForStringIndex( + line: CTLineRef, + charIndex: CFIndex, + secondaryOffset: *const CGFloat, + ) -> CGFloat; } diff --git a/core-text/src/run.rs b/core-text/src/run.rs index b7cb37616..f84fb46cb 100644 --- a/core-text/src/run.rs +++ b/core-text/src/run.rs @@ -7,14 +7,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::borrow::Cow; -use std::os::raw::c_void; -use std::slice; -use core_foundation::base::{CFIndex, CFTypeID, TCFType, CFType, CFRange}; +use core_foundation::base::{CFIndex, CFRange, CFType, CFTypeID, TCFType}; use core_foundation::dictionary::{CFDictionary, CFDictionaryRef}; use core_foundation::string::CFString; use core_graphics::font::CGGlyph; use core_graphics::geometry::CGPoint; +use std::borrow::Cow; +use std::os::raw::c_void; +use std::slice; #[repr(C)] pub struct __CTRun(c_void); @@ -38,9 +38,7 @@ impl CTRun { } } pub fn glyph_count(&self) -> CFIndex { - unsafe { - CTRunGetGlyphCount(self.0) - } + unsafe { CTRunGetGlyphCount(self.0) } } pub fn glyphs(&self) -> Cow<[CGGlyph]> { @@ -107,21 +105,30 @@ impl CTRun { #[test] fn create_runs() { use core_foundation::attributed_string::CFMutableAttributedString; - use string_attributes::*; - use line::*; use font; + use line::*; + use string_attributes::*; let mut string = CFMutableAttributedString::new(); string.replace_str(&CFString::new("Food"), CFRange::init(0, 0)); let len = string.char_len(); unsafe { - string.set_attribute(CFRange::init(0, len), kCTFontAttributeName, &font::new_from_name("Helvetica", 16.).unwrap()); + string.set_attribute( + CFRange::init(0, len), + kCTFontAttributeName, + &font::new_from_name("Helvetica", 16.).unwrap(), + ); } let line = CTLine::new_with_attributed_string(string.as_concrete_TypeRef()); let runs = line.glyph_runs(); assert_eq!(runs.len(), 1); for run in runs.iter() { assert_eq!(run.glyph_count(), 4); - let font = run.attributes().unwrap().get(CFString::new("NSFont")).downcast::().unwrap(); + let font = run + .attributes() + .unwrap() + .get(CFString::new("NSFont")) + .downcast::() + .unwrap(); assert_eq!(font.pt_size(), 16.); let positions = run.positions(); @@ -139,7 +146,7 @@ fn create_runs() { } #[link(name = "CoreText", kind = "framework")] -extern { +extern "C" { fn CTRunGetTypeID() -> CFTypeID; fn CTRunGetAttributes(run: CTRunRef) -> CFDictionaryRef; fn CTRunGetGlyphCount(run: CTRunRef) -> CFIndex; diff --git a/core-text/src/string_attributes.rs b/core-text/src/string_attributes.rs index dde1936c4..4f38ced4b 100644 --- a/core-text/src/string_attributes.rs +++ b/core-text/src/string_attributes.rs @@ -1,6 +1,6 @@ use core_foundation::string::CFStringRef; -extern { +extern "C" { pub static kCTCharacterShapeAttributeName: CFStringRef; pub static kCTFontAttributeName: CFStringRef; pub static kCTKernAttributeName: CFStringRef; diff --git a/io-surface/src/lib.rs b/io-surface/src/lib.rs index 4bf687d73..a032843de 100644 --- a/io-surface/src/lib.rs +++ b/io-surface/src/lib.rs @@ -10,24 +10,24 @@ #![crate_name = "io_surface"] #![crate_type = "rlib"] -extern crate libc; +extern crate cgl; extern crate core_foundation; extern crate core_foundation_sys; -extern crate cgl; extern crate leaky_cow; +extern crate libc; // Rust bindings to the IOSurface framework on macOS. -use core_foundation::base::{CFRelease, CFRetain, CFTypeID, CFTypeRef, CFType, TCFType}; +use cgl::{kCGLNoError, CGLErrorString, CGLGetCurrentContext, CGLTexImageIOSurface2D, GLenum}; +use core_foundation::base::{CFRelease, CFRetain, CFType, CFTypeID, CFTypeRef, TCFType}; use core_foundation::dictionary::{CFDictionary, CFDictionaryRef}; use core_foundation::string::{CFString, CFStringRef}; use core_foundation_sys::base::mach_port_t; -use cgl::{kCGLNoError, CGLGetCurrentContext, CGLTexImageIOSurface2D, CGLErrorString, GLenum}; +use leaky_cow::LeakyCow; use libc::{c_int, size_t}; +use std::ffi::CStr; use std::os::raw::c_void; -use leaky_cow::LeakyCow; use std::slice; -use std::ffi::CStr; const BGRA: GLenum = 0x80E1; const RGBA: GLenum = 0x1908; @@ -55,9 +55,7 @@ pub struct IOSurface { impl Drop for IOSurface { fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } + unsafe { CFRelease(self.as_CFTypeRef()) } } } @@ -66,9 +64,7 @@ pub type IOSurfaceID = u32; impl Clone for IOSurface { #[inline] fn clone(&self) -> IOSurface { - unsafe { - TCFType::wrap_under_get_rule(self.obj) - } + unsafe { TCFType::wrap_under_get_rule(self.obj) } } } @@ -83,16 +79,12 @@ impl TCFType for IOSurface { #[inline] unsafe fn wrap_under_create_rule(obj: IOSurfaceRef) -> IOSurface { assert!(!obj.is_null(), "Attempted to create a NULL object."); - IOSurface { - obj: obj, - } + IOSurface { obj: obj } } #[inline] fn type_id() -> CFTypeID { - unsafe { - IOSurfaceGetTypeID() - } + unsafe { IOSurfaceGetTypeID() } } #[inline] @@ -109,40 +101,40 @@ impl TCFType for IOSurface { } pub fn new(properties: &CFDictionary) -> IOSurface { - unsafe { - TCFType::wrap_under_create_rule(IOSurfaceCreate(properties.as_concrete_TypeRef())) - } + unsafe { TCFType::wrap_under_create_rule(IOSurfaceCreate(properties.as_concrete_TypeRef())) } } /// Looks up an `IOSurface` by its global ID. /// /// FIXME(pcwalton): This should return an `Option`. pub fn lookup(csid: IOSurfaceID) -> IOSurface { - unsafe { - TCFType::wrap_under_create_rule(IOSurfaceLookup(csid)) - } + unsafe { TCFType::wrap_under_create_rule(IOSurfaceLookup(csid)) } } impl IOSurface { pub fn get_id(&self) -> IOSurfaceID { - unsafe { - IOSurfaceGetID(self.as_concrete_TypeRef()) - } + unsafe { IOSurfaceGetID(self.as_concrete_TypeRef()) } } /// Binds to the current GL texture. pub fn bind_to_gl_texture(&self, width: i32, height: i32, has_alpha: bool) { unsafe { let context = CGLGetCurrentContext(); - let gl_error = CGLTexImageIOSurface2D(context, - TEXTURE_RECTANGLE_ARB, - if has_alpha { RGBA as GLenum } else { RGB as GLenum }, - width, - height, - BGRA as GLenum, - UNSIGNED_INT_8_8_8_8_REV, - self.as_concrete_TypeRef() as *mut libc::c_void, - 0); + let gl_error = CGLTexImageIOSurface2D( + context, + TEXTURE_RECTANGLE_ARB, + if has_alpha { + RGBA as GLenum + } else { + RGB as GLenum + }, + width, + height, + BGRA as GLenum, + UNSIGNED_INT_8_8_8_8_REV, + self.as_concrete_TypeRef() as *mut libc::c_void, + 0, + ); if gl_error != kCGLNoError { let error_msg = CStr::from_ptr(CGLErrorString(gl_error)); @@ -175,7 +167,7 @@ impl IOSurface { } #[link(name = "IOSurface", kind = "framework")] -extern { +extern "C" { pub static kIOSurfaceAllocSize: CFStringRef; pub static kIOSurfaceWidth: CFStringRef; pub static kIOSurfaceHeight: CFStringRef;