From b009c87f2da0038bb474800cd88597843e5dbdae Mon Sep 17 00:00:00 2001 From: micolous Date: Tue, 25 Jul 2023 12:22:25 +1000 Subject: [PATCH] Auto-format code with "cargo fmt" and check in CI (#615) * add rustfmt check to CI * Run "cargo fmt" (rustfmt) over core-foundation-rs --- .github/workflows/rust.yml | 9 + cocoa-foundation/src/foundation.rs | 710 +++++--- cocoa-foundation/tests/foundation.rs | 49 +- cocoa/examples/color.rs | 73 +- cocoa/examples/fullscreen.rs | 64 +- cocoa/examples/hello_world.rs | 24 +- cocoa/examples/nsvisualeffectview_blur.rs | 40 +- cocoa/examples/tab_view.rs | 46 +- cocoa/src/appkit.rs | 1538 ++++++++++------- cocoa/src/base.rs | 1 - cocoa/src/lib.rs | 3 +- cocoa/src/quartzcore.rs | 751 +++----- core-foundation-sys/src/array.rs | 102 +- core-foundation-sys/src/attributed_string.rs | 100 +- core-foundation-sys/src/bag.rs | 43 +- core-foundation-sys/src/base.rs | 53 +- core-foundation-sys/src/binary_heap.rs | 48 +- core-foundation-sys/src/bit_vector.rs | 37 +- core-foundation-sys/src/bundle.rs | 145 +- core-foundation-sys/src/calendar.rs | 76 +- core-foundation-sys/src/characterset.rs | 73 +- core-foundation-sys/src/data.rs | 31 +- core-foundation-sys/src/date.rs | 8 +- core-foundation-sys/src/date_formatter.rs | 73 +- core-foundation-sys/src/dictionary.rs | 83 +- core-foundation-sys/src/error.rs | 11 +- core-foundation-sys/src/file_security.rs | 42 +- core-foundation-sys/src/filedescriptor.rs | 40 +- core-foundation-sys/src/lib.rs | 17 +- core-foundation-sys/src/locale.rs | 58 +- core-foundation-sys/src/mach_port.rs | 44 +- core-foundation-sys/src/messageport.rs | 64 +- .../src/notification_center.rs | 51 +- core-foundation-sys/src/number.rs | 54 +- core-foundation-sys/src/number_formatter.rs | 68 +- core-foundation-sys/src/plugin.rs | 61 +- core-foundation-sys/src/preferences.rs | 83 +- core-foundation-sys/src/propertylist.rs | 74 +- core-foundation-sys/src/runloop.rs | 158 +- core-foundation-sys/src/set.rs | 49 +- core-foundation-sys/src/socket.rs | 114 +- core-foundation-sys/src/stream.rs | 165 +- core-foundation-sys/src/string.rs | 324 +++- core-foundation-sys/src/string_tokenizer.rs | 48 +- core-foundation-sys/src/timezone.rs | 43 +- core-foundation-sys/src/tree.rs | 26 +- core-foundation-sys/src/url.rs | 272 ++- core-foundation-sys/src/url_enumerator.rs | 27 +- core-foundation-sys/src/user_notification.rs | 75 +- core-foundation-sys/src/uuid.rs | 64 +- core-foundation-sys/src/xml_node.rs | 42 +- core-foundation-sys/src/xml_parser.rs | 98 +- core-foundation/src/array.rs | 65 +- core-foundation/src/attributed_string.rs | 47 +- core-foundation/src/base.rs | 58 +- core-foundation/src/boolean.rs | 15 +- core-foundation/src/bundle.rs | 53 +- core-foundation/src/characterset.rs | 2 +- core-foundation/src/data.rs | 39 +- core-foundation/src/date.rs | 21 +- core-foundation/src/dictionary.rs | 188 +- core-foundation/src/error.rs | 11 +- core-foundation/src/filedescriptor.rs | 86 +- core-foundation/src/lib.rs | 22 +- core-foundation/src/mach_port.rs | 11 +- core-foundation/src/number.rs | 52 +- core-foundation/src/propertylist.rs | 73 +- core-foundation/src/runloop.rs | 56 +- core-foundation/src/set.rs | 23 +- core-foundation/src/string.rs | 96 +- core-foundation/src/timezone.rs | 15 +- core-foundation/src/url.rs | 73 +- core-foundation/src/uuid.rs | 26 +- core-graphics-types/src/base.rs | 4 +- core-graphics-types/src/geometry.rs | 58 +- core-graphics-types/src/lib.rs | 2 +- core-graphics/src/color.rs | 17 +- core-graphics/src/color_space.rs | 13 +- core-graphics/src/context.rs | 516 +++--- core-graphics/src/data_provider.rs | 59 +- core-graphics/src/display.rs | 104 +- core-graphics/src/event.rs | 50 +- core-graphics/src/event_source.rs | 6 +- core-graphics/src/font.rs | 74 +- core-graphics/src/geometry.rs | 2 +- core-graphics/src/gradient.rs | 44 +- core-graphics/src/image.rs | 125 +- core-graphics/src/lib.rs | 10 +- core-graphics/src/path.rs | 28 +- core-graphics/src/private.rs | 56 +- core-graphics/src/sys.rs | 16 +- core-graphics/src/window.rs | 79 +- core-text/src/font.rs | 592 ++++--- core-text/src/font_collection.rs | 53 +- core-text/src/font_descriptor.rs | 148 +- core-text/src/font_manager.rs | 24 +- core-text/src/frame.rs | 19 +- core-text/src/lib.rs | 1 - core-text/src/line.rs | 68 +- core-text/src/run.rs | 31 +- core-text/src/string_attributes.rs | 2 +- io-surface/src/lib.rs | 66 +- 102 files changed, 6072 insertions(+), 3579 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 16d18456d..db1da771a 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -12,6 +12,15 @@ env: CARGO_TERM_COLOR: always jobs: + rustfmt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: stable + components: rustfmt + - run: cargo fmt --check semver: runs-on: macos-11.0 steps: diff --git a/cocoa-foundation/src/foundation.rs b/cocoa-foundation/src/foundation.rs index db7092ce4..26da47e65 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/nsvisualeffectview_blur.rs b/cocoa/examples/nsvisualeffectview_blur.rs index d20ae541f..b3fb07cdd 100644 --- a/cocoa/examples/nsvisualeffectview_blur.rs +++ b/cocoa/examples/nsvisualeffectview_blur.rs @@ -1,13 +1,16 @@ extern crate cocoa; extern crate objc; +use cocoa::base::{nil, selector, NO}; use objc::*; -use cocoa::base::{selector, nil, NO}; - -use cocoa::foundation::{NSRect, NSPoint, NSSize, NSAutoreleasePool, NSProcessInfo, - NSString}; -use cocoa::appkit::{NSApp, NSColor, NSApplication, NSApplicationActivationPolicyRegular, NSMenu, NSMenuItem, NSWindowStyleMask, NSBackingStoreType, NSWindow, NSView, NSVisualEffectMaterial, NSVisualEffectView, NSViewWidthSizable, NSViewHeightSizable, NSVisualEffectBlendingMode, NSVisualEffectState, NSWindowOrderingMode}; +use cocoa::appkit::{ + NSApp, NSApplication, NSApplicationActivationPolicyRegular, NSBackingStoreType, NSColor, + NSMenu, NSMenuItem, NSView, NSViewHeightSizable, NSViewWidthSizable, + NSVisualEffectBlendingMode, NSVisualEffectMaterial, NSVisualEffectState, NSVisualEffectView, + NSWindow, NSWindowOrderingMode, NSWindowStyleMask, +}; +use cocoa::foundation::{NSAutoreleasePool, NSPoint, NSProcessInfo, NSRect, NSSize, NSString}; fn main() { unsafe { @@ -36,21 +39,22 @@ fn main() { app_menu.addItem_(quit_item); app_menu_item.setSubmenu_(app_menu); - // Create some colors let clear = NSColor::clearColor(nil); // Create windows with different color types. - 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_(NSString::alloc(nil).init_str("NSVisualEffectView_blur")); @@ -60,7 +64,8 @@ fn main() { //NSVisualEffectView blur let ns_view = window.contentView(); let bounds = NSView::bounds(ns_view); - let blurred_view = NSVisualEffectView::initWithFrame_(NSVisualEffectView::alloc(nil), bounds); + let blurred_view = + NSVisualEffectView::initWithFrame_(NSVisualEffectView::alloc(nil), bounds); blurred_view.autorelease(); blurred_view.setMaterial_(NSVisualEffectMaterial::HudWindow); @@ -73,4 +78,3 @@ fn main() { app.run(); } } - 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 bac30c1d4..c73839f95 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,22 +231,22 @@ 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, } pub enum NSWindowToolbarStyle { - NSWindowToolbarStyleAutomatic = 0, - NSWindowToolbarStyleExpanded = 1, - NSWindowToolbarStylePreference = 2, - NSWindowToolbarStyleUnified = 3, + NSWindowToolbarStyleAutomatic = 0, + NSWindowToolbarStyleExpanded = 1, + NSWindowToolbarStylePreference = 2, + NSWindowToolbarStyleUnified = 3, NSWindowToolbarStyleUnifiedCompact = 4, } @@ -296,45 +297,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)] @@ -349,45 +350,45 @@ 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, } // https://developer.apple.com/documentation/appkit/nsvisualeffectview/blendingmode @@ -396,7 +397,7 @@ pub enum NSBezelStyle { #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSVisualEffectBlendingMode { BehindWindow = 0, - WithinWindow = 1 + WithinWindow = 1, } // https://developer.apple.com/documentation/appkit/nsvisualeffectview/state @@ -406,7 +407,7 @@ pub enum NSVisualEffectBlendingMode { pub enum NSVisualEffectState { FollowsWindowActiveState = 0, Active = 1, - Inactive = 2 + Inactive = 2, } /// @@ -443,7 +444,7 @@ pub enum NSVisualEffectMaterial { Tooltip = 17, ContentBackground = 18, UnderWindowBackground = 21, - UnderPageBackground = 22 + UnderPageBackground = 22, } // macOS 10.10+ - https://developer.apple.com/documentation/appkit/nsvisualeffectview @@ -532,7 +533,7 @@ impl NSVisualEffectView for id { #[repr(u64)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSRequestUserAttentionType { - NSCriticalRequest = 0, + NSCriticalRequest = 0, NSInformationalRequest = 10, } @@ -553,11 +554,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); @@ -571,7 +574,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 { @@ -584,19 +587,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) { @@ -607,11 +610,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 @@ -619,7 +624,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) { @@ -627,15 +632,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] } } @@ -647,13 +652,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] } } @@ -667,15 +675,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 { @@ -702,7 +713,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; @@ -727,7 +738,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 { @@ -751,27 +762,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 { @@ -799,11 +810,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 { @@ -813,7 +824,6 @@ impl NSPasteboard for id { unsafe fn readFileWrapper(self) -> id { msg_send![self, readFileWrapper] } - } pub trait NSPasteboardItem: Sized { @@ -851,15 +861,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] } } @@ -874,28 +884,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] } } @@ -903,7 +921,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 { @@ -913,9 +935,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] } @@ -927,7 +953,7 @@ pub enum NSPasteboardReadingOptions { NSPasteboardReadingAsData = 0, NSPasteboardReadingAsString = 1 << 0, NSPasteboardReadingAsPropertyList = 1 << 1, - NSPasteboardReadingAsKeyedArchive = 1 << 2 + NSPasteboardReadingAsKeyedArchive = 1 << 2, } #[repr(u64)] @@ -955,7 +981,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) { @@ -963,7 +989,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 { @@ -971,7 +997,7 @@ impl NSMenu for id { } unsafe fn itemAtIndex_(self, index: NSInteger) -> id { - msg_send![self, itemAtIndex:index] + msg_send![self, itemAtIndex: index] } } @@ -1000,15 +1026,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] } } @@ -1044,17 +1070,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; @@ -1080,9 +1110,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; @@ -1093,9 +1125,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; @@ -1153,7 +1197,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); @@ -1217,9 +1265,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 @@ -1230,7 +1280,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; @@ -1289,23 +1343,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 @@ -1324,7 +1382,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 { @@ -1336,7 +1394,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 { @@ -1344,7 +1402,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 { @@ -1352,7 +1410,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 { @@ -1360,7 +1418,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 { @@ -1368,7 +1426,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 { @@ -1376,7 +1434,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 { @@ -1384,11 +1442,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 { @@ -1396,7 +1454,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) { @@ -1404,18 +1462,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) { @@ -1427,7 +1487,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 { @@ -1435,31 +1495,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 @@ -1473,7 +1545,7 @@ impl NSWindow for id { } unsafe fn setWindowController_(self, windowController: id) { - msg_send![self, setWindowController:windowController] + msg_send![self, setWindowController: windowController] } // TODO: Managing Sheets @@ -1485,11 +1557,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) { @@ -1497,7 +1569,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) { @@ -1517,7 +1589,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 { @@ -1525,7 +1597,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 { @@ -1533,15 +1605,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 { @@ -1553,7 +1625,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 { @@ -1561,7 +1633,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 { @@ -1569,7 +1641,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 { @@ -1583,7 +1658,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 { @@ -1591,7 +1666,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 { @@ -1599,7 +1674,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 { @@ -1607,7 +1682,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 { @@ -1615,7 +1690,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 @@ -1631,22 +1706,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] } @@ -1655,7 +1734,7 @@ impl NSWindow for id { } unsafe fn setLevel_(self, level: NSInteger) { - msg_send![self, setLevel:level] + msg_send![self, setLevel: level] } // Managing Key Status @@ -1673,7 +1752,7 @@ impl NSWindow for id { } unsafe fn makeKeyAndOrderFront_(self, sender: id) { - msg_send![self, makeKeyAndOrderFront:sender] + msg_send![self, makeKeyAndOrderFront: sender] } // Managing Main Status @@ -1697,15 +1776,15 @@ impl NSWindow for id { } unsafe fn setToolbar_(self, toolbar: id /* NSToolbar */) { - msg_send![self, setToolbar:toolbar] + msg_send![self, setToolbar: toolbar] } unsafe fn setToolbarStyle_(self, toolbarStyle: NSWindowToolbarStyle) { - msg_send![self, setToolbarStyle:toolbarStyle] + msg_send![self, setToolbarStyle: toolbarStyle] } unsafe fn runToolbarCustomizationPalette(self, sender: id) { - msg_send![self, runToolbarCustomizationPalette:sender] + msg_send![self, runToolbarCustomizationPalette: sender] } // TODO: Managing Attached Windows @@ -1718,7 +1797,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 @@ -1727,7 +1806,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 { @@ -1747,7 +1829,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 @@ -1763,11 +1845,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 @@ -1775,7 +1857,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 @@ -1789,7 +1871,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 { @@ -1797,12 +1879,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] } @@ -1812,24 +1896,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 @@ -1839,7 +1927,7 @@ impl NSWindow for id { } unsafe fn setDocumentEdited_(self, documentEdited: BOOL) { - msg_send![self, setDocumentEdited:documentEdited] + msg_send![self, setDocumentEdited: documentEdited] } // Managing Titles @@ -1849,19 +1937,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 { @@ -1869,7 +1957,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 { @@ -1877,7 +1965,7 @@ impl NSWindow for id { } unsafe fn setRepresentedURL_(self, representedURL: id) { - msg_send![self, setRepresentedURL:representedURL] + msg_send![self, setRepresentedURL: representedURL] } // Accessing Screen Information @@ -1895,17 +1983,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) { @@ -1915,7 +2009,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) { @@ -1923,21 +2017,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 { @@ -1945,7 +2039,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 { @@ -1953,7 +2047,7 @@ impl NSWindow for id { } unsafe fn setMiniwindowTitle_(self, miniwindowTitle: id) { - msg_send![self, setMiniwindowTitle:miniwindowTitle] + msg_send![self, setMiniwindowTitle: miniwindowTitle] } unsafe fn setAppearance(self, appearance: id) { @@ -2133,7 +2227,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 { @@ -2145,11 +2239,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) { @@ -2157,7 +2251,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 { @@ -2165,7 +2259,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 { @@ -2177,7 +2271,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 { @@ -2185,7 +2279,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 { @@ -2193,7 +2287,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 { @@ -2205,7 +2299,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 { @@ -2243,7 +2337,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] } @@ -2252,11 +2346,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] } } @@ -2271,21 +2365,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] } @@ -2300,7 +2403,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 @@ -2332,12 +2439,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 @@ -2357,7 +2468,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 *) */ { @@ -2391,7 +2502,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 { @@ -2448,36 +2559,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! { @@ -2517,7 +2628,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, + } } } @@ -2649,11 +2762,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, @@ -2661,10 +2775,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, @@ -2672,10 +2787,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, @@ -2683,10 +2799,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; @@ -2762,12 +2879,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 @@ -2797,12 +2922,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 @@ -2822,11 +2947,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 @@ -2845,11 +2970,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 @@ -2868,11 +2993,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 @@ -2885,11 +3010,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 @@ -2989,12 +3114,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 { @@ -3125,7 +3250,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] } @@ -3139,7 +3268,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] } @@ -3153,7 +3286,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 @@ -3182,7 +3315,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] } } @@ -3202,7 +3335,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; @@ -3255,7 +3392,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] } @@ -3264,11 +3405,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] } } @@ -3284,64 +3425,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] } } @@ -3355,13 +3496,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 *) */; @@ -3378,23 +3522,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 *) */; @@ -3411,14 +3577,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 *) */; @@ -3430,35 +3604,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 *) */ { @@ -3466,7 +3643,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 { @@ -3478,7 +3655,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 ) */ { @@ -3490,11 +3667,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 *) */ { @@ -3502,13 +3679,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] } @@ -3525,22 +3704,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 @@ -3549,7 +3744,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] } @@ -3566,7 +3765,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) { @@ -3593,8 +3792,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] } @@ -3602,9 +3804,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 @@ -3617,11 +3824,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 { @@ -3630,7 +3837,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; @@ -3706,20 +3913,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)] @@ -3728,7 +3935,7 @@ pub enum NSImageCacheMode { NSImageCacheDefault, NSImageCacheAlways, NSImageCacheBySize, - NSImageCacheNever + NSImageCacheNever, } #[repr(usize)] @@ -3741,7 +3948,7 @@ pub enum NSTIFFCompression { NSTIFFCompressionJPEG = 6, NSTIFFCompressionNEXT = 32766, NSTIFFCompressionPackBits = 32773, - NSTIFFCompressionOldJPEG = 32865 + NSTIFFCompressionOldJPEG = 32865, } #[repr(usize)] @@ -3751,12 +3958,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; @@ -3776,7 +3983,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; @@ -3800,11 +4007,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 { @@ -3856,7 +4063,7 @@ impl NSSound for id { } unsafe fn writeToPasteboard_(self, pasteboard: id) { - msg_send![self, writeToPasteboard:pasteboard] + msg_send![self, writeToPasteboard: pasteboard] } } @@ -3886,7 +4093,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 { @@ -3910,11 +4117,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 { @@ -3922,7 +4129,7 @@ impl NSStatusBar for id { } } -extern { +extern "C" { pub fn NSRectFill(rect: NSRect); } @@ -3937,192 +4144,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] } } @@ -4130,7 +4340,7 @@ impl NSTabView for id { pub enum NSTabState { NSSelectedTab = 0, NSBackgroundTab = 1, - NSPressedTab = 2 + NSPressedTab = 2, } pub trait NSTabViewItem: Sized { @@ -4141,91 +4351,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] } } @@ -4235,7 +4445,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] } } @@ -4247,74 +4457,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] } @@ -4322,8 +4535,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] @@ -4335,11 +4551,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; @@ -4361,24 +4607,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 { @@ -4437,7 +4713,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 { @@ -4445,22 +4721,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); @@ -4471,9 +4750,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] } @@ -4483,7 +4764,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 @@ -4501,7 +4783,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) { @@ -4646,7 +4928,7 @@ impl NSDockTile for id { } unsafe fn setShowsApplicatinBadge_(self, value: BOOL) -> id { - msg_send![self, setShowsApplicationBadge:value] + msg_send![self, setShowsApplicationBadge: value] } unsafe fn badgeLabel(self) -> id /* NSString */ { @@ -4654,7 +4936,7 @@ impl NSDockTile for id { } unsafe fn setBadgeLabel_(self, label: id /* NSString */) -> id { - msg_send![self, setBadgeLabel:label] + msg_send![self, setBadgeLabel: label] } } 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 d85b6dcd0..b9ce43c3e 100644 --- a/core-foundation-sys/src/array.rs +++ b/core-foundation-sys/src/array.rs @@ -9,13 +9,15 @@ use std::os::raw::c_void; -use base::{CFRange, CFIndex, CFAllocatorRef, CFTypeID, Boolean, CFComparatorFunction}; +use base::{Boolean, CFAllocatorRef, CFComparatorFunction, 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); #[repr(C)] @@ -34,7 +36,7 @@ pub struct __CFArray(c_void); pub type CFArrayRef = *const __CFArray; pub type CFMutableArrayRef = *mut __CFArray; -extern { +extern "C" { /* * CFArray.h */ @@ -43,36 +45,98 @@ extern { /* CFArray */ /* Creating an Array */ - 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 CFArrayCreate( + allocator: CFAllocatorRef, + values: *const *const c_void, + numValues: CFIndex, + callBacks: *const CFArrayCallBacks, + ) -> CFArrayRef; + pub fn CFArrayCreateCopy(allocator: CFAllocatorRef, theArray: CFArrayRef) -> CFArrayRef; /* Examining an Array */ - pub fn CFArrayBSearchValues(theArray: CFArrayRef, range: CFRange, value: *const c_void, comparator: CFComparatorFunction, context: *mut c_void) -> CFIndex; - pub fn CFArrayContainsValue(theArray: CFArrayRef, range: CFRange, value: *const c_void) -> Boolean; + pub fn CFArrayBSearchValues( + theArray: CFArrayRef, + range: CFRange, + value: *const c_void, + comparator: CFComparatorFunction, + context: *mut c_void, + ) -> CFIndex; + pub fn CFArrayContainsValue( + theArray: CFArrayRef, + range: CFRange, + value: *const c_void, + ) -> Boolean; pub fn CFArrayGetCount(theArray: CFArrayRef) -> CFIndex; - pub fn CFArrayGetCountOfValue(theArray: CFArrayRef, range: CFRange, value: *const c_void) -> CFIndex; - 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 CFArrayGetCountOfValue( + theArray: CFArrayRef, + range: CFRange, + value: *const c_void, + ) -> CFIndex; + 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 CFArrayGetValues(theArray: CFArrayRef, range: CFRange, values: *mut *const c_void); pub fn CFArrayGetValueAtIndex(theArray: CFArrayRef, idx: CFIndex) -> *const c_void; /* Applying a Function to Elements */ - pub fn CFArrayApplyFunction(theArray: CFArrayRef, range: CFRange, applier: CFArrayApplierFunction, context: *mut c_void); + pub fn CFArrayApplyFunction( + theArray: CFArrayRef, + range: CFRange, + applier: CFArrayApplierFunction, + context: *mut c_void, + ); /* Getting the CFArray Type ID */ pub fn CFArrayGetTypeID() -> CFTypeID; /* CFMutableArray */ /* CFMutableArray Miscellaneous Functions */ - pub fn CFArrayAppendArray(theArray: CFMutableArrayRef, otherArray: CFArrayRef, otherRange: CFRange); + pub fn CFArrayAppendArray( + theArray: CFMutableArrayRef, + otherArray: CFArrayRef, + otherRange: CFRange, + ); pub fn CFArrayAppendValue(theArray: CFMutableArrayRef, value: *const c_void); - pub fn CFArrayCreateMutable(allocator: CFAllocatorRef, capacity: CFIndex, callBacks: *const CFArrayCallBacks) -> CFMutableArrayRef; - pub fn CFArrayCreateMutableCopy(allocator: CFAllocatorRef, capacity: CFIndex, theArray: CFArrayRef)-> CFMutableArrayRef; - pub fn CFArrayExchangeValuesAtIndices(theArray: CFMutableArrayRef, idx1: CFIndex, idx2: CFIndex); - pub fn CFArrayInsertValueAtIndex(theArray: CFMutableArrayRef, idx: CFIndex, value: *const c_void); + pub fn CFArrayCreateMutable( + allocator: CFAllocatorRef, + capacity: CFIndex, + callBacks: *const CFArrayCallBacks, + ) -> CFMutableArrayRef; + pub fn CFArrayCreateMutableCopy( + allocator: CFAllocatorRef, + capacity: CFIndex, + theArray: CFArrayRef, + ) -> CFMutableArrayRef; + pub fn CFArrayExchangeValuesAtIndices( + theArray: CFMutableArrayRef, + idx1: CFIndex, + idx2: CFIndex, + ); + pub fn CFArrayInsertValueAtIndex( + theArray: CFMutableArrayRef, + idx: CFIndex, + value: *const c_void, + ); pub fn CFArrayRemoveAllValues(theArray: CFMutableArrayRef); pub fn CFArrayRemoveValueAtIndex(theArray: CFMutableArrayRef, idx: CFIndex); - pub fn CFArrayReplaceValues(theArray: CFMutableArrayRef, range: CFRange, newValues: *mut *const c_void, newCount: CFIndex); + pub fn CFArrayReplaceValues( + theArray: CFMutableArrayRef, + range: CFRange, + newValues: *mut *const c_void, + newCount: CFIndex, + ); pub fn CFArraySetValueAtIndex(theArray: CFMutableArrayRef, idx: CFIndex, value: *const c_void); - pub fn CFArraySortValues(theArray: CFMutableArrayRef, range: CFRange, comparator: CFComparatorFunction, context: *mut c_void); + pub fn CFArraySortValues( + theArray: CFMutableArrayRef, + range: CFRange, + comparator: CFComparatorFunction, + context: *mut c_void, + ); } diff --git a/core-foundation-sys/src/attributed_string.rs b/core-foundation-sys/src/attributed_string.rs index 36c0d699d..93fbf63f2 100644 --- a/core-foundation-sys/src/attributed_string.rs +++ b/core-foundation-sys/src/attributed_string.rs @@ -7,11 +7,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::os::raw::c_void; -use base::{CFAllocatorRef, CFTypeRef, CFIndex, CFRange, CFTypeID, Boolean}; -use string::CFStringRef; +use base::{Boolean, CFAllocatorRef, CFIndex, CFRange, CFTypeID, CFTypeRef}; use dictionary::CFDictionaryRef; +use std::os::raw::c_void; use string::CFMutableStringRef; +use string::CFStringRef; #[repr(C)] pub struct __CFAttributedString(c_void); @@ -19,40 +19,102 @@ pub struct __CFAttributedString(c_void); pub type CFAttributedStringRef = *const __CFAttributedString; pub type CFMutableAttributedStringRef = *mut __CFAttributedString; -extern { +extern "C" { /* * CFAttributedString.h */ /* CFAttributedString */ /* Creating a CFAttributedString */ - pub fn CFAttributedStringCreate(allocator: CFAllocatorRef, str: CFStringRef, attributes: CFDictionaryRef) -> CFAttributedStringRef; - pub fn CFAttributedStringCreateCopy(alloc: CFAllocatorRef, aStr: CFAttributedStringRef) -> CFAttributedStringRef; - pub fn CFAttributedStringCreateWithSubstring(alloc: CFAllocatorRef, aStr: CFAttributedStringRef, range: CFRange) -> CFAttributedStringRef; + pub fn CFAttributedStringCreate( + allocator: CFAllocatorRef, + str: CFStringRef, + attributes: CFDictionaryRef, + ) -> CFAttributedStringRef; + pub fn CFAttributedStringCreateCopy( + alloc: CFAllocatorRef, + aStr: CFAttributedStringRef, + ) -> CFAttributedStringRef; + pub fn CFAttributedStringCreateWithSubstring( + alloc: CFAllocatorRef, + aStr: CFAttributedStringRef, + range: CFRange, + ) -> CFAttributedStringRef; pub fn CFAttributedStringGetLength(astr: CFAttributedStringRef) -> CFIndex; pub fn CFAttributedStringGetString(aStr: CFAttributedStringRef) -> CFStringRef; /* Accessing Attributes */ - pub fn CFAttributedStringGetAttribute(aStr: CFAttributedStringRef, loc: CFIndex, attrName: CFStringRef, effectiveRange: *mut CFRange) -> CFTypeRef; - pub fn CFAttributedStringGetAttributes(aStr: CFAttributedStringRef, loc: CFIndex, effectiveRange: *mut CFRange) -> CFDictionaryRef; - pub fn CFAttributedStringGetAttributeAndLongestEffectiveRange(aStr: CFAttributedStringRef, loc: CFIndex, attrName: CFStringRef, inRange: CFRange, longestEffectiveRange: *mut CFRange) -> CFTypeRef; - pub fn CFAttributedStringGetAttributesAndLongestEffectiveRange(aStr: CFAttributedStringRef, loc: CFIndex, inRange: CFRange, longestEffectiveRange: *mut CFRange) -> CFDictionaryRef; + pub fn CFAttributedStringGetAttribute( + aStr: CFAttributedStringRef, + loc: CFIndex, + attrName: CFStringRef, + effectiveRange: *mut CFRange, + ) -> CFTypeRef; + pub fn CFAttributedStringGetAttributes( + aStr: CFAttributedStringRef, + loc: CFIndex, + effectiveRange: *mut CFRange, + ) -> CFDictionaryRef; + pub fn CFAttributedStringGetAttributeAndLongestEffectiveRange( + aStr: CFAttributedStringRef, + loc: CFIndex, + attrName: CFStringRef, + inRange: CFRange, + longestEffectiveRange: *mut CFRange, + ) -> CFTypeRef; + pub fn CFAttributedStringGetAttributesAndLongestEffectiveRange( + aStr: CFAttributedStringRef, + loc: CFIndex, + inRange: CFRange, + longestEffectiveRange: *mut CFRange, + ) -> CFDictionaryRef; /* Getting Attributed String Properties */ pub fn CFAttributedStringGetTypeID() -> CFTypeID; /* CFMutableAttributedString */ /* Creating a CFMutableAttributedString */ - pub fn CFAttributedStringCreateMutable(allocator: CFAllocatorRef, max_length: CFIndex) -> CFMutableAttributedStringRef; - pub fn CFAttributedStringCreateMutableCopy(allocator: CFAllocatorRef, max_length: CFIndex, astr: CFAttributedStringRef) -> CFMutableAttributedStringRef; + pub fn CFAttributedStringCreateMutable( + allocator: CFAllocatorRef, + max_length: CFIndex, + ) -> CFMutableAttributedStringRef; + pub fn CFAttributedStringCreateMutableCopy( + allocator: CFAllocatorRef, + max_length: CFIndex, + astr: CFAttributedStringRef, + ) -> CFMutableAttributedStringRef; /* Modifying a CFMutableAttributedString */ pub fn CFAttributedStringBeginEditing(aStr: CFMutableAttributedStringRef); pub fn CFAttributedStringEndEditing(aStr: CFMutableAttributedStringRef); - pub fn CFAttributedStringGetMutableString(aStr: CFMutableAttributedStringRef) -> CFMutableStringRef; - pub fn CFAttributedStringRemoveAttribute(aStr: CFMutableAttributedStringRef, range: CFRange, attrName: CFStringRef); - pub fn CFAttributedStringReplaceString(aStr: CFMutableAttributedStringRef, range: CFRange, replacement: CFStringRef); - pub fn CFAttributedStringReplaceAttributedString(aStr: CFMutableAttributedStringRef, range: CFRange, replacement: CFAttributedStringRef); - pub fn CFAttributedStringSetAttribute(aStr: CFMutableAttributedStringRef, range: CFRange, attrName: CFStringRef, value: CFTypeRef); - pub fn CFAttributedStringSetAttributes(aStr: CFMutableAttributedStringRef, range: CFRange, replacement: CFDictionaryRef, clearOtherAttributes: Boolean); + pub fn CFAttributedStringGetMutableString( + aStr: CFMutableAttributedStringRef, + ) -> CFMutableStringRef; + pub fn CFAttributedStringRemoveAttribute( + aStr: CFMutableAttributedStringRef, + range: CFRange, + attrName: CFStringRef, + ); + pub fn CFAttributedStringReplaceString( + aStr: CFMutableAttributedStringRef, + range: CFRange, + replacement: CFStringRef, + ); + pub fn CFAttributedStringReplaceAttributedString( + aStr: CFMutableAttributedStringRef, + range: CFRange, + replacement: CFAttributedStringRef, + ); + pub fn CFAttributedStringSetAttribute( + aStr: CFMutableAttributedStringRef, + range: CFRange, + attrName: CFStringRef, + value: CFTypeRef, + ); + pub fn CFAttributedStringSetAttributes( + aStr: CFMutableAttributedStringRef, + range: CFRange, + replacement: CFDictionaryRef, + clearOtherAttributes: Boolean, + ); } diff --git a/core-foundation-sys/src/bag.rs b/core-foundation-sys/src/bag.rs index 3199f0062..143484101 100644 --- a/core-foundation-sys/src/bag.rs +++ b/core-foundation-sys/src/bag.rs @@ -9,7 +9,7 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, Boolean, CFHashCode, CFIndex, CFTypeID}; +use base::{Boolean, CFAllocatorRef, CFHashCode, CFIndex, CFTypeID}; use string::CFStringRef; #[repr(C)] @@ -18,10 +18,12 @@ pub struct __CFBag(c_void); pub type CFBagRef = *const __CFBag; pub type CFMutableBagRef = *mut __CFBag; -pub type CFBagRetainCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; +pub type CFBagRetainCallBack = + extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; pub type CFBagReleaseCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void); pub type CFBagCopyDescriptionCallBack = extern "C" fn(value: *const c_void) -> CFStringRef; -pub type CFBagEqualCallBack = extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; +pub type CFBagEqualCallBack = + extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; pub type CFBagHashCallBack = extern "C" fn(value: *const c_void) -> CFHashCode; #[repr(C)] @@ -32,12 +34,12 @@ pub struct CFBagCallBacks { pub release: CFBagReleaseCallBack, pub copyDescription: CFBagCopyDescriptionCallBack, pub equal: CFBagEqualCallBack, - pub hash: CFBagHashCallBack + pub hash: CFBagHashCallBack, } pub type CFBagApplierFunction = extern "C" fn(value: *const c_void, context: *mut c_void); -extern { +extern "C" { /* * CFBag.h */ @@ -47,7 +49,12 @@ extern { /* CFBag */ /* Creating a Bag */ - pub fn CFBagCreate(allocator: CFAllocatorRef, values: *const *const c_void, numValues: CFIndex, callBacks: *const CFBagCallBacks) -> CFBagRef; + pub fn CFBagCreate( + allocator: CFAllocatorRef, + values: *const *const c_void, + numValues: CFIndex, + callBacks: *const CFBagCallBacks, + ) -> CFBagRef; pub fn CFBagCreateCopy(allocator: CFAllocatorRef, theBag: CFBagRef) -> CFBagRef; /* Examining a Bag */ @@ -55,19 +62,35 @@ extern { pub fn CFBagGetCount(theBag: CFBagRef) -> CFIndex; pub fn CFBagGetCountOfValue(theBag: CFBagRef, value: *const c_void) -> CFIndex; pub fn CFBagGetValue(theBag: CFBagRef, value: *const c_void) -> *const c_void; - pub fn CFBagGetValueIfPresent(theBag: CFBagRef, candidate: *const c_void, value: *const *const c_void) -> Boolean; + pub fn CFBagGetValueIfPresent( + theBag: CFBagRef, + candidate: *const c_void, + value: *const *const c_void, + ) -> Boolean; pub fn CFBagGetValues(theBag: CFBagRef, values: *const *const c_void); /* Applying a Function to the Contents of a Bag */ - pub fn CFBagApplyFunction(theBag: CFBagRef, applier: CFBagApplierFunction, context: *mut c_void); + pub fn CFBagApplyFunction( + theBag: CFBagRef, + applier: CFBagApplierFunction, + context: *mut c_void, + ); /* Getting the CFBag Type ID */ pub fn CFBagGetTypeID() -> CFTypeID; /* CFMutableBag */ /* Creating a Mutable Bag */ - pub fn CFBagCreateMutable(allocator: CFAllocatorRef, capacity: CFIndex, callBacks: *const CFBagCallBacks) -> CFMutableBagRef; - pub fn CFBagCreateMutableCopy(allocator: CFAllocatorRef, capacity: CFIndex, theBag: CFBagRef) -> CFMutableBagRef; + pub fn CFBagCreateMutable( + allocator: CFAllocatorRef, + capacity: CFIndex, + callBacks: *const CFBagCallBacks, + ) -> CFMutableBagRef; + pub fn CFBagCreateMutableCopy( + allocator: CFAllocatorRef, + capacity: CFIndex, + theBag: CFBagRef, + ) -> CFMutableBagRef; /* Modifying a Mutable Bag */ pub fn CFBagAddValue(theBag: CFMutableBagRef, value: *const c_void); diff --git a/core-foundation-sys/src/base.rs b/core-foundation-sys/src/base.rs index 05dfb53c2..fa6eb8d02 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, c_short, c_uchar, c_ushort}; +use std::os::raw::{c_int, c_short, c_uchar, c_uint, c_ushort, c_void}; use string::CFStringRef; pub type Boolean = u8; @@ -43,14 +43,18 @@ pub enum CFComparisonResult { GreaterThan = 1, } -pub type CFComparatorFunction = extern "C" fn(val1: *const c_void, val2: *const c_void, context: *mut c_void) -> CFComparisonResult; +pub type CFComparatorFunction = extern "C" fn( + val1: *const c_void, + val2: *const c_void, + context: *mut c_void, +) -> CFComparisonResult; impl Into for CFComparisonResult { fn into(self) -> Ordering { match self { CFComparisonResult::LessThan => Ordering::Less, CFComparisonResult::EqualTo => Ordering::Equal, - CFComparisonResult::GreaterThan => Ordering::Greater + CFComparisonResult::GreaterThan => Ordering::Greater, } } } @@ -59,7 +63,7 @@ impl Into for CFComparisonResult { #[derive(Clone, Copy, Debug, PartialEq)] pub struct CFRange { pub location: CFIndex, - pub length: CFIndex + pub length: CFIndex, } // for back-compat @@ -75,10 +79,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, Debug)] @@ -91,7 +102,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. @@ -124,7 +135,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 */ @@ -138,11 +149,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/binary_heap.rs b/core-foundation-sys/src/binary_heap.rs index 479ff29a8..7bcb14464 100644 --- a/core-foundation-sys/src/binary_heap.rs +++ b/core-foundation-sys/src/binary_heap.rs @@ -9,7 +9,7 @@ use std::os::raw::c_void; -use base::{CFTypeID, CFAllocatorRef, Boolean, CFIndex, CFComparisonResult}; +use base::{Boolean, CFAllocatorRef, CFComparisonResult, CFIndex, CFTypeID}; use string::CFStringRef; #[repr(C)] @@ -22,24 +22,28 @@ pub type CFBinaryHeapRef = *mut __CFBinaryHeap; pub struct CFBinaryHeapCompareContext { pub version: CFIndex, pub info: *mut c_void, - pub retain: extern "C" fn (info: *const c_void) -> *const c_void, - pub release: extern "C" fn (info: *const c_void), - pub copyDescription: extern "C" fn (info: *const c_void) -> CFStringRef, + pub retain: extern "C" fn(info: *const c_void) -> *const c_void, + pub release: extern "C" fn(info: *const c_void), + pub copyDescription: extern "C" fn(info: *const c_void) -> CFStringRef, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct CFBinaryHeapCallBacks { pub version: CFIndex, - pub retain: extern "C" fn (allocator: CFAllocatorRef, ptr: *const c_void) -> *const c_void, - pub release: extern "C" fn (allocator: CFAllocatorRef, ptr: *const c_void), - pub copyDescription: extern "C" fn (ptr: *const c_void) -> CFStringRef, - pub compare: extern "C" fn (ptr1: *const c_void, ptr2: *const c_void, context: *mut c_void) -> CFComparisonResult + pub retain: extern "C" fn(allocator: CFAllocatorRef, ptr: *const c_void) -> *const c_void, + pub release: extern "C" fn(allocator: CFAllocatorRef, ptr: *const c_void), + pub copyDescription: extern "C" fn(ptr: *const c_void) -> CFStringRef, + pub compare: extern "C" fn( + ptr1: *const c_void, + ptr2: *const c_void, + context: *mut c_void, + ) -> CFComparisonResult, } -pub type CFBinaryHeapApplierFunction = extern "C" fn (val: *const c_void, context: *const c_void); +pub type CFBinaryHeapApplierFunction = extern "C" fn(val: *const c_void, context: *const c_void); -extern { +extern "C" { /* * CFBinaryHeap.h */ @@ -48,14 +52,30 @@ extern { /* CFBinaryHeap Miscellaneous Functions */ pub fn CFBinaryHeapAddValue(heap: CFBinaryHeapRef, value: *const c_void); - pub fn CFBinaryHeapApplyFunction(heap: CFBinaryHeapRef, applier: CFBinaryHeapApplierFunction, context: *mut c_void); + pub fn CFBinaryHeapApplyFunction( + heap: CFBinaryHeapRef, + applier: CFBinaryHeapApplierFunction, + context: *mut c_void, + ); pub fn CFBinaryHeapContainsValue(heap: CFBinaryHeapRef, value: *const c_void) -> Boolean; - pub fn CFBinaryHeapCreate(allocator: CFAllocatorRef, capacity: CFIndex, callBacks: *const CFBinaryHeapCallBacks, compareContext: *const CFBinaryHeapCompareContext) -> CFBinaryHeapRef; - pub fn CFBinaryHeapCreateCopy(allocator: CFAllocatorRef, capacity: CFIndex, heap: CFBinaryHeapRef) -> CFBinaryHeapRef; + pub fn CFBinaryHeapCreate( + allocator: CFAllocatorRef, + capacity: CFIndex, + callBacks: *const CFBinaryHeapCallBacks, + compareContext: *const CFBinaryHeapCompareContext, + ) -> CFBinaryHeapRef; + pub fn CFBinaryHeapCreateCopy( + allocator: CFAllocatorRef, + capacity: CFIndex, + heap: CFBinaryHeapRef, + ) -> CFBinaryHeapRef; pub fn CFBinaryHeapGetCount(heap: CFBinaryHeapRef) -> CFIndex; pub fn CFBinaryHeapGetCountOfValue(heap: CFBinaryHeapRef, value: *const c_void) -> CFIndex; pub fn CFBinaryHeapGetMinimum(heap: CFBinaryHeapRef) -> *const c_void; - pub fn CFBinaryHeapGetMinimumIfPresent(heap: CFBinaryHeapRef, value: *const *const c_void) -> Boolean; + pub fn CFBinaryHeapGetMinimumIfPresent( + heap: CFBinaryHeapRef, + value: *const *const c_void, + ) -> Boolean; pub fn CFBinaryHeapGetTypeID() -> CFTypeID; pub fn CFBinaryHeapGetValues(heap: CFBinaryHeapRef, values: *const *const c_void); pub fn CFBinaryHeapRemoveAllValues(heap: CFBinaryHeapRef); diff --git a/core-foundation-sys/src/bit_vector.rs b/core-foundation-sys/src/bit_vector.rs index 1c5fc72ce..3072584b8 100644 --- a/core-foundation-sys/src/bit_vector.rs +++ b/core-foundation-sys/src/bit_vector.rs @@ -9,7 +9,7 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, Boolean, UInt32, CFIndex, CFTypeID, CFRange, UInt8}; +use base::{Boolean, CFAllocatorRef, CFIndex, CFRange, CFTypeID, UInt32, UInt8}; #[repr(C)] pub struct __CFBitVector(c_void); @@ -18,14 +18,18 @@ pub type CFBitVectorRef = *const __CFBitVector; pub type CFMutableBitVectorRef = *mut __CFBitVector; pub type CFBit = UInt32; -extern { +extern "C" { /* - * CFBitVector.h - */ + * CFBitVector.h + */ /* CFBitVector */ /* Creating a Bit Vector */ - pub fn CFBitVectorCreate(allocator: CFAllocatorRef, bytes: *const UInt8, numBits: CFIndex) -> CFBitVectorRef; + pub fn CFBitVectorCreate( + allocator: CFAllocatorRef, + bytes: *const UInt8, + numBits: CFIndex, + ) -> CFBitVectorRef; pub fn CFBitVectorCreateCopy(allocator: CFAllocatorRef, bv: CFBitVectorRef) -> CFBitVectorRef; /* Getting Information About a Bit Vector */ @@ -34,16 +38,31 @@ extern { pub fn CFBitVectorGetBits(bv: CFBitVectorRef, range: CFRange, bytes: *mut UInt8); pub fn CFBitVectorGetCount(bv: CFBitVectorRef) -> CFIndex; pub fn CFBitVectorGetCountOfBit(bv: CFBitVectorRef, range: CFRange, value: CFBit) -> CFIndex; - pub fn CFBitVectorGetFirstIndexOfBit(bv: CFBitVectorRef, range: CFRange, value: CFBit) -> CFIndex; - pub fn CFBitVectorGetLastIndexOfBit(bv: CFBitVectorRef, range: CFRange, value: CFBit) -> CFIndex; + pub fn CFBitVectorGetFirstIndexOfBit( + bv: CFBitVectorRef, + range: CFRange, + value: CFBit, + ) -> CFIndex; + pub fn CFBitVectorGetLastIndexOfBit( + bv: CFBitVectorRef, + range: CFRange, + value: CFBit, + ) -> CFIndex; /* Getting the CFBitVector Type ID */ pub fn CFBitVectorGetTypeID() -> CFTypeID; /* CFMutableBitVector */ /* Creating a CFMutableBitVector Object */ - pub fn CFBitVectorCreateMutable(allocator: CFAllocatorRef, capacity: CFIndex) -> CFMutableBitVectorRef; - pub fn CFBitVectorCreateMutableCopy(allocator: CFAllocatorRef, capacity: CFIndex, bv: CFBitVectorRef) -> CFMutableBitVectorRef; + pub fn CFBitVectorCreateMutable( + allocator: CFAllocatorRef, + capacity: CFIndex, + ) -> CFMutableBitVectorRef; + pub fn CFBitVectorCreateMutableCopy( + allocator: CFAllocatorRef, + capacity: CFIndex, + bv: CFBitVectorRef, + ) -> CFMutableBitVectorRef; /* Modifying a Bit Vector */ pub fn CFBitVectorFlipBitAtIndex(bv: CFMutableBitVectorRef, idx: CFIndex); diff --git a/core-foundation-sys/src/bundle.rs b/core-foundation-sys/src/bundle.rs index 792c04858..031ac263f 100644 --- a/core-foundation-sys/src/bundle.rs +++ b/core-foundation-sys/src/bundle.rs @@ -9,13 +9,13 @@ use std::os::raw::c_void; -use base::{CFTypeID, CFAllocatorRef, Boolean, CFTypeRef, UInt32, SInt32}; -use std::os::raw::{c_uint, c_int}; -use url::CFURLRef; -use dictionary::CFDictionaryRef; -use string::CFStringRef; use array::CFArrayRef; +use base::{Boolean, CFAllocatorRef, CFTypeID, CFTypeRef, SInt32, UInt32}; +use dictionary::CFDictionaryRef; use error::CFErrorRef; +use std::os::raw::{c_int, c_uint}; +use string::CFStringRef; +use url::CFURLRef; #[repr(C)] pub struct __CFBundle(c_void); @@ -31,17 +31,32 @@ pub unsafe fn CFCopyLocalizedString(key: CFStringRef, comment: CFStringRef) -> C } #[allow(unused)] #[inline(always)] -pub unsafe fn CFCopyLocalizedStringFromTable(key: CFStringRef, tbl: CFStringRef, comment: CFStringRef) -> CFStringRef { +pub unsafe fn CFCopyLocalizedStringFromTable( + key: CFStringRef, + tbl: CFStringRef, + comment: CFStringRef, +) -> CFStringRef { CFBundleCopyLocalizedString(CFBundleGetMainBundle(), key, key, tbl) } #[allow(unused)] #[inline(always)] -pub unsafe fn CFCopyLocalizedStringFromTableInBundle(key: CFStringRef, tbl: CFStringRef, bundle: CFBundleRef, comment: CFStringRef) -> CFStringRef { +pub unsafe fn CFCopyLocalizedStringFromTableInBundle( + key: CFStringRef, + tbl: CFStringRef, + bundle: CFBundleRef, + comment: CFStringRef, +) -> CFStringRef { CFBundleCopyLocalizedString(bundle, key, key, tbl) } #[allow(unused)] #[inline(always)] -pub unsafe fn CFCopyLocalizedStringWithDefaultValue(key: CFStringRef, tbl: CFStringRef, bundle: CFBundleRef, value: CFStringRef, comment: CFStringRef) -> CFStringRef { +pub unsafe fn CFCopyLocalizedStringWithDefaultValue( + key: CFStringRef, + tbl: CFStringRef, + bundle: CFBundleRef, + value: CFStringRef, + comment: CFStringRef, +) -> CFStringRef { CFBundleCopyLocalizedString(bundle, key, value, tbl) } @@ -51,7 +66,7 @@ pub static kCFBundleExecutableArchitectureX86_64: c_uint = 0x01000007; pub static kCFBundleExecutableArchitecturePPC64: c_uint = 0x01000012; //pub static kCFBundleExecutableArchitectureARM64: c_uint = 0x0100000c; //macos(11.0)+ -extern { +extern "C" { /* * CFBundle.h */ @@ -67,7 +82,11 @@ extern { /* Creating and Accessing Bundles */ pub fn CFBundleCreate(allocator: CFAllocatorRef, bundleURL: CFURLRef) -> CFBundleRef; - pub fn CFBundleCreateBundlesFromDirectory(allocator: CFAllocatorRef, directoryURL: CFURLRef, bundleType: CFStringRef) -> CFArrayRef; + pub fn CFBundleCreateBundlesFromDirectory( + allocator: CFAllocatorRef, + directoryURL: CFURLRef, + bundleType: CFStringRef, + ) -> CFArrayRef; pub fn CFBundleGetAllBundles() -> CFArrayRef; pub fn CFBundleGetBundleWithIdentifier(bundleID: CFStringRef) -> CFBundleRef; pub fn CFBundleGetMainBundle() -> CFBundleRef; @@ -76,11 +95,17 @@ extern { pub fn CFBundleIsExecutableLoaded(bundle: CFBundleRef) -> Boolean; pub fn CFBundlePreflightExecutable(bundle: CFBundleRef, error: *mut CFErrorRef) -> Boolean; pub fn CFBundleLoadExecutable(bundle: CFBundleRef) -> Boolean; - pub fn CFBundleLoadExecutableAndReturnError(bundle: CFBundleRef, error: *mut CFErrorRef) -> Boolean; + pub fn CFBundleLoadExecutableAndReturnError( + bundle: CFBundleRef, + error: *mut CFErrorRef, + ) -> Boolean; pub fn CFBundleUnloadExecutable(bundle: CFBundleRef); /* Finding Locations in a Bundle */ - pub fn CFBundleCopyAuxiliaryExecutableURL(bundle: CFBundleRef, executableName: CFStringRef) -> CFURLRef; + pub fn CFBundleCopyAuxiliaryExecutableURL( + bundle: CFBundleRef, + executableName: CFStringRef, + ) -> CFURLRef; pub fn CFBundleCopyBuiltInPlugInsURL(bundle: CFBundleRef) -> CFURLRef; pub fn CFBundleCopyExecutableURL(bundle: CFBundleRef) -> CFURLRef; pub fn CFBundleCopyPrivateFrameworksURL(bundle: CFBundleRef) -> CFURLRef; @@ -92,29 +117,84 @@ extern { /* Locating Bundle Resources */ #[cfg(target_os = "macos")] pub fn CFBundleCloseBundleResourceMap(bundle: CFBundleRef, refNum: CFBundleRefNum); // DEPRECATED macosx(10.0, 10.15) - pub fn CFBundleCopyResourceURL(bundle: CFBundleRef, resourceName: CFStringRef, resourceType: CFStringRef, subDirName: CFStringRef) -> CFURLRef; - pub fn CFBundleCopyResourceURLInDirectory(bundleURL: CFURLRef, resourceName: CFStringRef, resourceType: CFStringRef, subDirName: CFStringRef) -> CFURLRef; - pub fn CFBundleCopyResourceURLsOfType(bundle: CFBundleRef, resourceType: CFStringRef, subDirName: CFStringRef) -> CFArrayRef; - pub fn CFBundleCopyResourceURLsOfTypeInDirectory(bundleURL: CFURLRef, resourceType: CFStringRef, subDirName: CFStringRef) -> CFArrayRef; - pub fn CFBundleCopyResourceURLForLocalization(bundle: CFBundleRef, resourceName: CFStringRef, resourceType: CFStringRef, subDirName: CFStringRef, localizationName: CFStringRef) -> CFURLRef; - pub fn CFBundleCopyResourceURLsOfTypeForLocalization(bundle: CFBundleRef, resourceType: CFStringRef, subDirName: CFStringRef, localizationName: CFStringRef) -> CFArrayRef; + pub fn CFBundleCopyResourceURL( + bundle: CFBundleRef, + resourceName: CFStringRef, + resourceType: CFStringRef, + subDirName: CFStringRef, + ) -> CFURLRef; + pub fn CFBundleCopyResourceURLInDirectory( + bundleURL: CFURLRef, + resourceName: CFStringRef, + resourceType: CFStringRef, + subDirName: CFStringRef, + ) -> CFURLRef; + pub fn CFBundleCopyResourceURLsOfType( + bundle: CFBundleRef, + resourceType: CFStringRef, + subDirName: CFStringRef, + ) -> CFArrayRef; + pub fn CFBundleCopyResourceURLsOfTypeInDirectory( + bundleURL: CFURLRef, + resourceType: CFStringRef, + subDirName: CFStringRef, + ) -> CFArrayRef; + pub fn CFBundleCopyResourceURLForLocalization( + bundle: CFBundleRef, + resourceName: CFStringRef, + resourceType: CFStringRef, + subDirName: CFStringRef, + localizationName: CFStringRef, + ) -> CFURLRef; + pub fn CFBundleCopyResourceURLsOfTypeForLocalization( + bundle: CFBundleRef, + resourceType: CFStringRef, + subDirName: CFStringRef, + localizationName: CFStringRef, + ) -> CFArrayRef; #[cfg(target_os = "macos")] - pub fn CFBundleOpenBundleResourceFiles(bundle: CFBundleRef, refNum: *mut CFBundleRefNum, localizedRefNum: *mut CFBundleRefNum) -> SInt32; // DEPRECATED macosx(10.0, 10.15) + pub fn CFBundleOpenBundleResourceFiles( + bundle: CFBundleRef, + refNum: *mut CFBundleRefNum, + localizedRefNum: *mut CFBundleRefNum, + ) -> SInt32; // DEPRECATED macosx(10.0, 10.15) #[cfg(target_os = "macos")] pub fn CFBundleOpenBundleResourceMap(bundle: CFBundleRef) -> CFBundleRefNum; // DEPRECATED macosx(10.0, 10.15) /* Managing Localizations */ pub fn CFBundleCopyBundleLocalizations(bundle: CFBundleRef) -> CFArrayRef; - pub fn CFBundleCopyLocalizedString(bundle: CFBundleRef, key: CFStringRef, value: CFStringRef, tableName: CFStringRef) -> CFStringRef; - pub fn CFBundleCopyLocalizationsForPreferences(locArray: CFArrayRef, prefArray: CFArrayRef) -> CFArrayRef; + pub fn CFBundleCopyLocalizedString( + bundle: CFBundleRef, + key: CFStringRef, + value: CFStringRef, + tableName: CFStringRef, + ) -> CFStringRef; + pub fn CFBundleCopyLocalizationsForPreferences( + locArray: CFArrayRef, + prefArray: CFArrayRef, + ) -> CFArrayRef; pub fn CFBundleCopyLocalizationsForURL(url: CFURLRef) -> CFArrayRef; pub fn CFBundleCopyPreferredLocalizationsFromArray(locArray: CFArrayRef) -> CFArrayRef; /* Managing Executable Code */ - pub fn CFBundleGetDataPointerForName(bundle: CFBundleRef, symbolName: CFStringRef) -> *mut c_void; - pub fn CFBundleGetDataPointersForNames(bundle: CFBundleRef, symbolNames: CFArrayRef, stbl: *mut [c_void]); - pub fn CFBundleGetFunctionPointerForName(bundle: CFBundleRef, function_name: CFStringRef) -> *const c_void; - pub fn CFBundleGetFunctionPointersForNames(bundle: CFBundleRef, functionNames: CFArrayRef, ftbl: *mut [c_void]); + pub fn CFBundleGetDataPointerForName( + bundle: CFBundleRef, + symbolName: CFStringRef, + ) -> *mut c_void; + pub fn CFBundleGetDataPointersForNames( + bundle: CFBundleRef, + symbolNames: CFArrayRef, + stbl: *mut [c_void], + ); + pub fn CFBundleGetFunctionPointerForName( + bundle: CFBundleRef, + function_name: CFStringRef, + ) -> *const c_void; + pub fn CFBundleGetFunctionPointersForNames( + bundle: CFBundleRef, + functionNames: CFArrayRef, + ftbl: *mut [c_void], + ); pub fn CFBundleGetPlugIn(bundle: CFBundleRef) -> CFPlugInRef; /* Getting Bundle Properties */ @@ -123,11 +203,20 @@ extern { pub fn CFBundleGetIdentifier(bundle: CFBundleRef) -> CFStringRef; pub fn CFBundleGetInfoDictionary(bundle: CFBundleRef) -> CFDictionaryRef; pub fn CFBundleGetLocalInfoDictionary(bundle: CFBundleRef) -> CFDictionaryRef; - pub fn CFBundleGetValueForInfoDictionaryKey(bundle: CFBundleRef, key: CFStringRef) -> CFTypeRef; + pub fn CFBundleGetValueForInfoDictionaryKey(bundle: CFBundleRef, key: CFStringRef) + -> CFTypeRef; pub fn CFBundleCopyInfoDictionaryInDirectory(bundleURL: CFURLRef) -> CFDictionaryRef; pub fn CFBundleCopyInfoDictionaryForURL(url: CFURLRef) -> CFDictionaryRef; - pub fn CFBundleGetPackageInfo(bundle: CFBundleRef, packageType: *mut UInt32, packageCreator: *mut UInt32); - pub fn CFBundleGetPackageInfoInDirectory(url: CFURLRef, packageType: *mut UInt32, packageCreator: *mut UInt32) -> Boolean; + pub fn CFBundleGetPackageInfo( + bundle: CFBundleRef, + packageType: *mut UInt32, + packageCreator: *mut UInt32, + ); + pub fn CFBundleGetPackageInfoInDirectory( + url: CFURLRef, + packageType: *mut UInt32, + packageCreator: *mut UInt32, + ) -> Boolean; pub fn CFBundleCopyExecutableArchitectures(bundle: CFBundleRef) -> CFArrayRef; pub fn CFBundleCopyExecutableArchitecturesForURL(url: CFURLRef) -> CFArrayRef; pub fn CFBundleGetVersionNumber(bundle: CFBundleRef) -> UInt32; diff --git a/core-foundation-sys/src/calendar.rs b/core-foundation-sys/src/calendar.rs index 175bb0453..efae5d249 100644 --- a/core-foundation-sys/src/calendar.rs +++ b/core-foundation-sys/src/calendar.rs @@ -7,12 +7,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::os::raw::{c_void, c_char}; +use std::os::raw::{c_char, c_void}; -use base::{CFAllocatorRef, CFTypeID, Boolean, CFIndex, CFOptionFlags, CFRange}; +use base::{Boolean, CFAllocatorRef, CFIndex, CFOptionFlags, CFRange, CFTypeID}; +use date::{CFAbsoluteTime, CFTimeInterval}; use locale::{CFCalendarIdentifier, CFLocaleRef}; use timezone::CFTimeZoneRef; -use date::{CFAbsoluteTime, CFTimeInterval}; #[repr(C)] pub struct __CFCalendar(c_void); @@ -36,27 +36,75 @@ pub const kCFCalendarUnitYearForWeekOfYear: CFCalendarUnit = 1 << 14; pub const kCFCalendarComponentsWrap: CFOptionFlags = 1 << 0; -extern { +extern "C" { /* * CFCalendar.h */ /* Creating a Calendar */ pub fn CFCalendarCopyCurrent() -> CFCalendarRef; - pub fn CFCalendarCreateWithIdentifier(allocator: CFAllocatorRef, identifier: CFCalendarIdentifier) -> CFCalendarRef; + pub fn CFCalendarCreateWithIdentifier( + allocator: CFAllocatorRef, + identifier: CFCalendarIdentifier, + ) -> CFCalendarRef; /* Calendrical Calculations */ - pub fn CFCalendarAddComponents(identifier: CFCalendarIdentifier, /* inout */ at: *mut CFAbsoluteTime, options: CFOptionFlags, componentDesc: *const char, ...) -> Boolean; - pub fn CFCalendarComposeAbsoluteTime(identifier: CFCalendarIdentifier, /* out */ at: *mut CFAbsoluteTime, componentDesc: *const c_char, ...) -> Boolean; - pub fn CFCalendarDecomposeAbsoluteTime(identifier: CFCalendarIdentifier, at: CFAbsoluteTime, componentDesc: *const c_char, ...) -> Boolean; - pub fn CFCalendarGetComponentDifference(identifier: CFCalendarIdentifier, startingAT: CFAbsoluteTime, resultAT: CFAbsoluteTime, options: CFOptionFlags, componentDesc: *const c_char, ...) -> Boolean; + pub fn CFCalendarAddComponents( + identifier: CFCalendarIdentifier, + /* inout */ at: *mut CFAbsoluteTime, + options: CFOptionFlags, + componentDesc: *const char, + ... + ) -> Boolean; + pub fn CFCalendarComposeAbsoluteTime( + identifier: CFCalendarIdentifier, + /* out */ at: *mut CFAbsoluteTime, + componentDesc: *const c_char, + ... + ) -> Boolean; + pub fn CFCalendarDecomposeAbsoluteTime( + identifier: CFCalendarIdentifier, + at: CFAbsoluteTime, + componentDesc: *const c_char, + ... + ) -> Boolean; + pub fn CFCalendarGetComponentDifference( + identifier: CFCalendarIdentifier, + startingAT: CFAbsoluteTime, + resultAT: CFAbsoluteTime, + options: CFOptionFlags, + componentDesc: *const c_char, + ... + ) -> Boolean; /* Getting Ranges of Units */ - pub fn CFCalendarGetRangeOfUnit(identifier: CFCalendarIdentifier, smallerUnit: CFCalendarUnit, biggerUnit: CFCalendarUnit, at: CFAbsoluteTime) -> CFRange; - pub fn CFCalendarGetOrdinalityOfUnit(identifier: CFCalendarIdentifier, smallerUnit: CFCalendarUnit, biggerUnit: CFCalendarUnit, at: CFAbsoluteTime) -> CFIndex; - pub fn CFCalendarGetTimeRangeOfUnit(identifier: CFCalendarIdentifier, unit: CFCalendarUnit, at: CFAbsoluteTime, startp: *mut CFAbsoluteTime, tip: *mut CFTimeInterval) -> Boolean; - pub fn CFCalendarGetMaximumRangeOfUnit(identifier: CFCalendarIdentifier, unit: CFCalendarUnit) -> CFRange; - pub fn CFCalendarGetMinimumRangeOfUnit(identifier: CFCalendarIdentifier, unit: CFCalendarUnit) -> CFRange; + pub fn CFCalendarGetRangeOfUnit( + identifier: CFCalendarIdentifier, + smallerUnit: CFCalendarUnit, + biggerUnit: CFCalendarUnit, + at: CFAbsoluteTime, + ) -> CFRange; + pub fn CFCalendarGetOrdinalityOfUnit( + identifier: CFCalendarIdentifier, + smallerUnit: CFCalendarUnit, + biggerUnit: CFCalendarUnit, + at: CFAbsoluteTime, + ) -> CFIndex; + pub fn CFCalendarGetTimeRangeOfUnit( + identifier: CFCalendarIdentifier, + unit: CFCalendarUnit, + at: CFAbsoluteTime, + startp: *mut CFAbsoluteTime, + tip: *mut CFTimeInterval, + ) -> Boolean; + pub fn CFCalendarGetMaximumRangeOfUnit( + identifier: CFCalendarIdentifier, + unit: CFCalendarUnit, + ) -> CFRange; + pub fn CFCalendarGetMinimumRangeOfUnit( + identifier: CFCalendarIdentifier, + unit: CFCalendarUnit, + ) -> CFRange; /* Getting and Setting the Time Zone */ pub fn CFCalendarCopyTimeZone(identifier: CFCalendarIdentifier) -> CFTimeZoneRef; diff --git a/core-foundation-sys/src/characterset.rs b/core-foundation-sys/src/characterset.rs index d3c65e655..19bb11fbd 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, UTF32Char}; use data::CFDataRef; +use std::os::raw::c_void; use string::{CFStringRef, UniChar}; pub type CFCharacterSetPredefinedSet = CFIndex; @@ -37,28 +37,54 @@ pub struct __CFCharacterSet(c_void); pub type CFCharacterSetRef = *const __CFCharacterSet; pub type CFMutableCharacterSetRef = *mut __CFCharacterSet; -extern { +extern "C" { /* * CFCharacterSet.h */ /* CFCharacterSet */ /* Creating Character Sets */ - pub fn CFCharacterSetCreateCopy(alloc: CFAllocatorRef, theSet: CFCharacterSetRef) -> CFCharacterSetRef; - pub fn CFCharacterSetCreateInvertedSet(alloc: CFAllocatorRef, theSet: CFCharacterSetRef) -> 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 CFCharacterSetCreateCopy( + alloc: CFAllocatorRef, + theSet: CFCharacterSetRef, + ) -> CFCharacterSetRef; + pub fn CFCharacterSetCreateInvertedSet( + alloc: CFAllocatorRef, + theSet: CFCharacterSetRef, + ) -> 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; /* Getting Predefined Character Sets */ - pub fn CFCharacterSetGetPredefined(theSetIdentifier: CFCharacterSetPredefinedSet) -> CFCharacterSetRef; + pub fn CFCharacterSetGetPredefined( + theSetIdentifier: CFCharacterSetPredefinedSet, + ) -> CFCharacterSetRef; /* Querying Character Sets */ - pub fn CFCharacterSetCreateBitmapRepresentation(alloc: CFAllocatorRef, theSet: CFCharacterSetRef) -> CFDataRef; + pub fn CFCharacterSetCreateBitmapRepresentation( + alloc: CFAllocatorRef, + theSet: CFCharacterSetRef, + ) -> CFDataRef; pub fn CFCharacterSetHasMemberInPlane(theSet: CFCharacterSetRef, thePlane: CFIndex) -> Boolean; pub fn CFCharacterSetIsCharacterMember(theSet: CFCharacterSetRef, theChar: UniChar) -> Boolean; - pub fn CFCharacterSetIsLongCharacterMember(theSet: CFCharacterSetRef, theChar: UTF32Char) -> Boolean; - pub fn CFCharacterSetIsSupersetOfSet(theSet: CFCharacterSetRef, theOtherset: CFCharacterSetRef) -> Boolean; + pub fn CFCharacterSetIsLongCharacterMember( + theSet: CFCharacterSetRef, + theChar: UTF32Char, + ) -> Boolean; + pub fn CFCharacterSetIsSupersetOfSet( + theSet: CFCharacterSetRef, + theOtherset: CFCharacterSetRef, + ) -> Boolean; /* Getting the Character Set Type Identifier */ pub fn CFCharacterSetGetTypeID() -> CFTypeID; @@ -66,18 +92,33 @@ extern { /* CFMutableCharacterSet */ /* Creating a Mutable Character Set */ pub fn CFCharacterSetCreateMutable(alloc: CFAllocatorRef) -> CFMutableCharacterSetRef; - pub fn CFCharacterSetCreateMutableCopy(alloc: CFAllocatorRef, theSet: CFCharacterSetRef) -> CFMutableCharacterSetRef; + pub fn CFCharacterSetCreateMutableCopy( + alloc: CFAllocatorRef, + theSet: CFCharacterSetRef, + ) -> CFMutableCharacterSetRef; /* Adding Characters */ pub fn CFCharacterSetAddCharactersInRange(theSet: CFMutableCharacterSetRef, theRange: CFRange); - pub fn CFCharacterSetAddCharactersInString(theSet: CFMutableCharacterSetRef, theString: CFStringRef); + pub fn CFCharacterSetAddCharactersInString( + theSet: CFMutableCharacterSetRef, + theString: CFStringRef, + ); /* Removing Characters */ - pub fn CFCharacterSetRemoveCharactersInRange(theSet: CFMutableCharacterSetRef, theRange: CFRange); - pub fn CFCharacterSetRemoveCharactersInString(theSet: CFMutableCharacterSetRef, theString: CFStringRef); + pub fn CFCharacterSetRemoveCharactersInRange( + theSet: CFMutableCharacterSetRef, + theRange: CFRange, + ); + pub fn CFCharacterSetRemoveCharactersInString( + theSet: CFMutableCharacterSetRef, + theString: CFStringRef, + ); /* Logical Operations */ - pub fn CFCharacterSetIntersect(theSet: CFMutableCharacterSetRef, theOtherSet: CFCharacterSetRef); + pub fn CFCharacterSetIntersect( + theSet: CFMutableCharacterSetRef, + theOtherSet: CFCharacterSetRef, + ); pub fn CFCharacterSetInvert(theSet: CFMutableCharacterSetRef); pub fn CFCharacterSetUnion(theSet: CFMutableCharacterSetRef, theOtherSet: CFCharacterSetRef); } diff --git a/core-foundation-sys/src/data.rs b/core-foundation-sys/src/data.rs index a332e4ef8..639666990 100644 --- a/core-foundation-sys/src/data.rs +++ b/core-foundation-sys/src/data.rs @@ -7,8 +7,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use base::{CFAllocatorRef, CFIndex, CFOptionFlags, CFRange, CFTypeID}; use std::os::raw::c_void; -use base::{CFAllocatorRef, CFTypeID, CFIndex, CFRange, CFOptionFlags}; #[repr(C)] pub struct __CFData(c_void); @@ -21,7 +21,7 @@ pub type CFDataSearchFlags = CFOptionFlags; pub const kCFDataSearchBackwards: CFDataSearchFlags = 1usize << 0; pub const kCFDataSearchAnchored: CFDataSearchFlags = 1usize << 1; -extern { +extern "C" { /* * CFData.h */ @@ -30,13 +30,23 @@ extern { /* Creating a CFData Object */ pub fn CFDataCreate(allocator: CFAllocatorRef, bytes: *const u8, length: CFIndex) -> CFDataRef; pub fn CFDataCreateCopy(allocator: CFAllocatorRef, theData: CFDataRef) -> CFDataRef; - pub fn CFDataCreateWithBytesNoCopy(allocator: CFAllocatorRef, bytes: *const u8, length: CFIndex, bytesDeallocator: CFAllocatorRef) -> CFDataRef; + pub fn CFDataCreateWithBytesNoCopy( + allocator: CFAllocatorRef, + bytes: *const u8, + length: CFIndex, + bytesDeallocator: CFAllocatorRef, + ) -> CFDataRef; /* Examining a CFData Object */ pub fn CFDataGetBytePtr(theData: CFDataRef) -> *const u8; pub fn CFDataGetBytes(theData: CFDataRef, range: CFRange, buffer: *mut u8); pub fn CFDataGetLength(theData: CFDataRef) -> CFIndex; - pub fn CFDataFind(theData: CFDataRef, dataToFind: CFDataRef, searchRange: CFRange, compareOptions: CFDataSearchFlags) -> CFRange; + pub fn CFDataFind( + theData: CFDataRef, + dataToFind: CFDataRef, + searchRange: CFRange, + compareOptions: CFDataSearchFlags, + ) -> CFRange; /* Getting the CFData Type ID */ pub fn CFDataGetTypeID() -> CFTypeID; @@ -44,7 +54,11 @@ extern { /* CFMutableData */ /* Creating a Mutable Data Object */ pub fn CFDataCreateMutable(allocator: CFAllocatorRef, capacity: CFIndex) -> CFMutableDataRef; - pub fn CFDataCreateMutableCopy(allocator: CFAllocatorRef, capacity: CFIndex, theData: CFDataRef) -> CFMutableDataRef; + pub fn CFDataCreateMutableCopy( + allocator: CFAllocatorRef, + capacity: CFIndex, + theData: CFDataRef, + ) -> CFMutableDataRef; /* Accessing Data */ pub fn CFDataGetMutableBytePtr(theData: CFMutableDataRef) -> *mut u8; @@ -52,7 +66,12 @@ extern { /* Modifying a Mutable Data Object */ pub fn CFDataAppendBytes(theData: CFMutableDataRef, bytes: *const u8, length: CFIndex); pub fn CFDataDeleteBytes(theData: CFMutableDataRef, range: CFRange); - pub fn CFDataReplaceBytes(theData: CFMutableDataRef, range: CFRange, newBytes: *const u8, newLength: CFIndex); + pub fn CFDataReplaceBytes( + theData: CFMutableDataRef, + range: CFRange, + newBytes: *const u8, + newLength: CFIndex, + ); pub fn CFDataIncreaseLength(theData: CFMutableDataRef, extraLength: CFIndex); pub fn CFDataSetLength(theData: CFMutableDataRef, length: CFIndex); } 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/date_formatter.rs b/core-foundation-sys/src/date_formatter.rs index f545cfc4e..41a54bb25 100644 --- a/core-foundation-sys/src/date_formatter.rs +++ b/core-foundation-sys/src/date_formatter.rs @@ -9,10 +9,10 @@ use std::os::raw::c_void; -use base::{CFIndex, CFOptionFlags, CFAllocatorRef, CFTypeID, CFTypeRef, CFRange, Boolean}; -use string::CFStringRef; +use base::{Boolean, CFAllocatorRef, CFIndex, CFOptionFlags, CFRange, CFTypeID, CFTypeRef}; +use date::{CFAbsoluteTime, CFDateRef}; use locale::CFLocaleRef; -use date::{CFDateRef, CFAbsoluteTime}; +use string::CFStringRef; #[repr(C)] pub struct __CFDateFormatter(c_void); @@ -44,7 +44,7 @@ pub const kCFDateFormatterFullStyle: CFDateFormatterStyle = 4; //pub const kCFISO8601DateFormatWithFullTime: CFISO8601DateFormatOptions = kCFISO8601DateFormatWithTime | kCFISO8601DateFormatWithColonSeparatorInTime | kCFISO8601DateFormatWithTimeZone | kCFISO8601DateFormatWithColonSeparatorInTimeZone; // macosx(10.12)+ //pub const kCFISO8601DateFormatWithInternetDateTime: CFISO8601DateFormatOptions = kCFISO8601DateFormatWithFullDate | kCFISO8601DateFormatWithFullTime; // macosx(10.12)+ -extern { +extern "C" { /* * CFDateFormatter.h */ @@ -56,14 +56,14 @@ extern { pub static kCFDateFormatterTimeZone: CFDateFormatterKey; // CFTimeZone pub static kCFDateFormatterCalendarName: CFDateFormatterKey; // CFString pub static kCFDateFormatterDefaultFormat: CFDateFormatterKey; // CFString - pub static kCFDateFormatterTwoDigitStartDate: CFDateFormatterKey; // CFDate + pub static kCFDateFormatterTwoDigitStartDate: CFDateFormatterKey; // CFDate pub static kCFDateFormatterDefaultDate: CFDateFormatterKey; // CFDate pub static kCFDateFormatterCalendar: CFDateFormatterKey; // CFCalendar pub static kCFDateFormatterEraSymbols: CFDateFormatterKey; // CFArray of CFString pub static kCFDateFormatterMonthSymbols: CFDateFormatterKey; // CFArray of CFString - pub static kCFDateFormatterShortMonthSymbols: CFDateFormatterKey; // CFArray of CFString + pub static kCFDateFormatterShortMonthSymbols: CFDateFormatterKey; // CFArray of CFString pub static kCFDateFormatterWeekdaySymbols: CFDateFormatterKey; // CFArray of CFString - pub static kCFDateFormatterShortWeekdaySymbols: CFDateFormatterKey; // CFArray of CFString + pub static kCFDateFormatterShortWeekdaySymbols: CFDateFormatterKey; // CFArray of CFString pub static kCFDateFormatterAMSymbol: CFDateFormatterKey; // CFString pub static kCFDateFormatterPMSymbol: CFDateFormatterKey; // CFString pub static kCFDateFormatterLongEraSymbols: CFDateFormatterKey; // CFArray of CFString @@ -77,29 +77,64 @@ extern { pub static kCFDateFormatterVeryShortStandaloneWeekdaySymbols: CFDateFormatterKey; // CFArray of CFString pub static kCFDateFormatterQuarterSymbols: CFDateFormatterKey; // CFArray of CFString pub static kCFDateFormatterShortQuarterSymbols: CFDateFormatterKey; // CFArray of CFString - pub static kCFDateFormatterStandaloneQuarterSymbols: CFDateFormatterKey; // CFArray of CFString - pub static kCFDateFormatterShortStandaloneQuarterSymbols: CFDateFormatterKey; // CFArray of CFString - pub static kCFDateFormatterGregorianStartDate: CFDateFormatterKey; // CFDate - pub static kCFDateFormatterDoesRelativeDateFormattingKey: CFDateFormatterKey; // CFBoolean + pub static kCFDateFormatterStandaloneQuarterSymbols: CFDateFormatterKey; // CFArray of CFString + pub static kCFDateFormatterShortStandaloneQuarterSymbols: CFDateFormatterKey; // CFArray of CFString + pub static kCFDateFormatterGregorianStartDate: CFDateFormatterKey; // CFDate + pub static kCFDateFormatterDoesRelativeDateFormattingKey: CFDateFormatterKey; // CFBoolean /* Creating a Date Formatter */ - pub fn CFDateFormatterCreate(allocator: CFAllocatorRef, locale: CFLocaleRef, dateStyle: CFDateFormatterStyle, timeStyle: CFDateFormatterStyle) -> CFDateFormatterRef; + pub fn CFDateFormatterCreate( + allocator: CFAllocatorRef, + locale: CFLocaleRef, + dateStyle: CFDateFormatterStyle, + timeStyle: CFDateFormatterStyle, + ) -> CFDateFormatterRef; /* Configuring a Date Formatter */ pub fn CFDateFormatterSetFormat(formatter: CFDateFormatterRef, formatString: CFStringRef); - pub fn CFDateFormatterSetProperty(formatter: CFDateFormatterRef, key: CFStringRef, value: CFTypeRef); + pub fn CFDateFormatterSetProperty( + formatter: CFDateFormatterRef, + key: CFStringRef, + value: CFTypeRef, + ); /* Parsing Strings */ - pub fn CFDateFormatterCreateDateFromString(allocator: CFAllocatorRef, formatter: CFDateFormatterRef, string: CFStringRef, rangep: *mut CFRange) -> CFDateRef; - pub fn CFDateFormatterGetAbsoluteTimeFromString(formatter: CFDateFormatterRef, string: CFStringRef, rangep: *mut CFRange, atp: *mut CFAbsoluteTime) -> Boolean; + pub fn CFDateFormatterCreateDateFromString( + allocator: CFAllocatorRef, + formatter: CFDateFormatterRef, + string: CFStringRef, + rangep: *mut CFRange, + ) -> CFDateRef; + pub fn CFDateFormatterGetAbsoluteTimeFromString( + formatter: CFDateFormatterRef, + string: CFStringRef, + rangep: *mut CFRange, + atp: *mut CFAbsoluteTime, + ) -> Boolean; /* Creating Strings From Data */ - pub fn CFDateFormatterCreateStringWithAbsoluteTime(allocator: CFAllocatorRef, formatter: CFDateFormatterRef, at: CFAbsoluteTime) -> CFStringRef; - pub fn CFDateFormatterCreateStringWithDate(allocator: CFAllocatorRef, formatter: CFDateFormatterRef, date: CFDateRef) -> CFStringRef; - pub fn CFDateFormatterCreateDateFormatFromTemplate(allocator: CFAllocatorRef, tmplate: CFStringRef, options: CFOptionFlags, locale: CFLocaleRef) -> CFStringRef; + pub fn CFDateFormatterCreateStringWithAbsoluteTime( + allocator: CFAllocatorRef, + formatter: CFDateFormatterRef, + at: CFAbsoluteTime, + ) -> CFStringRef; + pub fn CFDateFormatterCreateStringWithDate( + allocator: CFAllocatorRef, + formatter: CFDateFormatterRef, + date: CFDateRef, + ) -> CFStringRef; + pub fn CFDateFormatterCreateDateFormatFromTemplate( + allocator: CFAllocatorRef, + tmplate: CFStringRef, + options: CFOptionFlags, + locale: CFLocaleRef, + ) -> CFStringRef; /* Getting Information About a Date Formatter */ - pub fn CFDateFormatterCopyProperty(formatter: CFDateFormatterRef, key: CFDateFormatterKey) -> CFTypeRef; + pub fn CFDateFormatterCopyProperty( + formatter: CFDateFormatterRef, + key: CFDateFormatterKey, + ) -> CFTypeRef; pub fn CFDateFormatterGetDateStyle(formatter: CFDateFormatterRef) -> CFDateFormatterStyle; pub fn CFDateFormatterGetFormat(formatter: CFDateFormatterRef) -> CFStringRef; pub fn CFDateFormatterGetLocale(formatter: CFDateFormatterRef) -> CFLocaleRef; diff --git a/core-foundation-sys/src/dictionary.rs b/core-foundation-sys/src/dictionary.rs index 4e6436839..f243c5bab 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 */ @@ -58,8 +62,18 @@ extern { /* CFDictionary */ /* Creating a dictionary */ - 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 CFDictionaryCreateCopy(allocator: CFAllocatorRef, theDict: CFDictionaryRef) -> 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 CFDictionaryCreateCopy( + allocator: CFAllocatorRef, + theDict: CFDictionaryRef, + ) -> CFDictionaryRef; /* Examining a dictionary */ pub fn CFDictionaryContainsKey(theDict: CFDictionaryRef, key: *const c_void) -> Boolean; @@ -67,26 +81,59 @@ extern { pub fn CFDictionaryGetCount(theDict: CFDictionaryRef) -> CFIndex; pub fn CFDictionaryGetCountOfKey(theDict: CFDictionaryRef, key: *const c_void) -> CFIndex; pub fn CFDictionaryGetCountOfValue(heDict: CFDictionaryRef, value: *const c_void) -> CFIndex; - pub fn CFDictionaryGetKeysAndValues(theDict: CFDictionaryRef, keys: *mut *const c_void, values: *mut *const c_void); + pub fn CFDictionaryGetKeysAndValues( + theDict: CFDictionaryRef, + keys: *mut *const c_void, + values: *mut *const c_void, + ); pub fn CFDictionaryGetValue(theDict: CFDictionaryRef, key: *const c_void) -> *const c_void; - pub fn CFDictionaryGetValueIfPresent(theDict: CFDictionaryRef, key: *const c_void, value: *mut *const c_void) -> Boolean; + pub fn CFDictionaryGetValueIfPresent( + theDict: CFDictionaryRef, + key: *const c_void, + value: *mut *const c_void, + ) -> Boolean; /* Applying a function to a dictionary */ - pub fn CFDictionaryApplyFunction(theDict: CFDictionaryRef, applier: CFDictionaryApplierFunction, context: *mut c_void); + pub fn CFDictionaryApplyFunction( + theDict: CFDictionaryRef, + applier: CFDictionaryApplierFunction, + context: *mut c_void, + ); /* Getting the CFDictionary type ID */ pub fn CFDictionaryGetTypeID() -> CFTypeID; /* CFMutableDictionary */ /* Creating a Mutable Dictionary */ - 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 CFDictionaryCreateMutable( + allocator: CFAllocatorRef, + capacity: CFIndex, + keyCallbacks: *const CFDictionaryKeyCallBacks, + valueCallbacks: *const CFDictionaryValueCallBacks, + ) -> CFMutableDictionaryRef; + pub fn CFDictionaryCreateMutableCopy( + allocator: CFAllocatorRef, + capacity: CFIndex, + theDict: CFDictionaryRef, + ) -> CFMutableDictionaryRef; /* Modifying a Dictionary */ - pub fn CFDictionaryAddValue(theDict: CFMutableDictionaryRef, key: *const c_void, value: *const c_void); + pub fn CFDictionaryAddValue( + theDict: CFMutableDictionaryRef, + key: *const c_void, + value: *const c_void, + ); pub fn CFDictionaryRemoveAllValues(theDict: CFMutableDictionaryRef); pub fn CFDictionaryRemoveValue(theDict: CFMutableDictionaryRef, key: *const c_void); - pub fn CFDictionaryReplaceValue(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 CFDictionarySetValue( + theDict: CFMutableDictionaryRef, + key: *const c_void, + value: *const c_void, + ); } diff --git a/core-foundation-sys/src/error.rs b/core-foundation-sys/src/error.rs index 3082bf638..15f26bb16 100644 --- a/core-foundation-sys/src/error.rs +++ b/core-foundation-sys/src/error.rs @@ -9,9 +9,9 @@ use std::os::raw::c_void; -use base::{CFTypeID, CFIndex, CFAllocatorRef}; -use string::CFStringRef; +use base::{CFAllocatorRef, CFIndex, CFTypeID}; use dictionary::CFDictionaryRef; +use string::CFStringRef; #[repr(C)] pub struct __CFError(c_void); @@ -41,7 +41,12 @@ extern "C" { pub static kCFErrorFilePathKey: CFStringRef; /* Creating a CFError */ - pub fn CFErrorCreate(allocator: CFAllocatorRef, domain: CFErrorDomain, code: CFIndex, userInfo: CFDictionaryRef) -> CFErrorRef; + pub fn CFErrorCreate( + allocator: CFAllocatorRef, + domain: CFErrorDomain, + code: CFIndex, + userInfo: CFDictionaryRef, + ) -> CFErrorRef; //pub fn CFErrorCreateWithUserInfoKeysAndValues /* Getting Information About an Error */ diff --git a/core-foundation-sys/src/file_security.rs b/core-foundation-sys/src/file_security.rs index cb51e98ad..f9783e628 100644 --- a/core-foundation-sys/src/file_security.rs +++ b/core-foundation-sys/src/file_security.rs @@ -9,40 +9,49 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, Boolean, CFTypeID}; -#[cfg(feature="mac_os_10_8_features")] +#[cfg(feature = "mac_os_10_8_features")] use base::CFOptionFlags; +use base::{Boolean, CFAllocatorRef, CFTypeID}; use uuid::CFUUIDRef; #[repr(C)] pub struct __CFFileSecurity(c_void); pub type CFFileSecurityRef = *mut __CFFileSecurity; -#[cfg(feature="mac_os_10_8_features")] +#[cfg(feature = "mac_os_10_8_features")] pub type CFFileSecurityClearOptions = CFOptionFlags; -#[cfg(feature="mac_os_10_8_features")] +#[cfg(feature = "mac_os_10_8_features")] pub const kCFFileSecurityClearOwner: CFFileSecurityClearOptions = 1 << 0; -#[cfg(feature="mac_os_10_8_features")] +#[cfg(feature = "mac_os_10_8_features")] pub const kCFFileSecurityClearGroup: CFFileSecurityClearOptions = 1 << 1; -#[cfg(feature="mac_os_10_8_features")] +#[cfg(feature = "mac_os_10_8_features")] pub const kCFFileSecurityClearMode: CFFileSecurityClearOptions = 1 << 2; -#[cfg(feature="mac_os_10_8_features")] +#[cfg(feature = "mac_os_10_8_features")] pub const kCFFileSecurityClearOwnerUUID: CFFileSecurityClearOptions = 1 << 3; -#[cfg(feature="mac_os_10_8_features")] +#[cfg(feature = "mac_os_10_8_features")] pub const kCFFileSecurityClearGroupUUID: CFFileSecurityClearOptions = 1 << 4; -#[cfg(feature="mac_os_10_8_features")] +#[cfg(feature = "mac_os_10_8_features")] pub const kCFFileSecurityClearAccessControlList: CFFileSecurityClearOptions = 1 << 5; -extern { +extern "C" { /* * CFFileSecurity.h */ pub fn CFFileSecurityGetTypeID() -> CFTypeID; pub fn CFFileSecurityCreate(allocator: CFAllocatorRef) -> CFFileSecurityRef; - pub fn CFFileSecurityCreateCopy(allocator: CFAllocatorRef, fileSec: CFFileSecurityRef) -> CFFileSecurityRef; - pub fn CFFileSecurityCopyOwnerUUID(fileSec: CFFileSecurityRef, ownerUUID: *mut CFUUIDRef) -> Boolean; + pub fn CFFileSecurityCreateCopy( + allocator: CFAllocatorRef, + fileSec: CFFileSecurityRef, + ) -> CFFileSecurityRef; + pub fn CFFileSecurityCopyOwnerUUID( + fileSec: CFFileSecurityRef, + ownerUUID: *mut CFUUIDRef, + ) -> Boolean; pub fn CFFileSecuritySetOwnerUUID(fileSec: CFFileSecurityRef, ownerUUID: CFUUIDRef) -> Boolean; - pub fn CFFileSecurityCopyGroupUUID(fileSec: CFFileSecurityRef, groupUUID: *mut CFUUIDRef) -> Boolean; + pub fn CFFileSecurityCopyGroupUUID( + fileSec: CFFileSecurityRef, + groupUUID: *mut CFUUIDRef, + ) -> Boolean; pub fn CFFileSecuritySetGroupUUID(fileSec: CFFileSecurityRef, groupUUID: CFUUIDRef) -> Boolean; //pub fn CFFileSecurityCopyAccessControlList(fileSec: CFFileSecurityRef, accessControlList: *mut acl_t) -> Boolean; //pub fn CFFileSecuritySetAccessControlList(fileSec: CFFileSecurityRef, accessControlList: acl_t) -> Boolean; @@ -53,7 +62,10 @@ extern { //pub fn CFFileSecurityGetMode(fileSec: CFFileSecurityRef, mode: *mut mode_t) -> Boolean; //pub fn CFFileSecuritySetMode(fileSec: CFFileSecurityRef, mode: mode_t) -> Boolean; - #[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 fn CFFileSecurityClearProperties(fileSec: CFFileSecurityRef, clearPropertyMask: CFFileSecurityClearOptions) -> Boolean; + pub fn CFFileSecurityClearProperties( + fileSec: CFFileSecurityRef, + clearPropertyMask: CFFileSecurityClearOptions, + ) -> Boolean; } diff --git a/core-foundation-sys/src/filedescriptor.rs b/core-foundation-sys/src/filedescriptor.rs index 036d8d58a..d2c81cd4f 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,33 +21,45 @@ 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(Debug, 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 */ /* Creating a CFFileDescriptor */ - 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; /* Getting Information About a File Descriptor */ - pub fn CFFileDescriptorGetNativeDescriptor(f: CFFileDescriptorRef) -> CFFileDescriptorNativeDescriptor; + pub fn CFFileDescriptorGetNativeDescriptor( + f: CFFileDescriptorRef, + ) -> CFFileDescriptorNativeDescriptor; pub fn CFFileDescriptorIsValid(f: CFFileDescriptorRef) -> Boolean; - pub fn CFFileDescriptorGetContext(f: CFFileDescriptorRef, context: *mut CFFileDescriptorContext); + pub fn CFFileDescriptorGetContext( + f: CFFileDescriptorRef, + context: *mut CFFileDescriptorContext, + ); /* Invalidating a File Descriptor */ pub fn CFFileDescriptorInvalidate(f: CFFileDescriptorRef); @@ -57,7 +69,11 @@ extern { pub fn CFFileDescriptorDisableCallBacks(f: CFFileDescriptorRef, callBackTypes: CFOptionFlags); /* Creating a Run Loop Source */ - pub fn CFFileDescriptorCreateRunLoopSource(allocator: CFAllocatorRef, f: CFFileDescriptorRef, order: CFIndex) -> CFRunLoopSourceRef; + pub fn CFFileDescriptorCreateRunLoopSource( + allocator: CFAllocatorRef, + f: CFFileDescriptorRef, + order: CFIndex, + ) -> CFRunLoopSourceRef; /* Getting the CFFileDescriptor Type ID */ pub fn CFFileDescriptorGetTypeID() -> CFTypeID; diff --git a/core-foundation-sys/src/lib.rs b/core-foundation-sys/src/lib.rs index 9f434adba..edd6dd0fc 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 // Link to CoreFoundation on any Apple device. // @@ -34,8 +41,8 @@ pub mod date; pub mod date_formatter; pub mod dictionary; pub mod error; -pub mod filedescriptor; pub mod file_security; +pub mod filedescriptor; pub mod locale; pub mod mach_port; pub mod messageport; @@ -51,8 +58,8 @@ pub mod socket; pub mod stream; pub mod string; pub mod string_tokenizer; -pub mod tree; pub mod timezone; +pub mod tree; pub mod url; pub mod url_enumerator; #[cfg(target_os = "macos")] diff --git a/core-foundation-sys/src/locale.rs b/core-foundation-sys/src/locale.rs index a1fd764d5..96cd765e5 100644 --- a/core-foundation-sys/src/locale.rs +++ b/core-foundation-sys/src/locale.rs @@ -7,12 +7,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::os::raw::c_void; -use base::{CFIndex, CFAllocatorRef, CFTypeRef, LangCode, RegionCode, CFTypeID}; use array::CFArrayRef; -use string::CFStringRef; +use base::{CFAllocatorRef, CFIndex, CFTypeID, CFTypeRef, LangCode, RegionCode}; use dictionary::CFDictionaryRef; use notification_center::CFNotificationName; +use std::os::raw::c_void; +use string::CFStringRef; #[repr(C)] pub struct __CFLocale(c_void); @@ -29,7 +29,7 @@ pub const kCFLocaleLanguageDirectionRightToLeft: CFLocaleLanguageDirection = 2; pub const kCFLocaleLanguageDirectionTopToBottom: CFLocaleLanguageDirection = 3; pub const kCFLocaleLanguageDirectionBottomToTop: CFLocaleLanguageDirection = 4; -extern { +extern "C" { /* * CFLocale.h */ @@ -77,7 +77,10 @@ extern { /* Creating a Locale */ pub fn CFLocaleCopyCurrent() -> CFLocaleRef; - pub fn CFLocaleCreate(allocator: CFAllocatorRef, localeIdentifier: CFLocaleIdentifier) -> CFLocaleRef; + pub fn CFLocaleCreate( + allocator: CFAllocatorRef, + localeIdentifier: CFLocaleIdentifier, + ) -> CFLocaleRef; pub fn CFLocaleCreateCopy(allocator: CFAllocatorRef, locale: CFLocaleRef) -> CFLocaleRef; pub fn CFLocaleGetSystem() -> CFLocaleRef; @@ -94,21 +97,48 @@ extern { pub fn CFLocaleCopyPreferredLanguages() -> CFArrayRef; /* Getting Information About a Locale */ - pub fn CFLocaleCopyDisplayNameForPropertyValue(displayLocale: CFLocaleRef, key: CFLocaleKey, value: CFStringRef) -> CFStringRef; + pub fn CFLocaleCopyDisplayNameForPropertyValue( + displayLocale: CFLocaleRef, + key: CFLocaleKey, + value: CFStringRef, + ) -> CFStringRef; pub fn CFLocaleGetValue(locale: CFLocaleRef, key: CFLocaleKey) -> CFTypeRef; pub fn CFLocaleGetIdentifier(locale: CFLocaleRef) -> CFLocaleIdentifier; /* Getting and Creating Locale Identifiers */ - pub fn CFLocaleCreateCanonicalLocaleIdentifierFromScriptManagerCodes(allocator: CFAllocatorRef, lcode: LangCode, rcode: RegionCode) -> CFLocaleIdentifier; - pub fn CFLocaleCreateCanonicalLanguageIdentifierFromString(allocator: CFAllocatorRef, localeIdentifier: CFStringRef) -> CFLocaleIdentifier; - pub fn CFLocaleCreateCanonicalLocaleIdentifierFromString(allocator: CFAllocatorRef, localeIdentifier: CFStringRef) -> CFLocaleIdentifier; - pub fn CFLocaleCreateComponentsFromLocaleIdentifier(allocator: CFAllocatorRef, localeID: CFLocaleIdentifier) -> CFDictionaryRef; - pub fn CFLocaleCreateLocaleIdentifierFromComponents(allocator: CFAllocatorRef, dictionary: CFDictionaryRef) -> CFLocaleIdentifier; - pub fn CFLocaleCreateLocaleIdentifierFromWindowsLocaleCode(allocator: CFAllocatorRef, lcid: u32) -> CFLocaleIdentifier; - pub fn CFLocaleGetWindowsLocaleCodeFromLocaleIdentifier(localeIdentifier: CFLocaleIdentifier) -> u32; + pub fn CFLocaleCreateCanonicalLocaleIdentifierFromScriptManagerCodes( + allocator: CFAllocatorRef, + lcode: LangCode, + rcode: RegionCode, + ) -> CFLocaleIdentifier; + pub fn CFLocaleCreateCanonicalLanguageIdentifierFromString( + allocator: CFAllocatorRef, + localeIdentifier: CFStringRef, + ) -> CFLocaleIdentifier; + pub fn CFLocaleCreateCanonicalLocaleIdentifierFromString( + allocator: CFAllocatorRef, + localeIdentifier: CFStringRef, + ) -> CFLocaleIdentifier; + pub fn CFLocaleCreateComponentsFromLocaleIdentifier( + allocator: CFAllocatorRef, + localeID: CFLocaleIdentifier, + ) -> CFDictionaryRef; + pub fn CFLocaleCreateLocaleIdentifierFromComponents( + allocator: CFAllocatorRef, + dictionary: CFDictionaryRef, + ) -> CFLocaleIdentifier; + pub fn CFLocaleCreateLocaleIdentifierFromWindowsLocaleCode( + allocator: CFAllocatorRef, + lcid: u32, + ) -> CFLocaleIdentifier; + pub fn CFLocaleGetWindowsLocaleCodeFromLocaleIdentifier( + localeIdentifier: CFLocaleIdentifier, + ) -> u32; /* Getting Line and Character Direction for a Language */ - pub fn CFLocaleGetLanguageCharacterDirection(isoLangCode: CFStringRef) -> CFLocaleLanguageDirection; + pub fn CFLocaleGetLanguageCharacterDirection( + isoLangCode: CFStringRef, + ) -> CFLocaleLanguageDirection; pub fn CFLocaleGetLanguageLineDirection(isoLangCode: CFStringRef) -> CFLocaleLanguageDirection; /* Getting the CFLocale Type ID */ diff --git a/core-foundation-sys/src/mach_port.rs b/core-foundation-sys/src/mach_port.rs index 1474d311a..4ae67c053 100644 --- a/core-foundation-sys/src/mach_port.rs +++ b/core-foundation-sys/src/mach_port.rs @@ -7,27 +7,28 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use string::CFStringRef; +use base::{mach_port_t, Boolean}; pub use base::{CFAllocatorRef, CFIndex, CFTypeID}; -use base::{Boolean, mach_port_t}; use runloop::CFRunLoopSourceRef; use std::os::raw::c_void; +use string::CFStringRef; #[repr(C)] pub struct __CFMachPort(c_void); pub type CFMachPortRef = *mut __CFMachPort; -pub type CFMachPortCallBack = extern "C" fn (port: CFMachPortRef, msg: *mut c_void, size: CFIndex, info: *mut c_void); -pub type CFMachPortInvalidationCallBack = extern "C" fn (port: CFMachPortRef, info: *mut c_void); +pub type CFMachPortCallBack = + extern "C" fn(port: CFMachPortRef, msg: *mut c_void, size: CFIndex, info: *mut c_void); +pub type CFMachPortInvalidationCallBack = extern "C" fn(port: CFMachPortRef, info: *mut c_void); #[repr(C)] #[derive(Clone, Copy)] pub struct CFMachPortContext { pub version: CFIndex, pub info: *mut c_void, - pub retain: extern "C" fn (info: *const c_void) -> *const c_void, - pub release: extern "C" fn (info: *const c_void), - pub copyDescription: extern "C" fn (info: *const c_void) -> CFStringRef, + pub retain: extern "C" fn(info: *const c_void) -> *const c_void, + pub release: extern "C" fn(info: *const c_void), + pub copyDescription: extern "C" fn(info: *const c_void) -> CFStringRef, } extern "C" { @@ -36,17 +37,36 @@ extern "C" { */ /* Creating a CFMachPort Object */ - pub fn CFMachPortCreate(allocator: CFAllocatorRef, callout: CFMachPortCallBack, context: *mut CFMachPortContext, shouldFreeInfo: *mut Boolean) -> CFMachPortRef; - pub fn CFMachPortCreateWithPort(allocator: CFAllocatorRef, portNum: mach_port_t, callout: CFMachPortCallBack, context: *mut CFMachPortContext, shouldFreeInfo: *mut Boolean) -> CFMachPortRef; + pub fn CFMachPortCreate( + allocator: CFAllocatorRef, + callout: CFMachPortCallBack, + context: *mut CFMachPortContext, + shouldFreeInfo: *mut Boolean, + ) -> CFMachPortRef; + pub fn CFMachPortCreateWithPort( + allocator: CFAllocatorRef, + portNum: mach_port_t, + callout: CFMachPortCallBack, + context: *mut CFMachPortContext, + shouldFreeInfo: *mut Boolean, + ) -> CFMachPortRef; /* Configuring a CFMachPort Object */ pub fn CFMachPortInvalidate(port: CFMachPortRef); - pub fn CFMachPortCreateRunLoopSource(allocator: CFAllocatorRef, port: CFMachPortRef, order: CFIndex) -> CFRunLoopSourceRef; - pub fn CFMachPortSetInvalidationCallBack(port: CFMachPortRef, callout: CFMachPortInvalidationCallBack); + pub fn CFMachPortCreateRunLoopSource( + allocator: CFAllocatorRef, + port: CFMachPortRef, + order: CFIndex, + ) -> CFRunLoopSourceRef; + pub fn CFMachPortSetInvalidationCallBack( + port: CFMachPortRef, + callout: CFMachPortInvalidationCallBack, + ); /* Examining a CFMachPort Object */ pub fn CFMachPortGetContext(port: CFMachPortRef, context: *mut CFMachPortContext); - pub fn CFMachPortGetInvalidationCallBack(port: CFMachPortRef) -> CFMachPortInvalidationCallBack; + pub fn CFMachPortGetInvalidationCallBack(port: CFMachPortRef) + -> CFMachPortInvalidationCallBack; pub fn CFMachPortGetPort(port: CFMachPortRef) -> mach_port_t; pub fn CFMachPortIsValid(port: CFMachPortRef) -> Boolean; diff --git a/core-foundation-sys/src/messageport.rs b/core-foundation-sys/src/messageport.rs index 263f0c52b..91a5801b1 100644 --- a/core-foundation-sys/src/messageport.rs +++ b/core-foundation-sys/src/messageport.rs @@ -9,7 +9,7 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, CFIndex, CFTypeID, Boolean, SInt32}; +use base::{Boolean, CFAllocatorRef, CFIndex, CFTypeID, SInt32}; use data::CFDataRef; use date::CFTimeInterval; use runloop::CFRunLoopSourceRef; @@ -20,20 +20,22 @@ use string::CFStringRef; 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; /* CFMessagePortSendRequest Error Codes */ pub const kCFMessagePortSuccess: SInt32 = 0; @@ -47,28 +49,54 @@ pub const kCFMessagePortBecameInvalidError: SInt32 = -5; pub struct __CFMessagePort(c_void); pub type CFMessagePortRef = *mut __CFMessagePort; -extern { +extern "C" { /* * CFMessagePort.h */ /* Creating a CFMessagePort Object */ - 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; /* Configuring a CFMessagePort Object */ - pub fn CFMessagePortCreateRunLoopSource(allocator: CFAllocatorRef, local: CFMessagePortRef, order: CFIndex) -> CFRunLoopSourceRef; - pub fn CFMessagePortSetInvalidationCallBack(ms: CFMessagePortRef, callout: CFMessagePortInvalidationCallBack); + pub fn CFMessagePortCreateRunLoopSource( + allocator: CFAllocatorRef, + local: CFMessagePortRef, + order: CFIndex, + ) -> CFRunLoopSourceRef; + pub fn CFMessagePortSetInvalidationCallBack( + ms: CFMessagePortRef, + callout: CFMessagePortInvalidationCallBack, + ); pub fn CFMessagePortSetName(ms: CFMessagePortRef, newName: CFStringRef) -> Boolean; /* Using a Message Port */ pub fn CFMessagePortInvalidate(ms: CFMessagePortRef); - pub fn CFMessagePortSendRequest(remote: CFMessagePortRef, msgid: i32, data: CFDataRef, sendTimeout: CFTimeInterval, rcvTimeout: CFTimeInterval, replyMode: CFStringRef, returnData: *mut CFDataRef) -> i32; + pub fn CFMessagePortSendRequest( + remote: CFMessagePortRef, + msgid: i32, + data: CFDataRef, + sendTimeout: CFTimeInterval, + rcvTimeout: CFTimeInterval, + replyMode: CFStringRef, + returnData: *mut CFDataRef, + ) -> i32; //pub fn CFMessagePortSetDispatchQueue(ms: CFMessagePortRef, queue: dispatch_queue_t); /* Examining a Message Port */ pub fn CFMessagePortGetContext(ms: CFMessagePortRef, context: *mut CFMessagePortContext); - pub fn CFMessagePortGetInvalidationCallBack(ms: CFMessagePortRef) -> CFMessagePortInvalidationCallBack; + pub fn CFMessagePortGetInvalidationCallBack( + ms: CFMessagePortRef, + ) -> CFMessagePortInvalidationCallBack; pub fn CFMessagePortGetName(ms: CFMessagePortRef) -> CFStringRef; pub fn CFMessagePortIsRemote(ms: CFMessagePortRef) -> Boolean; pub fn CFMessagePortIsValid(ms: CFMessagePortRef) -> Boolean; diff --git a/core-foundation-sys/src/notification_center.rs b/core-foundation-sys/src/notification_center.rs index 002c1fe27..b24058e03 100644 --- a/core-foundation-sys/src/notification_center.rs +++ b/core-foundation-sys/src/notification_center.rs @@ -9,7 +9,7 @@ use std::os::raw::c_void; -use base::{CFOptionFlags, CFIndex, CFTypeID, Boolean}; +use base::{Boolean, CFIndex, CFOptionFlags, CFTypeID}; use dictionary::CFDictionaryRef; use string::CFStringRef; @@ -19,7 +19,13 @@ pub struct __CFNotificationCenter(c_void); pub type CFNotificationCenterRef = *mut __CFNotificationCenter; pub type CFNotificationName = CFStringRef; -pub type CFNotificationCallback = extern "C" fn (center: CFNotificationCenterRef, observer: *mut c_void, name: CFNotificationName, object: *const c_void, userInfo: CFDictionaryRef); +pub type CFNotificationCallback = extern "C" fn( + center: CFNotificationCenterRef, + observer: *mut c_void, + name: CFNotificationName, + object: *const c_void, + userInfo: CFDictionaryRef, +); pub type CFNotificationSuspensionBehavior = CFIndex; pub const CFNotificationSuspensionBehaviorDrop: CFNotificationSuspensionBehavior = 1; @@ -31,25 +37,52 @@ pub const CFNotificationSuspensionBehaviorDeliverImmediately: CFNotificationSusp pub const kCFNotificationDeliverImmediately: CFOptionFlags = 1usize << 0; pub const kCFNotificationPostToAllSessions: CFOptionFlags = 1usize << 1; -extern { +extern "C" { /* * CFNotificationCenter.h */ /* Accessing a Notification Center */ pub fn CFNotificationCenterGetDarwinNotifyCenter() -> CFNotificationCenterRef; - #[cfg(any(target_os="macos", target_os="windows"))] + #[cfg(any(target_os = "macos", target_os = "windows"))] pub fn CFNotificationCenterGetDistributedCenter() -> CFNotificationCenterRef; pub fn CFNotificationCenterGetLocalCenter() -> CFNotificationCenterRef; /* Posting a Notification */ - pub fn CFNotificationCenterPostNotification(center: CFNotificationCenterRef, name: CFNotificationName, object: *const c_void, userInfo: CFDictionaryRef, deliverImmediately: Boolean); - pub fn CFNotificationCenterPostNotificationWithOptions(center: CFNotificationCenterRef, name: CFNotificationName, object: *const c_void, userInfo: CFDictionaryRef, options: CFOptionFlags); + pub fn CFNotificationCenterPostNotification( + center: CFNotificationCenterRef, + name: CFNotificationName, + object: *const c_void, + userInfo: CFDictionaryRef, + deliverImmediately: Boolean, + ); + pub fn CFNotificationCenterPostNotificationWithOptions( + center: CFNotificationCenterRef, + name: CFNotificationName, + object: *const c_void, + userInfo: CFDictionaryRef, + options: CFOptionFlags, + ); /* Adding and Removing Observers */ - pub fn CFNotificationCenterAddObserver(center: CFNotificationCenterRef, observer: *const c_void, callBack: CFNotificationCallback, name: CFStringRef, object: *const c_void, suspensionBehavior: CFNotificationSuspensionBehavior); - pub fn CFNotificationCenterRemoveEveryObserver(center: CFNotificationCenterRef, observer: *const c_void); - pub fn CFNotificationCenterRemoveObserver(center: CFNotificationCenterRef, observer: *const c_void, name: CFNotificationName, object: *const c_void); + pub fn CFNotificationCenterAddObserver( + center: CFNotificationCenterRef, + observer: *const c_void, + callBack: CFNotificationCallback, + name: CFStringRef, + object: *const c_void, + suspensionBehavior: CFNotificationSuspensionBehavior, + ); + pub fn CFNotificationCenterRemoveEveryObserver( + center: CFNotificationCenterRef, + observer: *const c_void, + ); + pub fn CFNotificationCenterRemoveObserver( + center: CFNotificationCenterRef, + observer: *const c_void, + name: CFNotificationName, + object: *const c_void, + ); /* Getting the CFNotificationCenter Type ID */ pub fn CFNotificationCenterGetTypeID() -> CFTypeID; diff --git a/core-foundation-sys/src/number.rs b/core-foundation-sys/src/number.rs index a355baaed..ce174d5b6 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, Boolean, CFIndex}; +use base::{Boolean, CFAllocatorRef, CFComparisonResult, CFIndex, 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 */ @@ -54,16 +54,28 @@ extern { pub static kCFNumberNaN: CFNumberRef; /* Creating a Number */ - pub fn CFNumberCreate(allocator: CFAllocatorRef, theType: CFNumberType, valuePtr: *const c_void) -> CFNumberRef; + pub fn CFNumberCreate( + allocator: CFAllocatorRef, + theType: CFNumberType, + valuePtr: *const c_void, + ) -> CFNumberRef; /* Getting Information About Numbers */ pub fn CFNumberGetByteSize(number: CFNumberRef) -> CFIndex; pub fn CFNumberGetType(number: CFNumberRef) -> CFNumberType; - pub fn CFNumberGetValue(number: CFNumberRef, theType: CFNumberType, valuePtr: *mut c_void) -> bool; + pub fn CFNumberGetValue( + number: CFNumberRef, + theType: CFNumberType, + valuePtr: *mut c_void, + ) -> bool; pub fn CFNumberIsFloatType(number: CFNumberRef) -> Boolean; /* Comparing Numbers */ - pub fn CFNumberCompare(date: CFNumberRef, other: CFNumberRef, context: *mut c_void) -> CFComparisonResult; + pub fn CFNumberCompare( + date: CFNumberRef, + other: CFNumberRef, + context: *mut c_void, + ) -> CFComparisonResult; /* Getting the CFNumber Type ID */ pub fn CFNumberGetTypeID() -> CFTypeID; diff --git a/core-foundation-sys/src/number_formatter.rs b/core-foundation-sys/src/number_formatter.rs index 8960c61fa..9bb03a359 100644 --- a/core-foundation-sys/src/number_formatter.rs +++ b/core-foundation-sys/src/number_formatter.rs @@ -7,12 +7,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::os::raw::{c_void, c_double}; +use std::os::raw::{c_double, c_void}; -use base::{CFIndex, CFOptionFlags, CFAllocatorRef, CFTypeID, CFRange, Boolean, CFTypeRef}; -use string::CFStringRef; +use base::{Boolean, CFAllocatorRef, CFIndex, CFOptionFlags, CFRange, CFTypeID, CFTypeRef}; use locale::CFLocaleRef; use number::{CFNumberRef, CFNumberType}; +use string::CFStringRef; #[repr(C)] pub struct __CFNumberFormatter(c_void); @@ -55,7 +55,7 @@ pub const kCFNumberFormatterPadAfterPrefix: CFNumberFormatterPadPosition = 1; pub const kCFNumberFormatterPadBeforeSuffix: CFNumberFormatterPadPosition = 2; pub const kCFNumberFormatterPadAfterSuffix: CFNumberFormatterPadPosition = 3; -extern { +extern "C" { /* * CFNumberFormatter.h */ @@ -65,8 +65,8 @@ extern { // The specific types for each key are specified above. pub static kCFNumberFormatterCurrencyCode: CFNumberFormatterKey; // CFString pub static kCFNumberFormatterDecimalSeparator: CFNumberFormatterKey; // CFString - pub static kCFNumberFormatterCurrencyDecimalSeparator: CFNumberFormatterKey; // CFString - pub static kCFNumberFormatterAlwaysShowDecimalSeparator: CFNumberFormatterKey; // CFBoolean + pub static kCFNumberFormatterCurrencyDecimalSeparator: CFNumberFormatterKey; // CFString + pub static kCFNumberFormatterAlwaysShowDecimalSeparator: CFNumberFormatterKey; // CFBoolean pub static kCFNumberFormatterGroupingSeparator: CFNumberFormatterKey; // CFString pub static kCFNumberFormatterUseGroupingSeparator: CFNumberFormatterKey; // CFBoolean pub static kCFNumberFormatterPercentSymbol: CFNumberFormatterKey; // CFString @@ -95,29 +95,65 @@ extern { pub static kCFNumberFormatterNegativePrefix: CFNumberFormatterKey; // CFString pub static kCFNumberFormatterNegativeSuffix: CFNumberFormatterKey; // CFString pub static kCFNumberFormatterPerMillSymbol: CFNumberFormatterKey; // CFString - pub static kCFNumberFormatterInternationalCurrencySymbol: CFNumberFormatterKey; // CFString - pub static kCFNumberFormatterCurrencyGroupingSeparator: CFNumberFormatterKey; // CFString + pub static kCFNumberFormatterInternationalCurrencySymbol: CFNumberFormatterKey; // CFString + pub static kCFNumberFormatterCurrencyGroupingSeparator: CFNumberFormatterKey; // CFString pub static kCFNumberFormatterIsLenient: CFNumberFormatterKey; // CFBoolean pub static kCFNumberFormatterUseSignificantDigits: CFNumberFormatterKey; // CFBoolean pub static kCFNumberFormatterMinSignificantDigits: CFNumberFormatterKey; // CFNumber pub static kCFNumberFormatterMaxSignificantDigits: CFNumberFormatterKey; // CFNumber /* Creating a Number Formatter */ - pub fn CFNumberFormatterCreate(allocator: CFAllocatorRef, locale: CFLocaleRef, style: CFNumberFormatterStyle) -> CFNumberFormatterRef; + pub fn CFNumberFormatterCreate( + allocator: CFAllocatorRef, + locale: CFLocaleRef, + style: CFNumberFormatterStyle, + ) -> CFNumberFormatterRef; /* Configuring a Number Formatter */ pub fn CFNumberFormatterSetFormat(formatter: CFNumberFormatterRef, formatString: CFStringRef); - pub fn CFNumberFormatterSetProperty(formatter: CFNumberFormatterRef, key: CFNumberFormatterKey, value: CFTypeRef); + pub fn CFNumberFormatterSetProperty( + formatter: CFNumberFormatterRef, + key: CFNumberFormatterKey, + value: CFTypeRef, + ); /* Formatting Values */ - pub fn CFNumberFormatterCreateNumberFromString(allocator: CFAllocatorRef, formatter: CFNumberFormatterRef, string: CFStringRef, rangep: *mut CFRange, options: CFOptionFlags) -> CFNumberRef; - pub fn CFNumberFormatterCreateStringWithNumber(allocator: CFAllocatorRef, formatter: CFNumberFormatterRef, number: CFNumberRef) -> CFStringRef; - pub fn CFNumberFormatterCreateStringWithValue(allocator: CFAllocatorRef, formatter: CFNumberFormatterRef, numberType: CFNumberType, valuePtr: *const c_void) -> CFStringRef; - pub fn CFNumberFormatterGetDecimalInfoForCurrencyCode(currencyCode: CFStringRef, defaultFractionDigits: *mut i32, roundingIncrement: *mut c_double) -> Boolean; - pub fn CFNumberFormatterGetValueFromString(formatter: CFNumberFormatterRef, string: CFStringRef, rangep: *mut CFRange, numberType: CFNumberType, valuePtr: *mut c_void) -> Boolean; + pub fn CFNumberFormatterCreateNumberFromString( + allocator: CFAllocatorRef, + formatter: CFNumberFormatterRef, + string: CFStringRef, + rangep: *mut CFRange, + options: CFOptionFlags, + ) -> CFNumberRef; + pub fn CFNumberFormatterCreateStringWithNumber( + allocator: CFAllocatorRef, + formatter: CFNumberFormatterRef, + number: CFNumberRef, + ) -> CFStringRef; + pub fn CFNumberFormatterCreateStringWithValue( + allocator: CFAllocatorRef, + formatter: CFNumberFormatterRef, + numberType: CFNumberType, + valuePtr: *const c_void, + ) -> CFStringRef; + pub fn CFNumberFormatterGetDecimalInfoForCurrencyCode( + currencyCode: CFStringRef, + defaultFractionDigits: *mut i32, + roundingIncrement: *mut c_double, + ) -> Boolean; + pub fn CFNumberFormatterGetValueFromString( + formatter: CFNumberFormatterRef, + string: CFStringRef, + rangep: *mut CFRange, + numberType: CFNumberType, + valuePtr: *mut c_void, + ) -> Boolean; /* Examining a Number Formatter */ - pub fn CFNumberFormatterCopyProperty(formatter: CFNumberFormatterRef, key: CFNumberFormatterKey) -> CFTypeRef; + pub fn CFNumberFormatterCopyProperty( + formatter: CFNumberFormatterRef, + key: CFNumberFormatterKey, + ) -> CFTypeRef; pub fn CFNumberFormatterGetFormat(formatter: CFNumberFormatterRef) -> CFStringRef; pub fn CFNumberFormatterGetLocale(formatter: CFNumberFormatterRef) -> CFLocaleRef; pub fn CFNumberFormatterGetStyle(formatter: CFNumberFormatterRef) -> CFNumberFormatterStyle; diff --git a/core-foundation-sys/src/plugin.rs b/core-foundation-sys/src/plugin.rs index f5f133f4d..71263fa0c 100644 --- a/core-foundation-sys/src/plugin.rs +++ b/core-foundation-sys/src/plugin.rs @@ -9,25 +9,30 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, CFTypeID, Boolean, CFIndex}; -use bundle::{CFPlugInRef, CFBundleRef}; -use uuid::CFUUIDRef; +use array::CFArrayRef; +use base::{Boolean, CFAllocatorRef, CFIndex, CFTypeID}; +use bundle::{CFBundleRef, CFPlugInRef}; use string::CFStringRef; use url::CFURLRef; -use array::CFArrayRef; +use uuid::CFUUIDRef; #[repr(C)] pub struct __CFPlugInInstance(c_void); pub type CFPlugInInstanceRef = *mut __CFPlugInInstance; -pub type CFPlugInDynamicRegisterFunction = extern "C" fn (plugIn: CFPlugInRef); -pub type CFPlugInUnloadFunction = extern "C" fn (plugIn: CFPlugInRef); -pub type CFPlugInFactoryFunction = extern "C" fn (allocator: CFAllocatorRef, typeUUID: CFUUIDRef) -> *mut c_void; +pub type CFPlugInDynamicRegisterFunction = extern "C" fn(plugIn: CFPlugInRef); +pub type CFPlugInUnloadFunction = extern "C" fn(plugIn: CFPlugInRef); +pub type CFPlugInFactoryFunction = + extern "C" fn(allocator: CFAllocatorRef, typeUUID: CFUUIDRef) -> *mut c_void; -pub type CFPlugInInstanceGetInterfaceFunction = extern "C" fn (instance: CFPlugInInstanceRef, interfaceName: CFStringRef, ftbl: *mut *mut c_void) -> Boolean; -pub type CFPlugInInstanceDeallocateInstanceDataFunction = extern "C" fn (instanceData: *mut c_void); +pub type CFPlugInInstanceGetInterfaceFunction = extern "C" fn( + instance: CFPlugInInstanceRef, + interfaceName: CFStringRef, + ftbl: *mut *mut c_void, +) -> Boolean; +pub type CFPlugInInstanceDeallocateInstanceDataFunction = extern "C" fn(instanceData: *mut c_void); -extern { +extern "C" { /* * CFPlugIn.h */ @@ -42,11 +47,22 @@ extern { /* Creating Plug-ins */ pub fn CFPlugInCreate(allocator: CFAllocatorRef, plugInURL: CFURLRef) -> CFPlugInRef; - pub fn CFPlugInInstanceCreate(allocator: CFAllocatorRef, factoryUUID: CFUUIDRef, typeUUID: CFUUIDRef) -> *mut c_void; + pub fn CFPlugInInstanceCreate( + allocator: CFAllocatorRef, + factoryUUID: CFUUIDRef, + typeUUID: CFUUIDRef, + ) -> *mut c_void; /* Registration */ - pub fn CFPlugInRegisterFactoryFunction(factoryUUID: CFUUIDRef, func: CFPlugInFactoryFunction) -> Boolean; - pub fn CFPlugInRegisterFactoryFunctionByName(CfactoryUUID: CFUUIDRef, plugIn: CFPlugInRef, functionName: CFStringRef) -> Boolean; + pub fn CFPlugInRegisterFactoryFunction( + factoryUUID: CFUUIDRef, + func: CFPlugInFactoryFunction, + ) -> Boolean; + pub fn CFPlugInRegisterFactoryFunctionByName( + CfactoryUUID: CFUUIDRef, + plugIn: CFPlugInRef, + functionName: CFStringRef, + ) -> Boolean; pub fn CFPlugInRegisterPlugInType(factoryUUID: CFUUIDRef, typeUUID: CFUUIDRef) -> Boolean; pub fn CFPlugInUnregisterFactory(factoryUUID: CFUUIDRef) -> Boolean; pub fn CFPlugInUnregisterPlugInType(factoryUUID: CFUUIDRef, typeUUID: CFUUIDRef) -> Boolean; @@ -54,7 +70,10 @@ extern { /* CFPlugIn Miscellaneous Functions */ pub fn CFPlugInAddInstanceForFactory(factoryID: CFUUIDRef); pub fn CFPlugInFindFactoriesForPlugInType(typeUUID: CFUUIDRef) -> CFArrayRef; - pub fn CFPlugInFindFactoriesForPlugInTypeInPlugIn(typeUUID: CFUUIDRef, plugIn: CFPlugInRef) -> CFArrayRef; + pub fn CFPlugInFindFactoriesForPlugInTypeInPlugIn( + typeUUID: CFUUIDRef, + plugIn: CFPlugInRef, + ) -> CFArrayRef; pub fn CFPlugInGetBundle(plugIn: CFPlugInRef) -> CFBundleRef; pub fn CFPlugInGetTypeID() -> CFTypeID; pub fn CFPlugInIsLoadOnDemand(plugIn: CFPlugInRef) -> Boolean; @@ -62,9 +81,19 @@ extern { pub fn CFPlugInSetLoadOnDemand(plugIn: CFPlugInRef, flag: Boolean); /* CFPlugInInstance: deprecated */ - pub fn CFPlugInInstanceCreateWithInstanceDataSize(allocator: CFAllocatorRef, instanceDataSize: CFIndex, deallocateInstanceFunction: CFPlugInInstanceDeallocateInstanceDataFunction, factoryName: CFStringRef, getInterfaceFunction: CFPlugInInstanceGetInterfaceFunction) -> CFPlugInInstanceRef; + pub fn CFPlugInInstanceCreateWithInstanceDataSize( + allocator: CFAllocatorRef, + instanceDataSize: CFIndex, + deallocateInstanceFunction: CFPlugInInstanceDeallocateInstanceDataFunction, + factoryName: CFStringRef, + getInterfaceFunction: CFPlugInInstanceGetInterfaceFunction, + ) -> CFPlugInInstanceRef; pub fn CFPlugInInstanceGetFactoryName(instance: CFPlugInInstanceRef) -> CFStringRef; pub fn CFPlugInInstanceGetInstanceData(instance: CFPlugInInstanceRef) -> *mut c_void; - pub fn CFPlugInInstanceGetInterfaceFunctionTable(instance: CFPlugInInstanceRef, interfaceName: CFStringRef, ftbl: *mut *mut c_void) -> Boolean; + pub fn CFPlugInInstanceGetInterfaceFunctionTable( + instance: CFPlugInInstanceRef, + interfaceName: CFStringRef, + ftbl: *mut *mut c_void, + ) -> Boolean; pub fn CFPlugInInstanceGetTypeID() -> CFTypeID; } diff --git a/core-foundation-sys/src/preferences.rs b/core-foundation-sys/src/preferences.rs index 35f1dda63..eef8b30c3 100644 --- a/core-foundation-sys/src/preferences.rs +++ b/core-foundation-sys/src/preferences.rs @@ -7,13 +7,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use base::{Boolean, CFIndex}; -use string::CFStringRef; -use propertylist::CFPropertyListRef; use array::CFArrayRef; +use base::{Boolean, CFIndex}; use dictionary::CFDictionaryRef; +use propertylist::CFPropertyListRef; +use string::CFStringRef; -extern { +extern "C" { /* * CFPreferences.h */ @@ -26,27 +26,78 @@ extern { pub static kCFPreferencesCurrentUser: CFStringRef; /* Getting Preference Values */ - pub fn CFPreferencesCopyAppValue(key: CFStringRef, applicationID: CFStringRef) -> CFPropertyListRef; - pub fn CFPreferencesCopyKeyList(applicationID: CFStringRef, userName: CFStringRef, hostName: CFStringRef) -> CFArrayRef; - pub fn CFPreferencesCopyMultiple(keysToFetch: CFArrayRef, applicationID: CFStringRef, userName: CFStringRef, hostName: CFStringRef) -> CFDictionaryRef; - pub fn CFPreferencesCopyValue(key: CFStringRef, applicationID: CFStringRef, userName: CFStringRef, hostName: CFStringRef) -> CFPropertyListRef; - pub fn CFPreferencesGetAppBooleanValue(key: CFStringRef, applicationID: CFStringRef, keyExistsAndHasValidFormat: *mut Boolean) -> Boolean; - pub fn CFPreferencesGetAppIntegerValue(key: CFStringRef, applicationID: CFStringRef, keyExistsAndHasValidFormat: *mut Boolean) -> CFIndex; + pub fn CFPreferencesCopyAppValue( + key: CFStringRef, + applicationID: CFStringRef, + ) -> CFPropertyListRef; + pub fn CFPreferencesCopyKeyList( + applicationID: CFStringRef, + userName: CFStringRef, + hostName: CFStringRef, + ) -> CFArrayRef; + pub fn CFPreferencesCopyMultiple( + keysToFetch: CFArrayRef, + applicationID: CFStringRef, + userName: CFStringRef, + hostName: CFStringRef, + ) -> CFDictionaryRef; + pub fn CFPreferencesCopyValue( + key: CFStringRef, + applicationID: CFStringRef, + userName: CFStringRef, + hostName: CFStringRef, + ) -> CFPropertyListRef; + pub fn CFPreferencesGetAppBooleanValue( + key: CFStringRef, + applicationID: CFStringRef, + keyExistsAndHasValidFormat: *mut Boolean, + ) -> Boolean; + pub fn CFPreferencesGetAppIntegerValue( + key: CFStringRef, + applicationID: CFStringRef, + keyExistsAndHasValidFormat: *mut Boolean, + ) -> CFIndex; /* Setting Preference Values */ - pub fn CFPreferencesSetAppValue(key: CFStringRef, value: CFPropertyListRef, applicationID: CFStringRef); - pub fn CFPreferencesSetMultiple(keysToSet: CFDictionaryRef, keysToRemove: CFArrayRef, applicationID: CFStringRef, userName: CFStringRef, hostName: CFStringRef); - pub fn CFPreferencesSetValue(key: CFStringRef, value: CFPropertyListRef, applicationID: CFStringRef, userName: CFStringRef, hostName: CFStringRef); + pub fn CFPreferencesSetAppValue( + key: CFStringRef, + value: CFPropertyListRef, + applicationID: CFStringRef, + ); + pub fn CFPreferencesSetMultiple( + keysToSet: CFDictionaryRef, + keysToRemove: CFArrayRef, + applicationID: CFStringRef, + userName: CFStringRef, + hostName: CFStringRef, + ); + pub fn CFPreferencesSetValue( + key: CFStringRef, + value: CFPropertyListRef, + applicationID: CFStringRef, + userName: CFStringRef, + hostName: CFStringRef, + ); /* Synchronizing Preferences */ pub fn CFPreferencesAppSynchronize(applicationID: CFStringRef) -> Boolean; - pub fn CFPreferencesSynchronize(applicationID: CFStringRef, userName: CFStringRef, hostName: CFStringRef) -> Boolean; + pub fn CFPreferencesSynchronize( + applicationID: CFStringRef, + userName: CFStringRef, + hostName: CFStringRef, + ) -> Boolean; /* Adding and Removing Suite Preferences */ pub fn CFPreferencesAddSuitePreferencesToApp(applicationID: CFStringRef, suiteID: CFStringRef); - pub fn CFPreferencesRemoveSuitePreferencesFromApp(applicationID: CFStringRef, suiteID: CFStringRef); + pub fn CFPreferencesRemoveSuitePreferencesFromApp( + applicationID: CFStringRef, + suiteID: CFStringRef, + ); /* Miscellaneous Functions */ pub fn CFPreferencesAppValueIsForced(key: CFStringRef, applicationID: CFStringRef) -> Boolean; - pub fn CFPreferencesCopyApplicationList(userName: CFStringRef, hostName: CFStringRef) -> CFArrayRef; // deprecated since macos 10.9 + pub fn CFPreferencesCopyApplicationList( + userName: CFStringRef, + hostName: CFStringRef, + ) -> CFArrayRef; // deprecated since macos 10.9 } diff --git a/core-foundation-sys/src/propertylist.rs b/core-foundation-sys/src/propertylist.rs index 0af9afb57..8a5e7c3fa 100644 --- a/core-foundation-sys/src/propertylist.rs +++ b/core-foundation-sys/src/propertylist.rs @@ -7,11 +7,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use base::{CFAllocatorRef, CFIndex, CFOptionFlags, CFTypeRef, Boolean}; +use base::{Boolean, CFAllocatorRef, CFIndex, CFOptionFlags, CFTypeRef}; use data::CFDataRef; use error::CFErrorRef; +use stream::{CFReadStreamRef, CFWriteStreamRef}; use string::CFStringRef; -use stream::{CFWriteStreamRef, CFReadStreamRef}; pub type CFPropertyListRef = CFTypeRef; @@ -37,18 +37,68 @@ extern "C" { */ /* Creating a Property List */ - pub fn CFPropertyListCreateWithData(allocator: CFAllocatorRef, data: CFDataRef, options: CFPropertyListMutabilityOptions, format: *mut CFPropertyListFormat, error: *mut CFErrorRef) -> CFPropertyListRef; - pub fn CFPropertyListCreateWithStream(allocator: CFAllocatorRef, stream: CFReadStreamRef, streamLength: CFIndex, options: CFOptionFlags, format: *mut CFPropertyListFormat, error: *mut CFErrorRef) -> CFPropertyListRef; - pub fn CFPropertyListCreateDeepCopy(allocator: CFAllocatorRef, propertyList: CFPropertyListRef, mutabilityOption: CFOptionFlags) -> CFPropertyListRef; - pub fn CFPropertyListCreateFromXMLData(allocator: CFAllocatorRef, xmlData: CFDataRef, mutabilityOption: CFOptionFlags, errorString: *mut CFStringRef) -> CFPropertyListRef; // deprecated - pub fn CFPropertyListCreateFromStream(allocator: CFAllocatorRef, stream: CFReadStreamRef, streamLength: CFIndex, mutabilityOption: CFOptionFlags, format: *mut CFPropertyListFormat, errorString: *mut CFStringRef) -> CFPropertyListRef; // deprecated + pub fn CFPropertyListCreateWithData( + allocator: CFAllocatorRef, + data: CFDataRef, + options: CFPropertyListMutabilityOptions, + format: *mut CFPropertyListFormat, + error: *mut CFErrorRef, + ) -> CFPropertyListRef; + pub fn CFPropertyListCreateWithStream( + allocator: CFAllocatorRef, + stream: CFReadStreamRef, + streamLength: CFIndex, + options: CFOptionFlags, + format: *mut CFPropertyListFormat, + error: *mut CFErrorRef, + ) -> CFPropertyListRef; + pub fn CFPropertyListCreateDeepCopy( + allocator: CFAllocatorRef, + propertyList: CFPropertyListRef, + mutabilityOption: CFOptionFlags, + ) -> CFPropertyListRef; + pub fn CFPropertyListCreateFromXMLData( + allocator: CFAllocatorRef, + xmlData: CFDataRef, + mutabilityOption: CFOptionFlags, + errorString: *mut CFStringRef, + ) -> CFPropertyListRef; // deprecated + pub fn CFPropertyListCreateFromStream( + allocator: CFAllocatorRef, + stream: CFReadStreamRef, + streamLength: CFIndex, + mutabilityOption: CFOptionFlags, + format: *mut CFPropertyListFormat, + errorString: *mut CFStringRef, + ) -> CFPropertyListRef; // deprecated /* Exporting a Property List */ - pub fn CFPropertyListCreateData(allocator: CFAllocatorRef, propertyList: CFPropertyListRef, format: CFPropertyListFormat, options: CFOptionFlags, error: *mut CFErrorRef) -> CFDataRef; - pub fn CFPropertyListWrite(propertyList: CFPropertyListRef, stream: CFWriteStreamRef, format: CFPropertyListFormat, options: CFOptionFlags, error: *mut CFErrorRef) -> CFIndex; - pub fn CFPropertyListCreateXMLData(allocator: CFAllocatorRef, propertyList: CFPropertyListRef) -> CFDataRef; // deprecated - pub fn CFPropertyListWriteToStream(propertyList: CFPropertyListRef, stream: CFWriteStreamRef, format: CFPropertyListFormat, errorString: *mut CFStringRef) -> CFIndex; + pub fn CFPropertyListCreateData( + allocator: CFAllocatorRef, + propertyList: CFPropertyListRef, + format: CFPropertyListFormat, + options: CFOptionFlags, + error: *mut CFErrorRef, + ) -> CFDataRef; + pub fn CFPropertyListWrite( + propertyList: CFPropertyListRef, + stream: CFWriteStreamRef, + format: CFPropertyListFormat, + options: CFOptionFlags, + error: *mut CFErrorRef, + ) -> CFIndex; + pub fn CFPropertyListCreateXMLData( + allocator: CFAllocatorRef, + propertyList: CFPropertyListRef, + ) -> CFDataRef; // deprecated + pub fn CFPropertyListWriteToStream( + propertyList: CFPropertyListRef, + stream: CFWriteStreamRef, + format: CFPropertyListFormat, + errorString: *mut CFStringRef, + ) -> CFIndex; /* Validating a Property List */ - pub fn CFPropertyListIsValid(plist: CFPropertyListRef, format: CFPropertyListFormat) -> Boolean; + pub fn CFPropertyListIsValid(plist: CFPropertyListRef, format: CFPropertyListFormat) + -> Boolean; } diff --git a/core-foundation-sys/src/runloop.rs b/core-foundation-sys/src/runloop.rs index 062b93cb1..9bc4896a9 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,20 +30,20 @@ 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)] @@ -51,14 +51,14 @@ pub const kCFRunLoopAllActivities: CFOptionFlags = 0x0FFFFFFF; 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)] @@ -66,21 +66,26 @@ pub struct CFRunLoopSourceContext { 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>, - - #[cfg(any(target_os="macos", target_os="ios"))] - pub getPort: extern "C" fn (info: *mut c_void) -> mach_port_t, - #[cfg(any(target_os="macos", target_os="ios"))] - pub perform: extern "C" fn (msg: *mut c_void, size: CFIndex, allocator: CFAllocatorRef, info: *mut c_void) -> *mut c_void, - - #[cfg(not(any(target_os="macos", target_os="ios")))] - pub getPort: extern "C" fn (info: *mut c_void) -> *mut c_void, - #[cfg(not(any(target_os="macos", target_os="ios")))] - pub perform: extern "C" fn (info: *mut c_void) -> *mut c_void, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, + pub equal: Option Boolean>, + pub hash: Option CFHashCode>, + + #[cfg(any(target_os = "macos", target_os = "ios"))] + pub getPort: extern "C" fn(info: *mut c_void) -> mach_port_t, + #[cfg(any(target_os = "macos", target_os = "ios"))] + pub perform: extern "C" fn( + msg: *mut c_void, + size: CFIndex, + allocator: CFAllocatorRef, + info: *mut c_void, + ) -> *mut c_void, + + #[cfg(not(any(target_os = "macos", target_os = "ios")))] + pub getPort: extern "C" fn(info: *mut c_void) -> *mut c_void, + #[cfg(not(any(target_os = "macos", target_os = "ios")))] + pub perform: extern "C" fn(info: *mut c_void) -> *mut c_void, } #[repr(C)] @@ -88,31 +93,32 @@ pub struct CFRunLoopSourceContext1 { 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)] #[derive(Clone, Copy, Debug)] 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 */ @@ -127,20 +133,40 @@ extern { /* Starting and Stopping a Run Loop */ 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 CFRunLoopWakeUp(rl: CFRunLoopRef); pub fn CFRunLoopStop(rl: CFRunLoopRef); pub fn CFRunLoopIsWaiting(rl: CFRunLoopRef) -> Boolean; /* Managing Sources */ pub fn CFRunLoopAddSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef); - pub fn CFRunLoopContainsSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef) -> Boolean; + pub fn CFRunLoopContainsSource( + rl: CFRunLoopRef, + source: CFRunLoopSourceRef, + mode: CFStringRef, + ) -> Boolean; pub fn CFRunLoopRemoveSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef); /* Managing Observers */ - pub fn CFRunLoopAddObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef); - pub fn CFRunLoopContainsObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef) -> Boolean; - pub fn CFRunLoopRemoveObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef); + pub fn CFRunLoopAddObserver( + rl: CFRunLoopRef, + observer: CFRunLoopObserverRef, + mode: CFStringRef, + ); + pub fn CFRunLoopContainsObserver( + rl: CFRunLoopRef, + observer: CFRunLoopObserverRef, + mode: CFStringRef, + ) -> Boolean; + pub fn CFRunLoopRemoveObserver( + rl: CFRunLoopRef, + observer: CFRunLoopObserverRef, + mode: CFStringRef, + ); /* Managing Run Loop Modes */ pub fn CFRunLoopAddCommonMode(rl: CFRunLoopRef, mode: CFStringRef); @@ -151,7 +177,11 @@ extern { pub fn CFRunLoopAddTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef); pub fn CFRunLoopGetNextTimerFireDate(rl: CFRunLoopRef, mode: CFStringRef) -> CFAbsoluteTime; pub fn CFRunLoopRemoveTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef); - pub fn CFRunLoopContainsTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef) -> Boolean; + pub fn CFRunLoopContainsTimer( + rl: CFRunLoopRef, + timer: CFRunLoopTimerRef, + mode: CFStringRef, + ) -> Boolean; /* Scheduling Blocks */ // fn CFRunLoopPerformBlock(rl: CFRunLoopRef, mode: CFTypeRef, block: void (^)(void)); @@ -161,22 +191,38 @@ extern { /* CFRunLoopSource */ /* CFRunLoopSource Miscellaneous Functions */ - pub fn CFRunLoopSourceCreate(allocator: CFAllocatorRef, order: CFIndex, context: *mut CFRunLoopSourceContext) -> CFRunLoopSourceRef; - pub fn CFRunLoopSourceGetContext(source: CFRunLoopSourceRef, context: *mut CFRunLoopSourceContext); + pub fn CFRunLoopSourceCreate( + allocator: CFAllocatorRef, + order: CFIndex, + context: *mut CFRunLoopSourceContext, + ) -> CFRunLoopSourceRef; + pub fn CFRunLoopSourceGetContext( + source: CFRunLoopSourceRef, + context: *mut CFRunLoopSourceContext, + ); pub fn CFRunLoopSourceGetOrder(source: CFRunLoopSourceRef) -> CFIndex; pub fn CFRunLoopSourceGetTypeID() -> CFTypeID; pub fn CFRunLoopSourceInvalidate(source: CFRunLoopSourceRef); pub fn CFRunLoopSourceIsValid(source: CFRunLoopSourceRef) -> Boolean; pub fn CFRunLoopSourceSignal(source: CFRunLoopSourceRef); - /* CFRunLoopObserver */ /* CFRunLoopObserver Miscellaneous Functions */ // fn CFRunLoopObserverCreateWithHandler(allocator: CFAllocatorRef, activities: CFOptionFlags, repeats: Boolean, order: CFIndex, block: void (^) (CFRunLoopObserverRef observer, CFRunLoopActivity activity)) -> CFRunLoopObserverRef; - 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; pub fn CFRunLoopObserverDoesRepeat(observer: CFRunLoopObserverRef) -> Boolean; pub fn CFRunLoopObserverGetActivities(observer: CFRunLoopObserverRef) -> CFOptionFlags; - pub fn CFRunLoopObserverGetContext(observer: CFRunLoopObserverRef, context: *mut CFRunLoopObserverContext); + pub fn CFRunLoopObserverGetContext( + observer: CFRunLoopObserverRef, + context: *mut CFRunLoopObserverContext, + ); pub fn CFRunLoopObserverGetOrder(observer: CFRunLoopObserverRef) -> CFIndex; pub fn CFRunLoopObserverGetTypeID() -> CFTypeID; pub fn CFRunLoopObserverInvalidate(observer: CFRunLoopObserverRef); @@ -185,7 +231,15 @@ extern { /* CFRunLoopTimer */ /* CFRunLoopTimer Miscellaneous Functions */ // fn CFRunLoopTimerCreateWithHandler(allocator: CFAllocatorRef, fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, block: void (^) (CFRunLoopTimerRef timer)) -> CFRunLoopTimerRef; - 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; pub fn CFRunLoopTimerDoesRepeat(timer: CFRunLoopTimerRef) -> Boolean; pub fn CFRunLoopTimerGetContext(timer: CFRunLoopTimerRef, context: *mut CFRunLoopTimerContext); pub fn CFRunLoopTimerGetInterval(timer: CFRunLoopTimerRef) -> CFTimeInterval; diff --git a/core-foundation-sys/src/set.rs b/core-foundation-sys/src/set.rs index 57440e352..127e3989a 100644 --- a/core-foundation-sys/src/set.rs +++ b/core-foundation-sys/src/set.rs @@ -9,15 +9,17 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, CFIndex, CFTypeID, Boolean, CFHashCode}; +use base::{Boolean, CFAllocatorRef, CFHashCode, CFIndex, CFTypeID}; use string::CFStringRef; -pub type CFSetApplierFunction = extern "C" fn (value: *const c_void, context: *const c_void); -pub type CFSetRetainCallBack = extern "C" fn (allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; -pub type CFSetReleaseCallBack = extern "C" fn (allocator: CFAllocatorRef, value: *const c_void); -pub type CFSetCopyDescriptionCallBack = extern "C" fn (value: *const c_void) -> CFStringRef; -pub type CFSetEqualCallBack = extern "C" fn (value1: *const c_void, value2: *const c_void) -> Boolean; -pub type CFSetHashCallBack = extern "C" fn (value: *const c_void) -> CFHashCode; +pub type CFSetApplierFunction = extern "C" fn(value: *const c_void, context: *const c_void); +pub type CFSetRetainCallBack = + extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; +pub type CFSetReleaseCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void); +pub type CFSetCopyDescriptionCallBack = extern "C" fn(value: *const c_void) -> CFStringRef; +pub type CFSetEqualCallBack = + extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; +pub type CFSetHashCallBack = extern "C" fn(value: *const c_void) -> CFHashCode; #[repr(C)] #[derive(Clone, Copy)] @@ -36,7 +38,7 @@ pub struct __CFSet(c_void); pub type CFSetRef = *const __CFSet; pub type CFMutableSetRef = *mut __CFSet; -extern { +extern "C" { /* * CFSet.h */ @@ -46,7 +48,12 @@ extern { /* CFSet */ /* 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 */ @@ -54,11 +61,19 @@ 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; @@ -66,8 +81,16 @@ extern { /* CFMutableSet */ /* CFMutableSet Miscellaneous Functions */ pub fn CFSetAddValue(theSet: CFMutableSetRef, value: *const c_void); - pub fn CFSetCreateMutable(allocator: CFAllocatorRef, capacity: CFIndex, callBacks: *const CFSetCallBacks) -> CFMutableSetRef; - pub fn CFSetCreateMutableCopy(allocator: CFAllocatorRef, capacity: CFIndex, theSet: CFSetRef) -> CFMutableSetRef; + pub fn CFSetCreateMutable( + allocator: CFAllocatorRef, + capacity: CFIndex, + callBacks: *const CFSetCallBacks, + ) -> CFMutableSetRef; + pub fn CFSetCreateMutableCopy( + allocator: CFAllocatorRef, + capacity: CFIndex, + theSet: CFSetRef, + ) -> CFMutableSetRef; pub fn CFSetRemoveAllValues(theSet: CFMutableSetRef); pub fn CFSetRemoveValue(theSet: CFMutableSetRef, value: *const c_void); pub fn CFSetReplaceValue(theSet: CFMutableSetRef, value: *const c_void); diff --git a/core-foundation-sys/src/socket.rs b/core-foundation-sys/src/socket.rs index a3d81c455..be9dc31f8 100644 --- a/core-foundation-sys/src/socket.rs +++ b/core-foundation-sys/src/socket.rs @@ -9,12 +9,12 @@ use std::os::raw::c_void; -use base::{CFIndex, CFOptionFlags, SInt32, CFTypeID, CFAllocatorRef, UInt16, Boolean}; +use base::{Boolean, CFAllocatorRef, CFIndex, CFOptionFlags, CFTypeID, SInt32, UInt16}; use data::CFDataRef; -use string::CFStringRef; use date::CFTimeInterval; -use runloop::CFRunLoopSourceRef; use propertylist::CFPropertyListRef; +use runloop::CFRunLoopSourceRef; +use string::CFStringRef; #[repr(C)] pub struct __CFSocket(c_void); @@ -23,7 +23,13 @@ pub type CFSocketRef = *mut __CFSocket; pub type CFSocketError = CFIndex; pub type CFSocketCallBackType = CFOptionFlags; -pub type CFSocketCallBack = extern "C" fn (s: CFSocketRef, _type: CFSocketCallBackType, address: CFDataRef, cdata: *const c_void, info: *mut c_void); +pub type CFSocketCallBack = extern "C" fn( + s: CFSocketRef, + _type: CFSocketCallBackType, + address: CFDataRef, + cdata: *const c_void, + info: *mut c_void, +); #[cfg(not(target_os = "windows"))] pub type CFSocketNativeHandle = std::os::raw::c_int; #[cfg(target_os = "windows")] @@ -39,7 +45,7 @@ pub struct CFSocketSignature { pub protocolFamily: SInt32, pub socketType: SInt32, pub protocol: SInt32, - pub address: CFDataRef + pub address: CFDataRef, } #[derive(Debug, Copy, Clone)] @@ -47,9 +53,9 @@ pub struct CFSocketSignature { pub struct CFSocketContext { pub version: CFIndex, pub info: *mut c_void, - pub retain: extern "C" fn (info: *const c_void) -> *const c_void, - pub release: extern "C" fn (info: *const c_void), - pub copyDescription: extern "C" fn (info: *const c_void) -> CFStringRef, + pub retain: extern "C" fn(info: *const c_void) -> *const c_void, + pub release: extern "C" fn(info: *const c_void), + pub copyDescription: extern "C" fn(info: *const c_void) -> CFStringRef, } pub const kCFSocketNoCallBack: CFSocketError = 0; @@ -66,7 +72,7 @@ pub const kCFSocketAutomaticallyReenableWriteCallBack: CFOptionFlags = 8; pub const kCFSocketLeaveErrors: CFOptionFlags = 64; pub const kCFSocketCloseOnInvalidate: CFOptionFlags = 128; -extern { +extern "C" { /* * CFSocket.h */ @@ -81,10 +87,37 @@ extern { pub static kCFSocketRetrieveCommand: CFStringRef; /* Creating Sockets */ - pub fn CFSocketCreate(allocator: CFAllocatorRef, protocolFamily: SInt32, socketType: SInt32, protocol: SInt32, callBackTypes: CFOptionFlags, callout: CFSocketCallBack, context: *const CFSocketContext) -> CFSocketRef; - pub fn CFSocketCreateConnectedToSocketSignature(allocator: CFAllocatorRef, signature: *const CFSocketSignature, callBackTypes: CFOptionFlags, callout: CFSocketCallBack, context: *const CFSocketContext, timeout: CFTimeInterval) -> CFSocketRef; - pub fn CFSocketCreateWithNative(allocator: CFAllocatorRef, sock: CFSocketNativeHandle, callBackTypes: CFOptionFlags, callout: CFSocketCallBack, context: *const CFSocketContext) -> CFSocketRef; - pub fn CFSocketCreateWithSocketSignature(allocator: CFAllocatorRef, signature: *const CFSocketSignature, callBackTypes: CFOptionFlags, callout: CFSocketCallBack, context: *const CFSocketContext) -> CFSocketRef; + pub fn CFSocketCreate( + allocator: CFAllocatorRef, + protocolFamily: SInt32, + socketType: SInt32, + protocol: SInt32, + callBackTypes: CFOptionFlags, + callout: CFSocketCallBack, + context: *const CFSocketContext, + ) -> CFSocketRef; + pub fn CFSocketCreateConnectedToSocketSignature( + allocator: CFAllocatorRef, + signature: *const CFSocketSignature, + callBackTypes: CFOptionFlags, + callout: CFSocketCallBack, + context: *const CFSocketContext, + timeout: CFTimeInterval, + ) -> CFSocketRef; + pub fn CFSocketCreateWithNative( + allocator: CFAllocatorRef, + sock: CFSocketNativeHandle, + callBackTypes: CFOptionFlags, + callout: CFSocketCallBack, + context: *const CFSocketContext, + ) -> CFSocketRef; + pub fn CFSocketCreateWithSocketSignature( + allocator: CFAllocatorRef, + signature: *const CFSocketSignature, + callBackTypes: CFOptionFlags, + callout: CFSocketCallBack, + context: *const CFSocketContext, + ) -> CFSocketRef; /* Configuring Sockets */ pub fn CFSocketCopyAddress(s: CFSocketRef) -> CFDataRef; @@ -98,19 +131,58 @@ extern { pub fn CFSocketSetSocketFlags(s: CFSocketRef, flags: CFOptionFlags); /* Using Sockets */ - pub fn CFSocketConnectToAddress(s: CFSocketRef, address: CFDataRef, timeout: CFTimeInterval) -> CFSocketError; - pub fn CFSocketCreateRunLoopSource(allocator: CFAllocatorRef, s: CFSocketRef, order: CFIndex) -> CFRunLoopSourceRef; + pub fn CFSocketConnectToAddress( + s: CFSocketRef, + address: CFDataRef, + timeout: CFTimeInterval, + ) -> CFSocketError; + pub fn CFSocketCreateRunLoopSource( + allocator: CFAllocatorRef, + s: CFSocketRef, + order: CFIndex, + ) -> CFRunLoopSourceRef; pub fn CFSocketGetTypeID() -> CFTypeID; pub fn CFSocketInvalidate(s: CFSocketRef); pub fn CFSocketIsValid(s: CFSocketRef) -> Boolean; - pub fn CFSocketSendData(s: CFSocketRef, address: CFDataRef, data: CFDataRef, timeout: CFTimeInterval) -> CFSocketError; + pub fn CFSocketSendData( + s: CFSocketRef, + address: CFDataRef, + data: CFDataRef, + timeout: CFTimeInterval, + ) -> CFSocketError; /* Socket Name Server Utilities */ - pub fn CFSocketCopyRegisteredSocketSignature(nameServerSignature: *const CFSocketSignature, timeout: CFTimeInterval, name: CFStringRef, signature: *mut CFSocketSignature, nameServerAddress: *mut CFDataRef) -> CFSocketError; - pub fn CFSocketCopyRegisteredValue(nameServerSignature: *const CFSocketSignature, timeout: CFTimeInterval, name: CFStringRef, value: *mut CFPropertyListRef, nameServerAddress: *mut CFDataRef) -> CFSocketError; + pub fn CFSocketCopyRegisteredSocketSignature( + nameServerSignature: *const CFSocketSignature, + timeout: CFTimeInterval, + name: CFStringRef, + signature: *mut CFSocketSignature, + nameServerAddress: *mut CFDataRef, + ) -> CFSocketError; + pub fn CFSocketCopyRegisteredValue( + nameServerSignature: *const CFSocketSignature, + timeout: CFTimeInterval, + name: CFStringRef, + value: *mut CFPropertyListRef, + nameServerAddress: *mut CFDataRef, + ) -> CFSocketError; pub fn CFSocketGetDefaultNameRegistryPortNumber() -> UInt16; - pub fn CFSocketRegisterSocketSignature(nameServerSignature: *const CFSocketSignature, timeout: CFTimeInterval, name: CFStringRef, signature: *const CFSocketSignature) -> CFSocketError; - pub fn CFSocketRegisterValue(nameServerSignature: *const CFSocketSignature, timeout: CFTimeInterval, name: CFStringRef, value: CFPropertyListRef) -> CFSocketError; + pub fn CFSocketRegisterSocketSignature( + nameServerSignature: *const CFSocketSignature, + timeout: CFTimeInterval, + name: CFStringRef, + signature: *const CFSocketSignature, + ) -> CFSocketError; + pub fn CFSocketRegisterValue( + nameServerSignature: *const CFSocketSignature, + timeout: CFTimeInterval, + name: CFStringRef, + value: CFPropertyListRef, + ) -> CFSocketError; pub fn CFSocketSetDefaultNameRegistryPortNumber(port: UInt16); - pub fn CFSocketUnregister(nameServerSignature: *const CFSocketSignature, timeout: CFTimeInterval, name: CFStringRef) -> CFSocketError; + pub fn CFSocketUnregister( + nameServerSignature: *const CFSocketSignature, + timeout: CFTimeInterval, + name: CFStringRef, + ) -> CFSocketError; } diff --git a/core-foundation-sys/src/stream.rs b/core-foundation-sys/src/stream.rs index 26816e16a..b35ca206c 100644 --- a/core-foundation-sys/src/stream.rs +++ b/core-foundation-sys/src/stream.rs @@ -7,14 +7,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::os::raw::{c_void, c_int}; +use std::os::raw::{c_int, c_void}; -use base::{CFIndex, CFOptionFlags, SInt32, CFTypeID, CFAllocatorRef, UInt8, Boolean, CFTypeRef, UInt32}; -use string::CFStringRef; -use url::CFURLRef; +use base::{ + Boolean, CFAllocatorRef, CFIndex, CFOptionFlags, CFTypeID, CFTypeRef, SInt32, UInt32, UInt8, +}; use error::CFErrorRef; use runloop::CFRunLoopRef; use socket::{CFSocketNativeHandle, CFSocketSignature}; +use string::CFStringRef; +use url::CFURLRef; #[repr(C)] pub struct __CFReadStream(c_void); @@ -33,7 +35,7 @@ pub type CFStreamErrorDomain = CFIndex; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct CFStreamError { pub domain: CFIndex, - pub error: SInt32 + pub error: SInt32, } /* CFStreamStatus: Constants that describe the status of a stream */ @@ -59,21 +61,28 @@ pub const kCFStreamEventCanAcceptBytes: CFStreamEventType = 4; pub const kCFStreamEventErrorOccurred: CFStreamEventType = 8; pub const kCFStreamEventEndEncountered: CFStreamEventType = 16; - #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct CFStreamClientContext { pub version: CFIndex, pub info: *mut c_void, - pub retain: extern "C" fn (info: *const c_void) -> *const c_void, - pub release: extern "C" fn (info: *const c_void), - pub copyDescription: extern "C" fn (info: *const c_void) -> CFStringRef, + pub retain: extern "C" fn(info: *const c_void) -> *const c_void, + pub release: extern "C" fn(info: *const c_void), + pub copyDescription: extern "C" fn(info: *const c_void) -> CFStringRef, } -pub type CFReadStreamClientCallBack = extern "C" fn (stream: CFReadStreamRef, _type: CFStreamEventType, clientCallBackInfo: *mut c_void); -pub type CFWriteStreamClientCallBack = extern "C" fn (stream: CFWriteStreamRef, _type: CFStreamEventType, clientCallBackInfo: *mut c_void); - -extern { +pub type CFReadStreamClientCallBack = extern "C" fn( + stream: CFReadStreamRef, + _type: CFStreamEventType, + clientCallBackInfo: *mut c_void, +); +pub type CFWriteStreamClientCallBack = extern "C" fn( + stream: CFWriteStreamRef, + _type: CFStreamEventType, + clientCallBackInfo: *mut c_void, +); + +extern "C" { /* * CFStream.h */ @@ -110,10 +119,31 @@ extern { pub static kCFStreamErrorDomainSSL: c_int; /* CFStream: Creating Streams */ - pub fn CFStreamCreatePairWithPeerSocketSignature(alloc: CFAllocatorRef, signature: *const CFSocketSignature,readStream: *mut CFReadStreamRef, writeStream: *mut CFWriteStreamRef); // deprecated - pub fn CFStreamCreatePairWithSocketToHost(alloc: CFAllocatorRef, host: CFStringRef, port: UInt32, readStream: *mut CFReadStreamRef, writeStream: *mut CFWriteStreamRef); // deprecated - pub fn CFStreamCreatePairWithSocket(alloc: CFAllocatorRef, sock: CFSocketNativeHandle, readStream: *mut CFReadStreamRef, writeStream: *mut CFWriteStreamRef); // deprecated - pub fn CFStreamCreateBoundPair(alloc: CFAllocatorRef, readStream: *mut CFReadStreamRef, writeStream: *mut CFWriteStreamRef, transferBufferSize: CFIndex); + pub fn CFStreamCreatePairWithPeerSocketSignature( + alloc: CFAllocatorRef, + signature: *const CFSocketSignature, + readStream: *mut CFReadStreamRef, + writeStream: *mut CFWriteStreamRef, + ); // deprecated + pub fn CFStreamCreatePairWithSocketToHost( + alloc: CFAllocatorRef, + host: CFStringRef, + port: UInt32, + readStream: *mut CFReadStreamRef, + writeStream: *mut CFWriteStreamRef, + ); // deprecated + pub fn CFStreamCreatePairWithSocket( + alloc: CFAllocatorRef, + sock: CFSocketNativeHandle, + readStream: *mut CFReadStreamRef, + writeStream: *mut CFWriteStreamRef, + ); // deprecated + pub fn CFStreamCreateBoundPair( + alloc: CFAllocatorRef, + readStream: *mut CFReadStreamRef, + writeStream: *mut CFWriteStreamRef, + transferBufferSize: CFIndex, + ); //pub fn CFReadStreamSetDispatchQueue(stream: CFReadStreamRef, q: dispatch_queue_t); // macos(10.9)+ //pub fn CFWriteStreamSetDispatchQueue(stream: CFWriteStreamRef, q: dispatch_queue_t); // macos(10.9)+ @@ -122,7 +152,12 @@ extern { /* CFReadStream */ /* Creating a Read Stream */ - pub fn CFReadStreamCreateWithBytesNoCopy(alloc: CFAllocatorRef, bytes: *const UInt8, length: CFIndex, bytesDeallocator: CFAllocatorRef) -> CFReadStreamRef; + pub fn CFReadStreamCreateWithBytesNoCopy( + alloc: CFAllocatorRef, + bytes: *const UInt8, + length: CFIndex, + bytesDeallocator: CFAllocatorRef, + ) -> CFReadStreamRef; pub fn CFReadStreamCreateWithFile(alloc: CFAllocatorRef, fileURL: CFURLRef) -> CFReadStreamRef; /* Opening and Closing a Read Stream */ @@ -130,54 +165,116 @@ extern { pub fn CFReadStreamOpen(stream: CFReadStreamRef) -> Boolean; /* Reading from a Stream */ - pub fn CFReadStreamRead(stream: CFReadStreamRef, buffer: *mut UInt8, bufferLength: CFIndex) -> CFIndex; + pub fn CFReadStreamRead( + stream: CFReadStreamRef, + buffer: *mut UInt8, + bufferLength: CFIndex, + ) -> CFIndex; /* Scheduling a Read Stream */ - pub fn CFReadStreamScheduleWithRunLoop(stream: CFReadStreamRef, runLoop: CFRunLoopRef, runLoopMode: CFStringRef); - pub fn CFReadStreamUnscheduleFromRunLoop(stream: CFReadStreamRef, runLoop: CFRunLoopRef, runLoopMode: CFStringRef); + pub fn CFReadStreamScheduleWithRunLoop( + stream: CFReadStreamRef, + runLoop: CFRunLoopRef, + runLoopMode: CFStringRef, + ); + pub fn CFReadStreamUnscheduleFromRunLoop( + stream: CFReadStreamRef, + runLoop: CFRunLoopRef, + runLoopMode: CFStringRef, + ); /* Examining Stream Properties */ - pub fn CFReadStreamCopyProperty(stream: CFReadStreamRef, propertyName: CFStreamPropertyKey) -> CFTypeRef; - pub fn CFReadStreamGetBuffer(stream: CFReadStreamRef, maxBytesToRead: CFIndex, numBytesRead: *mut CFIndex) -> *const UInt8; + pub fn CFReadStreamCopyProperty( + stream: CFReadStreamRef, + propertyName: CFStreamPropertyKey, + ) -> CFTypeRef; + pub fn CFReadStreamGetBuffer( + stream: CFReadStreamRef, + maxBytesToRead: CFIndex, + numBytesRead: *mut CFIndex, + ) -> *const UInt8; pub fn CFReadStreamCopyError(stream: CFReadStreamRef) -> CFErrorRef; pub fn CFReadStreamGetError(stream: CFReadStreamRef) -> CFStreamError; // deprecated pub fn CFReadStreamGetStatus(stream: CFReadStreamRef) -> CFStreamStatus; pub fn CFReadStreamHasBytesAvailable(stream: CFReadStreamRef) -> Boolean; /* Setting Stream Properties */ - pub fn CFReadStreamSetClient(stream: CFReadStreamRef, streamEvents: CFOptionFlags, clientCB: CFReadStreamClientCallBack, clientContext: *mut CFStreamClientContext) -> Boolean; - pub fn CFReadStreamSetProperty(stream: CFReadStreamRef, propertyName: CFStreamPropertyKey, propertyValue: CFTypeRef) -> Boolean; + pub fn CFReadStreamSetClient( + stream: CFReadStreamRef, + streamEvents: CFOptionFlags, + clientCB: CFReadStreamClientCallBack, + clientContext: *mut CFStreamClientContext, + ) -> Boolean; + pub fn CFReadStreamSetProperty( + stream: CFReadStreamRef, + propertyName: CFStreamPropertyKey, + propertyValue: CFTypeRef, + ) -> Boolean; /* Getting the CFReadStream Type ID */ pub fn CFReadStreamGetTypeID() -> CFTypeID; /* CFWriteStream */ /* Creating a Write Stream */ - pub fn CFWriteStreamCreateWithAllocatedBuffers(alloc: CFAllocatorRef, bufferAllocator: CFAllocatorRef) -> CFWriteStreamRef; - pub fn CFWriteStreamCreateWithBuffer(alloc: CFAllocatorRef, buffer: *mut UInt8, bufferCapacity: CFIndex) -> CFWriteStreamRef; - pub fn CFWriteStreamCreateWithFile(alloc: CFAllocatorRef, fileURL: CFURLRef) -> CFWriteStreamRef; + pub fn CFWriteStreamCreateWithAllocatedBuffers( + alloc: CFAllocatorRef, + bufferAllocator: CFAllocatorRef, + ) -> CFWriteStreamRef; + pub fn CFWriteStreamCreateWithBuffer( + alloc: CFAllocatorRef, + buffer: *mut UInt8, + bufferCapacity: CFIndex, + ) -> CFWriteStreamRef; + pub fn CFWriteStreamCreateWithFile( + alloc: CFAllocatorRef, + fileURL: CFURLRef, + ) -> CFWriteStreamRef; /* Opening and Closing a Stream */ pub fn CFWriteStreamClose(stream: CFWriteStreamRef); pub fn CFWriteStreamOpen(stream: CFWriteStreamRef) -> Boolean; /* Writing to a Stream */ - pub fn CFWriteStreamWrite(stream: CFWriteStreamRef, buffer: *const UInt8, bufferLength: CFIndex) -> CFIndex; + pub fn CFWriteStreamWrite( + stream: CFWriteStreamRef, + buffer: *const UInt8, + bufferLength: CFIndex, + ) -> CFIndex; /* Scheduling a Write Stream */ - pub fn CFWriteStreamScheduleWithRunLoop(stream: CFWriteStreamRef, runLoop: CFRunLoopRef, runLoopMode: CFStringRef); - pub fn CFWriteStreamUnscheduleFromRunLoop(stream: CFWriteStreamRef, runLoop: CFRunLoopRef, runLoopMode: CFStringRef); + pub fn CFWriteStreamScheduleWithRunLoop( + stream: CFWriteStreamRef, + runLoop: CFRunLoopRef, + runLoopMode: CFStringRef, + ); + pub fn CFWriteStreamUnscheduleFromRunLoop( + stream: CFWriteStreamRef, + runLoop: CFRunLoopRef, + runLoopMode: CFStringRef, + ); /* Examining Stream Properties */ pub fn CFWriteStreamCanAcceptBytes(stream: CFWriteStreamRef) -> Boolean; - pub fn CFWriteStreamCopyProperty(stream: CFWriteStreamRef, propertyName: CFStreamPropertyKey) -> CFTypeRef; + pub fn CFWriteStreamCopyProperty( + stream: CFWriteStreamRef, + propertyName: CFStreamPropertyKey, + ) -> CFTypeRef; pub fn CFWriteStreamCopyError(stream: CFWriteStreamRef) -> CFErrorRef; pub fn CFWriteStreamGetError(stream: CFWriteStreamRef) -> CFStreamError; // deprecated pub fn CFWriteStreamGetStatus(stream: CFWriteStreamRef) -> CFStreamStatus; /* Setting Stream Properties */ - pub fn CFWriteStreamSetClient(stream: CFWriteStreamRef, streamEvents: CFOptionFlags, clientCB: CFWriteStreamClientCallBack, clientContext: *mut CFStreamClientContext) -> Boolean; - pub fn CFWriteStreamSetProperty(stream: CFWriteStreamRef, propertyName: CFStreamPropertyKey, propertyValue: CFTypeRef) -> Boolean; + pub fn CFWriteStreamSetClient( + stream: CFWriteStreamRef, + streamEvents: CFOptionFlags, + clientCB: CFWriteStreamClientCallBack, + clientContext: *mut CFStreamClientContext, + ) -> Boolean; + pub fn CFWriteStreamSetProperty( + stream: CFWriteStreamRef, + propertyName: CFStreamPropertyKey, + propertyValue: CFTypeRef, + ) -> Boolean; /* Getting the CFWriteStream Type ID */ pub fn CFWriteStreamGetTypeID() -> CFTypeID; diff --git a/core-foundation-sys/src/string.rs b/core-foundation-sys/src/string.rs index 46a94bee5..03e54dedb 100644 --- a/core-foundation-sys/src/string.rs +++ b/core-foundation-sys/src/string.rs @@ -7,13 +7,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::os::raw::{c_char, c_void, c_ulong, c_double, c_ushort}; -use base::{Boolean, CFOptionFlags, CFIndex, CFAllocatorRef, ConstStr255Param, CFRange, CFTypeID, SInt32, UInt32, UInt8, CFComparisonResult, StringPtr, ConstStringPtr, UTF32Char}; use array::CFArrayRef; +use base::{ + Boolean, CFAllocatorRef, CFComparisonResult, CFIndex, CFOptionFlags, CFRange, CFTypeID, + ConstStr255Param, ConstStringPtr, SInt32, StringPtr, UInt32, UInt8, UTF32Char, +}; +use characterset::CFCharacterSetRef; use data::CFDataRef; use dictionary::CFDictionaryRef; -use characterset::CFCharacterSetRef; use locale::CFLocaleRef; +use std::os::raw::{c_char, c_double, c_ulong, c_ushort, c_void}; pub type CFStringCompareFlags = CFOptionFlags; pub const kCFCompareCaseInsensitive: CFStringCompareFlags = 1; @@ -203,7 +206,7 @@ pub fn CFStringInitInlineBuffer(str: CFStringRef, buf: *mut CFStringInlineBuffer pub fn CFStringGetCharacterFromInlineBuffer(buf: *mut CFStringInlineBuffer, idx: CFIndex) -> UniChar; */ -extern { +extern "C" { /* * CFString.h */ @@ -213,52 +216,203 @@ extern { /* CFString */ /* Creating a CFString */ //fn CFSTR - pub fn CFStringCreateArrayBySeparatingStrings(alloc: CFAllocatorRef, theString: CFStringRef, separatorString: CFStringRef) -> CFArrayRef; - pub fn CFStringCreateByCombiningStrings(alloc: CFAllocatorRef, theArray: CFArrayRef, separatorString: CFStringRef) -> CFStringRef; + pub fn CFStringCreateArrayBySeparatingStrings( + alloc: CFAllocatorRef, + theString: CFStringRef, + separatorString: CFStringRef, + ) -> CFArrayRef; + pub fn CFStringCreateByCombiningStrings( + alloc: CFAllocatorRef, + theArray: CFArrayRef, + separatorString: CFStringRef, + ) -> CFStringRef; pub fn CFStringCreateCopy(alloc: CFAllocatorRef, theString: CFStringRef) -> CFStringRef; - pub fn CFStringCreateFromExternalRepresentation(alloc: CFAllocatorRef, data: CFDataRef, encoding: CFStringEncoding) -> CFStringRef; - pub fn CFStringCreateWithBytes(alloc: CFAllocatorRef, bytes: *const UInt8, numBytes: CFIndex, encoding: CFStringEncoding, isExternalRepresentation: Boolean) -> CFStringRef; - pub fn CFStringCreateWithBytesNoCopy(alloc: CFAllocatorRef, bytes: *const UInt8, numBytes: CFIndex, encoding: CFStringEncoding, isExternalRepresentation: Boolean, contentsDeallocator: CFAllocatorRef) -> CFStringRef; - pub fn CFStringCreateWithCharacters(alloc: CFAllocatorRef, chars: *const UniChar, numChars: CFIndex) -> 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; - pub fn CFStringCreateWithCStringNoCopy(alloc: CFAllocatorRef, cStr: *const c_char, encoding: CFStringEncoding, contentsDeallocator: CFAllocatorRef) -> CFStringRef; - pub fn CFStringCreateWithFormat(alloc: CFAllocatorRef, formatOptions: CFDictionaryRef, format: CFStringRef, ...) -> CFStringRef; + pub fn CFStringCreateFromExternalRepresentation( + alloc: CFAllocatorRef, + data: CFDataRef, + encoding: CFStringEncoding, + ) -> CFStringRef; + pub fn CFStringCreateWithBytes( + alloc: CFAllocatorRef, + bytes: *const UInt8, + numBytes: CFIndex, + encoding: CFStringEncoding, + isExternalRepresentation: Boolean, + ) -> CFStringRef; + pub fn CFStringCreateWithBytesNoCopy( + alloc: CFAllocatorRef, + bytes: *const UInt8, + numBytes: CFIndex, + encoding: CFStringEncoding, + isExternalRepresentation: Boolean, + contentsDeallocator: CFAllocatorRef, + ) -> CFStringRef; + pub fn CFStringCreateWithCharacters( + alloc: CFAllocatorRef, + chars: *const UniChar, + numChars: CFIndex, + ) -> 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; + pub fn CFStringCreateWithCStringNoCopy( + alloc: CFAllocatorRef, + cStr: *const c_char, + encoding: CFStringEncoding, + contentsDeallocator: CFAllocatorRef, + ) -> CFStringRef; + pub fn CFStringCreateWithFormat( + alloc: CFAllocatorRef, + formatOptions: CFDictionaryRef, + format: CFStringRef, + ... + ) -> CFStringRef; //pub fn CFStringCreateWithFormatAndArguments(alloc: CFAllocatorRef, formatOptions: CFDictionaryRef, format: CFStringRef, arguments: va_list) -> CFStringRef; - pub fn CFStringCreateWithPascalString(alloc: CFAllocatorRef, pStr: ConstStr255Param, encoding: CFStringEncoding) -> CFStringRef; - pub fn CFStringCreateWithPascalStringNoCopy(alloc: CFAllocatorRef, pStr: ConstStr255Param, encoding: CFStringEncoding, contentsDeallocator: CFAllocatorRef) -> CFStringRef; - pub fn CFStringCreateWithSubstring(alloc: CFAllocatorRef, str: CFStringRef, range: CFRange) -> CFStringRef; + pub fn CFStringCreateWithPascalString( + alloc: CFAllocatorRef, + pStr: ConstStr255Param, + encoding: CFStringEncoding, + ) -> CFStringRef; + pub fn CFStringCreateWithPascalStringNoCopy( + alloc: CFAllocatorRef, + pStr: ConstStr255Param, + encoding: CFStringEncoding, + contentsDeallocator: CFAllocatorRef, + ) -> CFStringRef; + pub fn CFStringCreateWithSubstring( + alloc: CFAllocatorRef, + str: CFStringRef, + range: CFRange, + ) -> CFStringRef; /* Searching Strings */ - pub fn CFStringCreateArrayWithFindResults(alloc: CFAllocatorRef, theString: CFStringRef, stringToFind: CFStringRef, rangeToSearch: CFRange, compareOptions: CFStringCompareFlags) -> CFArrayRef; - pub fn CFStringFind(theString: CFStringRef, stringToFind: CFStringRef, compareOptions: CFStringCompareFlags) -> CFRange; - pub fn CFStringFindCharacterFromSet(theString: CFStringRef, theSet: CFCharacterSetRef, rangeToSearch: CFRange, searchOptions: CFStringCompareFlags, result: *mut CFRange) -> Boolean; - pub fn CFStringFindWithOptions(theString: CFStringRef, stringToFind: CFStringRef, rangeToSearch: CFRange, searchOptions: CFStringCompareFlags, result: *mut CFRange) -> Boolean; - pub fn CFStringFindWithOptionsAndLocale(theString: CFStringRef, stringToFind: CFStringRef, rangeToSearch: CFRange, searchOptions: CFStringCompareFlags, locale: CFLocaleRef, result: *mut CFRange) -> Boolean; - pub fn CFStringGetLineBounds(theString: CFStringRef, range: CFRange, lineBeginIndex: *mut CFIndex, lineEndIndex: *mut CFIndex, contentsEndIndex: *mut CFIndex); + pub fn CFStringCreateArrayWithFindResults( + alloc: CFAllocatorRef, + theString: CFStringRef, + stringToFind: CFStringRef, + rangeToSearch: CFRange, + compareOptions: CFStringCompareFlags, + ) -> CFArrayRef; + pub fn CFStringFind( + theString: CFStringRef, + stringToFind: CFStringRef, + compareOptions: CFStringCompareFlags, + ) -> CFRange; + pub fn CFStringFindCharacterFromSet( + theString: CFStringRef, + theSet: CFCharacterSetRef, + rangeToSearch: CFRange, + searchOptions: CFStringCompareFlags, + result: *mut CFRange, + ) -> Boolean; + pub fn CFStringFindWithOptions( + theString: CFStringRef, + stringToFind: CFStringRef, + rangeToSearch: CFRange, + searchOptions: CFStringCompareFlags, + result: *mut CFRange, + ) -> Boolean; + pub fn CFStringFindWithOptionsAndLocale( + theString: CFStringRef, + stringToFind: CFStringRef, + rangeToSearch: CFRange, + searchOptions: CFStringCompareFlags, + locale: CFLocaleRef, + result: *mut CFRange, + ) -> Boolean; + pub fn CFStringGetLineBounds( + theString: CFStringRef, + range: CFRange, + lineBeginIndex: *mut CFIndex, + lineEndIndex: *mut CFIndex, + contentsEndIndex: *mut CFIndex, + ); /* Comparing Strings */ - pub fn CFStringCompare(theString1: CFStringRef, theString2: CFStringRef, compareOptions: CFStringCompareFlags) -> CFComparisonResult; - pub fn CFStringCompareWithOptions(theString1: CFStringRef, theString2: CFStringRef, rangeToCompare: CFRange, compareOptions: CFStringCompareFlags) -> CFComparisonResult; - pub fn CFStringCompareWithOptionsAndLocale(theString1: CFStringRef, theString2: CFStringRef, rangeToCompare: CFRange, compareOptions: CFStringCompareFlags, locale: CFLocaleRef) -> CFComparisonResult; + pub fn CFStringCompare( + theString1: CFStringRef, + theString2: CFStringRef, + compareOptions: CFStringCompareFlags, + ) -> CFComparisonResult; + pub fn CFStringCompareWithOptions( + theString1: CFStringRef, + theString2: CFStringRef, + rangeToCompare: CFRange, + compareOptions: CFStringCompareFlags, + ) -> CFComparisonResult; + pub fn CFStringCompareWithOptionsAndLocale( + theString1: CFStringRef, + theString2: CFStringRef, + rangeToCompare: CFRange, + compareOptions: CFStringCompareFlags, + locale: CFLocaleRef, + ) -> CFComparisonResult; pub fn CFStringHasPrefix(theString: CFStringRef, prefix: CFStringRef) -> Boolean; pub fn CFStringHasSuffix(theString: CFStringRef, suffix: CFStringRef) -> Boolean; /* Accessing Characters */ - pub fn CFStringCreateExternalRepresentation(alloc: CFAllocatorRef, theString: CFStringRef, encoding: CFStringEncoding, lossByte: UInt8) -> CFDataRef; - pub fn CFStringGetBytes(theString: CFStringRef, range: CFRange, encoding: CFStringEncoding, lossByte: UInt8, isExternalRepresentation: Boolean, buffer: *mut UInt8, maxBufLen: CFIndex, usedBufLen: *mut CFIndex) -> CFIndex; + pub fn CFStringCreateExternalRepresentation( + alloc: CFAllocatorRef, + theString: CFStringRef, + encoding: CFStringEncoding, + lossByte: UInt8, + ) -> CFDataRef; + pub fn CFStringGetBytes( + theString: CFStringRef, + range: CFRange, + encoding: CFStringEncoding, + lossByte: UInt8, + isExternalRepresentation: Boolean, + buffer: *mut UInt8, + maxBufLen: CFIndex, + usedBufLen: *mut CFIndex, + ) -> CFIndex; pub fn CFStringGetCharacterAtIndex(theString: CFStringRef, idx: CFIndex) -> UniChar; pub fn CFStringGetCharacters(theString: CFStringRef, range: CFRange, buffer: *mut UniChar); pub fn CFStringGetCharactersPtr(theString: CFStringRef) -> *const UniChar; - 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; - pub fn CFStringGetPascalString(theString: CFStringRef, buffer: StringPtr, bufferSize: CFIndex, encoding: CFStringEncoding) -> Boolean; - pub fn CFStringGetPascalStringPtr(theString: CFStringRef, encoding: CFStringEncoding) -> ConstStringPtr; - pub fn CFStringGetRangeOfComposedCharactersAtIndex(theString: CFStringRef, theIndex: CFIndex) -> CFRange; + pub fn CFStringGetPascalString( + theString: CFStringRef, + buffer: StringPtr, + bufferSize: CFIndex, + encoding: CFStringEncoding, + ) -> Boolean; + pub fn CFStringGetPascalStringPtr( + theString: CFStringRef, + encoding: CFStringEncoding, + ) -> ConstStringPtr; + pub fn CFStringGetRangeOfComposedCharactersAtIndex( + theString: CFStringRef, + theIndex: CFIndex, + ) -> CFRange; /* Working With Hyphenation */ - pub fn CFStringGetHyphenationLocationBeforeIndex(string: CFStringRef, location: CFIndex, limitRange: CFRange, options: CFOptionFlags, locale: CFLocaleRef, character: *mut UTF32Char) -> CFIndex; + pub fn CFStringGetHyphenationLocationBeforeIndex( + string: CFStringRef, + location: CFIndex, + limitRange: CFRange, + options: CFOptionFlags, + locale: CFLocaleRef, + character: *mut UTF32Char, + ) -> CFIndex; pub fn CFStringIsHyphenationAvailableForLocale(locale: CFLocaleRef) -> Boolean; /* Working With Encodings */ @@ -270,8 +424,13 @@ extern { pub fn CFStringConvertWindowsCodepageToEncoding(codepage: UInt32) -> CFStringEncoding; pub fn CFStringGetFastestEncoding(theString: CFStringRef) -> CFStringEncoding; pub fn CFStringGetListOfAvailableEncodings() -> *const CFStringEncoding; - pub fn CFStringGetMaximumSizeForEncoding(length: CFIndex, encoding: CFStringEncoding) -> CFIndex; - pub fn CFStringGetMostCompatibleMacStringEncoding(encoding: CFStringEncoding) -> CFStringEncoding; + pub fn CFStringGetMaximumSizeForEncoding( + length: CFIndex, + encoding: CFStringEncoding, + ) -> CFIndex; + pub fn CFStringGetMostCompatibleMacStringEncoding( + encoding: CFStringEncoding, + ) -> CFStringEncoding; pub fn CFStringGetNameOfEncoding(encoding: CFStringEncoding) -> CFStringRef; pub fn CFStringGetSmallestEncoding(theString: CFStringRef) -> CFStringEncoding; pub fn CFStringGetSystemEncoding() -> CFStringEncoding; @@ -286,36 +445,101 @@ extern { pub fn CFStringGetTypeID() -> CFTypeID; /* String File System Representations */ - pub fn CFStringCreateWithFileSystemRepresentation(alloc: CFAllocatorRef, buffer: *const c_char) -> CFStringRef; - pub fn CFStringGetFileSystemRepresentation(string: CFStringRef, buffer: *mut c_char, maxBufLen: CFIndex) -> Boolean; + pub fn CFStringCreateWithFileSystemRepresentation( + alloc: CFAllocatorRef, + buffer: *const c_char, + ) -> CFStringRef; + pub fn CFStringGetFileSystemRepresentation( + string: CFStringRef, + buffer: *mut c_char, + maxBufLen: CFIndex, + ) -> Boolean; pub fn CFStringGetMaximumSizeOfFileSystemRepresentation(string: CFStringRef) -> CFIndex; /* Getting Paragraph Bounds */ - pub fn CFStringGetParagraphBounds(string: CFStringRef, range: CFRange, parBeginIndex: *mut CFIndex, parEndIndex: *mut CFIndex, contentsEndIndex: *mut CFIndex); + pub fn CFStringGetParagraphBounds( + string: CFStringRef, + range: CFRange, + parBeginIndex: *mut CFIndex, + parEndIndex: *mut CFIndex, + contentsEndIndex: *mut CFIndex, + ); /* CFMutableString */ /* CFMutableString Miscellaneous Functions */ pub fn CFStringAppend(theString: CFMutableStringRef, appendedString: CFStringRef); - pub fn CFStringAppendCharacters(theString: CFMutableStringRef, chars: *const UniChar, numChars: CFIndex); - pub fn CFStringAppendCString(theString: CFMutableStringRef, cStr: *const c_char, encoding: CFStringEncoding); - pub fn CFStringAppendFormat(theString: CFMutableStringRef, formatOptions: CFDictionaryRef, format: CFStringRef, ...); + pub fn CFStringAppendCharacters( + theString: CFMutableStringRef, + chars: *const UniChar, + numChars: CFIndex, + ); + pub fn CFStringAppendCString( + theString: CFMutableStringRef, + cStr: *const c_char, + encoding: CFStringEncoding, + ); + pub fn CFStringAppendFormat( + theString: CFMutableStringRef, + formatOptions: CFDictionaryRef, + format: CFStringRef, + ... + ); //pub fn CFStringAppendFormatAndArguments(theString: CFMutableStringRef, formatOptions: CFDictionaryRef, format: CFStringRef, arguments: va_list); - pub fn CFStringAppendPascalString(theString: CFMutableStringRef, pStr: ConstStr255Param, encoding: CFStringEncoding); + pub fn CFStringAppendPascalString( + theString: CFMutableStringRef, + pStr: ConstStr255Param, + encoding: CFStringEncoding, + ); pub fn CFStringCapitalize(theString: CFMutableStringRef, locale: CFLocaleRef); pub fn CFStringCreateMutable(alloc: CFAllocatorRef, maxLength: CFIndex) -> CFMutableStringRef; - pub fn CFStringCreateMutableCopy(alloc: CFAllocatorRef, maxLength: CFIndex, theString: CFStringRef) -> CFMutableStringRef; - pub fn CFStringCreateMutableWithExternalCharactersNoCopy(alloc: CFAllocatorRef, chars: *mut UniChar, numChars: CFIndex, capacity: CFIndex, externalCharactersAllocator: CFAllocatorRef) -> CFMutableStringRef; + pub fn CFStringCreateMutableCopy( + alloc: CFAllocatorRef, + maxLength: CFIndex, + theString: CFStringRef, + ) -> CFMutableStringRef; + pub fn CFStringCreateMutableWithExternalCharactersNoCopy( + alloc: CFAllocatorRef, + chars: *mut UniChar, + numChars: CFIndex, + capacity: CFIndex, + externalCharactersAllocator: CFAllocatorRef, + ) -> CFMutableStringRef; pub fn CFStringDelete(theString: CFMutableStringRef, range: CFRange); - pub fn CFStringFindAndReplace(theString: CFMutableStringRef, stringToFind: CFStringRef, replacementString: CFStringRef, rangeToSearch: CFRange, compareOptions: CFStringCompareFlags) -> CFIndex; - pub fn CFStringFold(theString: CFMutableStringRef, theFlags: CFStringCompareFlags, theLocale: CFLocaleRef); + pub fn CFStringFindAndReplace( + theString: CFMutableStringRef, + stringToFind: CFStringRef, + replacementString: CFStringRef, + rangeToSearch: CFRange, + compareOptions: CFStringCompareFlags, + ) -> CFIndex; + pub fn CFStringFold( + theString: CFMutableStringRef, + theFlags: CFStringCompareFlags, + theLocale: CFLocaleRef, + ); pub fn CFStringInsert(str: CFMutableStringRef, idx: CFIndex, insertedStr: CFStringRef); pub fn CFStringLowercase(theString: CFMutableStringRef, locale: CFLocaleRef); pub fn CFStringNormalize(theString: CFMutableStringRef, theForm: CFStringNormalizationForm); - pub fn CFStringPad(theString: CFMutableStringRef, padString: CFStringRef, length: CFIndex, indexIntoPad: CFIndex); + pub fn CFStringPad( + theString: CFMutableStringRef, + padString: CFStringRef, + length: CFIndex, + indexIntoPad: CFIndex, + ); pub fn CFStringReplace(theString: CFMutableStringRef, range: CFRange, replacement: CFStringRef); pub fn CFStringReplaceAll(theString: CFMutableStringRef, replacement: CFStringRef); - pub fn CFStringSetExternalCharactersNoCopy(theString: CFMutableStringRef, chars: *mut UniChar, length: CFIndex, capacity: CFIndex); - pub fn CFStringTransform(string: CFMutableStringRef, range: *mut CFRange, transform: CFStringRef, reverse: Boolean) -> Boolean; + pub fn CFStringSetExternalCharactersNoCopy( + theString: CFMutableStringRef, + chars: *mut UniChar, + length: CFIndex, + capacity: CFIndex, + ); + pub fn CFStringTransform( + string: CFMutableStringRef, + range: *mut CFRange, + transform: CFStringRef, + reverse: Boolean, + ) -> Boolean; pub fn CFStringTrim(theString: CFMutableStringRef, trimString: CFStringRef); pub fn CFStringTrimWhitespace(theString: CFMutableStringRef); pub fn CFStringUppercase(theString: CFMutableStringRef, locale: CFLocaleRef); diff --git a/core-foundation-sys/src/string_tokenizer.rs b/core-foundation-sys/src/string_tokenizer.rs index f4c23d4a4..45382cbeb 100644 --- a/core-foundation-sys/src/string_tokenizer.rs +++ b/core-foundation-sys/src/string_tokenizer.rs @@ -9,10 +9,10 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, CFTypeID, CFRange, CFIndex, CFOptionFlags, CFTypeRef}; -use string::CFStringRef; -use locale::CFLocaleRef; use array::CFMutableArrayRef; +use base::{CFAllocatorRef, CFIndex, CFOptionFlags, CFRange, CFTypeID, CFTypeRef}; +use locale::CFLocaleRef; +use string::CFStringRef; #[repr(C)] pub struct __CFStringTokenizer(c_void); @@ -37,28 +37,54 @@ pub const kCFStringTokenizerUnitWordBoundary: CFOptionFlags = 4; pub const kCFStringTokenizerAttributeLatinTranscription: CFOptionFlags = 1 << 16; pub const kCFStringTokenizerAttributeLanguage: CFOptionFlags = 1 << 17; -extern { +extern "C" { /* * CFStringTokenizer.h */ /* Creating a Tokenizer */ - pub fn CFStringTokenizerCreate(alloc: CFAllocatorRef, string: CFStringRef, range: CFRange, options: CFOptionFlags, locale: CFLocaleRef) -> CFStringTokenizerRef; + pub fn CFStringTokenizerCreate( + alloc: CFAllocatorRef, + string: CFStringRef, + range: CFRange, + options: CFOptionFlags, + locale: CFLocaleRef, + ) -> CFStringTokenizerRef; /* Setting the String */ - pub fn CFStringTokenizerSetString(tokenizer: CFStringTokenizerRef, string: CFStringRef, range: CFRange); + pub fn CFStringTokenizerSetString( + tokenizer: CFStringTokenizerRef, + string: CFStringRef, + range: CFRange, + ); /* Changing the Location */ - pub fn CFStringTokenizerAdvanceToNextToken(tokenizer: CFStringTokenizerRef) -> CFStringTokenizerTokenType; - pub fn CFStringTokenizerGoToTokenAtIndex(tokenizer: CFStringTokenizerRef, index: CFIndex) -> CFStringTokenizerTokenType; + pub fn CFStringTokenizerAdvanceToNextToken( + tokenizer: CFStringTokenizerRef, + ) -> CFStringTokenizerTokenType; + pub fn CFStringTokenizerGoToTokenAtIndex( + tokenizer: CFStringTokenizerRef, + index: CFIndex, + ) -> CFStringTokenizerTokenType; /* Getting Information About the Current Token */ - pub fn CFStringTokenizerCopyCurrentTokenAttribute(tokenizer: CFStringTokenizerRef, attribute: CFOptionFlags) -> CFTypeRef; + pub fn CFStringTokenizerCopyCurrentTokenAttribute( + tokenizer: CFStringTokenizerRef, + attribute: CFOptionFlags, + ) -> CFTypeRef; pub fn CFStringTokenizerGetCurrentTokenRange(tokenizer: CFStringTokenizerRef) -> CFRange; - pub fn CFStringTokenizerGetCurrentSubTokens(tokenizer: CFStringTokenizerRef, ranges: *mut CFRange, maxRangeLength: CFIndex, derivedSubTokens: CFMutableArrayRef) -> CFIndex; + pub fn CFStringTokenizerGetCurrentSubTokens( + tokenizer: CFStringTokenizerRef, + ranges: *mut CFRange, + maxRangeLength: CFIndex, + derivedSubTokens: CFMutableArrayRef, + ) -> CFIndex; /* Identifying a Language */ - pub fn CFStringTokenizerCopyBestStringLanguage(string: CFStringRef, range: CFRange) -> CFStringRef; + pub fn CFStringTokenizerCopyBestStringLanguage( + string: CFStringRef, + range: CFRange, + ) -> CFStringRef; /* Getting the CFStringTokenizer Type ID */ pub fn CFStringTokenizerGetTypeID() -> CFTypeID; diff --git a/core-foundation-sys/src/timezone.rs b/core-foundation-sys/src/timezone.rs index 91e7ed0b1..95fbc9e71 100644 --- a/core-foundation-sys/src/timezone.rs +++ b/core-foundation-sys/src/timezone.rs @@ -9,14 +9,14 @@ use std::os::raw::c_void; -use base::{CFAllocatorRef, CFTypeID, Boolean, CFIndex}; -use date::{CFTimeInterval, CFAbsoluteTime}; -use string::CFStringRef; use array::CFArrayRef; -use dictionary::CFDictionaryRef; +use base::{Boolean, CFAllocatorRef, CFIndex, CFTypeID}; use data::CFDataRef; +use date::{CFAbsoluteTime, CFTimeInterval}; +use dictionary::CFDictionaryRef; use locale::CFLocaleRef; use notification_center::CFNotificationName; +use string::CFStringRef; #[repr(C)] pub struct __CFTimeZone(c_void); @@ -32,7 +32,7 @@ pub const kCFTimeZoneNameStyleShortDaylightSaving: CFTimeZoneNameStyle = 3; pub const kCFTimeZoneNameStyleGeneric: CFTimeZoneNameStyle = 4; pub const kCFTimeZoneNameStyleShortGeneric: CFTimeZoneNameStyle = 5; -extern { +extern "C" { /* * CFTimeZone.h */ @@ -40,9 +40,20 @@ extern { pub static kCFTimeZoneSystemTimeZoneDidChangeNotification: CFNotificationName; /* Creating a Time Zone */ - pub fn CFTimeZoneCreate(allocator: CFAllocatorRef, name: CFStringRef, data: CFDataRef) -> CFTimeZoneRef; - pub fn CFTimeZoneCreateWithName(allocator: CFAllocatorRef, name: CFStringRef, tryAbbrev: Boolean) -> CFTimeZoneRef; - pub fn CFTimeZoneCreateWithTimeIntervalFromGMT(allocator: CFAllocatorRef, interval: CFTimeInterval) -> CFTimeZoneRef; + pub fn CFTimeZoneCreate( + allocator: CFAllocatorRef, + name: CFStringRef, + data: CFDataRef, + ) -> CFTimeZoneRef; + pub fn CFTimeZoneCreateWithName( + allocator: CFAllocatorRef, + name: CFStringRef, + tryAbbrev: Boolean, + ) -> CFTimeZoneRef; + pub fn CFTimeZoneCreateWithTimeIntervalFromGMT( + allocator: CFAllocatorRef, + interval: CFTimeInterval, + ) -> CFTimeZoneRef; /* System and Default Time Zones and Information */ pub fn CFTimeZoneCopyAbbreviationDictionary() -> CFDictionaryRef; @@ -56,14 +67,24 @@ extern { /* Getting Information About Time Zones */ pub fn CFTimeZoneGetName(tz: CFTimeZoneRef) -> CFStringRef; - pub fn CFTimeZoneCopyLocalizedName(tz: CFTimeZoneRef, style: CFTimeZoneNameStyle, locale: CFLocaleRef) -> CFStringRef; + pub fn CFTimeZoneCopyLocalizedName( + tz: CFTimeZoneRef, + style: CFTimeZoneNameStyle, + locale: CFLocaleRef, + ) -> CFStringRef; pub fn CFTimeZoneGetSecondsFromGMT(tz: CFTimeZoneRef, time: CFAbsoluteTime) -> CFTimeInterval; pub fn CFTimeZoneGetData(tz: CFTimeZoneRef) -> CFDataRef; /* Getting Daylight Savings Time Information */ pub fn CFTimeZoneIsDaylightSavingTime(tz: CFTimeZoneRef, at: CFAbsoluteTime) -> Boolean; - pub fn CFTimeZoneGetDaylightSavingTimeOffset(tz: CFTimeZoneRef, at: CFAbsoluteTime) -> CFTimeInterval; - pub fn CFTimeZoneGetNextDaylightSavingTimeTransition(tz: CFTimeZoneRef, at: CFAbsoluteTime) -> CFAbsoluteTime; + pub fn CFTimeZoneGetDaylightSavingTimeOffset( + tz: CFTimeZoneRef, + at: CFAbsoluteTime, + ) -> CFTimeInterval; + pub fn CFTimeZoneGetNextDaylightSavingTimeTransition( + tz: CFTimeZoneRef, + at: CFAbsoluteTime, + ) -> CFAbsoluteTime; /* Getting the CFTimeZone Type ID */ pub fn CFTimeZoneGetTypeID() -> CFTypeID; diff --git a/core-foundation-sys/src/tree.rs b/core-foundation-sys/src/tree.rs index ddc5fdf74..8219a7c9e 100644 --- a/core-foundation-sys/src/tree.rs +++ b/core-foundation-sys/src/tree.rs @@ -9,17 +9,17 @@ use std::os::raw::c_void; -use base::{CFIndex, CFTypeID, CFAllocatorRef, CFComparatorFunction}; +use base::{CFAllocatorRef, CFComparatorFunction, CFIndex, CFTypeID}; use string::CFStringRef; #[repr(C)] pub struct __CFTree(c_void); pub type CFTreeRef = *mut __CFTree; -pub type CFTreeRetainCallBack = extern "C" fn (info: *const c_void) -> *const c_void; -pub type CFTreeReleaseCallBack = extern "C" fn (info: *const c_void); -pub type CFTreeCopyDescriptionCallBack = extern "C" fn (info: *const c_void) -> CFStringRef; -pub type CFTreeApplierFunction = extern "C" fn (value: *const c_void, context: *mut c_void); +pub type CFTreeRetainCallBack = extern "C" fn(info: *const c_void) -> *const c_void; +pub type CFTreeReleaseCallBack = extern "C" fn(info: *const c_void); +pub type CFTreeCopyDescriptionCallBack = extern "C" fn(info: *const c_void) -> CFStringRef; +pub type CFTreeApplierFunction = extern "C" fn(value: *const c_void, context: *mut c_void); #[repr(C)] pub struct CFTreeContext { @@ -27,10 +27,10 @@ pub struct CFTreeContext { pub info: *mut c_void, pub retain: CFTreeRetainCallBack, pub release: CFTreeReleaseCallBack, - pub copyDescription: CFTreeCopyDescriptionCallBack + pub copyDescription: CFTreeCopyDescriptionCallBack, } -extern { +extern "C" { /* * CFTree.h */ @@ -46,7 +46,11 @@ extern { pub fn CFTreeSetContext(tree: CFTreeRef, context: *const CFTreeContext); /* Sorting a Tree */ - pub fn CFTreeSortChildren(tree: CFTreeRef, comparator: CFComparatorFunction, context: *mut c_void); + pub fn CFTreeSortChildren( + tree: CFTreeRef, + comparator: CFComparatorFunction, + context: *mut c_void, + ); /* Examining a Tree */ pub fn CFTreeFindRoot(tree: CFTreeRef) -> CFTreeRef; @@ -59,7 +63,11 @@ extern { pub fn CFTreeGetParent(tree: CFTreeRef) -> CFTreeRef; /* Performing an Operation on Tree Elements */ - pub fn CFTreeApplyFunctionToChildren(tree: CFTreeRef, applier: CFTreeApplierFunction, context: *mut c_void); + pub fn CFTreeApplyFunctionToChildren( + tree: CFTreeRef, + applier: CFTreeApplierFunction, + context: *mut c_void, + ); /* Getting the Tree Type ID */ pub fn CFTreeGetTypeID() -> CFTypeID; diff --git a/core-foundation-sys/src/url.rs b/core-foundation-sys/src/url.rs index 75235fcb6..e98a4d7f3 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, CFRange}; -use data::CFDataRef; use array::CFArrayRef; +use base::{Boolean, CFAllocatorRef, CFIndex, CFOptionFlags, CFRange, 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; /* Bookmark Data Creation Options */ @@ -38,11 +38,11 @@ pub static kCFURLBookmarkCreationMinimalBookmarkMask: CFURLBookmarkCreationOptio pub static kCFURLBookmarkCreationSuitableForBookmarkFile: CFURLBookmarkCreationOptions = (1u32 << 10) as usize; -#[cfg(target_os="macos")] +#[cfg(target_os = "macos")] pub static kCFURLBookmarkCreationWithSecurityScope: CFURLBookmarkCreationOptions = (1u32 << 11) as usize; -#[cfg(target_os="macos")] +#[cfg(target_os = "macos")] pub static kCFURLBookmarkCreationSecurityScopeAllowOnlyReadAccess: CFURLBookmarkCreationOptions = (1u32 << 12) as usize; @@ -63,20 +63,24 @@ pub const kCFURLComponentPassword: CFIndex = 6; pub const kCFURLComponentUserInfo: CFIndex = 7; pub const kCFURLComponentHost: CFIndex = 8; pub const kCFURLComponentPort: CFIndex = 9; -pub const kCFURLComponentParameterString: CFIndex= 10; +pub const kCFURLComponentParameterString: CFIndex = 10; pub const kCFURLComponentQuery: CFIndex = 11; pub const kCFURLComponentFragment: CFIndex = 12; /* Bookmark Data Resolution Options */ -pub const kCFURLBookmarkResolutionWithoutUIMask: CFURLBookmarkResolutionOptions = ( 1u32 << 8 ) as usize; -pub const kCFURLBookmarkResolutionWithoutMountingMask: CFURLBookmarkResolutionOptions = ( 1u32 << 9 ) as usize; -#[cfg(target_os="macos")] -pub const kCFURLBookmarkResolutionWithSecurityScope: CFURLBookmarkResolutionOptions = ( 1u32 << 10 ) as usize; +pub const kCFURLBookmarkResolutionWithoutUIMask: CFURLBookmarkResolutionOptions = + (1u32 << 8) as usize; +pub const kCFURLBookmarkResolutionWithoutMountingMask: CFURLBookmarkResolutionOptions = + (1u32 << 9) as usize; +#[cfg(target_os = "macos")] +pub const kCFURLBookmarkResolutionWithSecurityScope: CFURLBookmarkResolutionOptions = + (1u32 << 10) as usize; //pub const kCFURLBookmarkResolutionWithoutImplicitStartAccessing: CFURLBookmarkResolutionOptions = ( 1u32 << 15 ) as usize; // macos(11.2)+ -pub const kCFBookmarkResolutionWithoutUIMask: CFURLBookmarkResolutionOptions = ( 1u32 << 8 ) as usize; -pub const kCFBookmarkResolutionWithoutMountingMask: CFURLBookmarkResolutionOptions = ( 1u32 << 9 ) as usize; +pub const kCFBookmarkResolutionWithoutUIMask: CFURLBookmarkResolutionOptions = (1u32 << 8) as usize; +pub const kCFBookmarkResolutionWithoutMountingMask: CFURLBookmarkResolutionOptions = + (1u32 << 9) as usize; -extern { +extern "C" { /* * CFURL.h */ @@ -128,13 +132,13 @@ extern { pub static kCFURLIsExecutableKey: CFStringRef; pub static kCFURLFileSecurityKey: 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 kCFURLTagNamesKey: CFStringRef; //macos(10.9)+ - #[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 kCFURLPathKey: CFStringRef; // macos(10.8)+ + pub static kCFURLPathKey: CFStringRef; // macos(10.8)+ pub static kCFURLCanonicalPathKey: CFStringRef; // macos(10.12)+ pub static kCFURLIsMountTriggerKey: CFStringRef; @@ -228,10 +232,10 @@ extern { pub static kCFURLUbiquitousItemIsUploadingKey: CFStringRef; pub static kCFURLUbiquitousItemPercentDownloadedKey: CFStringRef; // deprecated pub static kCFURLUbiquitousItemPercentUploadedKey: CFStringRef; // deprecated - // pub static kCFURLUbiquitousItemDownloadingStatusKey: CFStringRef; // macos(10.9)+ - // pub static kCFURLUbiquitousItemDownloadingErrorKey: CFStringRef; // macos(10.9)+ - // pub static kCFURLUbiquitousItemUploadingErrorKey: CFStringRef; // macos(10.9)+ - // pub static kCFURLUbiquitousItemIsExcludedFromSyncKey: CFStringRef; // macos(11.3)+ + // pub static kCFURLUbiquitousItemDownloadingStatusKey: CFStringRef; // macos(10.9)+ + // pub static kCFURLUbiquitousItemDownloadingErrorKey: CFStringRef; // macos(10.9)+ + // pub static kCFURLUbiquitousItemUploadingErrorKey: CFStringRef; // macos(10.9)+ + // pub static kCFURLUbiquitousItemIsExcludedFromSyncKey: CFStringRef; // macos(11.3)+ /* The values returned for kCFURLUbiquitousItemDownloadingStatusKey */ // pub static kCFURLUbiquitousItemDownloadingStatusNotDownloaded: CFStringRef; // macos(10.9)+ @@ -243,34 +247,111 @@ extern { /* 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 CFURLCreateCopyAppendingPathComponent(allocator: CFAllocatorRef, url: CFURLRef, pathComponent: CFStringRef, isDirectory: Boolean) -> CFURLRef; - pub fn CFURLCreateCopyAppendingPathExtension(allocator: CFAllocatorRef, url: CFURLRef, extension: CFStringRef) -> CFURLRef; - pub fn CFURLCreateCopyDeletingLastPathComponent(allocator: CFAllocatorRef, url: CFURLRef) -> CFURLRef; - pub fn CFURLCreateCopyDeletingPathExtension(allocator: CFAllocatorRef, url: CFURLRef) -> CFURLRef; - pub fn CFURLCreateFilePathURL(allocator: CFAllocatorRef, url: CFURLRef, error: *mut CFErrorRef) -> CFURLRef; - pub fn CFURLCreateFileReferenceURL(allocator: CFAllocatorRef, url: CFURLRef, error: *mut CFErrorRef) -> CFURLRef; - pub fn CFURLCreateFromFileSystemRepresentation(allocator: CFAllocatorRef, buffer: *const u8, bufLen: CFIndex, isDirectory: Boolean) -> CFURLRef; - pub fn CFURLCreateFromFileSystemRepresentationRelativeToBase(allocator: CFAllocatorRef, buffer: *const u8, bufLen: CFIndex, isDirectory: Boolean, baseURL: 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 CFURLCreateCopyAppendingPathComponent( + allocator: CFAllocatorRef, + url: CFURLRef, + pathComponent: CFStringRef, + isDirectory: Boolean, + ) -> CFURLRef; + pub fn CFURLCreateCopyAppendingPathExtension( + allocator: CFAllocatorRef, + url: CFURLRef, + extension: CFStringRef, + ) -> CFURLRef; + pub fn CFURLCreateCopyDeletingLastPathComponent( + allocator: CFAllocatorRef, + url: CFURLRef, + ) -> CFURLRef; + pub fn CFURLCreateCopyDeletingPathExtension( + allocator: CFAllocatorRef, + url: CFURLRef, + ) -> CFURLRef; + pub fn CFURLCreateFilePathURL( + allocator: CFAllocatorRef, + url: CFURLRef, + error: *mut CFErrorRef, + ) -> CFURLRef; + pub fn CFURLCreateFileReferenceURL( + allocator: CFAllocatorRef, + url: CFURLRef, + error: *mut CFErrorRef, + ) -> CFURLRef; + pub fn CFURLCreateFromFileSystemRepresentation( + allocator: CFAllocatorRef, + buffer: *const u8, + bufLen: CFIndex, + isDirectory: Boolean, + ) -> CFURLRef; + pub fn CFURLCreateFromFileSystemRepresentationRelativeToBase( + allocator: CFAllocatorRef, + buffer: *const u8, + bufLen: CFIndex, + isDirectory: Boolean, + baseURL: CFURLRef, + ) -> CFURLRef; //pub fn CFURLCreateFromFSRef(allocator: CFAllocatorRef, fsRef: *const FSRef) -> 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; - pub fn CFURLCreateWithString(allocator: CFAllocatorRef, URLString: CFStringRef, 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; + pub 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; // deprecated + pub fn CFURLCopyParameterString( + anURL: CFURLRef, + charactersToLeaveEscaped: CFStringRef, + ) -> CFStringRef; // deprecated 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; @@ -279,11 +360,36 @@ extern { pub fn CFURLHasDirectoryPath(anURL: CFURLRef) -> Boolean; /* Converting URLs to Other Representations */ - pub fn CFURLCreateData(allocator: CFAllocatorRef, url: CFURLRef, encoding: CFStringEncoding, escapeWhitespace: Boolean) -> CFDataRef; - pub fn CFURLCreateStringByAddingPercentEscapes(allocator: CFAllocatorRef, originalString: CFStringRef, charactersToLeaveUnescaped: CFStringRef, legalURLCharactersToBeEscaped: CFStringRef, encoding: CFStringEncoding) -> CFStringRef; // API_DEPRECATED("Use [NSString stringByAddingPercentEncodingWithAllowedCharacters:] instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent (since each URL component or subcomponent has different rules for what characters are valid).", macos(10.0,10.11), ios(2.0,9.0), watchos(2.0,2.0), tvos(9.0,9.0)); - pub fn CFURLCreateStringByReplacingPercentEscapes(allocator: CFAllocatorRef, originalString: CFStringRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; - pub fn CFURLCreateStringByReplacingPercentEscapesUsingEncoding(allocator: CFAllocatorRef, origString: CFStringRef, charsToLeaveEscaped: CFStringRef, encoding: CFStringEncoding) -> CFStringRef; // deprecated - pub fn CFURLGetFileSystemRepresentation(anURL: CFURLRef, resolveAgainstBase: Boolean, buffer: *mut u8, maxBufLen: CFIndex) -> Boolean; + pub fn CFURLCreateData( + allocator: CFAllocatorRef, + url: CFURLRef, + encoding: CFStringEncoding, + escapeWhitespace: Boolean, + ) -> CFDataRef; + pub fn CFURLCreateStringByAddingPercentEscapes( + allocator: CFAllocatorRef, + originalString: CFStringRef, + charactersToLeaveUnescaped: CFStringRef, + legalURLCharactersToBeEscaped: CFStringRef, + encoding: CFStringEncoding, + ) -> CFStringRef; // API_DEPRECATED("Use [NSString stringByAddingPercentEncodingWithAllowedCharacters:] instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent (since each URL component or subcomponent has different rules for what characters are valid).", macos(10.0,10.11), ios(2.0,9.0), watchos(2.0,2.0), tvos(9.0,9.0)); + pub fn CFURLCreateStringByReplacingPercentEscapes( + allocator: CFAllocatorRef, + originalString: CFStringRef, + charactersToLeaveEscaped: CFStringRef, + ) -> CFStringRef; + pub fn CFURLCreateStringByReplacingPercentEscapesUsingEncoding( + allocator: CFAllocatorRef, + origString: CFStringRef, + charsToLeaveEscaped: CFStringRef, + encoding: CFStringEncoding, + ) -> CFStringRef; // deprecated + pub fn CFURLGetFileSystemRepresentation( + anURL: CFURLRef, + resolveAgainstBase: Boolean, + buffer: *mut u8, + maxBufLen: CFIndex, + ) -> Boolean; //pub fn CFURLIsFileReferenceURL(url: CFURLRef) -> Boolean; // macos(10.9)+ //pub fn CFURLGetFSRef(url: CFURLRef, fsRef: *mut FSRef) -> Boolean; pub fn CFURLGetString(anURL: CFURLRef) -> CFStringRef; @@ -291,35 +397,83 @@ extern { /* Getting URL Properties */ pub fn CFURLGetBaseURL(anURL: CFURLRef) -> CFURLRef; pub fn CFURLGetBytes(anURL: CFURLRef, buffer: *mut u8, bufferLength: CFIndex) -> CFIndex; - pub fn CFURLGetByteRangeForComponent(url: CFURLRef, component:CFURLComponentType, rangeIncludingSeparators: *mut CFRange) -> CFRange; + pub fn CFURLGetByteRangeForComponent( + url: CFURLRef, + component: CFURLComponentType, + rangeIncludingSeparators: *mut CFRange, + ) -> CFRange; pub fn CFURLGetTypeID() -> CFTypeID; pub fn CFURLResourceIsReachable(url: CFURLRef, error: *mut CFErrorRef) -> Boolean; /* Getting and Setting File System Resource Properties */ pub fn CFURLClearResourcePropertyCache(url: CFURLRef); pub fn CFURLClearResourcePropertyCacheForKey(url: CFURLRef, key: CFStringRef); - pub fn CFURLCopyResourcePropertiesForKeys(url: CFURLRef, keys: CFArrayRef, error: *mut CFErrorRef) -> CFDictionaryRef; + pub fn CFURLCopyResourcePropertiesForKeys( + url: CFURLRef, + keys: CFArrayRef, + error: *mut CFErrorRef, + ) -> CFDictionaryRef; //pub fn CFURLCopyResourcePropertyForKey(url: CFURLRef, key: CFStringRef, propertyValueTypeRefPtr: *mut c_void, error: *mut CFErrorRef) -> Boolean - pub fn CFURLCreateResourcePropertiesForKeysFromBookmarkData(allocator: CFAllocatorRef, resourcePropertiesToReturn: CFArrayRef, bookmark: CFDataRef) -> CFDictionaryRef; - pub fn CFURLCreateResourcePropertyForKeyFromBookmarkData(allocator: CFAllocatorRef, resourcePropertyKey: CFStringRef, bookmark: CFDataRef) -> CFTypeRef; - pub fn CFURLSetResourcePropertiesForKeys(url: CFURLRef, keyedPropertyValues: CFDictionaryRef, error: *mut CFErrorRef) -> Boolean; - pub fn CFURLSetResourcePropertyForKey(url: CFURLRef, key: CFStringRef, value: CFTypeRef, error: *mut CFErrorRef) -> Boolean; - pub fn CFURLSetTemporaryResourcePropertyForKey(url: CFURLRef, key: CFStringRef, propertyValue: CFTypeRef); + pub fn CFURLCreateResourcePropertiesForKeysFromBookmarkData( + allocator: CFAllocatorRef, + resourcePropertiesToReturn: CFArrayRef, + bookmark: CFDataRef, + ) -> CFDictionaryRef; + pub fn CFURLCreateResourcePropertyForKeyFromBookmarkData( + allocator: CFAllocatorRef, + resourcePropertyKey: CFStringRef, + bookmark: CFDataRef, + ) -> CFTypeRef; + pub fn CFURLSetResourcePropertiesForKeys( + url: CFURLRef, + keyedPropertyValues: CFDictionaryRef, + error: *mut CFErrorRef, + ) -> Boolean; + pub fn CFURLSetResourcePropertyForKey( + url: CFURLRef, + key: CFStringRef, + value: CFTypeRef, + error: *mut CFErrorRef, + ) -> Boolean; + pub fn CFURLSetTemporaryResourcePropertyForKey( + url: CFURLRef, + key: CFStringRef, + propertyValue: CFTypeRef, + ); /* Working with Bookmark Data */ - pub fn CFURLCreateBookmarkData(allocator: CFAllocatorRef, url: CFURLRef, options: CFURLBookmarkCreationOptions, resourcePropertiesToInclude: CFArrayRef, relativeToURL: CFURLRef, error: *mut CFErrorRef) -> CFDataRef; - - #[cfg(target_os="macos")] - pub fn CFURLCreateBookmarkDataFromAliasRecord(allocator: CFAllocatorRef, aliasRecordDataRef: CFDataRef) -> CFDataRef; // deprecated - - 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; + + #[cfg(target_os = "macos")] + pub fn CFURLCreateBookmarkDataFromAliasRecord( + allocator: CFAllocatorRef, + aliasRecordDataRef: CFDataRef, + ) -> CFDataRef; // deprecated + + 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/url_enumerator.rs b/core-foundation-sys/src/url_enumerator.rs index 553426625..7b15a414a 100644 --- a/core-foundation-sys/src/url_enumerator.rs +++ b/core-foundation-sys/src/url_enumerator.rs @@ -9,10 +9,10 @@ use std::os::raw::c_void; -use base::{CFOptionFlags, CFIndex, CFTypeID, CFAllocatorRef, Boolean}; -use url::CFURLRef; -use error::CFErrorRef; use array::CFArrayRef; +use base::{Boolean, CFAllocatorRef, CFIndex, CFOptionFlags, CFTypeID}; +use error::CFErrorRef; +use url::CFURLRef; #[repr(C)] pub struct __CFURLEnumerator(c_void); @@ -35,14 +35,27 @@ pub const kCFURLEnumeratorEnd: CFURLEnumeratorOptions = 2; pub const kCFURLEnumeratorError: CFURLEnumeratorOptions = 3; pub const kCFURLEnumeratorDirectoryPostOrderSuccess: CFURLEnumeratorOptions = 4; -extern { +extern "C" { /* * CFURLEnumerator.h */ pub fn CFURLEnumeratorGetTypeID() -> CFTypeID; - pub fn CFURLEnumeratorCreateForDirectoryURL(alloc: CFAllocatorRef, directoryURL: CFURLRef, option: CFURLEnumeratorOptions, propertyKeys: CFArrayRef) -> CFURLEnumeratorRef; - pub fn CFURLEnumeratorCreateForMountedVolumes(alloc: CFAllocatorRef, option: CFURLEnumeratorOptions, propertyKeys: CFArrayRef) -> CFURLEnumeratorRef; - pub fn CFURLEnumeratorGetNextURL(enumerator: CFURLEnumeratorRef, url: *mut CFURLRef, error: *mut CFErrorRef) -> CFURLEnumeratorResult; + pub fn CFURLEnumeratorCreateForDirectoryURL( + alloc: CFAllocatorRef, + directoryURL: CFURLRef, + option: CFURLEnumeratorOptions, + propertyKeys: CFArrayRef, + ) -> CFURLEnumeratorRef; + pub fn CFURLEnumeratorCreateForMountedVolumes( + alloc: CFAllocatorRef, + option: CFURLEnumeratorOptions, + propertyKeys: CFArrayRef, + ) -> CFURLEnumeratorRef; + pub fn CFURLEnumeratorGetNextURL( + enumerator: CFURLEnumeratorRef, + url: *mut CFURLRef, + error: *mut CFErrorRef, + ) -> CFURLEnumeratorResult; pub fn CFURLEnumeratorSkipDescendents(enumerator: CFURLEnumeratorRef); pub fn CFURLEnumeratorGetDescendentLevel(enumerator: CFURLEnumeratorRef) -> CFIndex; pub fn CFURLEnumeratorGetSourceDidChange(enumerator: CFURLEnumeratorRef) -> Boolean; // deprecated since macos 10.7 diff --git a/core-foundation-sys/src/user_notification.rs b/core-foundation-sys/src/user_notification.rs index 0e01856bb..654b35cd6 100644 --- a/core-foundation-sys/src/user_notification.rs +++ b/core-foundation-sys/src/user_notification.rs @@ -9,17 +9,18 @@ use std::os::raw::c_void; -use base::{CFOptionFlags, CFIndex, CFAllocatorRef, CFTypeID, SInt32}; -use dictionary::CFDictionaryRef; -use string::CFStringRef; +use base::{CFAllocatorRef, CFIndex, CFOptionFlags, CFTypeID, SInt32}; use date::CFTimeInterval; +use dictionary::CFDictionaryRef; use runloop::CFRunLoopSourceRef; +use string::CFStringRef; use url::CFURLRef; #[repr(C)] pub struct __CFUserNotification(c_void); -pub type CFUserNotificationCallBack = extern "C" fn (userNotification: CFUserNotificationRef, responseFlags: CFOptionFlags); +pub type CFUserNotificationCallBack = + extern "C" fn(userNotification: CFUserNotificationRef, responseFlags: CFOptionFlags); pub type CFUserNotificationRef = *mut __CFUserNotification; /* Alert Levels */ @@ -53,8 +54,7 @@ pub fn CFUserNotificationPopUpSelection(n: CFIndex) -> CFOptionFlags { (n << 24) as CFOptionFlags } - -extern { +extern "C" { /* * CFUserNotification.h */ @@ -79,13 +79,60 @@ extern { /* CFUserNotification Miscellaneous Functions */ pub fn CFUserNotificationCancel(userNotification: CFUserNotificationRef) -> SInt32; - pub fn CFUserNotificationCreate(allocator: CFAllocatorRef, timeout: CFTimeInterval, flags: CFOptionFlags, error: *mut SInt32, dictionary: CFDictionaryRef) -> CFUserNotificationRef; - pub fn CFUserNotificationCreateRunLoopSource(allocator: CFAllocatorRef, userNotification: CFUserNotificationRef, callout: CFUserNotificationCallBack, order: CFIndex) -> CFRunLoopSourceRef; - pub fn CFUserNotificationDisplayAlert(timeout: CFTimeInterval, flags: CFOptionFlags, iconURL: CFURLRef, soundURL: CFURLRef, localizationURL: CFURLRef, alertHeader: CFStringRef, alertMessage: CFStringRef, defaultButtonTitle: CFStringRef, alternateButtonTitle: CFStringRef, otherButtonTitle: CFStringRef, responseFlags: *mut CFOptionFlags) -> SInt32; - pub fn CFUserNotificationDisplayNotice(timeout: CFTimeInterval, flags: CFOptionFlags, iconURL: CFURLRef, soundURL: CFURLRef, localizationURL: CFURLRef, alertHeader: CFStringRef, alertMessage: CFStringRef, defaultButtonTitle: CFStringRef) -> SInt32; + pub fn CFUserNotificationCreate( + allocator: CFAllocatorRef, + timeout: CFTimeInterval, + flags: CFOptionFlags, + error: *mut SInt32, + dictionary: CFDictionaryRef, + ) -> CFUserNotificationRef; + pub fn CFUserNotificationCreateRunLoopSource( + allocator: CFAllocatorRef, + userNotification: CFUserNotificationRef, + callout: CFUserNotificationCallBack, + order: CFIndex, + ) -> CFRunLoopSourceRef; + pub fn CFUserNotificationDisplayAlert( + timeout: CFTimeInterval, + flags: CFOptionFlags, + iconURL: CFURLRef, + soundURL: CFURLRef, + localizationURL: CFURLRef, + alertHeader: CFStringRef, + alertMessage: CFStringRef, + defaultButtonTitle: CFStringRef, + alternateButtonTitle: CFStringRef, + otherButtonTitle: CFStringRef, + responseFlags: *mut CFOptionFlags, + ) -> SInt32; + pub fn CFUserNotificationDisplayNotice( + timeout: CFTimeInterval, + flags: CFOptionFlags, + iconURL: CFURLRef, + soundURL: CFURLRef, + localizationURL: CFURLRef, + alertHeader: CFStringRef, + alertMessage: CFStringRef, + defaultButtonTitle: CFStringRef, + ) -> SInt32; pub fn CFUserNotificationGetTypeID() -> CFTypeID; - pub fn CFUserNotificationGetResponseDictionary(userNotification: CFUserNotificationRef) -> CFDictionaryRef; - pub fn CFUserNotificationGetResponseValue(userNotification: CFUserNotificationRef, key: CFStringRef, idx: CFIndex) -> CFStringRef; - pub fn CFUserNotificationReceiveResponse(userNotification: CFUserNotificationRef, timeout: CFTimeInterval, responseFlags: *mut CFOptionFlags) -> SInt32; - pub fn CFUserNotificationUpdate(userNotification: CFUserNotificationRef, timeout: CFTimeInterval, flags: CFOptionFlags, dictionary: CFDictionaryRef) -> SInt32; + pub fn CFUserNotificationGetResponseDictionary( + userNotification: CFUserNotificationRef, + ) -> CFDictionaryRef; + pub fn CFUserNotificationGetResponseValue( + userNotification: CFUserNotificationRef, + key: CFStringRef, + idx: CFIndex, + ) -> CFStringRef; + pub fn CFUserNotificationReceiveResponse( + userNotification: CFUserNotificationRef, + timeout: CFTimeInterval, + responseFlags: *mut CFOptionFlags, + ) -> SInt32; + pub fn CFUserNotificationUpdate( + userNotification: CFUserNotificationRef, + timeout: CFTimeInterval, + flags: CFOptionFlags, + dictionary: CFDictionaryRef, + ) -> SInt32; } diff --git a/core-foundation-sys/src/uuid.rs b/core-foundation-sys/src/uuid.rs index d04c711d2..dc1edfbde 100644 --- a/core-foundation-sys/src/uuid.rs +++ b/core-foundation-sys/src/uuid.rs @@ -20,25 +20,25 @@ pub type CFUUIDRef = *const __CFUUID; #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, 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 */ @@ -47,11 +47,47 @@ extern { pub fn CFUUIDCreate(allocator: CFAllocatorRef) -> CFUUIDRef; pub fn CFUUIDCreateFromString(alloc: CFAllocatorRef, uuidStr: CFStringRef) -> CFUUIDRef; pub fn CFUUIDCreateFromUUIDBytes(allocator: CFAllocatorRef, bytes: CFUUIDBytes) -> CFUUIDRef; - pub fn CFUUIDCreateWithBytes(alloc: CFAllocatorRef, byte0: u8, byte1: u8, byte2: u8, byte3: u8, byte4: u8, byte5: u8, byte6: u8, byte7: u8, byte8: u8, byte9: u8, byte10: u8, byte11: u8, byte12: u8, byte13: u8, byte14: u8, byte15: u8) -> CFUUIDRef; + pub fn CFUUIDCreateWithBytes( + alloc: CFAllocatorRef, + byte0: u8, + byte1: u8, + byte2: u8, + byte3: u8, + byte4: u8, + byte5: u8, + byte6: u8, + byte7: u8, + byte8: u8, + byte9: u8, + byte10: u8, + byte11: u8, + byte12: u8, + byte13: u8, + byte14: u8, + byte15: u8, + ) -> CFUUIDRef; /* Getting Information About CFUUID Objects */ pub fn CFUUIDCreateString(allocator: CFAllocatorRef, uid: CFUUIDRef) -> CFStringRef; - pub fn CFUUIDGetConstantUUIDWithBytes(alloc: CFAllocatorRef, byte0: u8, byte1: u8, byte2: u8, byte3: u8, byte4: u8, byte5: u8, byte6: u8, byte7: u8, byte8: u8, byte9: u8, byte10: u8, byte11: u8, byte12: u8, byte13: u8, byte14: u8, byte15: u8) -> CFUUIDRef; + pub fn CFUUIDGetConstantUUIDWithBytes( + alloc: CFAllocatorRef, + byte0: u8, + byte1: u8, + byte2: u8, + byte3: u8, + byte4: u8, + byte5: u8, + byte6: u8, + byte7: u8, + byte8: u8, + byte9: u8, + byte10: u8, + byte11: u8, + byte12: u8, + byte13: u8, + byte14: u8, + byte15: u8, + ) -> CFUUIDRef; pub fn CFUUIDGetUUIDBytes(uuid: CFUUIDRef) -> CFUUIDBytes; /* Getting the CFUUID Type Identifier */ diff --git a/core-foundation-sys/src/xml_node.rs b/core-foundation-sys/src/xml_node.rs index 7626d3959..5a08838c6 100644 --- a/core-foundation-sys/src/xml_node.rs +++ b/core-foundation-sys/src/xml_node.rs @@ -7,13 +7,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::os::raw::{c_void, c_char}; +use std::os::raw::{c_char, c_void}; -use base::{Boolean, CFIndex, CFAllocatorRef, CFTypeID}; -use tree::CFTreeRef; -use dictionary::CFDictionaryRef; use array::CFArrayRef; -use string::{CFStringRef, CFStringEncoding}; +use base::{Boolean, CFAllocatorRef, CFIndex, CFTypeID}; +use dictionary::CFDictionaryRef; +use string::{CFStringEncoding, CFStringRef}; +use tree::CFTreeRef; use url::CFURLRef; #[repr(C)] @@ -47,45 +47,45 @@ pub struct CFXMLElementInfo { pub attributes: CFDictionaryRef, pub attributeOrder: CFArrayRef, pub isEmpty: Boolean, - pub _reserved: [c_char; 3] + pub _reserved: [c_char; 3], } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct CFXMLProcessingInstructionInfo { - pub dataString: CFStringRef + pub dataString: CFStringRef, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct CFXMLDocumentInfo { pub sourceURL: CFURLRef, - pub encoding: CFStringEncoding + pub encoding: CFStringEncoding, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct CFXMLExternalID { pub systemID: CFURLRef, - pub publicID: CFStringRef + pub publicID: CFStringRef, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct CFXMLDocumentTypeInfo { - pub externalID: CFXMLExternalID + pub externalID: CFXMLExternalID, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct CFXMLNotationInfo { - pub externalID: CFXMLExternalID + pub externalID: CFXMLExternalID, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct CFXMLElementTypeDeclarationInfo { - pub contentDescription: CFStringRef + pub contentDescription: CFStringRef, } #[repr(C)] @@ -93,14 +93,14 @@ pub struct CFXMLElementTypeDeclarationInfo { pub struct CFXMLAttributeDeclarationInfo { pub attributeName: CFStringRef, pub typeString: CFStringRef, - pub defaultString: CFStringRef + pub defaultString: CFStringRef, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct CFXMLAttributeListDeclarationInfo { pub numberOfAttributes: CFIndex, - pub attributes: *mut CFXMLAttributeDeclarationInfo + pub attributes: *mut CFXMLAttributeDeclarationInfo, } pub type CFXMLEntityTypeCode = CFIndex; @@ -116,21 +116,27 @@ pub struct CFXMLEntityInfo { pub entityType: CFXMLEntityTypeCode, pub replacementText: CFStringRef, pub entityID: CFXMLExternalID, - pub notationName: CFStringRef + pub notationName: CFStringRef, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct CFXMLEntityReferenceInfo { - pub entityType: CFXMLEntityTypeCode + pub entityType: CFXMLEntityTypeCode, } -extern { +extern "C" { /* * CFXMLNode.h */ pub fn CFXMLNodeGetTypeID() -> CFTypeID; - pub fn CFXMLNodeCreate(alloc: CFAllocatorRef, xmlType: CFXMLNodeTypeCode, dataString: CFStringRef, additionalInfoPtr: *const c_void, version: CFIndex) -> CFXMLNodeRef; + pub fn CFXMLNodeCreate( + alloc: CFAllocatorRef, + xmlType: CFXMLNodeTypeCode, + dataString: CFStringRef, + additionalInfoPtr: *const c_void, + version: CFIndex, + ) -> CFXMLNodeRef; pub fn CFXMLNodeCreateCopy(alloc: CFAllocatorRef, origNode: CFXMLNodeRef) -> CFXMLNodeRef; pub fn CFXMLNodeGetTypeCode(node: CFXMLNodeRef) -> CFXMLNodeTypeCode; pub fn CFXMLNodeGetString(node: CFXMLNodeRef) -> CFStringRef; diff --git a/core-foundation-sys/src/xml_parser.rs b/core-foundation-sys/src/xml_parser.rs index 091d624cd..e68cb8dca 100644 --- a/core-foundation-sys/src/xml_parser.rs +++ b/core-foundation-sys/src/xml_parser.rs @@ -9,12 +9,12 @@ use std::os::raw::c_void; -use base::{CFOptionFlags, CFIndex, Boolean, CFAllocatorRef, CFTypeID}; -use xml_node::{CFXMLNodeRef, CFXMLTreeRef, CFXMLExternalID}; +use base::{Boolean, CFAllocatorRef, CFIndex, CFOptionFlags, CFTypeID}; use data::CFDataRef; +use dictionary::CFDictionaryRef; use string::CFStringRef; use url::CFURLRef; -use dictionary::CFDictionaryRef; +use xml_node::{CFXMLExternalID, CFXMLNodeRef, CFXMLTreeRef}; #[repr(C)] pub struct __CFXMLParser(c_void); @@ -51,11 +51,26 @@ pub const kCFXMLErrorMalformedCharacterReference: CFIndex = 13; pub const kCFXMLErrorMalformedParsedCharacterData: CFIndex = 14; pub const kCFXMLErrorNoData: CFIndex = 15; -pub type CFXMLParserCreateXMLStructureCallBack = extern "C" fn (parser: CFXMLParserRef, nodeDesc: CFXMLNodeRef, info: *mut c_void) -> *mut c_void; -pub type CFXMLParserAddChildCallBack = extern "C" fn (parser: CFXMLParserRef, parent: *mut c_void, child: *mut c_void, info: *mut c_void); -pub type CFXMLParserEndXMLStructureCallBack = extern "C" fn (parser: CFXMLParserRef, xmlType: *mut c_void, info: *mut c_void); -pub type CFXMLParserResolveExternalEntityCallBack = extern "C" fn (parser: CFXMLParserRef, extID: *mut CFXMLExternalID, info: *mut c_void) -> CFDataRef; -pub type CFXMLParserHandleErrorCallBack = extern "C" fn (parser: CFXMLParserRef, error: CFXMLParserStatusCode, info: *mut c_void) -> Boolean; +pub type CFXMLParserCreateXMLStructureCallBack = + extern "C" fn(parser: CFXMLParserRef, nodeDesc: CFXMLNodeRef, info: *mut c_void) -> *mut c_void; +pub type CFXMLParserAddChildCallBack = extern "C" fn( + parser: CFXMLParserRef, + parent: *mut c_void, + child: *mut c_void, + info: *mut c_void, +); +pub type CFXMLParserEndXMLStructureCallBack = + extern "C" fn(parser: CFXMLParserRef, xmlType: *mut c_void, info: *mut c_void); +pub type CFXMLParserResolveExternalEntityCallBack = extern "C" fn( + parser: CFXMLParserRef, + extID: *mut CFXMLExternalID, + info: *mut c_void, +) -> CFDataRef; +pub type CFXMLParserHandleErrorCallBack = extern "C" fn( + parser: CFXMLParserRef, + error: CFXMLParserStatusCode, + info: *mut c_void, +) -> Boolean; #[repr(C)] #[derive(Debug, Clone, Copy)] @@ -69,7 +84,7 @@ pub struct CFXMLParserCallBacks { } pub type CFXMLParserRetainCallBack = extern "C" fn(info: *const c_void) -> *const c_void; -pub type CFXMLParserReleaseCallBack = extern "C" fn (info: *const c_void); +pub type CFXMLParserReleaseCallBack = extern "C" fn(info: *const c_void); pub type CFXMLParserCopyDescriptionCallBack = extern "C" fn(info: *const c_void) -> CFStringRef; #[repr(C)] @@ -79,10 +94,10 @@ pub struct CFXMLParserContext { pub info: *mut c_void, pub retain: CFXMLParserRetainCallBack, pub release: CFXMLParserReleaseCallBack, - pub copyDescription: CFXMLParserCopyDescriptionCallBack + pub copyDescription: CFXMLParserCopyDescriptionCallBack, } -extern { +extern "C" { /* * CFXMLParser.h */ @@ -93,8 +108,23 @@ extern { pub static kCFXMLTreeErrorStatusCode: CFStringRef; pub fn CFXMLParserGetTypeID() -> CFTypeID; - pub fn CFXMLParserCreate(allocator: CFAllocatorRef, xmlData: CFDataRef, dataSource: CFURLRef, parseOptions: CFOptionFlags, versionOfNodes: CFIndex, callBacks: *mut CFXMLParserCallBacks, context: *mut CFXMLParserContext) -> CFXMLParserRef; - pub fn CFXMLParserCreateWithDataFromURL(allocator: CFAllocatorRef, dataSource: CFURLRef, parseOptions: CFOptionFlags, versionOfNodes: CFIndex, callBacks: *mut CFXMLParserCallBacks, context: *mut CFXMLParserContext) -> CFXMLParserRef; + pub fn CFXMLParserCreate( + allocator: CFAllocatorRef, + xmlData: CFDataRef, + dataSource: CFURLRef, + parseOptions: CFOptionFlags, + versionOfNodes: CFIndex, + callBacks: *mut CFXMLParserCallBacks, + context: *mut CFXMLParserContext, + ) -> CFXMLParserRef; + pub fn CFXMLParserCreateWithDataFromURL( + allocator: CFAllocatorRef, + dataSource: CFURLRef, + parseOptions: CFOptionFlags, + versionOfNodes: CFIndex, + callBacks: *mut CFXMLParserCallBacks, + context: *mut CFXMLParserContext, + ) -> CFXMLParserRef; pub fn CFXMLParserGetContext(parser: CFXMLParserRef, context: *mut CFXMLParserContext); pub fn CFXMLParserGetCallBacks(parser: CFXMLParserRef, callBacks: *mut CFXMLParserCallBacks); pub fn CFXMLParserGetSourceURL(parser: CFXMLParserRef) -> CFURLRef; @@ -103,12 +133,42 @@ extern { pub fn CFXMLParserGetDocument(parser: CFXMLParserRef) -> *mut c_void; pub fn CFXMLParserGetStatusCode(parser: CFXMLParserRef) -> CFXMLParserStatusCode; pub fn CFXMLParserCopyErrorDescription(parser: CFXMLParserRef) -> CFStringRef; - pub fn CFXMLParserAbort(parser: CFXMLParserRef, errorCode: CFXMLParserStatusCode, errorDescription: CFStringRef); + pub fn CFXMLParserAbort( + parser: CFXMLParserRef, + errorCode: CFXMLParserStatusCode, + errorDescription: CFStringRef, + ); pub fn CFXMLParserParse(parser: CFXMLParserRef) -> Boolean; - pub fn CFXMLTreeCreateFromData(allocator: CFAllocatorRef, xmlData: CFDataRef, dataSource: CFURLRef, parseOptions: CFOptionFlags, versionOfNodes: CFIndex) -> CFXMLTreeRef; - pub fn CFXMLTreeCreateFromDataWithError(allocator: CFAllocatorRef, xmlData: CFDataRef, dataSource: CFURLRef, parseOptions: CFOptionFlags, versionOfNodes: CFIndex, errorDict: *mut CFDictionaryRef) -> CFXMLTreeRef; - pub fn CFXMLTreeCreateWithDataFromURL(allocator: CFAllocatorRef, dataSource: CFURLRef, parseOptions: CFOptionFlags, versionOfNodes: CFIndex) -> CFXMLTreeRef; + pub fn CFXMLTreeCreateFromData( + allocator: CFAllocatorRef, + xmlData: CFDataRef, + dataSource: CFURLRef, + parseOptions: CFOptionFlags, + versionOfNodes: CFIndex, + ) -> CFXMLTreeRef; + pub fn CFXMLTreeCreateFromDataWithError( + allocator: CFAllocatorRef, + xmlData: CFDataRef, + dataSource: CFURLRef, + parseOptions: CFOptionFlags, + versionOfNodes: CFIndex, + errorDict: *mut CFDictionaryRef, + ) -> CFXMLTreeRef; + pub fn CFXMLTreeCreateWithDataFromURL( + allocator: CFAllocatorRef, + dataSource: CFURLRef, + parseOptions: CFOptionFlags, + versionOfNodes: CFIndex, + ) -> CFXMLTreeRef; pub fn CFXMLTreeCreateXMLData(allocator: CFAllocatorRef, xmlTree: CFXMLTreeRef) -> CFDataRef; - pub fn CFXMLCreateStringByEscapingEntities(allocator: CFAllocatorRef, string: CFStringRef, entitiesDictionary: CFDictionaryRef) -> CFStringRef; - pub fn CFXMLCreateStringByUnescapingEntities(allocator: CFAllocatorRef, string: CFStringRef, entitiesDictionary: CFDictionaryRef) -> CFStringRef; + pub fn CFXMLCreateStringByEscapingEntities( + allocator: CFAllocatorRef, + string: CFStringRef, + entitiesDictionary: CFDictionaryRef, + ) -> CFStringRef; + pub fn CFXMLCreateStringByUnescapingEntities( + allocator: CFAllocatorRef, + string: CFStringRef, + entitiesDictionary: CFDictionaryRef, + ) -> CFStringRef; } diff --git a/core-foundation/src/array.rs b/core-foundation/src/array.rs index 6f2997d98..361af3011 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(), }) } } @@ -165,8 +179,8 @@ mod tests { use crate::number::CFNumber; use super::*; - use std::mem; use base::CFType; + use std::mem; #[test] fn to_untyped_correct_retain_count() { @@ -218,15 +232,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("alongerstring"); 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[..], &["alongerstring"]); 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 4bb7df7f9..20396ad8c 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 c2d081c93..e42bd6106 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 fd1954d5f..2c9a25b87 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); @@ -96,9 +95,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) { @@ -114,9 +111,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) { @@ -132,9 +127,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) { @@ -148,25 +141,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 { + 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); + 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 { @@ -175,7 +184,11 @@ impl CFRunLoopSource { } declare_TCFType!(CFRunLoopObserver, CFRunLoopObserverRef); -impl_TCFType!(CFRunLoopObserver, CFRunLoopObserverRef, CFRunLoopObserverGetTypeID); +impl_TCFType!( + CFRunLoopObserver, + CFRunLoopObserverRef, + CFRunLoopObserverGetTypeID +); #[cfg(test)] mod test { @@ -207,7 +220,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 03a85f155..4d8723319 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; diff --git a/core-graphics-types/src/geometry.rs b/core-graphics-types/src/geometry.rs index 586075270..de94b0da5 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,14 +125,12 @@ impl CGRect { #[inline] pub fn apply_transform(&self, t: &CGAffineTransform) -> CGRect { - unsafe { - ffi::CGRectApplyAffineTransform(*self, *t) - } + unsafe { ffi::CGRectApplyAffineTransform(*self, *t) } } #[inline] pub fn contains(&self, point: &CGPoint) -> bool { - unsafe { ffi::CGRectContainsPoint(*self,*point) == 1 } + unsafe { ffi::CGRectContainsPoint(*self, *point) == 1 } } } @@ -171,22 +160,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; @@ -196,7 +185,6 @@ mod ffi { pub fn CGRectApplyAffineTransform(rect: CGRect, t: CGAffineTransform) -> CGRect; pub fn CGSizeApplyAffineTransform(size: CGSize, t: CGAffineTransform) -> CGSize; - pub fn CGRectContainsPoint(rect:CGRect, point: CGPoint) -> boolean_t; + pub fn CGRectContainsPoint(rect: CGRect, point: CGPoint) -> boolean_t; } } - 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 2b2963575..90ee77b0a 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" { /// The Display P3 color space, created by Apple. pub static kCGColorSpaceDisplayP3: CFStringRef; /// The Display P3 color space, using the HLG transfer function. @@ -114,4 +116,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 aca5fb74d..570a23435 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()); } } @@ -420,75 +389,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) { @@ -498,10 +443,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) { @@ -520,36 +462,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, + ) } } @@ -584,26 +520,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, + ); } } @@ -631,14 +591,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()); @@ -652,18 +616,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; @@ -678,43 +643,56 @@ 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); @@ -722,43 +700,37 @@ extern { fn CGContextEOClip(c: ::sys::CGContextRef); fn CGContextResetClip(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; @@ -766,10 +738,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); @@ -779,12 +753,30 @@ 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, + ); fn CGContextSetAlpha(c: ::sys::CGContextRef, alpha: CGFloat); } - diff --git a/core-graphics/src/data_provider.rs b/core-graphics/src/data_provider.rs index 38d515e39..044575ea7 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 c5c167e40..a07af07f9 100644 --- a/core-graphics/src/display.rs +++ b/core-graphics/src/display.rs @@ -10,19 +10,19 @@ #![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 type CGWindowLevel = i32; pub const kCGNullWindowID: CGWindowID = 0 as CGWindowID; @@ -30,12 +30,12 @@ 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; @@ -46,28 +46,28 @@ 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 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 type CGDisplayBlendFraction = f32; pub const kCGDisplayBlendNormal: CGDisplayBlendFraction = 0.0; @@ -80,24 +80,25 @@ pub type CGDisplayFadeInterval = f32; pub type CGDisplayReservationInterval = f32; pub const kCGMaxDisplayReservationInterval: CGDisplayReservationInterval = 15.0; -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 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; @@ -562,7 +563,8 @@ impl CGDisplayMode { .map(|value0| { let x = *value0.deref() as *mut ::sys::CGDisplayMode; unsafe { CGDisplayMode::from_ptr(x) } - }).collect(); + }) + .collect(); Some(vec) } None => None, diff --git a/core-graphics/src/event.rs b/core-graphics/src/event.rs index aaddf821d..b160c0c57 100644 --- a/core-graphics/src/event.rs +++ b/core-graphics/src/event.rs @@ -439,7 +439,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}; @@ -526,9 +525,7 @@ foreign_type! { impl CGEvent { pub fn type_id() -> CFTypeID { - unsafe { - CGEventGetTypeID() - } + unsafe { CGEventGetTypeID() } } pub fn new(source: CGEventSource) -> Result { @@ -545,7 +542,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); @@ -561,11 +558,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 { @@ -630,9 +631,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) { @@ -642,9 +641,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]) { @@ -677,7 +674,7 @@ impl CGEvent { } #[link(name = "CoreGraphics", kind = "framework")] -extern { +extern "C" { /// Return the type identifier for the opaque type `CGEventRef'. fn CGEventGetTypeID() -> CFTypeID; @@ -695,8 +692,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. /// @@ -711,8 +711,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. /// @@ -767,9 +771,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 6db64a2dc..b12a68dd1 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 739b8ddf3..888e19ce2 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; use std::ptr::NonNull; @@ -34,9 +34,7 @@ foreign_type! { impl CGFont { pub fn type_id() -> CFTypeID { - unsafe { - CGFontGetTypeID() - } + unsafe { CGFontGetTypeID() } } pub fn from_data_provider(provider: CGDataProvider) -> Result { @@ -59,10 +57,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()); match NonNull::new(font_ref) { Some(font_ref) => Ok(CGFont(font_ref)), None => Err(()), @@ -80,33 +81,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 { @@ -138,11 +139,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; @@ -152,16 +156,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 a4fb2bf61..b06c31c1b 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 9e9323f4a..e702e7817 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 514558fb4..3c1b6443a 100644 --- a/core-graphics/src/lib.rs +++ b/core-graphics/src/lib.rs @@ -20,6 +20,8 @@ extern crate foreign_types; extern crate core_graphics_types; +#[cfg(target_os = "macos")] +pub mod access; pub mod base; pub mod color; pub mod color_space; @@ -34,12 +36,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 access; \ No newline at end of file +pub mod window; diff --git a/core-graphics/src/path.rs b/core-graphics/src/path.rs index c5ac93f40..a15949c90 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 f313b8975..6df9750ba 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; @@ -142,33 +142,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) } } @@ -181,9 +188,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 { @@ -192,15 +198,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()), ); @@ -218,9 +226,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) } } } @@ -242,24 +248,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 { @@ -311,119 +318,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 { @@ -443,25 +426,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(), + ) } } @@ -486,8 +476,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() { @@ -500,9 +493,7 @@ impl CTFont { #[inline] pub fn glyph_count(&self) -> CFIndex { - unsafe { - CTFontGetGlyphCount(self.0) - } + unsafe { CTFontGetGlyphCount(self.0) } } } @@ -512,12 +503,30 @@ pub fn debug_font_names(font: &CTFont) { font.get_string_by_name_key(key).unwrap() } - println!("kCTFontFamilyNameKey: {}", get_key(font, CTFontNameSpecifier::Family)); - println!("kCTFontSubFamilyNameKey: {}", get_key(font, CTFontNameSpecifier::SubFamily)); - println!("kCTFontStyleNameKey: {}", get_key(font, CTFontNameSpecifier::Style)); - println!("kCTFontUniqueNameKey: {}", get_key(font, CTFontNameSpecifier::Unique)); - println!("kCTFontFullNameKey: {}", get_key(font, CTFontNameSpecifier::Full)); - println!("kCTFontPostScriptNameKey: {}", get_key(font, CTFontNameSpecifier::PostScript)); + println!( + "kCTFontFamilyNameKey: {}", + get_key(font, CTFontNameSpecifier::Family) + ); + println!( + "kCTFontSubFamilyNameKey: {}", + get_key(font, CTFontNameSpecifier::SubFamily) + ); + println!( + "kCTFontStyleNameKey: {}", + get_key(font, CTFontNameSpecifier::Style) + ); + println!( + "kCTFontUniqueNameKey: {}", + get_key(font, CTFontNameSpecifier::Unique) + ); + println!( + "kCTFontFullNameKey: {}", + get_key(font, CTFontNameSpecifier::Full) + ); + println!( + "kCTFontPostScriptNameKey: {}", + get_key(font, CTFontNameSpecifier::PostScript) + ); } pub fn debug_font_traits(font: &CTFont) { @@ -531,21 +540,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 */ @@ -593,20 +606,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 @@ -627,8 +656,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 @@ -649,26 +680,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; @@ -679,27 +717,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; } @@ -730,20 +781,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!(), } } @@ -791,16 +857,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()); } @@ -821,17 +903,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(); @@ -845,11 +940,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) { @@ -864,51 +971,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(); @@ -921,11 +1053,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()); }; } } @@ -945,9 +1086,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) { @@ -963,5 +1107,9 @@ fn system_font_variation() { #[test] fn ui_font() { // pass some garbagey inputs - new_ui_font_for_language(kCTFontSystemDetailFontType, 10000009., Some(CFString::from("Gofld"))); + 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;